diff --git a/docs/reference/cli.md b/docs/reference/cli.md index 7fc58ad24..ffa775cc3 100644 --- a/docs/reference/cli.md +++ b/docs/reference/cli.md @@ -35,6 +35,10 @@ Each line is a pointer: the command, what its verbs govern, and where to read th (`docket diagnostic config`). Verbs: `docket diagnostic --help`. - **`docket evidence`** — record and verify the build evidence that certifies an exact tested commit. Verbs: `docket evidence --help`. +- **`docket export`** — write a clean Markdown copy of a change, spec, plan, or results file, + free of docket's links and generated blocks, and open it. Without an id it exports the change + whose branch is checked out. Agent sessions reach the export through the `docket-export` + skill. Details: `docket export --help`. - **`docket finalize`** — sequence a change's closing half: rebase, publish, merge, and closeout. Verbs: `docket finalize --help`. - **`docket gate`** — launch, observe, stop, and recover supervised local gate runs. Verbs: `docket gate --help`. - **`docket install`** — install docket's skills, agents, and dispatch material into your @@ -46,9 +50,7 @@ Each line is a pointer: the command, what its verbs govern, and where to read th (`docket status` stays read-only). Verbs: `docket maintenance --help`. - **`docket open`** — open the board, or a change's record, spec, plan, results, or pull request, as a GitHub page or from the local metadata checkout. Without an id it opens the change whose - branch is checked out. With `--export` it writes a clean Markdown copy of a change, spec, plan, - or results file, free of docket's links and generated blocks, and opens that copy. Agent - sessions reach the export through the `docket-export` skill. Details: `docket open --help`. + branch is checked out. Details: `docket open --help`. - **`docket pr`** — publish the ready-for-review pull request for an in-progress change's tested head. Verbs: `docket pr --help`. - **`docket repository`** — initialize, migrate, check, and repair the docket repository diff --git a/docs/reference/glossary.md b/docs/reference/glossary.md index a43b8e0fe..f91a17a0d 100644 --- a/docs/reference/glossary.md +++ b/docs/reference/glossary.md @@ -1763,8 +1763,8 @@ agent. ### docket-export The skill an agent session uses to hand a change, spec, plan, or results file to anything outside -docket. It runs the `open` operation's export (`--export --print --json`) and passes the clean copy -to a file or another tool, never the raw file. In a private repository it also rewrites what the +docket. It runs the `export` operation (`--print --json`) and passes the clean copy to a file or +another tool, never the raw file. In a private repository it also rewrites what the export leaves that names docket, checks the result, and shows you before → after before posting. **Used for:** putting a spec or other artifact into a document or message from an agent diff --git a/docs/superpowers/specs/2026-11-10-make-export-its-own-command-docket-export-type-change-id-design.md b/docs/superpowers/specs/2026-11-10-make-export-its-own-command-docket-export-type-change-id-design.md new file mode 100644 index 000000000..7a53debaa --- /dev/null +++ b/docs/superpowers/specs/2026-11-10-make-export-its-own-command-docket-export-type-change-id-design.md @@ -0,0 +1,84 @@ +# `docket export` — export as its own command + +Change 0589 — Make export its own command: docket export + +Change #589, groomed interactively on 2026-11-10. + +## Why + +Exporting an artifact is a different job from opening one, but today it is a flag on open: `docket open spec 9 --export`. That reads as "open this, and also export it", and `open` has to police flags (`--output-path`, `--warnings`) that only mean anything with `--export`. The ticket work (changes 581, 582, and the link-ticket and update-ticket skills) now routes ticket bodies and attachments through the export, so export is a first-class job and gets a command named for it. + +## Goals + +- `docket export []` does everything `docket open [] --export` does today, except the one opening change settled below (`--output-path` no longer opens the copy). +- `docket open` only opens. +- The `docket-export` skill and the docs name the new command. + +## Non-goals + +- Changing what the export writes: kept sections, link removal, reference rewriting, the self-check, its warnings, the file name. +- An export for the board or pull requests. +- Any other change to `docket open`. + +## Settled at grooming + +- **Command and catalog id.** A new top-level command `docket export []`, `` one of `change`, `spec`, `plan`, `results`. Its capability-catalog id is `export`, following the house pattern that a top-level command's id is its name (`open`, `status`). Without an id it resolves the change whose recorded branch is checked out, exactly as `open` does. +- **Opening behavior.** + - No `--output-path`: write the copy to the default destination (`~/Downloads` on macOS, the home directory elsewhere — unchanged) and **open the copy**, as `open --export` does today. + - `--output-path `: write the copy there and **print its path; open nothing**. The person named the destination, so they know where the file is. + - `--print`: write the copy and print its path; open nothing, whatever the destination. Kept because the `docket-export` skill exports to the default destination for file requests and must never pop a viewer at a person who may not be at the screen. +- **`docket open` loses `--export`, `--output-path`, and `--warnings` outright.** No alias, no message naming the new command — the same posture change 582 took for the `issue` → `ticket` kind rename. `open --export` fails with the CLI's ordinary unknown-flag error. +- **Flags of `docket export`:** `--output-path`, `--warnings all|leftovers|mentions` (default `all`), `--print`, `--repo-dir`, and the global `--json`. Their meaning, validation, and messages are today's, and so is where they are checked: usage mistakes stay **CLI usage errors** (`invalid-arguments`, exit 2, no operation document), caught in the command's argument check before the operation runs — a type outside the four (`board`, `pr`, anything else), a bad `--warnings` value, an empty `--output-path` (builder's call made at grooming: this matches today's `open --export`, whose `Args` hook rejects the same mistakes). Everything else about the flags is unchanged (`--output-path` given empty is refused; the destination rules — an existing directory takes the copy under its generated name, any other path is the exact file and its parent must exist; the source artifact and anything inside the metadata checkout are refused). + +## Design + +### Behavior that moves unchanged + +Everything below is today's `open --export` behavior and keeps working byte-for-byte; only its entry point changes. The one deliberate difference is that `--output-path` without `--print` no longer opens the copy (today it does — `openExport` ends in the shared open step, which launches unless `--print` is set); a moved test expecting that launch changes with it. + +- reading the artifact from the local metadata checkout whatever the repository's open routing (shared, private, `open.artifacts`), with the same stale-checkout note when preparing the checkout fails; +- the file name `--.md` (kinds `ticket`, `spec`, `plan`, `results`), the transform, the self-check, the atomic write, the `replaced` note; +- the refusal reasons and result classes: `unknown-change`, `ambiguous-change`, `artifact-unset`, `artifact-path-invalid`, the branch-inference reasons (`head-detached`, `branch-unmatched`, `branch-ambiguous`, `checkout-unreadable`), `file-missing`, `output-path-invalid`, `output-path-protected`, `export-failed`, `no-opener`, and `opener-failed`. A type outside the four is the CLI usage error above, not an operation reason; if the app-layer entry point is called directly with one it refuses as `invalid-target` (today's direct-call reason is `invalid-option`, which goes away with `ValidateOpenExport`). + +### Result document + +The result's envelope carries operation `export`. Its fields are today's export result: `what`, `change_id`, `exported_path`, `replaced`, `launched`, `notes` (always a list), `leftovers`, `mentions` (both following `--warnings`), and `reason` / `message` on a refusal or failure. Today's `target` and `target_kind` are dropped from it — on an export they always equal `exported_path` and `file` (builder's call made at grooming; nothing reads them for an export — the `docket-export` skill reads `result`, `exported_path`, `replaced`, `leftovers`, `mentions`, and `message`). Because the fields differ from `open`'s, the export has its own result type, registered in `internal/app/schema_registry.go` under `export` beside `open`'s `OpenResult` entry; its human text prints `exported_path` (`OpenResult.HumanText` prints `target`). Human output is unchanged: the path alone on success, so `"$(docket export spec 9 --print)"` composes; notes, then warnings, on stderr; the message on a refusal. + +`launched` is `true` only when the copy was handed to the opener; it is `false` under `--print` or `--output-path`. + +### Effects + +The `export` entry declares `read`, `local-write`, and `process-control` (it still launches the opener on the default path). `open` keeps the same three: it still prepares the metadata checkout and launches the opener. + +### `docket open` after the removal + +`OpenOptions` loses its export fields; `ValidateOpenExport` and the `invalid-option` reason go with them (no remaining use). Open's targets, routing, `--print`, and result are otherwise unchanged; `open`'s help text drops the export paragraphs. The change-resolution and local-artifact helpers `Open` and the export both need (target and change resolution, branch inference, `localArtifact`, `finishOpen`'s opener call) are shared, not copied — how to factor them is the builder's call. + +### Callers and docs + +Derive the site list from a whole-repo grep for `--export`, `--output-path`, `--warnings`, and the `open` operation, sorting hits into maintained source vs point-in-time records; only maintained source changes. Known sites today: + +- `skills/docket-export/SKILL.md`: section 1 takes the `export` entry's argv instead of `open`'s; section 3 runs ` [] --print --json --repo-dir `, always `--print --json`, with the same file-request and outside-tool rules (`--output-path` as today). +- `skills/docket-link-ticket/references/create.md` uses `open … spec --print --json` to get the spec's URL — that is a real open, not an export, and stays. +- `docs/reference/cli.md`: a `docket export` entry; the `docket open` entry drops its export sentence. +- `docs/reference/glossary.md`: the `docket-export` entry names the `export` operation. +- `internal/repoguard/prose_contracts_test.go`: the `change_0578_export_skill` sentinel's `` `--export --print --json` `` clause follows the skill's new spelling; mutation-test it. +- `internal/cli/capability_production_test.go`: the `open` usage string loses the three flags; an `export` usage string is added. +- `internal/app/schema_registry.go`: an `export` entry with the new result type. +- The embedded asset tree (`go generate ./internal/assets/`) after the skill edit. + +Point-in-time records (release notes, archived changes, results, specs, plans) keep `open --export` as written. + +## Acceptance criteria + +- `docket export spec --print --json` writes the same file, with the same bytes, that `docket open spec --export --print --json` writes before this change, and reports the same `exported_path`, `replaced`, `leftovers`, and `mentions`. +- `docket export spec ` with no `--output-path` and no `--print` opens the copy (`launched: true`); with `--output-path` or `--print` it opens nothing (`launched: false`) and prints the path. +- `docket export board`, `docket export pr 3`, `--warnings bogus`, and an empty `--output-path` are CLI usage errors (`invalid-arguments`, exit 2), as `open --export`'s are today. +- `docket open` rejects `--export`, `--output-path`, and `--warnings` as unknown flags. +- The capability catalog lists `export`, and the `docket-export` skill resolves its argv from that entry. +- The whole suite is green. + +## Left to the builder + +- How to factor the shared resolution code between `Open` and the export, and where the export's app-layer code lives. +- Test placement; the existing `open --export` tests move to the new command rather than being rewritten from scratch. diff --git a/internal/app/open_export.go b/internal/app/export.go similarity index 52% rename from internal/app/open_export.go rename to internal/app/export.go index eae1dce45..96d97b17f 100644 --- a/internal/app/open_export.go +++ b/internal/app/export.go @@ -1,6 +1,6 @@ package app -// open_export.go holds the --export branch of `docket open`: its usage check, +// export.go holds `docket export`: its argument grammar, its result document, // the destination rule, the atomic write of the clean copy, and the warnings // the self-check reports, filtered by --warnings. @@ -11,6 +11,7 @@ import ( "io/fs" "os" "path/filepath" + "slices" "strconv" "strings" @@ -19,6 +20,153 @@ import ( "github.com/danielhanold/docket/internal/exportcheck" ) +// OperationExport is the operation id of `docket export`. +const OperationExport = "export" + +// ExportTargets lists what `docket export` can export, in usage order. Each +// takes an optional change id. +var ExportTargets = []string{"change", "spec", "plan", "results"} + +// ExportOptions is one `docket export` request. +type ExportOptions struct { + RepoDir string + What string + ID int // 0 = infer from the checked-out branch + Print bool + OutputPath string // "" = the default destination + Warnings string // "" = WarningsAll +} + +// ExportResult is the document `docket export` emits for every outcome. +// ChangeID is omitted until the change is resolved; Notes is always a list, +// possibly empty; Leftovers and Mentions follow --warnings. +type ExportResult struct { + Envelope + What string `json:"what"` + ChangeID int `json:"change_id,omitempty"` + ExportedPath string `json:"exported_path,omitempty"` + Replaced bool `json:"replaced,omitempty"` + Launched bool `json:"launched"` + Notes []string `json:"notes"` + Leftovers []ExportLeftover `json:"leftovers,omitempty"` + Mentions *ExportMentions `json:"mentions,omitempty"` + Reason string `json:"reason,omitempty"` + Message string `json:"message,omitempty"` +} + +// HumanText renders the result for a terminal: the exported path alone on +// success (so it composes in command substitution), the path then the failure +// message when the opener failed after the copy was written, or the message +// alone. +func (r ExportResult) HumanText() string { + if r.Message == "" { + return r.ExportedPath + } + if r.ExportedPath != "" { + return r.ExportedPath + "\n" + r.Message + } + return r.Message +} + +// HumanNotes returns the notes a human renderer writes apart from HumanText. +func (r ExportResult) HumanNotes() []string { return r.Notes } + +// HumanWarnings returns the warning lines a human renderer writes after the +// notes. +func (r ExportResult) HumanWarnings() []string { return exportWarningLines(r.Leftovers, r.Mentions) } + +// ParseExportArgs parses `export [id]` into the type and the change id, +// 0 when none was given. Every error is a one-line usage message. +func ParseExportArgs(args []string) (string, int, error) { + types := strings.Join(ExportTargets, ", ") + switch { + case len(args) == 0: + return "", 0, fmt.Errorf("missing type — choose one of %s", types) + case len(args) > 2: + return "", 0, fmt.Errorf("too many arguments — usage: export [id], where is one of %s", types) + } + what := args[0] + if !slices.Contains(ExportTargets, what) { + return "", 0, fmt.Errorf("unknown type %q — choose one of %s", what, types) + } + if len(args) == 1 { + return what, 0, nil + } + n, err := parseChangeIDArg(args[1]) + if err != nil { + return "", 0, err + } + return what, n, nil +} + +// ValidateExportWarnings accepts the --warnings values: all, leftovers, +// mentions, or "" (all). +func ValidateExportWarnings(w string) error { + switch w { + case "", WarningsAll, WarningsLeftovers, WarningsMentions: + return nil + } + return fmt.Errorf("invalid --warnings value %q — choose all, leftovers, or mentions", w) +} + +// Export resolves what (and the change id, or the change the checked-out branch +// records when the id is 0) to an artifact in the local metadata checkout, +// whatever the repository's open routing, and writes its clean copy. Only an +// export to the default destination without Print opens the copy. +func Export(ctx context.Context, deps OpenDeps, o ExportOptions) ExportResult { + res := ExportResult{What: o.What, ChangeID: o.ID, Notes: []string{}} + fail := func(f openFailure) ExportResult { + res.Envelope = NewEnvelope(OperationExport, f.result) + res.Reason, res.Message = f.reason, f.message + return res + } + if !slices.Contains(ExportTargets, o.What) { + args := []string{o.What} + if o.ID != 0 { + args = append(args, strconv.Itoa(o.ID)) + } + _, _, err := ParseExportArgs(args) + return fail(openFailure{ResultInvalidInput, ReasonOpenInvalidTarget, err.Error()}) + } + // Reusing invalid-target here is deliberate: only direct app-layer callers + // reach this path, because the CLI rejects a bad --warnings value as a usage + // error (exit 2) before the operation runs, and the spec removed the old + // invalid-option reason. + if err := ValidateExportWarnings(o.Warnings); err != nil { + return fail(openFailure{ResultInvalidInput, ReasonOpenInvalidTarget, err.Error()}) + } + dir, branch, pin, f := openPrelude(ctx, deps, o.RepoDir, o.What, o.ID) + if f != nil { + return fail(*f) + } + c, snap, f := resolveOpenChange(ctx, deps.Reader, pin, o.ID, branch) + if f != nil { + return fail(*f) + } + res.ChangeID = int(c.ID()) + rel, f := changeArtifactPath(c, o.What) + if f != nil { + return fail(*f) + } + if f := checkArtifactPath(o.What, rel); f != nil { + return fail(*f) + } + cp, f := writeCleanCopy(ctx, deps, o.What, o.OutputPath, o.Warnings, dir, pin, c, snap, rel) + res.Notes = append(res.Notes, cp.Notes...) + if f != nil { + return fail(*f) + } + res.ExportedPath, res.Replaced, res.Leftovers, res.Mentions = cp.Path, cp.Replaced, cp.Leftovers, cp.Mentions + if !o.Print && o.OutputPath == "" { + if f := runOpener(ctx, deps.Opener, cp.Path); f != nil { + return fail(*f) + } + res.Launched = true + } + res.Envelope = NewEnvelope(OperationExport, ResultApplied) + return res +} + // The --warnings values: which warning lists an export reports. const ( WarningsAll = "all" @@ -46,41 +194,18 @@ type ExportMentions struct { Lines []int `json:"lines"` } -// ValidateOpenExport is the one usage check of the export flags, shared by the -// CLI and Open: --export takes no board or pr, --output-path and --warnings -// need --export, and --warnings takes all, leftovers, or mentions. -func ValidateOpenExport(o OpenOptions) error { - if !o.Export { - switch { - case o.OutputPath != "": - return errors.New("--output-path needs --export") - case o.Warnings != "": - return errors.New("--warnings needs --export") - } - return nil - } - if o.What == "board" || o.What == "pr" { - return fmt.Errorf("--export works on change, spec, plan, or results, not %s", o.What) - } - switch o.Warnings { - case "", WarningsAll, WarningsLeftovers, WarningsMentions: - return nil - } - return fmt.Errorf("invalid --warnings value %q — choose all, leftovers, or mentions", o.Warnings) -} - -// HumanWarnings returns the warning lines a human renderer writes after the -// notes: one per leftover, then one for the docket mentions when there are any. -func (r OpenResult) HumanWarnings() []string { +// exportWarningLines renders an export's warnings: one line per leftover, then +// one for the docket mentions when there are any. +func exportWarningLines(leftovers []ExportLeftover, mentions *ExportMentions) []string { out := []string{} - for _, l := range r.Leftovers { + for _, l := range leftovers { if l.Rule == ExportRuleStrayMarker { out = append(out, fmt.Sprintf("damaged marker removed at source line %d: %s — the source has an unpaired marker; the exported file is clean", l.SourceLine, l.Text)) continue } out = append(out, fmt.Sprintf("leftover line %d (%s): %s — docket machinery the export did not remove; edit it out before sharing", l.Line, l.Rule, l.Text)) } - if m := r.Mentions; m != nil && m.Count > 0 { + if m := mentions; m != nil && m.Count > 0 { nums := make([]string, len(m.Lines)) for i, n := range m.Lines { nums[i] = strconv.Itoa(n) @@ -99,39 +224,47 @@ var exportKinds = map[string]export.Kind{ "change": export.KindTicket, "spec": export.KindSpec, "plan": export.KindPlan, "results": export.KindResults, } -// openExport reads rel from the local metadata checkout (whatever the -// repository's open routing), writes its clean copy to the destination, runs -// the self-check, and opens or prints the copy. Warnings never block. -func openExport(ctx context.Context, deps OpenDeps, o OpenOptions, dir string, pin StatusPin, c domain.Change, snap domain.Snapshot, rel string, res OpenResult) OpenResult { - fail := func(f openFailure) OpenResult { - res.Envelope = NewEnvelope(OperationOpen, f.result) - res.Reason, res.Message = f.reason, f.message - return res - } +// exportCopy is what writeCleanCopy wrote: the copy's path, whether it +// replaced a file, the notes to attach, and the warnings --warnings keeps. +type exportCopy struct { + Path string + Replaced bool + Notes []string + Leftovers []ExportLeftover + Mentions *ExportMentions +} + +// writeCleanCopy reads rel from the local metadata checkout (whatever the +// repository's open routing), writes its clean copy to the destination +// outputPath names, and runs the self-check, keeping the warnings the +// warnings value asks for. Warnings never block. Notes carries the prepare +// notes even when a failure is returned. +func writeCleanCopy(ctx context.Context, deps OpenDeps, what, outputPath, warnings, dir string, pin StatusPin, c domain.Change, snap domain.Snapshot, rel string) (exportCopy, *openFailure) { + var cp exportCopy if deps.HomeDir == nil || deps.Getwd == nil || deps.GOOS == "" { - return fail(openFailure{ResultInternalError, ReasonOpenExportFailed, "export is not wired: home directory, working directory, and platform are required"}) + return cp, &openFailure{ResultInternalError, ReasonOpenExportFailed, "export is not wired: home directory, working directory, and platform are required"} } src, root, notes, f := localArtifact(ctx, deps, dir, pin, rel) - res.Notes = append(res.Notes, notes...) + cp.Notes = append(cp.Notes, notes...) if f != nil { - return fail(*f) + return cp, f } body, err := os.ReadFile(src) if err != nil { - return fail(openFailure{ResultExternalFailed, ReasonOpenExportFailed, fmt.Sprintf("could not read %s: %v", src, err)}) + return cp, &openFailure{ResultExternalFailed, ReasonOpenExportFailed, fmt.Sprintf("could not read %s: %v", src, err)} } - kind := exportKinds[o.What] + kind := exportKinds[what] created := "" if cr := c.Created(); cr.State == domain.FieldPresent { created = cr.Value.Format("2006-01-02") } - dest, f := exportDestination(deps, o.OutputPath, export.FileName(kind, rel, created, c.Slug())) + dest, f := exportDestination(deps, outputPath, export.FileName(kind, rel, created, c.Slug())) if f != nil { - return fail(*f) + return cp, f } if f := protectedDestination(dest, src, root); f != nil { - return fail(*f) + return cp, f } titles := exportTitles(snap) @@ -140,30 +273,28 @@ func openExport(ctx context.Context, deps OpenDeps, o OpenOptions, dir string, p replaced, err := writeExport(dest, out.Markdown) if err != nil { - return fail(openFailure{ResultExternalFailed, ReasonOpenExportFailed, fmt.Sprintf("could not write %s: %v", dest, err)}) + return cp, &openFailure{ResultExternalFailed, ReasonOpenExportFailed, fmt.Sprintf("could not write %s: %v", dest, err)} } if replaced { - res.Notes = append(res.Notes, "replaced "+dest) + cp.Notes = append(cp.Notes, "replaced "+dest) } - res.ExportedPath, res.Replaced = dest, replaced + cp.Path, cp.Replaced = dest, replaced - warnings := o.Warnings if warnings == "" { warnings = WarningsAll } if warnings != WarningsMentions { for _, s := range out.Stray { - res.Leftovers = append(res.Leftovers, ExportLeftover{SourceLine: s.SourceLine, Text: s.Text, Rule: ExportRuleStrayMarker}) + cp.Leftovers = append(cp.Leftovers, ExportLeftover{SourceLine: s.SourceLine, Text: s.Text, Rule: ExportRuleStrayMarker}) } for _, l := range report.Leftovers { - res.Leftovers = append(res.Leftovers, ExportLeftover{Line: l.Line, Text: l.Text, Rule: l.Rule}) + cp.Leftovers = append(cp.Leftovers, ExportLeftover{Line: l.Line, Text: l.Text, Rule: l.Rule}) } } if warnings != WarningsLeftovers { - res.Mentions = &ExportMentions{Count: report.Mentions.Count, Lines: append([]int{}, report.Mentions.Lines...)} + cp.Mentions = &ExportMentions{Count: report.Mentions.Count, Lines: append([]int{}, report.Mentions.Lines...)} } - res.Target, res.TargetKind = dest, OpenTargetKindFile - return finishOpen(ctx, deps, o, res) + return cp, nil } // exportTitles maps every change id exactly one record claims to its title; an diff --git a/internal/app/open_export_test.go b/internal/app/export_test.go similarity index 66% rename from internal/app/open_export_test.go rename to internal/app/export_test.go index 59f3804f9..b61a6ebc6 100644 --- a/internal/app/open_export_test.go +++ b/internal/app/export_test.go @@ -52,13 +52,13 @@ func (f *openFixture) exportDeps(home, goos, cwd string) OpenDeps { return d } -func (f *openFixture) export(t *testing.T, deps OpenDeps, what string, id int, mut func(*OpenOptions)) OpenResult { +func (f *openFixture) export(t *testing.T, deps OpenDeps, what string, id int, mut func(*ExportOptions)) ExportResult { t.Helper() - o := OpenOptions{RepoDir: f.repoDir, What: what, ID: id, Export: true} + o := ExportOptions{RepoDir: f.repoDir, What: what, ID: id} if mut != nil { mut(&o) } - return Open(context.Background(), deps, o) + return Export(context.Background(), deps, o) } func readExport(t *testing.T, path string) string { @@ -70,17 +70,17 @@ func readExport(t *testing.T, path string) string { return string(b) } -func TestOpenExportWritesCleanCopy(t *testing.T) { +func TestExportWritesCleanCopy(t *testing.T) { f := newOpenFixture(t, "", false, openWeb, exportCorpus()...) f.writeBody(t, widgetSpec, exportSpecBody) out := testsupport.TempDir(t) - res := f.export(t, f.exportDeps(testsupport.TempDir(t), "linux", "/nowhere"), "spec", 7, func(o *OpenOptions) { + res := f.export(t, f.exportDeps(testsupport.TempDir(t), "linux", "/nowhere"), "spec", 7, func(o *ExportOptions) { o.Print, o.OutputPath = true, out }) want := filepath.Join(out, "2026-01-02-spec-widget.md") - if res.Result != ResultApplied || res.Launched || res.ExportedPath != want || res.Target != want || - res.TargetKind != OpenTargetKindFile || len(f.opener.targets) != 0 { - t.Fatalf("Open = (%s, launched %v, exported %q, target %q, %s, %q)", res.Result, res.Launched, res.ExportedPath, res.Target, res.TargetKind, res.Message) + if res.Result != ResultApplied || res.Launched || res.ExportedPath != want || res.HumanText() != want || + res.Operation != OperationExport || len(f.opener.targets) != 0 { + t.Fatalf("Export = (%s, %s, launched %v, exported %q, human %q, %q)", res.Operation, res.Result, res.Launched, res.ExportedPath, res.HumanText(), res.Message) } if got := readExport(t, want); got != exportSpecClean { t.Errorf("exported bytes = %q, want %q", got, exportSpecClean) @@ -98,51 +98,175 @@ func TestOpenExportWritesCleanCopy(t *testing.T) { } } -func TestOpenExportOpensTheCopy(t *testing.T) { - f := newOpenFixture(t, "", false, openWeb, exportCorpus()...) - f.writeBody(t, widgetSpec, exportSpecBody) - out := testsupport.TempDir(t) - res := f.export(t, f.exportDeps(testsupport.TempDir(t), "linux", "/nowhere"), "spec", 7, func(o *OpenOptions) { o.OutputPath = out }) - want := filepath.Join(out, "2026-01-02-spec-widget.md") - if res.Result != ResultApplied || !res.Launched || !reflect.DeepEqual(f.opener.targets, []string{want}) { - t.Errorf("(%s, launched %v, opener %v), want the exported copy opened", res.Result, res.Launched, f.opener.targets) +// TestExportLaunchesOnlyAtTheDefaultDestination: only an export with neither +// --output-path nor --print hands the copy to the opener. +func TestExportLaunchesOnlyAtTheDefaultDestination(t *testing.T) { + for _, tc := range []struct{ output, print bool }{{false, false}, {true, false}, {true, true}, {false, true}} { + f := newOpenFixture(t, "", false, openWeb, exportCorpus()...) + f.writeBody(t, widgetSpec, exportSpecBody) + home := testsupport.TempDir(t) + out := testsupport.TempDir(t) + res := f.export(t, f.exportDeps(home, "linux", "/nowhere"), "spec", 7, func(o *ExportOptions) { + o.Print = tc.print + if tc.output { + o.OutputPath = out + } + }) + if res.Result != ResultApplied { + t.Errorf("%+v: (%s, %s, %q)", tc, res.Result, res.Reason, res.Message) + continue + } + if !tc.output && !tc.print { + want := []string{filepath.Join(home, "2026-01-02-spec-widget.md")} + if !res.Launched || !reflect.DeepEqual(f.opener.targets, want) { + t.Errorf("%+v: launched %v opener %v, want %v opened", tc, res.Launched, f.opener.targets, want) + } + continue + } + if res.Launched || len(f.opener.targets) != 0 || res.HumanText() != res.ExportedPath { + t.Errorf("%+v: launched %v opener %v human %q, want nothing opened and the path printed", tc, res.Launched, f.opener.targets, res.HumanText()) + } + } +} + +// TestExportOpenerFailureKeepsThePath: an opener failure after the copy was +// written keeps the copy and its path, and reports the failure after the path. +func TestExportOpenerFailureKeepsThePath(t *testing.T) { + for _, tc := range []struct { + err error + reason string + }{{&NoOpenerError{GOOS: "plan9"}, ReasonOpenNoOpener}, {errors.New("exit status 4"), ReasonOpenOpenerFailed}} { + f := newOpenFixture(t, "", false, openWeb, exportCorpus()...) + f.writeBody(t, widgetSpec, exportSpecBody) + f.opener.err = tc.err + res := f.export(t, f.exportDeps(testsupport.TempDir(t), "linux", "/nowhere"), "spec", 7, nil) + if res.Result != ResultExternalFailed || res.Reason != tc.reason || res.ExportedPath == "" || res.Launched || + !strings.HasPrefix(res.HumanText(), res.ExportedPath+"\n") { + t.Errorf("%s: (%s, %s, %q, launched %v, human %q)", tc.reason, res.Result, res.Reason, res.ExportedPath, res.Launched, res.HumanText()) + continue + } + if _, err := os.Stat(res.ExportedPath); err != nil { + t.Errorf("%s: the copy is gone: %v", tc.reason, err) + } + } +} + +// TestExportRefusesInvalidRequest: a type outside the four, or a bad +// --warnings value, refuses before any read and opens nothing. +func TestExportRefusesInvalidRequest(t *testing.T) { + for _, o := range []ExportOptions{{What: "board"}, {What: "pr", ID: 7}, {What: "bogus"}, {What: "spec", ID: 7, Warnings: "bogus"}} { + f := newOpenFixture(t, "", false, openWeb, exportCorpus()...) + o.RepoDir = f.repoDir + res := Export(context.Background(), f.deps(), o) + if res.Result != ResultInvalidInput || res.Reason != ReasonOpenInvalidTarget || res.Operation != OperationExport || + res.Message == "" || strings.Contains(res.Message, "\n") || f.reader.pinCount != 0 || len(f.opener.targets) != 0 { + t.Errorf("%+v: (%s, %s, %s, %q) pins %d opener %v", o, res.Operation, res.Result, res.Reason, res.Message, f.reader.pinCount, f.opener.targets) + } + } +} + +func TestExportResultJSON(t *testing.T) { + raw, _ := json.Marshal(ExportResult{What: "spec", Notes: []string{}, ExportedPath: "/d/x.md", Replaced: true, + Leftovers: []ExportLeftover{{SourceLine: 5, Text: "m", Rule: ExportRuleStrayMarker}, {Line: 2, Text: "t", Rule: "link"}}, + Mentions: &ExportMentions{Count: 1, Lines: []int{4}}}) + var doc map[string]any + if err := json.Unmarshal(raw, &doc); err != nil { + t.Fatal(err) + } + want := map[string]any{ + "exported_path": "/d/x.md", "replaced": true, + "leftovers": []any{ + map[string]any{"source_line": float64(5), "text": "m", "rule": "stray-marker"}, + map[string]any{"line": float64(2), "text": "t", "rule": "link"}, + }, + "mentions": map[string]any{"count": float64(1), "lines": []any{float64(4)}}, + "launched": false, + "notes": []any{}, + } + for k, w := range want { + if !reflect.DeepEqual(doc[k], w) { + t.Errorf("%s = %#v, want %#v (doc %s)", k, doc[k], w, raw) + } + } + for _, k := range []string{"target", "target_kind"} { + if _, ok := doc[k]; ok { + t.Errorf("export document carries %s: %s", k, raw) + } } } -// TestOpenExportIgnoresGitHubRouting: a shared repository with a GitHub origin +func TestParseExportArgs(t *testing.T) { + ok := []struct { + args []string + what string + id int + }{ + {[]string{"spec"}, "spec", 0}, {[]string{"change", "541"}, "change", 541}, + {[]string{"plan", "0541"}, "plan", 541}, {[]string{"results", "000012"}, "results", 12}, + } + for _, tc := range ok { + what, id, err := ParseExportArgs(tc.args) + if err != nil || what != tc.what || id != tc.id { + t.Errorf("ParseExportArgs(%q) = (%q, %d, %v), want (%q, %d)", tc.args, what, id, err, tc.what, tc.id) + } + } + bad := [][]string{nil, {"board"}, {"pr", "7"}, {"bogus"}, {"spec", "1", "2"}, {"spec", "#541"}, {"spec", "0"}, {"spec", "-5"}} + for _, args := range bad { + _, _, err := ParseExportArgs(args) + if err == nil || strings.Contains(err.Error(), "\n") { + t.Errorf("ParseExportArgs(%q) = %v, want a one-line error", args, err) + continue + } + if i := strings.Index(err.Error(), "one of "); i >= 0 { + if got := err.Error()[i+len("one of "):]; got != "change, spec, plan, results" { + t.Errorf("ParseExportArgs(%q) offers %q", args, got) + } + } + } + if _, _, err := ParseExportArgs([]string{"spec", "#541"}); err == nil || err.Error() != "invalid change id #541" { + t.Errorf("ParseExportArgs(spec #541) = %v", err) + } + for _, args := range [][]string{nil, {"board"}, {"pr", "7"}, {"bogus"}, {"spec", "1", "2"}} { + if _, _, err := ParseExportArgs(args); err == nil || !strings.Contains(err.Error(), "one of ") { + t.Errorf("ParseExportArgs(%q) = %v, want the four types listed", args, err) + } + } +} + +// TestExportIgnoresGitHubRouting: a shared repository with a GitHub origin // and the default open.artifacts still exports the local metadata-checkout file. -func TestOpenExportIgnoresGitHubRouting(t *testing.T) { +func TestExportIgnoresGitHubRouting(t *testing.T) { f := newOpenFixture(t, "", false, openWeb, exportCorpus()...) f.writeBody(t, widgetSpec, exportSpecBody) out := testsupport.TempDir(t) - res := f.export(t, f.exportDeps(testsupport.TempDir(t), "linux", "/nowhere"), "spec", 7, func(o *OpenOptions) { o.OutputPath, o.Print = out, true }) - if res.Result != ResultApplied || res.TargetKind != OpenTargetKindFile || !strings.HasPrefix(res.Target, out) || len(f.prepared) != 1 { - t.Errorf("(%s, %s, %q) prepared %v", res.Result, res.TargetKind, res.Target, f.prepared) + res := f.export(t, f.exportDeps(testsupport.TempDir(t), "linux", "/nowhere"), "spec", 7, func(o *ExportOptions) { o.OutputPath, o.Print = out, true }) + if res.Result != ResultApplied || !strings.HasPrefix(res.ExportedPath, out) || len(f.prepared) != 1 { + t.Errorf("(%s, %q) prepared %v", res.Result, res.ExportedPath, f.prepared) } if !reflect.DeepEqual(res.Notes, []string{}) { t.Errorf("notes %q, want none (no not-GitHub note on the export path)", res.Notes) } } -func TestOpenExportKeepsStalenessNote(t *testing.T) { +func TestExportKeepsStalenessNote(t *testing.T) { f := newOpenFixture(t, "", false, openWeb, exportCorpus()...) f.refusePrepare("metadata-worktree-dirty") f.writeBody(t, widgetSpec, exportSpecBody) out := testsupport.TempDir(t) - res := f.export(t, f.exportDeps(testsupport.TempDir(t), "linux", "/nowhere"), "spec", 7, func(o *OpenOptions) { o.OutputPath, o.Print = out, true }) + res := f.export(t, f.exportDeps(testsupport.TempDir(t), "linux", "/nowhere"), "spec", 7, func(o *ExportOptions) { o.OutputPath, o.Print = out, true }) if res.Result != ResultApplied || !reflect.DeepEqual(res.Notes, []string{openNoteStale("metadata-worktree-dirty")}) { t.Errorf("(%s, %q)", res.Result, res.Notes) } } -func TestOpenExportDefaultDestination(t *testing.T) { +func TestExportDefaultDestination(t *testing.T) { name := "2026-01-02-spec-widget.md" newF := func() *openFixture { f := newOpenFixture(t, "", false, openWeb, exportCorpus()...) f.writeBody(t, widgetSpec, exportSpecBody) return f } - print := func(o *OpenOptions) { o.Print = true } + print := func(o *ExportOptions) { o.Print = true } home := testsupport.TempDir(t) if err := os.Mkdir(filepath.Join(home, "Downloads"), 0o755); err != nil { @@ -180,7 +304,7 @@ func TestOpenExportDefaultDestination(t *testing.T) { } } -func TestOpenExportOutputPath(t *testing.T) { +func TestExportOutputPath(t *testing.T) { newF := func() *openFixture { f := newOpenFixture(t, "", false, openWeb, exportCorpus()...) f.writeBody(t, widgetSpec, exportSpecBody) @@ -188,7 +312,7 @@ func TestOpenExportOutputPath(t *testing.T) { } home := testsupport.TempDir(t) dir := testsupport.TempDir(t) - at := func(p string) func(*OpenOptions) { return func(o *OpenOptions) { o.OutputPath, o.Print = p, true } } + at := func(p string) func(*ExportOptions) { return func(o *ExportOptions) { o.OutputPath, o.Print = p, true } } f := newF() if res := f.export(t, f.exportDeps(home, "linux", "/nowhere"), "spec", 7, at(dir)); res.ExportedPath != filepath.Join(dir, "2026-01-02-spec-widget.md") { @@ -227,11 +351,11 @@ func TestOpenExportOutputPath(t *testing.T) { } } -// TestOpenExportRefusesProtectedDestination: --output-path never overwrites the +// TestExportRefusesProtectedDestination: --output-path never overwrites the // source artifact and never writes into the metadata checkout, however the path // is spelled — exactly, relatively, as a directory, or through a symlinked // parent. The refusal writes nothing and opens nothing. -func TestOpenExportRefusesProtectedDestination(t *testing.T) { +func TestExportRefusesProtectedDestination(t *testing.T) { home := testsupport.TempDir(t) cases := []struct { name string @@ -260,7 +384,7 @@ func TestOpenExportRefusesProtectedDestination(t *testing.T) { if tc.cwd != nil { cwd = tc.cwd(src) } - res := f.export(t, f.exportDeps(home, "linux", cwd), "spec", 7, func(o *OpenOptions) { o.OutputPath = tc.path(src) }) + res := f.export(t, f.exportDeps(home, "linux", cwd), "spec", 7, func(o *ExportOptions) { o.OutputPath = tc.path(src) }) if res.Result != ResultInvalidState || res.Reason != ReasonOpenOutputPathProtected || res.ExportedPath != "" || strings.Contains(res.Message, "\n") || len(f.opener.targets) != 0 { t.Errorf("%s: (%s, %s, %q, exported %q, opened %v)", tc.name, res.Result, res.Reason, res.Message, res.ExportedPath, f.opener.targets) @@ -275,12 +399,12 @@ func TestOpenExportRefusesProtectedDestination(t *testing.T) { } } -func TestOpenExportTicketNameAndH1(t *testing.T) { +func TestExportTicketNameAndH1(t *testing.T) { f := newOpenFixture(t, "", false, openWeb, exportCorpus()...) f.writeBody(t, "docs/changes/active/0007-widget.md", "---\nid: 7\ntitle: Widget export\n---\n\n# Widget export\n\n## Why\n\nBecause change 0003 broke.\n\n## Reconcile log\n\nnoise\n") out := testsupport.TempDir(t) - res := f.export(t, f.exportDeps(testsupport.TempDir(t), "linux", "/nowhere"), "change", 7, func(o *OpenOptions) { o.OutputPath, o.Print = out, true }) + res := f.export(t, f.exportDeps(testsupport.TempDir(t), "linux", "/nowhere"), "change", 7, func(o *ExportOptions) { o.OutputPath, o.Print = out, true }) want := filepath.Join(out, "2026-01-02-ticket-widget.md") if res.Result != ResultApplied || res.ExportedPath != want { t.Fatalf("(%s, %q, %q)", res.Result, res.ExportedPath, res.Message) @@ -290,7 +414,7 @@ func TestOpenExportTicketNameAndH1(t *testing.T) { } } -func TestOpenExportWarningsFilter(t *testing.T) { +func TestExportWarningsFilter(t *testing.T) { body := "# Widget design\n\n\nTalk about docket here.\n" for _, tc := range []struct { warnings string @@ -299,7 +423,7 @@ func TestOpenExportWarningsFilter(t *testing.T) { f := newOpenFixture(t, "", false, openWeb, exportCorpus()...) f.writeBody(t, widgetSpec, body) out := testsupport.TempDir(t) - res := f.export(t, f.exportDeps(testsupport.TempDir(t), "linux", "/nowhere"), "spec", 7, func(o *OpenOptions) { + res := f.export(t, f.exportDeps(testsupport.TempDir(t), "linux", "/nowhere"), "spec", 7, func(o *ExportOptions) { o.OutputPath, o.Print, o.Warnings = out, true, tc.warnings }) if res.Result != ResultApplied || res.ExportedPath == "" { @@ -333,8 +457,8 @@ func TestOpenExportWarningsFilter(t *testing.T) { } } -func TestOpenResultHumanWarningsWording(t *testing.T) { - r := OpenResult{ +func TestExportResultHumanWarningsWording(t *testing.T) { + r := ExportResult{ Leftovers: []ExportLeftover{{Line: 12, Text: "[x](y)", Rule: "link"}}, Mentions: &ExportMentions{Count: 3, Lines: []int{2, 5, 9}}, } @@ -345,19 +469,19 @@ func TestOpenResultHumanWarningsWording(t *testing.T) { if got := r.HumanWarnings(); !reflect.DeepEqual(got, want) { t.Errorf("HumanWarnings = %q, want %q", got, want) } - if got := (OpenResult{Mentions: &ExportMentions{Lines: []int{}}}).HumanWarnings(); len(got) != 0 { + if got := (ExportResult{Mentions: &ExportMentions{Lines: []int{}}}).HumanWarnings(); len(got) != 0 { t.Errorf("zero mentions render %q, want nothing", got) } } -// TestOpenExportAmbiguousIDLeftAsWritten (Review Focus 4): an id two records +// TestExportAmbiguousIDLeftAsWritten (Review Focus 4): an id two records // claim is unknown to the export, never given either record's title. -func TestOpenExportAmbiguousIDLeftAsWritten(t *testing.T) { +func TestExportAmbiguousIDLeftAsWritten(t *testing.T) { blobs := append(exportCorpus(), retitle(openChange(3, "old-copy", false, "branch: feat/old-copy\n"), "Copy gadget")) f := newOpenFixture(t, "", false, openWeb, blobs...) f.writeBody(t, widgetSpec, exportSpecBody) out := testsupport.TempDir(t) - res := f.export(t, f.exportDeps(testsupport.TempDir(t), "linux", "/nowhere"), "spec", 7, func(o *OpenOptions) { o.OutputPath, o.Print = out, true }) + res := f.export(t, f.exportDeps(testsupport.TempDir(t), "linux", "/nowhere"), "spec", 7, func(o *ExportOptions) { o.OutputPath, o.Print = out, true }) if res.Result != ResultApplied { t.Fatalf("(%s, %q)", res.Result, res.Message) } @@ -365,65 +489,3 @@ func TestOpenExportAmbiguousIDLeftAsWritten(t *testing.T) { t.Errorf("ambiguous id converted: %q", got) } } - -func TestValidateOpenExport(t *testing.T) { - bad := []OpenOptions{ - {What: "board", Export: true}, {What: "pr", ID: 7, Export: true}, - {What: "spec", OutputPath: "x.md"}, {What: "spec", Warnings: WarningsAll}, - {What: "spec", Export: true, Warnings: "bogus"}, - } - for _, o := range bad { - if err := ValidateOpenExport(o); err == nil || strings.Contains(err.Error(), "\n") { - t.Errorf("ValidateOpenExport(%+v) = %v, want a one-line error", o, err) - } - } - good := []OpenOptions{ - {What: "spec"}, {What: "board"}, {What: "pr", ID: 7}, - {What: "spec", Export: true}, {What: "change", Export: true, OutputPath: "x", Warnings: WarningsLeftovers}, - {What: "plan", Export: true, Warnings: WarningsMentions}, {What: "results", Export: true, Warnings: WarningsAll}, - } - for _, o := range good { - if err := ValidateOpenExport(o); err != nil { - t.Errorf("ValidateOpenExport(%+v) = %v, want nil", o, err) - } - } - // Open refuses the same way, writing nothing and opening nothing. - f := newOpenFixture(t, "", false, openWeb, exportCorpus()...) - res := Open(context.Background(), f.deps(), OpenOptions{RepoDir: f.repoDir, What: "pr", ID: 7, Export: true}) - if res.Result != ResultInvalidInput || res.Reason != ReasonOpenInvalidOption || len(f.opener.targets) != 0 || f.reader.pinCount != 0 { - t.Errorf("Open pr --export: (%s, %s, %q) opener %v", res.Result, res.Reason, res.Message, f.opener.targets) - } - res = Open(context.Background(), f.deps(), OpenOptions{RepoDir: f.repoDir, What: "spec", ID: 7, OutputPath: "x.md"}) - if res.Result != ResultInvalidInput || res.Reason != ReasonOpenInvalidOption { - t.Errorf("Open spec --output-path without --export: (%s, %s, %q)", res.Result, res.Reason, res.Message) - } -} - -func TestOpenResultExportJSON(t *testing.T) { - raw, _ := json.Marshal(OpenResult{What: "spec", Notes: []string{}, ExportedPath: "/d/x.md", Replaced: true, - Leftovers: []ExportLeftover{{SourceLine: 5, Text: "m", Rule: ExportRuleStrayMarker}, {Line: 2, Text: "t", Rule: "link"}}, - Mentions: &ExportMentions{Count: 1, Lines: []int{4}}}) - var doc map[string]any - if err := json.Unmarshal(raw, &doc); err != nil { - t.Fatal(err) - } - want := map[string]any{ - "exported_path": "/d/x.md", "replaced": true, - "leftovers": []any{ - map[string]any{"source_line": float64(5), "text": "m", "rule": "stray-marker"}, - map[string]any{"line": float64(2), "text": "t", "rule": "link"}, - }, - "mentions": map[string]any{"count": float64(1), "lines": []any{float64(4)}}, - } - for k, w := range want { - if !reflect.DeepEqual(doc[k], w) { - t.Errorf("%s = %#v, want %#v (doc %s)", k, doc[k], w, raw) - } - } - plain, _ := json.Marshal(OpenResult{What: "spec", Notes: []string{}}) - for k := range want { - if strings.Contains(string(plain), `"`+k+`"`) { - t.Errorf("non-export document carries %s: %s", k, plain) - } - } -} diff --git a/internal/app/open.go b/internal/app/open.go index 806bdd513..2d62b7970 100644 --- a/internal/app/open.go +++ b/internal/app/open.go @@ -55,7 +55,6 @@ const ( ReasonOpenFileMissing = "file-missing" ReasonOpenNoOpener = "no-opener" ReasonOpenOpenerFailed = "opener-failed" - ReasonOpenInvalidOption = "invalid-option" // an export flag used where it does not apply ReasonOpenOutputPathInvalid = "output-path-invalid" // the export destination cannot be written ReasonOpenExportFailed = "export-failed" // reading the source or writing the copy failed // ReasonOpenOutputPathProtected refuses an export destination that is the @@ -79,11 +78,6 @@ type OpenOptions struct { What string ID int // 0 = infer from the checked-out branch Print bool - - // Export writes a clean Markdown copy of the artifact and opens the copy. - Export bool - OutputPath string // "" = the default destination - Warnings string // "" = WarningsAll } // OpenDeps is what Open reads and runs, injected so tests start no real git @@ -94,7 +88,7 @@ type OpenDeps struct { Prepare func(ctx context.Context, repoDir string) RepositoryPrepareResult Opener Opener - // The export destination's seams; production sets all three. + // The export's destination seams (Export); production sets all three. HomeDir func() (string, error) Getwd func() (string, error) GOOS string @@ -112,12 +106,6 @@ type OpenResult struct { Notes []string `json:"notes"` Reason string `json:"reason,omitempty"` Message string `json:"message,omitempty"` - - // Export fields, set only by --export; Leftovers and Mentions follow --warnings. - ExportedPath string `json:"exported_path,omitempty"` - Replaced bool `json:"replaced,omitempty"` - Leftovers []ExportLeftover `json:"leftovers,omitempty"` - Mentions *ExportMentions `json:"mentions,omitempty"` } // HumanText renders the result for a terminal: the target alone on success @@ -168,21 +156,28 @@ func ParseOpenArgs(args []string) (string, int, error) { if what == "board" { return "", 0, fmt.Errorf("board takes no change id — the targets are %s, and only the last five take an id", targets) } - raw := args[1] + n, err := parseChangeIDArg(args[1]) + if err != nil { + return "", 0, err + } + return what, n, nil +} + +// parseChangeIDArg parses a positional change id: plain decimal digits, leading +// zeros allowed, greater than zero. +func parseChangeIDArg(raw string) (int, error) { n, err := strconv.Atoi(raw) if !openIDPattern.MatchString(raw) || err != nil || n <= 0 { - return "", 0, fmt.Errorf("invalid change id %s", raw) + return 0, fmt.Errorf("invalid change id %s", raw) } - return what, n, nil + return n, nil } // Open resolves what (and the change id, or the change the checked-out branch // records when the id is 0) to a target and opens it. A private repository, // open.artifacts: local, or a non-GitHub origin opens the file from the // metadata checkout after preparing it; otherwise the GitHub blob page opens. -// A change's PR always opens its URL. With Export set the local file is always -// read and its clean copy (openExport) is what opens. With Print set nothing is -// launched. +// A change's PR always opens its URL. With Print set nothing is launched. func Open(ctx context.Context, deps OpenDeps, o OpenOptions) OpenResult { res := OpenResult{What: o.What, ChangeID: o.ID, Notes: []string{}} fail := func(f openFailure) OpenResult { @@ -198,45 +193,19 @@ func Open(ctx context.Context, deps OpenDeps, o OpenOptions) OpenResult { _, _, err := ParseOpenArgs(args) return fail(openFailure{ResultInvalidInput, ReasonOpenInvalidTarget, err.Error()}) } - if err := ValidateOpenExport(o); err != nil { - return fail(openFailure{ResultInvalidInput, ReasonOpenInvalidOption, err.Error()}) - } - if o.RepoDir == "" { - return fail(openFailure{ResultInvalidInput, ReasonOpenInvalidTarget, "a repository directory is required"}) - } - // The checkout probe refuses a relative path, so every seam gets an - // absolute one. - dir, err := filepath.Abs(o.RepoDir) - if err != nil { - return fail(openFailure{ResultInvalidInput, ReasonOpenInvalidTarget, fmt.Sprintf("cannot resolve %s: %v", o.RepoDir, err)}) - } - branch := "" - if o.What != "board" && o.ID == 0 { // before any fetch - b, f := checkoutBranch(ctx, deps.Checkout, dir) - if f != nil { - return fail(*f) - } - branch = b - } - pin, err := deps.Reader.PinContext(ctx, dir) - if err != nil { - result, reason := classifyStatusError(ctx, err) - return fail(openFailure{result, reason, err.Error()}) + dir, branch, pin, pf := openPrelude(ctx, deps, o.RepoDir, o.What, o.ID) + if pf != nil { + return fail(*pf) } eff := pin.Config.Effective - var ( - rel string - c domain.Change - snap domain.Snapshot - ) + var rel string if o.What == "board" { if !slices.Contains(eff.BoardSurfaces.Value, boardSurfaceInline) { return fail(openFailure{ResultInvalidState, ReasonOpenBoardDisabled, "this repository has no board (board_surfaces has no inline surface)"}) } rel = boardCorpusPath(eff) } else { - var f *openFailure - c, snap, f = resolveOpenChange(ctx, deps.Reader, pin, o.ID, branch) + c, _, f := resolveOpenChange(ctx, deps.Reader, pin, o.ID, branch) if f != nil { return fail(*f) } @@ -253,13 +222,8 @@ func Open(ctx context.Context, deps OpenDeps, o OpenOptions) OpenResult { return fail(*f) } } - // A recorded path that escapes the repository is never opened, stat'ed, - // or linked. - if !filepath.IsLocal(filepath.FromSlash(rel)) { - return fail(openFailure{ResultInvalidState, ReasonOpenPathInvalid, fmt.Sprintf("%s path %q is not a path inside the repository", o.What, rel)}) - } - if o.Export { - return openExport(ctx, deps, o, dir, pin, c, snap, rel, res) + if f := checkArtifactPath(o.What, rel); f != nil { + return fail(*f) } if pin.Layout.Mode != layout.Private && eff.Open.Artifacts.Value != "local" { if u := linkContextOf(pin).BlobURL(rel); u != "" { @@ -277,6 +241,43 @@ func Open(ctx context.Context, deps OpenDeps, o OpenOptions) OpenResult { return finishOpen(ctx, deps, o, res) } +// openPrelude is the common start of Open and Export: it requires a repository +// directory and makes it absolute (the checkout probe refuses a relative +// path), reads the checked-out branch when a change is to be inferred from it +// (what is not the board and id is 0) before any fetch, then pins the status +// context. +func openPrelude(ctx context.Context, deps OpenDeps, repoDir, what string, id int) (dir string, branch string, pin StatusPin, f *openFailure) { + if repoDir == "" { + return "", "", StatusPin{}, &openFailure{ResultInvalidInput, ReasonOpenInvalidTarget, "a repository directory is required"} + } + dir, err := filepath.Abs(repoDir) + if err != nil { + return "", "", StatusPin{}, &openFailure{ResultInvalidInput, ReasonOpenInvalidTarget, fmt.Sprintf("cannot resolve %s: %v", repoDir, err)} + } + if what != "board" && id == 0 { + b, f := checkoutBranch(ctx, deps.Checkout, dir) + if f != nil { + return "", "", StatusPin{}, f + } + branch = b + } + pin, err = deps.Reader.PinContext(ctx, dir) + if err != nil { + result, reason := classifyStatusError(ctx, err) + return "", "", StatusPin{}, &openFailure{result, reason, err.Error()} + } + return dir, branch, pin, nil +} + +// checkArtifactPath refuses a recorded path that escapes the repository: it is +// never opened, stat'ed, read, or linked. +func checkArtifactPath(what, rel string) *openFailure { + if !filepath.IsLocal(filepath.FromSlash(rel)) { + return &openFailure{ResultInvalidState, ReasonOpenPathInvalid, fmt.Sprintf("%s path %q is not a path inside the repository", what, rel)} + } + return nil +} + // localArtifact prepares the metadata checkout and returns rel's path inside // it, and the checkout's root. A prepare that does not succeed never blocks // the open: it adds a staleness note, and the layout's metadata worktree @@ -392,24 +393,31 @@ func finishOpen(ctx context.Context, deps OpenDeps, o OpenOptions, res OpenResul res.Envelope = NewEnvelope(OperationOpen, ResultApplied) return res } - opener := deps.Opener + if f := runOpener(ctx, deps.Opener, res.Target); f != nil { + res.Envelope = NewEnvelope(OperationOpen, f.result) + res.Reason, res.Message = f.reason, f.message + return res + } + res.Envelope = NewEnvelope(OperationOpen, ResultApplied) + res.Launched = true + return res +} + +// runOpener hands target to opener and classifies a failure: no opener on +// this platform (a nil opener included) or the opener's own error. +func runOpener(ctx context.Context, opener Opener, target string) *openFailure { var err error if opener == nil { err = &NoOpenerError{GOOS: runtime.GOOS} } else { - err = opener.Open(ctx, res.Target) + err = opener.Open(ctx, target) } var none *NoOpenerError switch { case errors.As(err, &none): - res.Envelope = NewEnvelope(OperationOpen, ResultExternalFailed) - res.Reason, res.Message = ReasonOpenNoOpener, none.Error() + return &openFailure{ResultExternalFailed, ReasonOpenNoOpener, none.Error()} case err != nil: - res.Envelope = NewEnvelope(OperationOpen, ResultExternalFailed) - res.Reason, res.Message = ReasonOpenOpenerFailed, fmt.Sprintf("could not open %s: %v", res.Target, err) - default: - res.Envelope = NewEnvelope(OperationOpen, ResultApplied) - res.Launched = true + return &openFailure{ResultExternalFailed, ReasonOpenOpenerFailed, fmt.Sprintf("could not open %s: %v", target, err)} } - return res + return nil } diff --git a/internal/app/schema_registry.go b/internal/app/schema_registry.go index 0e55bfae9..50aedef8b 100644 --- a/internal/app/schema_registry.go +++ b/internal/app/schema_registry.go @@ -74,6 +74,7 @@ var operationBindings = []OperationBinding{ {ID: "evidence.recertify", Request: nil, Result: EvidenceRecertifyResult{}}, // EvidenceRecertify {ID: "evidence.record", Request: nil, Result: EvidenceOpResult{}}, // EvidenceRecord {ID: "evidence.verify", Request: nil, Result: EvidenceOpResult{}}, // EvidenceVerify + {ID: "export", Request: nil, Result: ExportResult{}}, // Export {ID: "finalize.block", Request: FinalizeBlockInput{}, Result: BlockResult{}}, // FinalizeBlock {ID: "finalize.cleanup", Request: nil, Result: CleanupOpResult{}}, // FinalizeCleanup {ID: "finalize.clear-block", Request: nil, Result: BlockResult{}}, // FinalizeClearBlock diff --git a/internal/assets/embedded/manifest.json b/internal/assets/embedded/manifest.json index 50cf0f444..f05cbfeae 100644 --- a/internal/assets/embedded/manifest.json +++ b/internal/assets/embedded/manifest.json @@ -1,7 +1,7 @@ { "format_version": 1, "asset_protocol": 1, - "asset_set_id": "sha256:029addf44b376758f00206f5400b6f9af46d25918e9c63f7cec9efa6a565f613", + "asset_set_id": "sha256:3953fb0eec7f0d1ccdbaddf904a81445076c3224ebf80406a5ab2da15b037039", "entries": [ { "path": ".docket.example.yml", @@ -357,8 +357,8 @@ "path": "skills/docket-export/SKILL.md", "role": "skill", "mode": 420, - "size": 6930, - "sha256": "c1cb6f771d041157c5d0c0c04fa5fc209288d00d07b1d897c84802221f5390dc" + "size": 6918, + "sha256": "1ce68aa2748818f53fdabcfdc8491224c6e92f96a255517c9cf583a11ad52821" }, { "path": "skills/docket-finalize-change/SKILL.md", diff --git a/internal/assets/embedded/tree/skills/docket-export/SKILL.md b/internal/assets/embedded/tree/skills/docket-export/SKILL.md index 27c5f06c5..01819846e 100644 --- a/internal/assets/embedded/tree/skills/docket-export/SKILL.md +++ b/internal/assets/embedded/tree/skills/docket-export/SKILL.md @@ -13,7 +13,7 @@ Creating a ticket from a change, or linking or importing one, is `docket-link-ti ## 1. Resolve the operations -Run `docket capabilities --json` as its own call — the one docket spelling this skill hard-codes. Check that `protocol_version` is 1 and take the `argv` of the entries `open`, `repository.prepare`, and `diagnostic.config`. If the binary is missing or an entry is absent, tell the person their docket installation is broken and stop — never a hand-made export. +Run `docket capabilities --json` as its own call — the one docket spelling this skill hard-codes. Check that `protocol_version` is 1 and take the `argv` of the entries `export`, `repository.prepare`, and `diagnostic.config`. If the binary is missing or an entry is absent, tell the person their docket installation is broken and stop — never a hand-made export. ## 2. Learn the visibility @@ -26,7 +26,7 @@ In a private repository, also run the `diagnostic.config` argv with `--repo-dir ## 3. Run the export -Run the `open` argv as ` [] --export --print --json --repo-dir `, where `` is `change`, `spec`, `plan`, or `results` and `` is the change the person named (omit it to use the change whose branch is checked out). Always `--export --print --json`: `--print` opens no viewer — the person may not be at the screen, and can ask you to open the file. Never pass `--warnings` unless the person asked for a filter on a file request; the default reports everything the private pass reads. +Run the `export` argv as ` [] --print --json --repo-dir `, where `` is `change`, `spec`, `plan`, or `results` and `` is the change the person named (omit it to use the change whose branch is checked out). Always `--print --json`: `--print` opens no viewer — the person may not be at the screen, and can ask you to open the file. Never pass `--warnings` unless the person asked for a filter on a file request; the default reports everything the private pass reads. - **File request** ("export the spec for 9"): the export's default destination, or `--output-path ` when the person names one. - **Outside-tool request** ("put the spec for 9 in a message to the design channel"): `--output-path` set to a fresh directory from `mktemp -d "${TMPDIR:-/tmp}/docket-export.XXXXXX"`, so the person's downloads folder does not collect one file per post. Leave the file there and report its path. diff --git a/internal/cli/capability_production_test.go b/internal/cli/capability_production_test.go index 5f7e5e530..d8a7489c3 100644 --- a/internal/cli/capability_production_test.go +++ b/internal/cli/capability_production_test.go @@ -349,7 +349,8 @@ func TestRepresentativeSignatures(t *testing.T) { "workspace.prepare": "--id --revision [--repo-dir ]", "workspace.checkout": "--id [--head ] [--repo-dir ] [--revision ]", // positional target and optional id lead, the optional flags trail sorted. - "open": " [] [--export] [--output-path ] [--print] [--repo-dir ] [--warnings =all]", + "open": " [] [--print] [--repo-dir ]", + "export": " [] [--output-path ] [--print] [--repo-dir ] [--warnings =all]", } for id, wantSig := range want { e, ok := entryByID(entries, id) @@ -375,6 +376,11 @@ func TestRepresentativeSignatures(t *testing.T) { if e, ok := entryByID(entries, "open"); !ok || strings.Join(e.Effects, " ") != "local-write process-control read" { t.Errorf("open effects = %v, want [local-write process-control read]", e.Effects) } + // export reads the corpus, prepares the metadata checkout, writes the + // copy, and launches the system opener. + if e, ok := entryByID(entries, "export"); !ok || strings.Join(e.Effects, " ") != "local-write process-control read" { + t.Errorf("export effects = %v, want [local-write process-control read]", e.Effects) + } // change 0472: no catalog operation's signature carries the retired // record-revision flags (the `version` op itself takes no flags). for _, e := range entries { diff --git a/internal/cli/export.go b/internal/cli/export.go new file mode 100644 index 000000000..ecce9150c --- /dev/null +++ b/internal/cli/export.go @@ -0,0 +1,93 @@ +package cli + +import ( + "context" + "errors" + + "github.com/spf13/cobra" + + "github.com/danielhanold/docket/internal/app" +) + +// exportRunner runs the export operation; tests replace it to observe the +// options the command parsed without reading, writing, or launching anything. +// The command shares open's dependency wiring, openDepsFor. +var exportRunner = func(ctx context.Context, d app.OpenDeps, o app.ExportOptions) app.OperationResult { + return app.Export(ctx, d, o) +} + +// newExportCommand builds `docket export []`: a thin adapter that +// parses the type and change id, then hands them to app.Export. setResult +// receives the operation's result document for the root to present. +func newExportCommand(setResult func(app.OperationResult)) *cobra.Command { + cmd := &cobra.Command{ + Use: "export []", + Short: "Write a clean Markdown copy of a change, spec, plan, or results file", + Long: `Without an id, exports the change whose recorded branch is checked out. It +always reads the local metadata checkout. The copy drops the frontmatter, +docket's generated blocks and markers, every link (keeping its text), and +docket-only sections; explicit change references become quoted titles. Fenced +code and inline code stay exactly as written. + +The copy is named --.md, kind one of ticket, spec, plan, or +results. By default it lands in ~/Downloads on macOS or the home directory on +Linux and opens. --output-path names a directory to write into or the exact +file to write, and opens nothing; --print opens nothing wherever the copy +goes. An existing file is replaced. Leftover docket machinery and mentions of +docket are reported as warnings on stderr; --warnings picks which. Warnings +never block.`, + Args: func(c *cobra.Command, args []string) error { + what, id, err := app.ParseExportArgs(args) + if err != nil { + return err + } + _, err = exportOptionsFromFlags(c, what, id) + return err + }, + Annotations: capability("export", EffectRead, EffectLocalWrite, EffectProcessControl), + RunE: func(c *cobra.Command, args []string) error { + what, id, err := app.ParseExportArgs(args) + if err != nil { + return err + } + repoDir, err := resolveRepoDir(c) + if err != nil { + return err + } + o, err := exportOptionsFromFlags(c, what, id) + if err != nil { + return err + } + o.RepoDir = repoDir + deps, err := openDepsFor() + if err != nil { + return err + } + setResult(exportRunner(c.Context(), deps, o)) + return nil + }, + } + cmd.Flags().String("output-path", "", "directory or exact file `path` for the copy, which is then not opened (default: ~/Downloads on macOS, the home directory on Linux)") + cmd.Flags().String("warnings", app.WarningsAll, "`which` warnings to report: all, leftovers, or mentions") + cmd.Flags().Bool("print", false, "print the copy's path without opening it") + cmd.Flags().String("repo-dir", "", "repository `dir` to operate on (default: current directory)") + return cmd +} + +// exportOptionsFromFlags builds the export options from the parsed type and the +// command's flags. Warnings is set only when --warnings was given, so the +// operation sees an explicit value and never the flag's default; an explicitly +// empty --output-path and an unknown --warnings value are refused. +func exportOptionsFromFlags(c *cobra.Command, what string, id int) (app.ExportOptions, error) { + f := c.Flags() + o := app.ExportOptions{What: what, ID: id} + o.Print, _ = f.GetBool("print") + o.OutputPath, _ = f.GetString("output-path") + if f.Changed("output-path") && o.OutputPath == "" { + return o, errors.New("--output-path needs a path") + } + if f.Changed("warnings") { + o.Warnings, _ = f.GetString("warnings") + } + return o, app.ValidateExportWarnings(o.Warnings) +} diff --git a/internal/cli/export_test.go b/internal/cli/export_test.go new file mode 100644 index 000000000..efdea8821 --- /dev/null +++ b/internal/cli/export_test.go @@ -0,0 +1,125 @@ +package cli + +import ( + "context" + "encoding/json" + "runtime" + "strings" + "testing" + + "github.com/danielhanold/docket/internal/app" +) + +// stubExport replaces the export operation and its dependency wiring for one +// test, recording every ExportOptions the command passes and returning res. +func stubExport(t *testing.T, res app.ExportResult) *[]app.ExportOptions { + t.Helper() + var got []app.ExportOptions + prevRunner, prevDeps := exportRunner, openDepsFor + t.Cleanup(func() { exportRunner, openDepsFor = prevRunner, prevDeps }) + openDepsFor = func() (app.OpenDeps, error) { return app.OpenDeps{}, nil } + exportRunner = func(_ context.Context, _ app.OpenDeps, o app.ExportOptions) app.OperationResult { + got = append(got, o) + return res + } + return &got +} + +// exportOK is a successful spec export to path carrying notes. +func exportOK(path string, notes ...string) app.ExportResult { + if notes == nil { + notes = []string{} + } + return app.ExportResult{Envelope: app.NewEnvelope(app.OperationExport, app.ResultApplied), What: "spec", ChangeID: 7, + ExportedPath: path, Notes: notes} +} + +func TestExportCLIPassesParsedOptions(t *testing.T) { + got := stubExport(t, exportOK("/tmp/x/2026-01-02-spec-widget.md")) + for _, args := range [][]string{ + {"export", "spec", "541", "--output-path", "/tmp/x", "--warnings", "leftovers", "--print", "--repo-dir", "/tmp/repo"}, + {"export", "spec", "0541", "--repo-dir", "/tmp/repo"}, + {"export", "plan", "--repo-dir", "/tmp/repo"}, + } { + if _, errS, code := runCLI(t, args...); code != 0 { + t.Fatalf("%q: code %d stderr %q", args, code, errS) + } + } + want := []app.ExportOptions{ + {RepoDir: "/tmp/repo", What: "spec", ID: 541, Print: true, OutputPath: "/tmp/x", Warnings: "leftovers"}, + {RepoDir: "/tmp/repo", What: "spec", ID: 541}, + {RepoDir: "/tmp/repo", What: "plan"}, + } + if len(*got) != len(want) { + t.Fatalf("options = %+v, want %+v", *got, want) + } + for i := range want { + if (*got)[i] != want[i] { + t.Errorf("options[%d] = %+v, want %+v", i, (*got)[i], want[i]) + } + } +} + +// TestExportCLIUsageErrors: every usage mistake is a CLI usage error caught +// before the operation runs — never an export operation document. +func TestExportCLIUsageErrors(t *testing.T) { + got := stubExport(t, exportOK("x")) + for _, args := range [][]string{ + {"export"}, {"export", "board"}, {"export", "pr", "5"}, {"export", "bogus"}, + {"export", "spec", "#541"}, {"export", "spec", "0"}, {"export", "spec", "1", "2"}, + {"export", "spec", "5", "--warnings", "bogus"}, + {"export", "spec", "5", "--output-path", ""}, + } { + if _, errS, code := runCLI(t, args...); code != 2 || errS == "" || strings.Contains(strings.TrimRight(errS, "\n"), "\n") { + t.Errorf("%q: code %d stderr %q, want exit 2 and one line", args, code, errS) + } + } + out, _, code := runCLI(t, "--json", "export", "board") + var doc map[string]any + if err := json.Unmarshal([]byte(out), &doc); err != nil || code != 2 { + t.Fatalf("--json export board: code %d stdout %q (%v)", code, out, err) + } + if doc["reason"] != app.ReasonInvalidArguments || doc["operation"] == app.OperationExport { + t.Errorf("--json export board = %s, want the CLI's %s document", out, app.ReasonInvalidArguments) + } + if len(*got) != 0 { + t.Errorf("usage errors reached the operation: %+v", *got) + } +} + +// TestExportCLIPrintsThePath: stdout is exactly the exported path, so it +// composes in command substitution; notes go to stderr. +func TestExportCLIPrintsThePath(t *testing.T) { + stubExport(t, exportOK("/d/2026-01-02-spec-widget.md", "replaced /d/2026-01-02-spec-widget.md")) + out, errS, code := runCLI(t, "export", "spec", "7", "--print", "--repo-dir", "/tmp/repo") + if code != 0 || out != "/d/2026-01-02-spec-widget.md\n" || errS != "note: replaced /d/2026-01-02-spec-widget.md\n" { + t.Fatalf("code %d stdout %q stderr %q", code, out, errS) + } +} + +// TestExportCLIDepsWiring pins the production wiring the export needs: the app +// layer refuses an export when any of these is unset. +func TestExportCLIDepsWiring(t *testing.T) { + d, err := openDepsFor() + if err != nil { + t.Skipf("git unavailable: %v", err) + } + if d.GOOS != runtime.GOOS || d.HomeDir == nil || d.Getwd == nil { + t.Fatalf("GOOS %q (want %q), HomeDir set %v, Getwd set %v", d.GOOS, runtime.GOOS, d.HomeDir != nil, d.Getwd != nil) + } +} + +// TestExportCLIHelpNamesTicketKind pins that the copy's kind list names the +// ticket kind, never the retired issue kind. +func TestExportCLIHelpNamesTicketKind(t *testing.T) { + out, errS, code := runCLI(t, "export", "--help") + if code != 0 { + t.Fatalf("export --help exit %d, stderr %q", code, errS) + } + if !strings.Contains(out, "kind one of ticket, spec, plan, or") { + t.Errorf("export --help must name the ticket kind:\n%s", out) + } + if strings.Contains(out, "one of issue") { + t.Errorf("export --help still names the retired issue kind:\n%s", out) + } +} diff --git a/internal/cli/install.go b/internal/cli/install.go index 7800536a1..1063f1f46 100644 --- a/internal/cli/install.go +++ b/internal/cli/install.go @@ -69,6 +69,7 @@ var assetIndependent = map[string]bool{ "evidence recertify": true, // composes the local gate + GitHub PR edit; reads no installed assets "open": true, // reads the corpus and launches the system opener; no installed assets + "export": true, // reads the corpus, writes the copy, and launches the system opener; no installed assets "pr": true, // the group itself; it reports a missing command "pr publish": true, "run": true, // the group itself; it reports a missing command diff --git a/internal/cli/open.go b/internal/cli/open.go index 39e616d0d..59445179c 100644 --- a/internal/cli/open.go +++ b/internal/cli/open.go @@ -2,7 +2,6 @@ package cli import ( "context" - "errors" "os" "os/exec" "runtime" @@ -49,30 +48,10 @@ func newOpenCommand(setResult func(app.OperationResult)) *cobra.Command { Short: "Open the board, or a change's record, spec, plan, results, or pull request", Long: `Without an id, opens the change whose recorded branch is checked out. Shared repositories open GitHub pages unless open.artifacts is local; private ones open -the metadata checkout's file; pr opens the pull request. - ---export writes a clean Markdown copy of a change, spec, plan, or results file -and opens that copy (--print prints its path). It always reads the local -metadata checkout. The copy drops the frontmatter, docket's generated blocks -and markers, every link (keeping its text), and docket-only sections; explicit -change references become quoted titles. Fenced code and inline code stay -exactly as written. - -The copy is named --.md, type one of ticket, spec, plan, or -results, and lands in ~/Downloads on macOS or the home directory on Linux. ---output-path names a directory to write into or the exact file to write; an -existing file is replaced. Leftover docket machinery and mentions of docket are -reported as warnings on stderr; --warnings picks which. Warnings never block.`, +the metadata checkout's file; pr opens the pull request.`, Args: func(c *cobra.Command, args []string) error { - what, id, err := app.ParseOpenArgs(args) - if err != nil { - return err - } - o, err := openOptionsFromFlags(c, what, id) - if err != nil { - return err - } - return app.ValidateOpenExport(o) + _, _, err := app.ParseOpenArgs(args) + return err }, Annotations: capability("open", EffectRead, EffectLocalWrite, EffectProcessControl), RunE: func(c *cobra.Command, args []string) error { @@ -84,10 +63,7 @@ reported as warnings on stderr; --warnings picks which. Warnings never block.`, if err != nil { return err } - o, err := openOptionsFromFlags(c, what, id) - if err != nil { - return err - } + o := openOptionsFromFlags(c, what, id) o.RepoDir = repoDir deps, err := openDepsFor() if err != nil { @@ -97,29 +73,15 @@ reported as warnings on stderr; --warnings picks which. Warnings never block.`, return nil }, } - cmd.Flags().Bool("export", false, "write a clean Markdown copy of the artifact and open that copy") - cmd.Flags().String("output-path", "", "directory or exact file `path` for the --export copy (default: ~/Downloads on macOS, the home directory on Linux)") - cmd.Flags().String("warnings", app.WarningsAll, "`which` --export warnings to report: all, leftovers, or mentions") cmd.Flags().Bool("print", false, "print the URL or path without opening it") cmd.Flags().String("repo-dir", "", "repository `dir` to operate on (default: current directory)") return cmd } // openOptionsFromFlags builds the open options from the parsed target and the -// command's flags. Warnings is set only when --warnings was given, so the -// export check sees an explicit value and never the flag's default; an -// explicitly empty --output-path is refused. -func openOptionsFromFlags(c *cobra.Command, what string, id int) (app.OpenOptions, error) { - f := c.Flags() +// command's flags. +func openOptionsFromFlags(c *cobra.Command, what string, id int) app.OpenOptions { o := app.OpenOptions{What: what, ID: id} - o.Print, _ = f.GetBool("print") - o.Export, _ = f.GetBool("export") - o.OutputPath, _ = f.GetString("output-path") - if f.Changed("output-path") && o.OutputPath == "" { - return o, errors.New("--output-path needs a path") - } - if f.Changed("warnings") { - o.Warnings, _ = f.GetString("warnings") - } - return o, nil + o.Print, _ = c.Flags().GetBool("print") + return o } diff --git a/internal/cli/open_test.go b/internal/cli/open_test.go index 3cf00aaf1..34323a9ea 100644 --- a/internal/cli/open_test.go +++ b/internal/cli/open_test.go @@ -2,7 +2,6 @@ package cli import ( "context" - "runtime" "strings" "testing" @@ -78,65 +77,33 @@ func TestOpenCLIUsageErrors(t *testing.T) { } } -func TestOpenCLIExportOptions(t *testing.T) { - got := stubOpen(t, openOK("/tmp/x/2026-01-02-spec-widget.md")) - if _, errS, code := runCLI(t, "open", "spec", "541", "--export", "--output-path", "/tmp/x", "--warnings", "leftovers", "--print", "--repo-dir", "/tmp/repo"); code != 0 { - t.Fatalf("code %d stderr %q", code, errS) - } - if _, errS, code := runCLI(t, "open", "spec", "541", "--export", "--repo-dir", "/tmp/repo"); code != 0 { - t.Fatalf("default-warnings code %d stderr %q", code, errS) - } - want := []app.OpenOptions{ - {RepoDir: "/tmp/repo", What: "spec", ID: 541, Print: true, Export: true, OutputPath: "/tmp/x", Warnings: "leftovers"}, - {RepoDir: "/tmp/repo", What: "spec", ID: 541, Export: true}, - } - if len(*got) != 2 || (*got)[0] != want[0] || (*got)[1] != want[1] { - t.Fatalf("options = %+v, want %+v", *got, want) - } -} - -func TestOpenCLIExportUsageErrors(t *testing.T) { +// TestOpenCLIRejectsExportFlags pins that the export lives only in +// `docket export`: open refuses the retired export flags as unknown, and its +// help names none of them. +func TestOpenCLIRejectsExportFlags(t *testing.T) { got := stubOpen(t, openOK("x")) - for _, args := range [][]string{ - {"open", "board", "--export"}, - {"open", "pr", "5", "--export"}, - {"open", "spec", "5", "--output-path", "x"}, - {"open", "spec", "5", "--warnings", "all"}, - {"open", "spec", "5", "--export", "--warnings", "bogus"}, - {"open", "spec", "5", "--export", "--output-path", ""}, + for _, c := range []struct { + args []string + flag string + }{ + {[]string{"open", "spec", "5", "--export"}, "--export"}, + {[]string{"open", "spec", "5", "--output-path", "x"}, "--output-path"}, + {[]string{"open", "spec", "5", "--warnings", "all"}, "--warnings"}, } { - if _, errS, code := runCLI(t, args...); code != 2 || errS == "" || strings.Contains(strings.TrimRight(errS, "\n"), "\n") { - t.Errorf("%q: code %d stderr %q, want exit 2 and one line", args, code, errS) + if _, errS, code := runCLI(t, c.args...); code != 2 || !strings.Contains(errS, "unknown flag: "+c.flag) { + t.Errorf("%q: code %d stderr %q, want exit 2 and unknown flag: %s", c.args, code, errS, c.flag) } } if len(*got) != 0 { - t.Errorf("usage errors reached the operation: %+v", *got) - } -} - -// TestOpenCLIExportDepsWiring pins the production wiring the export needs: -// the app layer refuses an export when any of these is unset. -func TestOpenCLIExportDepsWiring(t *testing.T) { - d, err := openDepsFor() - if err != nil { - t.Skipf("git unavailable: %v", err) - } - if d.GOOS != runtime.GOOS || d.HomeDir == nil || d.Getwd == nil { - t.Fatalf("GOOS %q (want %q), HomeDir set %v, Getwd set %v", d.GOOS, runtime.GOOS, d.HomeDir != nil, d.Getwd != nil) + t.Errorf("rejected flags reached the operation: %+v", *got) } -} - -// TestOpenCLIHelpNamesTicketKind pins that the export copy's type list names -// the ticket kind, never the retired issue kind. -func TestOpenCLIHelpNamesTicketKind(t *testing.T) { out, errS, code := runCLI(t, "open", "--help") if code != 0 { t.Fatalf("open --help exit %d, stderr %q", code, errS) } - if !strings.Contains(out, "type one of ticket, spec, plan, or") { - t.Errorf("open --help must name the ticket export kind:\n%s", out) - } - if strings.Contains(out, "one of issue") { - t.Errorf("open --help still names the retired issue kind:\n%s", out) + for _, s := range []string{"--export", "--output-path", "--warnings", "clean Markdown copy"} { + if strings.Contains(out, s) { + t.Errorf("open --help still names %q:\n%s", s, out) + } } } diff --git a/internal/cli/presenter_test.go b/internal/cli/presenter_test.go index d42a40148..715370b4a 100644 --- a/internal/cli/presenter_test.go +++ b/internal/cli/presenter_test.go @@ -97,12 +97,12 @@ func TestPresentHumanNotesGoToStderr(t *testing.T) { // exactly the exported path, stderr carries the notes and then one "warning:" // line each, and JSON mode writes nothing to stderr. func TestPresenterWritesWarningsToStderr(t *testing.T) { - r := app.OpenResult{ - Envelope: app.NewEnvelope(app.OperationOpen, app.ResultApplied), What: "spec", - Target: "/d/2026-01-02-spec-widget.md", ExportedPath: "/d/2026-01-02-spec-widget.md", - Notes: []string{"replaced /d/2026-01-02-spec-widget.md"}, - Leftovers: []app.ExportLeftover{{Line: 4, Text: "[a](b)", Rule: "link"}}, - Mentions: &app.ExportMentions{Count: 2, Lines: []int{1, 7}}, + r := app.ExportResult{ + Envelope: app.NewEnvelope(app.OperationExport, app.ResultApplied), What: "spec", + ExportedPath: "/d/2026-01-02-spec-widget.md", + Notes: []string{"replaced /d/2026-01-02-spec-widget.md"}, + Leftovers: []app.ExportLeftover{{Line: 4, Text: "[a](b)", Rule: "link"}}, + Mentions: &app.ExportMentions{Count: 2, Lines: []int{1, 7}}, } var out, errBuf bytes.Buffer Presenter{Stdout: &out, Stderr: &errBuf}.Present(r) diff --git a/internal/cli/root.go b/internal/cli/root.go index b83dcaaa3..69071d0ed 100644 --- a/internal/cli/root.go +++ b/internal/cli/root.go @@ -419,6 +419,7 @@ func run(args []string, stdin io.Reader, stdout, stderr io.Writer, info buildinf finalizeCmd := newFinalizeCommand(func(r app.OperationResult) { result = r }) maintenanceCmd := newMaintenanceCommand(func(r app.OperationResult) { result = r }) openCmd := newOpenCommand(func(r app.OperationResult) { result = r }) + exportCmd := newExportCommand(func(r app.OperationResult) { result = r }) repositoryCmd := newRepositoryCommand(func(r app.OperationResult) { result = r }) agentCmd := newAgentCommand(info, func(r app.OperationResult) { result = r }) instructionsCmd := newInstructionsCommand(stdin, jsonMode, @@ -430,7 +431,7 @@ func run(args []string, stdin io.Reader, stdout, stderr io.Writer, info buildinf installCmd.AddCommand(installCheckCmd, installCollectCmd) developmentCmd.AddCommand(developmentInstallCmd, developmentTestCmd) diagnosticCmd.AddCommand(runtimeCmd, configCmd) - root.AddCommand(capabilitiesCmd, schemaCmd, versionCmd, statusCmd, changeCmd, contextCmd, workspaceCmd, evidenceCmd, prCmd, runCmd, learningCmd, adrCmd, gateCmd, finalizeCmd, maintenanceCmd, openCmd, repositoryCmd, agentCmd, instructionsCmd, diagnosticCmd, installCmd, uninstallCmd, developmentCmd) + root.AddCommand(capabilitiesCmd, schemaCmd, versionCmd, statusCmd, changeCmd, contextCmd, workspaceCmd, evidenceCmd, prCmd, runCmd, learningCmd, adrCmd, gateCmd, finalizeCmd, maintenanceCmd, openCmd, exportCmd, repositoryCmd, agentCmd, instructionsCmd, diagnosticCmd, installCmd, uninstallCmd, developmentCmd) root.AddCommand(extra...) // The asset-dependence guard. Commands that do not read installed assets diff --git a/internal/repoguard/prose_contracts_test.go b/internal/repoguard/prose_contracts_test.go index a3b16ce0f..2ebcd7ea4 100644 --- a/internal/repoguard/prose_contracts_test.go +++ b/internal/repoguard/prose_contracts_test.go @@ -1529,11 +1529,13 @@ var alignmentContracts = []proseContract{ // change 0578 — the inline export skill: never a hand-built or raw export; // a failed export posts nothing; shared repositories get no rewrite pass and // no stop; private (or unknown) repositories get the rewrite pass, the word - // check, and a before → after stop. + // check, and a before → after stop. Change 0589: the export runs through the + // `export` operation, never `open --export`. {sentinel: "change_0578_export_skill", file: "skills/docket-export/SKILL.md", present: []string{ "**Never build an export by hand, and never send the raw file.**", - "`--export --print --json`", + "Run the `export` argv as ` [] --print --json --repo-dir `", + "take the `argv` of the entries `export`, `repository.prepare`, and `diagnostic.config`", "**A failed export posts nothing.**", "If `result` is not `applied` or there is no `exported_path`, tell the person the `message` and stop", "Never fall back to the raw file or a hand cleanup", @@ -1545,7 +1547,7 @@ var alignmentContracts = []proseContract{ "show the person every change as before → after and **post only after they say go**", "Creating a ticket from a change, or linking or importing one, is `docket-link-ticket`'s job; it calls this skill only for a file export.", }, - absent: []string{"context: fork", "agent: docket-export", "a Jira ticket body or comment"}}, + absent: []string{"context: fork", "agent: docket-export", "a Jira ticket body or comment", "--export", "the `open` argv"}}, // 0578 review: the export reports neither ADR numbers nor bare #N, so the private // ADR/change-number rewrite runs on every private export, not only on leftovers or mentions. {sentinel: "change_0578_export_skill", file: "skills/docket-export/SKILL.md", diff --git a/skills/docket-export/SKILL.md b/skills/docket-export/SKILL.md index 27c5f06c5..01819846e 100644 --- a/skills/docket-export/SKILL.md +++ b/skills/docket-export/SKILL.md @@ -13,7 +13,7 @@ Creating a ticket from a change, or linking or importing one, is `docket-link-ti ## 1. Resolve the operations -Run `docket capabilities --json` as its own call — the one docket spelling this skill hard-codes. Check that `protocol_version` is 1 and take the `argv` of the entries `open`, `repository.prepare`, and `diagnostic.config`. If the binary is missing or an entry is absent, tell the person their docket installation is broken and stop — never a hand-made export. +Run `docket capabilities --json` as its own call — the one docket spelling this skill hard-codes. Check that `protocol_version` is 1 and take the `argv` of the entries `export`, `repository.prepare`, and `diagnostic.config`. If the binary is missing or an entry is absent, tell the person their docket installation is broken and stop — never a hand-made export. ## 2. Learn the visibility @@ -26,7 +26,7 @@ In a private repository, also run the `diagnostic.config` argv with `--repo-dir ## 3. Run the export -Run the `open` argv as ` [] --export --print --json --repo-dir `, where `` is `change`, `spec`, `plan`, or `results` and `` is the change the person named (omit it to use the change whose branch is checked out). Always `--export --print --json`: `--print` opens no viewer — the person may not be at the screen, and can ask you to open the file. Never pass `--warnings` unless the person asked for a filter on a file request; the default reports everything the private pass reads. +Run the `export` argv as ` [] --print --json --repo-dir `, where `` is `change`, `spec`, `plan`, or `results` and `` is the change the person named (omit it to use the change whose branch is checked out). Always `--print --json`: `--print` opens no viewer — the person may not be at the screen, and can ask you to open the file. Never pass `--warnings` unless the person asked for a filter on a file request; the default reports everything the private pass reads. - **File request** ("export the spec for 9"): the export's default destination, or `--output-path ` when the person names one. - **Outside-tool request** ("put the spec for 9 in a message to the design channel"): `--output-path` set to a fresh directory from `mktemp -d "${TMPDIR:-/tmp}/docket-export.XXXXXX"`, so the person's downloads folder does not collect one file per post. Leave the file there and report its path.