From 047fca1d8e66700a8bfe01ed56d599a392d7f0f1 Mon Sep 17 00:00:00 2001 From: Daniel Hanold Date: Mon, 9 Nov 2026 17:46:28 -0500 Subject: [PATCH 01/12] Add design spec: Link a change to a ticket --- ...-11-09-link-a-change-to-a-ticket-design.md | 178 ++++++++++++++++++ 1 file changed, 178 insertions(+) create mode 100644 docs/superpowers/specs/2026-11-09-link-a-change-to-a-ticket-design.md diff --git a/docs/superpowers/specs/2026-11-09-link-a-change-to-a-ticket-design.md b/docs/superpowers/specs/2026-11-09-link-a-change-to-a-ticket-design.md new file mode 100644 index 000000000..0070a212d --- /dev/null +++ b/docs/superpowers/specs/2026-11-09-link-a-change-to-a-ticket-design.md @@ -0,0 +1,178 @@ +# Link a change to a ticket — design + +Change 0583 — Link a change to a ticket + +Change #583, groomed interactively on 2026-11-09. Position 2 of the ticket-integration split planned by change 581; this spec restates every settled decision it carries, so the build needs nothing from 581. + +## Intent + +Every later ticket capability (create, import, post updates) needs two things this change provides: a durable, typed link from a change to its ticket, and a place for the team's ticket settings. The legacy `issue:` field, an unused leftover of the removed GitHub board mirror, is retired so one word, *ticket*, runs through docket. + +A **ticket** is the item in the team's ticket system (a Jira issue, a Linear issue, a GitHub issue, an Azure DevOps work item). A **provider** is which ticket system (`jira`, `linear`, …). + +## Goals + +1. Three ticket fields on a change, written together by one dedicated operation that links, replaces, and unlinks, in any status. +2. `change.create` accepts the same three fields, so a later import can create a linked change in one step. +3. The `tickets.*` config keys exist, per-repo only, every automatic switch off. +4. implement-next's PR body carries one plain line linking the ticket. +5. `issue:` is gone from every read path. + +## Non-goals + +- Any connector call or ticket-system call — this change never contacts a ticket system. +- Skills that create, import, or update tickets (changes 584–588). Nothing in this change *consumes* the `tickets.*` keys. +- Any board change. +- A read operation for tickets beyond the implementation context field below (change 585's read operation owns that). +- Rewriting archived records to drop their empty `issue:` values (see below). Linking a ticket to an archived change through the operation is in scope: "any status" includes `done` and `killed`. + +## Settled decisions (fixed by 581 — not reopened) + +- **Three flat scalar fields:** + + ```yaml + ticket_provider: jira + ticket_id: CLOUD-123 + ticket_url: https://acme.atlassian.net/browse/CLOUD-123 + ``` + + Flat because the frontmatter value model has no mapping kind (`internal/document/value.go`; the patcher's `classifyShape` treats a mapping as `ShapeUnsupported`). +- **Provider and id are stored, not derived.** They are worked out once while linking with the human present, stay correct if config changes later, and the id gives readable link text with no provider knowledge. `ticket_provider` is a free lowercase token; docket keeps no list of providers. +- **One dedicated operation** writes the three together: revision-pinned, any status, refuses a partial set, clears all three on unlink, re-renders `## Artifacts`. It follows `change.relink`'s pattern (one purpose, any status) rather than `change.groom`, which works only while a change is `proposed`. +- **A partial or inconsistent set** (only a hand edit can produce one) is treated as "not linked" by every consumer and reported as a finding by the read side — visibility only, never a block. +- **`## Artifacts` gains a row:** `| Ticket | [CLOUD-123]() |`. The board does not change. +- **The PR body gets one plain line linking the ticket**, replacing implement-next's "Best-effort PR→issue reference". A ticket URL is not docket machinery, so the line is allowed in a private repository; like all PR text it is still subject to the leak check. +- **`issue:` is retired:** removed from decode, the domain model, `newChangeBuilder`, repair's field list, and implement-next's Step 7. +- **Config** (below): every `tickets.*` key per-repo only, no master switch, no "enable all" switch, no ticket-type key, `project` generic. +- **Testing:** no ticket-system call is ever made from the docket repository, and docket's own `.docket.yml` never carries a `tickets.*` key — a repository test guards it. + +## Decisions made in grooming + +### The operation: `change.link-ticket` + +A request-file operation (`--request [--repo-dir ]`), registered in the capability catalog and the `schema` registry like `change.block`, `metadata-write` effect. + +**Request:** + +| Key | Type | Notes | +|---|---|---| +| `change_id` | int, required | | +| `path` | string, required | record path, from `status --json` | +| `revision` | string, required | record blob revision, from `status --json` | +| `ticket_provider` | string | link mode: all three required together | +| `ticket_id` | string | | +| `ticket_url` | string | | +| `replace` | bool | required to overwrite a link to a *different* ticket | +| `unlink` | bool | clears all three; may not be combined with any ticket field or `replace` | + +**Modes and dispositions:** + +- **Link** (no current link, all three fields given): writes the three fields + `updated:`, re-renders `## Artifacts` and the inline board in one metadata commit (the board's bytes will not change, since the board shows no ticket, but the shared inclusion path decides that, not this op). Disposition `linked`. +- **Same link again** (current link equals all three given values): writes nothing. Disposition `already-linked`. +- **Replace** (a *different* complete link exists): refused with `already-linked-elsewhere` unless `replace: true`; with it, writes as for link. Disposition `replaced`. +- **Unlink** (`unlink: true`): clears all three fields + `updated:`, re-renders as above. Disposition `unlinked`. When the record carries none of the three: `nothing-to-unlink`, writes nothing. +- A record that currently carries a **partial or invalid** set: link requires `replace: true` (it overwrites what is there); unlink clears whatever is present. +- **Any status means any status:** `done` and `killed` records under `archive/` are resolved the same way (the path from `status --json`), and the archived record's `## Artifacts` block is re-rendered in the same commit. No status refusal exists. + +**Refusals (write nothing):** `partial-ticket` (one or two of the three fields given), `unlink-with-ticket` (unlink combined with ticket fields or `replace`), `empty-request` (neither fields nor unlink), `invalid-ticket-provider`, `invalid-ticket-id`, `invalid-ticket-url`, `contended` (revision moved), plus the standard planning refusals (unknown change, config preflight). + +**Validation** — one domain-level function, shared by `change.link-ticket`, `change.create`, and the decoder's read-side check (below): +- `ticket_provider`: matches the `change_types` token pattern `^[a-z][a-z0-9-]*$`. +- `ticket_id`: non-empty after trimming, single line. +- `ticket_url`: parses as an absolute `http` or `https` URL with a host. + +The writer quotes every string value (ADR-0071); callers never pre-quote. + +**"Replace" is the human's request, in plain words.** The human never has to say a flag: "switch it to CLOUD-456" or "this is actually CLOUD-456" is the explicit replace request, and the agent sends `replace: true` for it. What an agent must never do is replace a link on its own initiative. The convention's description of the operation says so. + +### `change.create` + +Accepts `ticket_provider`, `ticket_id`, `ticket_url`: all three or none, the same validation, the same refusal reasons. A new record with a complete set renders the Ticket row in `## Artifacts` at creation. + +### Frontmatter placement + +The three fields render immediately after `pr:` and before `blocked_by:` in `ChangeRecord` (the slot `issue:` held in old records) — builder's call to adjust if the record-order tests suggest otherwise. + +### Archived `issue:` values stay + +The four archived records carrying an empty `issue:` (0065, 0066, 0227, 0298) are left untouched. The decoder already treats unknown keys as compatibility data that never fails a decode (`changeWire`'s comment), no check flags them, and archived records are point-in-time history. Once decode drops the field, those values are inert. Nothing rewrites them. + +### Read side + +- **One notion of "linked".** A change is linked only when all three fields are present **and** pass the shared validation. Anything else that carries any ticket field — a partial set, or a complete set with an invalid value (`ticket_provider: JIRA`, a `javascript:` or relative URL, a multi-line id), which only a hand edit can produce — is "not linked" everywhere: no Ticket row in `## Artifacts`, no `ticket` in the implementation context, no PR line. Grooming call: one rule, so an unvalidated URL can never reach an Artifacts block or a published PR body. +- **The finding.** The decoder reports one warning finding, `ticket-link-invalid`, through the existing decode-finding mechanism (`(*decoder).report`) for either shape. It surfaces in `status --json` findings and in docket-status's report; it never blocks. The finding text names what is wrong (which fields are missing or which value fails which rule), that the change is treated as not linked, and the remedy (`change.link-ticket` with all three and `replace: true`, or `unlink: true`). The code joins the `finding_codes` vocabulary. +- **Typed ticket in the implementation context.** `context.implementation`'s `change.summary` gains an optional `ticket` object (`provider`, `id`, `url`), present only when the change is linked. A skill never scans raw record text for an optional key (learning `frontmatter-anchored-read`). + +### PR body line + +implement-next Step 7's "Best-effort PR→issue reference" paragraph is replaced, and the "PR-body assembly" paragraph just above it drops its "no `#` reference" clause (the private-repository rule it states otherwise stands): when the implementation context's `ticket` is present, the authored PR body carries one plain line, `Ticket: []()`; otherwise nothing. No fallback to any other reference (the `issue:` path is retired, and no record carries a non-empty `issue:`). In a private repository the line still goes in; `pr.publish`'s leak check scans it with the rest of the body. Never a build gate. + +### Config: `tickets.*` + +```yaml +tickets: + provider: "" # which tool (jira, linear, …) + site: "" # where it lives (acme.atlassian.net) + project: "" # where new tickets go + auto: # act on its own after each event; all false by default + change_created: false + spec_written: false + pr_opened: false + pr_merged: false + results_completed: false +``` + +- Each key is a fixed registry path (`buildRegistry`; the registry has no user-named map keys), `scopeRepoOnly`: set in the global config or `.docket.local.yml`, it is warned and ignored (ADR-0019's existing fence — no new ADR). In a shared repository it lives in the committed `.docket.yml`; in a private one, `.git/dckt/config.yml`. +- **Normal settings (`dispSupported`), not deferred.** Nothing reads them yet (`provider`/`site`/`project` gain a consumer in change 584, `auto.*` in change 587); setting `auto.pr_opened: true` today simply does nothing. A deferred disposition was rejected: it would make a `true` value block every docket write — a new blocking gate. +- Strings validate as single-line; `auto.*` as bools. Empty strings are the defaults. +- Each key gets its typed field, default, `assemble` assignment, `diagnostic.config` inspection line, and `.docket.example.yml` entry (checked by `example_correspondence_test.go`). The example carries this table as a comment: + +| Tool | `project` means | Ticket types | +|---|---|---| +| Jira | project | issue type (Story, Task, Bug) | +| Azure DevOps | project | work item type | +| GitLab | project | issue type | +| GitHub Issues | repository | issue type, where the organization has them | +| Shortcut | team | story type | +| Linear | team | none (labels) | +| Asana / Trello | project / board | none | + +### `issue:` retirement — exact sites + +Remove `Issue` from `changeWire` and `decodeChange` (`internal/repository/decode.go`), the `ChangeSpec` field and `Issue()` accessor (`internal/domain/entities.go`), `newChangeBuilder` (`internal/domain/actions.go`), and `"issue"` from repair's `changeStringFields` (`internal/reposetup/repair.go`, and its doc comment). Add the three ticket fields everywhere `issue` was, plus `ChangeRecord` (`internal/render/record.go`), which never had `issue`. A whole-repo grep for `issue` in executable code decides the final site list, not this one. + +**Folded-in fix (approved in grooming):** `internal/cli/open.go`'s `open` help text still says the export copy's type is "one of issue, spec, plan, or results", but the export kind for a change is now `ticket` (`KindTicket` in `internal/export/export.go`). Change that word to `ticket`. It is a stale-text leftover of the export-kind rename, unrelated to the ticket fields, folded in because the `issue` sweep lands on it. + +### Repository guard + +A test in `internal/repoguard` reads docket's own committed `.docket.yml` and fails if it declares any `tickets` key. Mutation-tested: add a `tickets:` key, watch it redden. + +## Docs and generated surfaces + +- The convention's change-manifest sketch gains the three fields (and loses nothing — `issue:` is not in it today); its operation prose names `change.link-ticket` with the "replace is the human's plain-words request" rule. Regenerate embedded twins with `go generate ./internal/assets/`. +- implement-next Step 7 rewritten as above, embedded twin regenerated. +- `.docket.example.yml` documents `tickets.*` with the tool table, written for someone who never heard of this change (learning `config-knob-ship-end-to-end`). + +## ADR + +Record one ADR at build (via docket-adr): **Ticket fields are three flat stored scalars, and `issue:` is retired** — context: no mapping kind in frontmatter, stored-not-derived rationale, the dead GitHub-mirror field; decision as above; alternatives: a nested `ticket:` mapping (needs a new value kind), deriving provider/id from the URL (breaks when config changes), keeping `issue:` (two words for one thing). + +## Acceptance criteria + +- `change.link-ticket` writes all three fields and the Ticket row in one commit; `already-linked` writes nothing; a different existing link is refused without `replace: true` and replaced with it; `unlink: true` clears all three; a partial request is refused. +- `change.create` with all three fields creates a linked record with the Ticket row; with one or two it refuses. +- `change.link-ticket` links a `done` change under `archive/` and re-renders its Ticket row. +- A hand-edited partial set, and a hand-edited complete set with an invalid URL, each yield a `ticket-link-invalid` warning in `status --json`, no Ticket row, and no `ticket` in the implementation context. +- `tickets.*` set in the global config or `.docket.local.yml` is warned and ignored; `docket diagnostic config --json` reports each key's effective value. +- implement-next's Step 7 text carries the ticket line and no `issue:` reference. +- No executable code reads `issue:`. +- `docket open --help` names the export type `ticket`, not `issue`. +- The repository guard fails when `.docket.yml` carries a `tickets` key. + +## Testing + +Repository tests and fixtures only. No ticket-system call is ever made from this repository, and no sandbox site or project name appears in it. There is no live human check for this change: it adds no capability that contacts a ticket system. + +## Left to the builder + +Go type and file names; exact message wording; the frontmatter slot if tests argue for another; how the operation's transaction reuses `change.relink`'s and `change.block`'s plumbing. From 1df743a187398dff88110c6bd8a083e19cf3d8f6 Mon Sep 17 00:00:00 2001 From: Daniel Hanold Date: Mon, 9 Nov 2026 18:02:55 -0500 Subject: [PATCH 02/12] feat(domain): add the ticket link model and its validation --- internal/domain/actions.go | 3 + internal/domain/entities.go | 3 + internal/domain/entities_test.go | 22 ++++++ internal/domain/ticket.go | 105 ++++++++++++++++++++++++++ internal/domain/ticket_test.go | 125 +++++++++++++++++++++++++++++++ 5 files changed, 258 insertions(+) create mode 100644 internal/domain/ticket.go create mode 100644 internal/domain/ticket_test.go diff --git a/internal/domain/actions.go b/internal/domain/actions.go index 7b9cf0ee5..72f749101 100644 --- a/internal/domain/actions.go +++ b/internal/domain/actions.go @@ -464,6 +464,9 @@ func newChangeBuilder(c Change) *changeBuilder { BranchPrefix: c.BranchPrefix(), Branch: c.Branch(), PR: c.PR(), + TicketProvider: c.TicketProvider(), + TicketID: c.TicketID(), + TicketURL: c.TicketURL(), Issue: c.Issue(), BlockedBy: c.BlockedBy(), Reconciled: c.Reconciled(), diff --git a/internal/domain/entities.go b/internal/domain/entities.go index 260d5499e..39103728c 100644 --- a/internal/domain/entities.go +++ b/internal/domain/entities.go @@ -96,6 +96,9 @@ type ChangeSpec struct { BranchPrefix OptionalString // per-change mint-prefix override; durable input Branch OptionalString PR OptionalString + TicketProvider OptionalString // ticket link: see Ticket and ValidateTicket + TicketID OptionalString + TicketURL OptionalString Issue OptionalString BlockedBy OptionalString Reconciled bool diff --git a/internal/domain/entities_test.go b/internal/domain/entities_test.go index 2afff8839..760c227d9 100644 --- a/internal/domain/entities_test.go +++ b/internal/domain/entities_test.go @@ -46,6 +46,9 @@ func fullChangeSpec(t *testing.T) ChangeSpec { Results: OptionalString{State: FieldAbsent}, Branch: OptionalString{State: FieldPresent, Value: "feat/domain-snapshot"}, PR: OptionalString{State: FieldPresent, Value: "https://example.test/pr/1"}, + TicketProvider: OptionalString{State: FieldPresent, Value: "jira"}, + TicketID: OptionalString{State: FieldEmpty}, + TicketURL: OptionalString{State: FieldMalformed, Value: "{a: b}"}, Issue: OptionalString{State: FieldMalformed, Value: "#"}, BlockedBy: OptionalString{State: FieldEmpty}, Reconciled: true, @@ -118,6 +121,25 @@ func TestChangeAccessorsRoundTrip(t *testing.T) { if got := c.Issue(); got != spec.Issue { t.Errorf("Issue() = %+v; want %+v", got, spec.Issue) } + if got := c.TicketProvider(); got != spec.TicketProvider { + t.Errorf("TicketProvider() = %+v; want %+v", got, spec.TicketProvider) + } + if got := c.TicketID(); got != spec.TicketID { + t.Errorf("TicketID() = %+v; want %+v", got, spec.TicketID) + } + if got := c.TicketURL(); got != spec.TicketURL { + t.Errorf("TicketURL() = %+v; want %+v", got, spec.TicketURL) + } + rebuilt := newChangeBuilder(c).result().Change + if got := rebuilt.TicketProvider(); got != spec.TicketProvider { + t.Errorf("builder TicketProvider() = %+v; want %+v", got, spec.TicketProvider) + } + if got := rebuilt.TicketID(); got != spec.TicketID { + t.Errorf("builder TicketID() = %+v; want %+v", got, spec.TicketID) + } + if got := rebuilt.TicketURL(); got != spec.TicketURL { + t.Errorf("builder TicketURL() = %+v; want %+v", got, spec.TicketURL) + } if got := c.BlockedBy(); got != spec.BlockedBy { t.Errorf("BlockedBy() = %+v; want %+v", got, spec.BlockedBy) } diff --git a/internal/domain/ticket.go b/internal/domain/ticket.go new file mode 100644 index 000000000..1fea0352a --- /dev/null +++ b/internal/domain/ticket.go @@ -0,0 +1,105 @@ +package domain + +import ( + "net/url" + "strings" +) + +// Ticket is a change's link to one ticket in an outside ticket system. The +// three values are stored exactly as given and never derived from each other. +type Ticket struct { + Provider string + ID string + URL string +} + +// The three frontmatter keys that hold a change's ticket link. +const ( + TicketFieldProvider = "ticket_provider" + TicketFieldID = "ticket_id" + TicketFieldURL = "ticket_url" +) + +// TicketFields lists the ticket keys in the fixed order every caller reports +// and writes them in. +var TicketFields = []string{TicketFieldProvider, TicketFieldID, TicketFieldURL} + +// TicketProblem names one ticket field that fails validation and the +// reader-facing rule it must meet. +type TicketProblem struct { + Field string + Rule string +} + +const ( + ticketRuleProvider = "a lowercase word: a letter, then letters, digits, or hyphens" + ticketRuleID = "non-empty, on one line" + ticketRuleURL = "an absolute http or https web address" +) + +// ValidateTicket checks every ticket field and returns one problem per failing +// field, in TicketFields order; nil when the ticket is valid. It is the single +// validation rule shared by the decoder, change creation, and ticket linking. +func ValidateTicket(t Ticket) []TicketProblem { + var problems []TicketProblem + if !ValidTypeToken(t.Provider) { + problems = append(problems, TicketProblem{Field: TicketFieldProvider, Rule: ticketRuleProvider}) + } + if strings.TrimSpace(t.ID) == "" || strings.ContainsAny(t.ID, "\r\n") { + problems = append(problems, TicketProblem{Field: TicketFieldID, Rule: ticketRuleID}) + } + if !validTicketURL(t.URL) { + problems = append(problems, TicketProblem{Field: TicketFieldURL, Rule: ticketRuleURL}) + } + return problems +} + +// validTicketURL reports whether s parses as an absolute http or https URL +// with a host. url.Parse lowercases the scheme, so "HTTPS://h/x" is accepted. +func validTicketURL(s string) bool { + u, err := url.Parse(s) + if err != nil || !u.IsAbs() || u.Host == "" { + return false + } + return u.Scheme == "http" || u.Scheme == "https" +} + +// TicketProvider returns the optional ticket provider field. +func (c Change) TicketProvider() OptionalString { return c.spec.TicketProvider } + +// TicketID returns the optional ticket id field. +func (c Change) TicketID() OptionalString { return c.spec.TicketID } + +// TicketURL returns the optional ticket URL field. +func (c Change) TicketURL() OptionalString { return c.spec.TicketURL } + +func (c Change) ticketFieldValues() []OptionalString { + return []OptionalString{c.spec.TicketProvider, c.spec.TicketID, c.spec.TicketURL} +} + +// HasTicketFields reports whether the change carries any ticket field with +// content: a malformed one, or a present one with a non-empty value. +func (c Change) HasTicketFields() bool { + for _, f := range c.ticketFieldValues() { + if f.State == FieldMalformed || (f.State == FieldPresent && f.Value != "") { + return true + } + } + return false +} + +// Ticket returns the change's ticket link. ok is true only when all three +// fields are present, non-empty, and pass ValidateTicket; anything else is +// "not linked" and returns the zero Ticket. +func (c Change) Ticket() (Ticket, bool) { + for _, f := range c.ticketFieldValues() { + if f.State != FieldPresent || f.Value == "" { + return Ticket{}, false + } + } + t := Ticket{Provider: c.spec.TicketProvider.Value, ID: c.spec.TicketID.Value, URL: c.spec.TicketURL.Value} + if ValidateTicket(t) != nil { + return Ticket{}, false + } + return t, true +} diff --git a/internal/domain/ticket_test.go b/internal/domain/ticket_test.go new file mode 100644 index 000000000..67d65cd34 --- /dev/null +++ b/internal/domain/ticket_test.go @@ -0,0 +1,125 @@ +package domain + +import ( + "slices" + "testing" +) + +const fixtureTicketURL = "https://tickets.example.com/browse/CLOUD-123" + +// problemFields returns the Field of each problem, in order. +func problemFields(ps []TicketProblem) []string { + out := make([]string, 0, len(ps)) + for _, p := range ps { + out = append(out, p.Field) + } + return out +} + +func checkTicketField(t *testing.T, field string, valid, invalid []string, mk func(string) Ticket) { + t.Helper() + for _, v := range valid { + if ps := ValidateTicket(mk(v)); ps != nil { + t.Errorf("%s %q: got problems %+v; want none", field, v, ps) + } + } + for _, v := range invalid { + ps := ValidateTicket(mk(v)) + if got := problemFields(ps); !slices.Equal(got, []string{field}) { + t.Errorf("%s %q: got problem fields %v; want [%s]", field, v, got, field) + } + for _, p := range ps { + if p.Rule == "" { + t.Errorf("%s %q: problem has empty Rule", field, v) + } + } + } +} + +func TestValidateTicketProvider(t *testing.T) { + checkTicketField(t, TicketFieldProvider, + []string{"jira", "azure-devops", "x1"}, + []string{"", "JIRA", "1jira", "ji ra", "-x"}, + func(v string) Ticket { return Ticket{Provider: v, ID: "CLOUD-123", URL: fixtureTicketURL} }) +} + +func TestValidateTicketID(t *testing.T) { + checkTicketField(t, TicketFieldID, + []string{"CLOUD-123", " CLOUD-123 "}, + []string{"", " ", "A\nB", "A\rB"}, + func(v string) Ticket { return Ticket{Provider: "jira", ID: v, URL: fixtureTicketURL} }) +} + +func TestValidateTicketURL(t *testing.T) { + checkTicketField(t, TicketFieldURL, + []string{fixtureTicketURL, "http://h/x", "HTTPS://Tickets.Example.com/x"}, + []string{"", "javascript:alert(1)", "/browse/X", "mailto:a@b.c", "https:///x", "ftp://h/x", "tickets.example.com/x"}, + func(v string) Ticket { return Ticket{Provider: "jira", ID: "CLOUD-123", URL: v} }) +} + +func TestValidateTicketReportsEveryBadField(t *testing.T) { + ps := ValidateTicket(Ticket{Provider: "JIRA", ID: "", URL: "x"}) + if got := problemFields(ps); !slices.Equal(got, TicketFields) { + t.Fatalf("problem fields = %v; want %v", got, TicketFields) + } + want := []string{ + "a lowercase word: a letter, then letters, digits, or hyphens", + "non-empty, on one line", + "an absolute http or https web address", + } + for i, p := range ps { + if p.Rule != want[i] { + t.Errorf("problem %d Rule = %q; want %q", i, p.Rule, want[i]) + } + } +} + +func TestTicketFieldsOrder(t *testing.T) { + want := []string{"ticket_provider", "ticket_id", "ticket_url"} + if !slices.Equal(TicketFields, want) { + t.Fatalf("TicketFields = %v; want %v", TicketFields, want) + } +} + +func TestChangeTicketLinkedness(t *testing.T) { + present := func(v string) OptionalString { return OptionalString{State: FieldPresent, Value: v} } + absent := OptionalString{} + empty := OptionalString{State: FieldEmpty} + malformed := OptionalString{State: FieldMalformed, Value: "{a: b}"} + + cases := []struct { + name string + provider, id OptionalString + url OptionalString + wantOK bool + wantHasFields bool + }{ + {"all valid", present("jira"), present("CLOUD-123"), present(fixtureTicketURL), true, true}, + {"two present", present("jira"), present("CLOUD-123"), absent, false, true}, + {"bad url", present("jira"), present("CLOUD-123"), present("javascript:x"), false, true}, + {"all absent", absent, absent, absent, false, false}, + {"all empty", empty, empty, empty, false, false}, + {"one malformed", absent, malformed, absent, false, true}, + {"present but blank value", present(""), absent, absent, false, false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + c := NewChange(ChangeSpec{TicketProvider: tc.provider, TicketID: tc.id, TicketURL: tc.url}) + got, ok := c.Ticket() + if ok != tc.wantOK { + t.Fatalf("Ticket() ok = %v; want %v", ok, tc.wantOK) + } + if ok { + want := Ticket{Provider: tc.provider.Value, ID: tc.id.Value, URL: tc.url.Value} + if got != want { + t.Errorf("Ticket() = %+v; want %+v", got, want) + } + } else if got != (Ticket{}) { + t.Errorf("Ticket() = %+v on not-linked; want zero", got) + } + if h := c.HasTicketFields(); h != tc.wantHasFields { + t.Errorf("HasTicketFields() = %v; want %v", h, tc.wantHasFields) + } + }) + } +} From 959504cf295eb13441b6d5c04fa30df8d105f582 Mon Sep 17 00:00:00 2001 From: Daniel Hanold Date: Mon, 9 Nov 2026 18:07:04 -0500 Subject: [PATCH 03/12] feat(repository): decode ticket fields, warn on a bad link, retire issue --- internal/app/finding_codes.go | 3 + internal/app/testdata/finding-catalog.txt | 10 ++ internal/app/validation_text.go | 28 +++++ internal/app/validation_text_test.go | 23 ++++ internal/domain/actions.go | 1 - internal/domain/entities.go | 4 - internal/domain/entities_test.go | 4 - internal/reposetup/repair.go | 6 +- internal/reposetup/repair_test.go | 21 ++++ internal/repository/decode.go | 83 +++++++++++++- internal/repository/decode_test.go | 134 +++++++++++++++++++++- 11 files changed, 301 insertions(+), 16 deletions(-) diff --git a/internal/app/finding_codes.go b/internal/app/finding_codes.go index 5e9e88e54..3caf88c25 100644 --- a/internal/app/finding_codes.go +++ b/internal/app/finding_codes.go @@ -1,5 +1,7 @@ package app +import "github.com/danielhanold/docket/internal/repository" + // FindingCode is the typed vocabulary of stable machine reasons that surface as // StatusFinding.Code and domain.Finding.Code on the request/result schema. Every // production finding code in package app is minted from a constant declared @@ -367,6 +369,7 @@ var AllFindingCodes = []FindingCode{ FCSectionEditFailed, FindingCode("self-reference"), FCSweepPRFactsUnresolved, + FindingCode(repository.CodeTicketLinkInvalid), FindingCode("unknown-adr"), FindingCode("unknown-change"), FCUnknownDeliverable, diff --git a/internal/app/testdata/finding-catalog.txt b/internal/app/testdata/finding-catalog.txt index b982aabc5..fe15b724e 100644 --- a/internal/app/testdata/finding-catalog.txt +++ b/internal/app/testdata/finding-catalog.txt @@ -334,6 +334,16 @@ docket can't read the frontmatter of `docs/changes/active/0263-x.md`: yaml: line docket skips this record, so it is missing from the board and from every other check. remedy: In `.docket/docs/changes/active/0263-x.md`, fix the frontmatter between the two `---` lines; then commit and push it from `.docket`, and run `docket repository repair` so the board and link blocks catch up. +### ticket-link-invalid — partial (warning) +The change record `docs/changes/active/0263-x.md` has an incomplete or invalid ticket link: `ticket_provider` is missing. +docket treats the change as not linked to a ticket: its Artifacts block shows no Ticket row, and its pull request carries no ticket line. +remedy: Run the `change.link-ticket` operation with all three ticket fields and `replace: true` to set the link, or with `unlink: true` to clear it. + +### ticket-link-invalid — invalid (warning) +The change record `docs/changes/active/0263-x.md` has an incomplete or invalid ticket link: `ticket_url` must be an absolute http or https web address. +docket treats the change as not linked to a ticket: its Artifacts block shows no Ticket row, and its pull request carries no ticket line. +remedy: Run the `change.link-ticket` operation with all three ticket fields and `replace: true` to set the link, or with `unlink: true` to clear it. + ## Remedy locations by layout ### shared checkout diff --git a/internal/app/validation_text.go b/internal/app/validation_text.go index 55399795f..e60ecee6c 100644 --- a/internal/app/validation_text.go +++ b/internal/app/validation_text.go @@ -315,6 +315,27 @@ func deliverableRemedy(f domain.Finding, loc reposetup.RecordLocator) string { return "Revise the change with docket-groom-next, or run `docket change groom` with a revise request, and set its deliverable to pr or results-artifact. To edit it by hand instead: " + lowerFirst(hand) } +// ticketProblems words a ticket-link-invalid finding's Detail: each missing +// field, then each invalid field with the rule it fails. +func ticketProblems(f domain.Finding) string { + var parts []string + if m := f.Detail["missing"]; m != "" { + for _, name := range strings.Split(m, ",") { + parts = append(parts, "`"+name+"` is missing") + } + } + if inv := f.Detail["invalid"]; inv != "" { + for _, entry := range strings.Split(inv, "; ") { + name, rule, _ := strings.Cut(entry, ": ") + parts = append(parts, "`"+name+"` must be "+rule) + } + } + if len(parts) == 0 { + return "`" + f.Field + "` needs fixing" + } + return strings.Join(parts, "; ") +} + // validationTexts is the plain-language table, keyed by validator code. var validationTexts = map[string]validationExplainer{ repository.CodeRecordUndecodable: func(f domain.Finding, loc reposetup.RecordLocator) findingText { @@ -350,6 +371,13 @@ var validationTexts = map[string]validationExplainer{ Remedy: handEdit(f, loc, "set `type:` to "+typeRule+", such as `feature` or `fix`"), } }, + repository.CodeTicketLinkInvalid: func(f domain.Finding, loc reposetup.RecordLocator) findingText { + return findingText{ + Message: fmt.Sprintf("%s has an incomplete or invalid ticket link: %s.", subjectOf(f.Entity), ticketProblems(f)), + Impact: "docket treats the change as not linked to a ticket: its Artifacts block shows no Ticket row, and its pull request carries no ticket line.", + Remedy: "Run the `change.link-ticket` operation with all three ticket fields and `replace: true` to set the link, or with `unlink: true` to clear it.", + } + }, repository.CodeADRStatusUnparseable: func(f domain.Finding, loc reposetup.RecordLocator) findingText { return findingText{ Message: fmt.Sprintf("%s has %s, which isn't an ADR status.", subjectOf(f.Entity), fieldValue("status", f.Detail["raw"])), diff --git a/internal/app/validation_text_test.go b/internal/app/validation_text_test.go index 65b294bcd..629f68ac4 100644 --- a/internal/app/validation_text_test.go +++ b/internal/app/validation_text_test.go @@ -172,6 +172,12 @@ func validationFixtures() map[string][]validationFixture { {"item", f(repository.CodeListItemMalformed, E, fxDecoded(domain.EntityChange, changePath), "depends_on", map[string]string{"raw": "#12", "index": "1"})}, {"raw empty", f(repository.CodeListItemMalformed, E, fxDecoded(domain.EntityChange, changePath), "related", map[string]string{"raw": "", "index": "0"})}, }, + repository.CodeTicketLinkInvalid: { + {"partial", f(repository.CodeTicketLinkInvalid, W, fxDecoded(domain.EntityChange, changePath), "ticket_provider", + map[string]string{"missing": "ticket_provider"})}, + {"invalid", f(repository.CodeTicketLinkInvalid, W, fxDecoded(domain.EntityChange, changePath), "ticket_url", + map[string]string{"invalid": "ticket_url: an absolute http or https web address"})}, + }, repository.CodeChangeTypeInvalid: { {"type", f(repository.CodeChangeTypeInvalid, E, fxDecoded(domain.EntityChange, changePath), "type", map[string]string{"raw": "Big Feature"})}, }, @@ -398,6 +404,23 @@ func TestExplainValidationTypeRuleMatchesValidator(t *testing.T) { } } +// TestExplainValidationTicketLinkNamesOperation pins that a bad ticket set's +// text names the offending field and points at change.link-ticket for both +// the replace and the unlink route. +func TestExplainValidationTicketLinkNamesOperation(t *testing.T) { + for _, x := range validationFixtures()[repository.CodeTicketLinkInvalid] { + got := explainValidation(x.finding, reposetup.RecordLocator{Checkout: ".docket"}) + for _, want := range []string{"change.link-ticket", "replace: true", "unlink: true"} { + if !strings.Contains(got.Remedy, want) { + t.Errorf("%s: Remedy %q lacks %q", x.label, got.Remedy, want) + } + } + if !strings.Contains(got.Message, "`"+x.finding.Field+"`") { + t.Errorf("%s: Message %q does not name `%s`", x.label, got.Message, x.finding.Field) + } + } +} + // TestExplainValidationIDInvalidNeverQuotesPlaceholder pins that an id the // validator reports as 0 (absent, zero, or not a number) is not quoted as a // stored `id: 0`, while a stored negative id is quoted as written. diff --git a/internal/domain/actions.go b/internal/domain/actions.go index 72f749101..8946e7650 100644 --- a/internal/domain/actions.go +++ b/internal/domain/actions.go @@ -467,7 +467,6 @@ func newChangeBuilder(c Change) *changeBuilder { TicketProvider: c.TicketProvider(), TicketID: c.TicketID(), TicketURL: c.TicketURL(), - Issue: c.Issue(), BlockedBy: c.BlockedBy(), Reconciled: c.Reconciled(), Location: c.Location(), diff --git a/internal/domain/entities.go b/internal/domain/entities.go index 39103728c..220e27a94 100644 --- a/internal/domain/entities.go +++ b/internal/domain/entities.go @@ -99,7 +99,6 @@ type ChangeSpec struct { TicketProvider OptionalString // ticket link: see Ticket and ValidateTicket TicketID OptionalString TicketURL OptionalString - Issue OptionalString BlockedBy OptionalString Reconciled bool Location RecordLocation @@ -227,9 +226,6 @@ func (c Change) Branch() OptionalString { return c.spec.Branch } // PR returns the optional pull request reference. func (c Change) PR() OptionalString { return c.spec.PR } -// Issue returns the optional issue reference. -func (c Change) Issue() OptionalString { return c.spec.Issue } - // BlockedBy returns the optional blocking reason. func (c Change) BlockedBy() OptionalString { return c.spec.BlockedBy } diff --git a/internal/domain/entities_test.go b/internal/domain/entities_test.go index 760c227d9..880f73a24 100644 --- a/internal/domain/entities_test.go +++ b/internal/domain/entities_test.go @@ -49,7 +49,6 @@ func fullChangeSpec(t *testing.T) ChangeSpec { TicketProvider: OptionalString{State: FieldPresent, Value: "jira"}, TicketID: OptionalString{State: FieldEmpty}, TicketURL: OptionalString{State: FieldMalformed, Value: "{a: b}"}, - Issue: OptionalString{State: FieldMalformed, Value: "#"}, BlockedBy: OptionalString{State: FieldEmpty}, Reconciled: true, Location: LocationActive, @@ -118,9 +117,6 @@ func TestChangeAccessorsRoundTrip(t *testing.T) { if got := c.PR(); got != spec.PR { t.Errorf("PR() = %+v; want %+v", got, spec.PR) } - if got := c.Issue(); got != spec.Issue { - t.Errorf("Issue() = %+v; want %+v", got, spec.Issue) - } if got := c.TicketProvider(); got != spec.TicketProvider { t.Errorf("TicketProvider() = %+v; want %+v", got, spec.TicketProvider) } diff --git a/internal/reposetup/repair.go b/internal/reposetup/repair.go index a524b17cc..4b3efe376 100644 --- a/internal/reposetup/repair.go +++ b/internal/reposetup/repair.go @@ -106,13 +106,15 @@ var changeListFields = map[string]bool{ // changeStringFields is the set of change-manifest fields the decode layer reads // as free-text strings: decode.go's decodeChange (*decoder).text / // (*decoder).optionalString call sites (slug, title, type, spec, plan, results, -// branch_prefix, branch, pr, issue, blocked_by). Quoting is type-safe only for +// branch_prefix, branch, pr, ticket_provider, ticket_id, ticket_url, +// blocked_by). Quoting is type-safe only for // these — quoting an int/date/bool field would change its decoded type — so the // quote roster is gated on membership here. var changeStringFields = map[string]bool{ "slug": true, "title": true, "type": true, "spec": true, "plan": true, "results": true, "branch_prefix": true, "branch": true, "pr": true, - "issue": true, "blocked_by": true, + "ticket_provider": true, "ticket_id": true, "ticket_url": true, + "blocked_by": true, } // PlanRepairs inspects one change record's bytes and returns the ordered set of diff --git a/internal/reposetup/repair_test.go b/internal/reposetup/repair_test.go index 2df15c119..63514fc6c 100644 --- a/internal/reposetup/repair_test.go +++ b/internal/reposetup/repair_test.go @@ -101,6 +101,27 @@ func TestRepairQuoteScalarRefused(t *testing.T) { } } +// TestRepairQuoteTicketFieldsLikePR pins that the three ticket fields join the +// free-text quote roster exactly like pr:, and that the retired issue: left it. +func TestRepairQuoteTicketFieldsLikePR(t *testing.T) { + const url = "https://tickets.example.com/browse/X" + for _, value := range []string{url, ":30"} { + prFS := planOne(t, "docs/changes/active/0001-x.md", "---\nid: 7\npr: "+value+"\n---\nbody\n") + for _, field := range []string{"ticket_provider", "ticket_id", "ticket_url"} { + fs := planOne(t, "docs/changes/active/0001-x.md", "---\nid: 7\n"+field+": "+value+"\n---\nbody\n") + if got, want := hasRepairableCode(fs, RepairQuoteScalar), hasRepairableCode(prFS, RepairQuoteScalar); got != want { + t.Errorf("%s: %q quote candidate = %v; pr: gives %v", field, value, got, want) + } + } + } + if fs := planOne(t, "docs/changes/active/0001-x.md", "---\nid: 7\nticket_url: :30\n---\nbody\n"); !hasRepairableCode(fs, RepairQuoteScalar) { + t.Errorf("ticket_url: :30 is not a quote candidate: %+v", fs) + } + if fs := planOne(t, "docs/changes/active/0001-x.md", "---\nid: 7\nissue: :30\n---\nbody\n"); len(fs) != 0 { + t.Errorf("retired issue: still planned: %+v", fs) + } +} + func TestRepairScalarToListEligible(t *testing.T) { cases := []struct { name string diff --git a/internal/repository/decode.go b/internal/repository/decode.go index e3bb7debe..f79d60422 100644 --- a/internal/repository/decode.go +++ b/internal/repository/decode.go @@ -31,6 +31,14 @@ const ( CodeADRStatusUnparseable = "adr-status-unparseable" // CodeLearningPromotionUnknown marks an unrecognized promotion state. CodeLearningPromotionUnknown = "learning-promotion-unknown" + // CodeTicketLinkInvalid marks a change carrying some ticket field but not + // a complete, valid ticket link; the change reads as not linked. A warning + // only: a bad hand-edited ticket set never invalidates the record. + // Field is the first offending field; Detail["missing"] comma-joins the + // absent or empty fields and Detail["invalid"] joins ": " + // entries with "; ", each in domain.TicketFields order and omitted when + // none. + CodeTicketLinkInvalid = "ticket-link-invalid" ) // dateLayout is the stored date-only spelling. @@ -123,7 +131,9 @@ type changeWire struct { BranchPrefix scalar `yaml:"branch_prefix"` Branch scalar `yaml:"branch"` PR scalar `yaml:"pr"` - Issue scalar `yaml:"issue"` + TicketProvider scalar `yaml:"ticket_provider"` + TicketID scalar `yaml:"ticket_id"` + TicketURL scalar `yaml:"ticket_url"` BlockedBy scalar `yaml:"blocked_by"` Reconciled scalar `yaml:"reconciled"` } @@ -225,6 +235,72 @@ func (d *decoder) optionalString(name string, s scalar) domain.OptionalString { return domain.OptionalString{State: st, Value: s.raw} } +// ticketString is optionalString for a ticket field, but it never reports +// field-malformed: a non-text value keeps State FieldMalformed and checkTicket +// reports it, at warning severity, inside the one ticket finding. +func (d *decoder) ticketString(name string, s scalar) domain.OptionalString { + st := d.state(name, s) + if st == domain.FieldAbsent { + return domain.OptionalString{} + } + return domain.OptionalString{State: st, Value: s.raw} +} + +// ticketRuleSingleValue is the rule a non-text ticket field fails. +const ticketRuleSingleValue = "a single text value" + +// checkTicket reports one ticket-link-invalid warning when the change carries +// any ticket field with content but not a complete, valid set. The values +// arrive in domain.TicketFields order. +func (d *decoder) checkTicket(provider, id, url domain.OptionalString) { + fields := []domain.OptionalString{provider, id, url} + if !domain.NewChange(domain.ChangeSpec{TicketProvider: provider, TicketID: id, TicketURL: url}).HasTicketFields() { + return + } + bad := make(map[string]string, len(fields)) // field -> rule; "" means missing + var missing []string + for i, f := range fields { + name := domain.TicketFields[i] + switch { + case f.State == domain.FieldMalformed: + bad[name] = ticketRuleSingleValue + case f.State != domain.FieldPresent || f.Value == "": + bad[name] = "" + missing = append(missing, name) + } + } + for _, p := range domain.ValidateTicket(domain.Ticket{Provider: provider.Value, ID: id.Value, URL: url.Value}) { + if _, seen := bad[p.Field]; !seen { + bad[p.Field] = p.Rule + } + } + if len(bad) == 0 { + return + } + var first string + var invalid []string + for _, name := range domain.TicketFields { + rule, ok := bad[name] + if !ok { + continue + } + if first == "" { + first = name + } + if rule != "" { + invalid = append(invalid, name+": "+rule) + } + } + detail := map[string]string{} + if len(missing) > 0 { + detail["missing"] = strings.Join(missing, ",") + } + if len(invalid) > 0 { + detail["invalid"] = strings.Join(invalid, "; ") + } + d.report(CodeTicketLinkInvalid, first, domain.SeverityWarning, detail) +} + // optionalInt converts a scalar into an optional integer field, keeping the // stored text for a value that does not parse. func (d *decoder) optionalInt(name string, s scalar) domain.OptionalInt { @@ -575,7 +651,10 @@ func decodeChange(in InputDocument) (domain.Change, []domain.Finding) { spec.BranchPrefix = d.optionalString("branch_prefix", wire.BranchPrefix) spec.Branch = d.optionalString("branch", wire.Branch) spec.PR = d.optionalString("pr", wire.PR) - spec.Issue = d.optionalString("issue", wire.Issue) + spec.TicketProvider = d.ticketString(domain.TicketFieldProvider, wire.TicketProvider) + spec.TicketID = d.ticketString(domain.TicketFieldID, wire.TicketID) + spec.TicketURL = d.ticketString(domain.TicketFieldURL, wire.TicketURL) + d.checkTicket(spec.TicketProvider, spec.TicketID, spec.TicketURL) spec.BlockedBy = d.optionalString("blocked_by", wire.BlockedBy) spec.Reconciled = d.boolean("reconciled", wire.Reconciled) diff --git a/internal/repository/decode_test.go b/internal/repository/decode_test.go index b449d6c76..7a93d9076 100644 --- a/internal/repository/decode_test.go +++ b/internal/repository/decode_test.go @@ -3,6 +3,7 @@ package repository import ( "crypto/sha256" "encoding/hex" + "reflect" "strings" "testing" "time" @@ -145,9 +146,6 @@ func TestDecodeChangeHappyPath(t *testing.T) { got.Value != "https://github.com/danielhanold/docket/pull/7" { t.Errorf("PR = %+v", got) } - if got := change.Issue(); got.State != domain.FieldPresent || got.Value != "42" { - t.Errorf("Issue = %+v", got) - } if got := change.BlockedBy(); got.State != domain.FieldEmpty { t.Errorf("BlockedBy = %+v", got) } @@ -976,3 +974,133 @@ func TestDecodeChangeHold(t *testing.T) { }) } } + +const ticketFixtureURL = "https://tickets.example.com/browse/CLOUD-123" + +// decodeTicketRecord decodes a minimal change record carrying the given +// frontmatter lines. +func decodeTicketRecord(t *testing.T, lines string) (domain.Change, []domain.Finding) { + t.Helper() + src := "---\nid: 1\nslug: s\n" + lines + "---\n\nbody\n" + return decodeChange(input(t, KindChange, LocationActive, "docs/changes/active/0001-s.md", src)) +} + +// onlyTicketWarning returns the single finding, failing unless it is exactly +// one warning-severity ticket-link-invalid finding. +func onlyTicketWarning(t *testing.T, findings []domain.Finding) domain.Finding { + t.Helper() + if len(findings) != 1 { + t.Fatalf("findings = %v; want exactly one %s", findingCodes(findings), CodeTicketLinkInvalid) + } + f := findings[0] + if f.Code != CodeTicketLinkInvalid || f.Severity != domain.SeverityWarning { + t.Fatalf("finding = %s/%s; want %s/warning", f.Code, f.Severity, CodeTicketLinkInvalid) + } + return f +} + +func TestDecodeTicketCompleteSetLinked(t *testing.T) { + change, findings := decodeTicketRecord(t, + "ticket_provider: jira\nticket_id: CLOUD-123\nticket_url: '"+ticketFixtureURL+"'\n") + if len(findings) != 0 { + t.Fatalf("findings = %v; want none", findingCodes(findings)) + } + got, ok := change.Ticket() + want := domain.Ticket{Provider: "jira", ID: "CLOUD-123", URL: ticketFixtureURL} + if !ok || got != want { + t.Fatalf("Ticket() = %+v, %v; want %+v, true", got, ok, want) + } +} + +func TestDecodeTicketPartialSetWarns(t *testing.T) { + change, findings := decodeTicketRecord(t, "ticket_id: CLOUD-123\nticket_url: '"+ticketFixtureURL+"'\n") + f := onlyTicketWarning(t, findings) + if f.Field != domain.TicketFieldProvider { + t.Errorf("Field = %q; want %q", f.Field, domain.TicketFieldProvider) + } + if f.Detail["missing"] != "ticket_provider" { + t.Errorf("Detail[missing] = %q; want ticket_provider", f.Detail["missing"]) + } + if _, has := f.Detail["invalid"]; has { + t.Errorf("Detail carries invalid %q; want no key", f.Detail["invalid"]) + } + if _, ok := change.Ticket(); ok { + t.Error("Ticket() ok on a partial set") + } +} + +func TestDecodeTicketMissingListsInFieldOrder(t *testing.T) { + _, findings := decodeTicketRecord(t, "ticket_provider: jira\nticket_id:\n") + f := onlyTicketWarning(t, findings) + if f.Detail["missing"] != "ticket_id,ticket_url" { + t.Errorf("Detail[missing] = %q; want ticket_id,ticket_url", f.Detail["missing"]) + } + if f.Field != domain.TicketFieldID { + t.Errorf("Field = %q; want ticket_id", f.Field) + } +} + +func TestDecodeTicketInvalidURLWarns(t *testing.T) { + change, findings := decodeTicketRecord(t, + "ticket_provider: jira\nticket_id: CLOUD-123\nticket_url: 'javascript:alert(1)'\n") + f := onlyTicketWarning(t, findings) + if !strings.HasPrefix(f.Detail["invalid"], "ticket_url: ") { + t.Errorf("Detail[invalid] = %q; want a ticket_url: prefix", f.Detail["invalid"]) + } + if _, has := f.Detail["missing"]; has { + t.Errorf("Detail carries missing %q; want no key", f.Detail["missing"]) + } + if f.Field != domain.TicketFieldURL { + t.Errorf("Field = %q; want ticket_url", f.Field) + } + if _, ok := change.Ticket(); ok { + t.Error("Ticket() ok with an invalid URL") + } +} + +func TestDecodeTicketNonScalarIsWarningOnly(t *testing.T) { + _, findings := decodeTicketRecord(t, "ticket_provider: jira\nticket_id: CLOUD-123\nticket_url: {a: b}\n") + f := onlyTicketWarning(t, findings) + if hasFinding(findings, CodeFieldMalformed, "ticket_url") { + t.Error("a non-text ticket_url raised field-malformed; want the ticket warning only") + } + if f.Detail["invalid"] != "ticket_url: a single text value" { + t.Errorf("Detail[invalid] = %q", f.Detail["invalid"]) + } +} + +func TestDecodeTicketAbsentKeysNoFinding(t *testing.T) { + for name, lines := range map[string]string{ + "absent": "", + "valueless": "ticket_provider:\nticket_id:\nticket_url:\n", + } { + t.Run(name, func(t *testing.T) { + change, findings := decodeTicketRecord(t, lines) + if len(findings) != 0 { + t.Errorf("findings = %v; want none", findingCodes(findings)) + } + if _, ok := change.Ticket(); ok { + t.Error("Ticket() ok with no ticket values") + } + }) + } +} + +// TestDecodeIgnoresRetiredIssueKey pins that the retired issue: key loads +// silently as unknown compatibility data and is no longer decoded. +func TestDecodeIgnoresRetiredIssueKey(t *testing.T) { + if !strings.Contains(happyChange, "\nissue: 42\n") { + t.Fatal("happyChange no longer carries issue: 42") + } + _, findings := decodeChange(input(t, KindChange, LocationActive, + "docs/changes/active/0307-domain-snapshot-validation-graphs-and-selection.md", happyChange)) + if len(findings) != 0 { + t.Errorf("findings = %v; want none", findingCodes(findings)) + } + wire := reflect.TypeOf(changeWire{}) + for i := 0; i < wire.NumField(); i++ { + if wire.Field(i).Tag.Get("yaml") == "issue" { + t.Errorf("changeWire.%s still decodes issue:", wire.Field(i).Name) + } + } +} From a38404b35d28f3778c1fcd7efc9d71f5d1a6e748 Mon Sep 17 00:00:00 2001 From: Daniel Hanold Date: Mon, 9 Nov 2026 18:09:13 -0500 Subject: [PATCH 04/12] feat(render): render the ticket row and a new record's ticket fields --- internal/render/artifacts.go | 32 ++++- internal/render/artifacts_test.go | 124 ++++++++++++++++++ internal/render/record.go | 7 + internal/render/record_test.go | 18 +++ .../render/testdata/records/change.golden.md | 3 + 5 files changed, 181 insertions(+), 3 deletions(-) diff --git a/internal/render/artifacts.go b/internal/render/artifacts.go index e7391bd97..5ff063232 100644 --- a/internal/render/artifacts.go +++ b/internal/render/artifacts.go @@ -20,9 +20,10 @@ const ( // ArtifactBlockContent renders the body of the managed docket:artifacts block — // the table BETWEEN the markers, no marker lines — for one change, from its -// typed fields: Spec, Plan, Results paths and the ADRs list. Rows appear in the -// fixed order Spec, Spec (merged), Plan, Results, ADRs; a row is omitted when -// its field is unset/empty. Empty content ("") means "no artifacts" — the caller +// typed fields: Spec, Plan, Results paths, the ADRs list, and the ticket link. Rows appear in the +// fixed order Spec, Spec (merged), Plan, Results, ADRs, Ticket; a row is +// omitted when its field is unset/empty, and the Ticket row appears only when +// the change is linked (domain.Change.Ticket). Empty content ("") means "no artifacts" — the caller // still writes the (empty) block via document.ReplaceBlock, which supplies the // markers this function omits. // @@ -78,6 +79,10 @@ func ArtifactBlockContent(c domain.Change, snap domain.Snapshot, link LinkContex rows = append(rows, "| ADRs | "+cell+" |") } + if t, ok := c.Ticket(); ok { + rows = append(rows, ticketRow(t)) + } + if len(rows) == 0 { return "", nil } @@ -91,6 +96,27 @@ func ArtifactBlockContent(c domain.Change, snap domain.Snapshot, link LinkContex return b.String(), nil } +// ticketLinkTextReplacer escapes the characters that would end a Markdown +// link text or a table cell early, and flattens line breaks to spaces (the +// boardCellReplacer rule plus the link-text brackets and backslash). +var ticketLinkTextReplacer = strings.NewReplacer( + "\\", "\\\\", "[", "\\[", "]", "\\]", "|", "\\|", + "\r\n", " ", "\n", " ", "\r", " ", +) + +// ticketLinkTargetReplacer percent-encodes the characters that would end a +// Markdown link target or a table cell early. +var ticketLinkTargetReplacer = strings.NewReplacer( + " ", "%20", "(", "%28", ")", "%29", "|", "%7C", "<", "%3C", ">", "%3E", +) + +// ticketRow renders the Ticket row: the ticket id as the link text and the +// ticket URL as the target, each escaped so the row stays one table row with +// a working link. +func ticketRow(t domain.Ticket) string { + return fmt.Sprintf("| Ticket | [%s](%s) |", ticketLinkTextReplacer.Replace(t.ID), ticketLinkTargetReplacer.Replace(t.URL)) +} + // legacyArtifactBranch reports whether a change's plan and results live off // the metadata branch, and on which branch. A closed change WITHOUT the // "## Build evidence" section closed out before plan and results moved to the diff --git a/internal/render/artifacts_test.go b/internal/render/artifacts_test.go index 4723324ad..fefce22e9 100644 --- a/internal/render/artifacts_test.go +++ b/internal/render/artifacts_test.go @@ -573,3 +573,127 @@ func TestArtifactBlockLegacyDonePRUnchanged(t *testing.T) { t.Fatalf("legacy done pr Results row %q missing:\n%s", row, got) } } + +// ticketChange returns fixture A (spec + ADRs) carrying the given ticket +// field values; "" leaves a field absent. +func ticketChange(provider, id, url string) domain.Change { + field := func(v string) domain.OptionalString { + if v == "" { + return domain.OptionalString{} + } + return optString(v) + } + return domain.NewChange(domain.ChangeSpec{ + ID: 7, + Slug: "alpha-change", + Title: "Alpha change", + ADRs: adrIDs(1, 2), + Spec: optString("docs/superpowers/specs/2026-08-16-alpha-change-design.md"), + Location: domain.LocationActive, + Path: "docs/changes/active/0007-alpha-change.md", + TicketProvider: field(provider), + TicketID: field(id), + TicketURL: field(url), + }) +} + +// ticketRows returns the block's lines that are the Ticket row. +func ticketRows(block string) []string { + var rows []string + for _, l := range strings.Split(block, "\n") { + if strings.HasPrefix(l, "| Ticket |") { + rows = append(rows, l) + } + } + return rows +} + +func TestArtifactTicketRow(t *testing.T) { + const url = "https://tickets.example.com/browse/CLOUD-123" + got, err := render.ArtifactBlockContent(ticketChange("jira", "CLOUD-123", url), adrSnapshot(), githubLink) + if err != nil { + t.Fatalf("ArtifactBlockContent: %v", err) + } + lines := strings.Split(strings.TrimSuffix(got, "\n"), "\n") + want := "| Ticket | [CLOUD-123](" + url + ") |" + if last := lines[len(lines)-1]; last != want { + t.Fatalf("last row = %q, want %q\n%s", last, want, got) + } + if prev := lines[len(lines)-2]; !strings.HasPrefix(prev, "| ADRs |") { + t.Fatalf("Ticket row does not follow the ADRs row:\n%s", got) + } + + bare := domain.NewChange(domain.ChangeSpec{ID: 9, Slug: "gamma", Title: "Gamma", Path: "docs/changes/active/0009-gamma.md"}) + empty, err := render.ArtifactBlockContent(bare, domain.Snapshot{}, githubLink) + if err != nil { + t.Fatalf("ArtifactBlockContent: %v", err) + } + if empty != "" { + t.Fatalf("no-field change rendered %q, want \"\"", empty) + } + + onlyTicket := domain.NewChange(domain.ChangeSpec{ + ID: 9, Slug: "gamma", Title: "Gamma", Path: "docs/changes/active/0009-gamma.md", + TicketProvider: optString("jira"), TicketID: optString("CLOUD-123"), TicketURL: optString(url), + }) + solo, err := render.ArtifactBlockContent(onlyTicket, domain.Snapshot{}, relativeLink) + if err != nil { + t.Fatalf("ArtifactBlockContent: %v", err) + } + if wantSolo := "| Artifact | Link |\n|---|---|\n" + want + "\n"; solo != wantSolo { + t.Fatalf("ticket-only block = %q, want %q", solo, wantSolo) + } +} + +func TestArtifactTicketRowAbsentWhenNotLinked(t *testing.T) { + for name, c := range map[string]domain.Change{ + "partial": ticketChange("jira", "CLOUD-123", ""), + "javascript": ticketChange("jira", "CLOUD-123", "javascript:x"), + } { + t.Run(name, func(t *testing.T) { + got, err := render.ArtifactBlockContent(c, adrSnapshot(), githubLink) + if err != nil { + t.Fatalf("ArtifactBlockContent: %v", err) + } + if rows := ticketRows(got); len(rows) != 0 { + t.Fatalf("unlinked change rendered a Ticket row: %q", rows) + } + }) + } +} + +func TestArtifactTicketRowEscapes(t *testing.T) { + c := ticketChange("jira", "A|B]C[", "https://tickets.example.com/a b(c)|d") + got, err := render.ArtifactBlockContent(c, adrSnapshot(), githubLink) + if err != nil { + t.Fatalf("ArtifactBlockContent: %v", err) + } + rows := ticketRows(got) + if len(rows) != 1 { + t.Fatalf("want exactly one Ticket row, got %q\n%s", rows, got) + } + row := rows[0] + for _, want := range []string{`[A\|B\]C\[]`, "(https://tickets.example.com/a%20b%28c%29%7Cd%3Ce%3E)"} { + if !strings.Contains(row, want) { + t.Fatalf("row %q lacks %q", row, want) + } + } + unescaped := strings.Count(row, "|") - strings.Count(row, `\|`) + if unescaped != 3 { + t.Fatalf("row %q holds %d unescaped pipes, want 3", row, unescaped) + } +} + +func TestArtifactTicketRowEscapesBackslash(t *testing.T) { + // A hand-edited id cannot be linked with a line break (ValidateTicket + // refuses it), so this pins the escaper's own flattening through a + // backslash, which a valid id may carry. + c := ticketChange("jira", `A\B`, "https://tickets.example.com/x") + got, err := render.ArtifactBlockContent(c, adrSnapshot(), githubLink) + if err != nil { + t.Fatalf("ArtifactBlockContent: %v", err) + } + if rows := ticketRows(got); len(rows) != 1 || !strings.Contains(rows[0], `[A\\B]`) { + t.Fatalf("backslash not escaped: %q", rows) + } +} diff --git a/internal/render/record.go b/internal/render/record.go index 98acc2f45..d648a2ca1 100644 --- a/internal/render/record.go +++ b/internal/render/record.go @@ -44,6 +44,10 @@ type NewChangeRecord struct { // line; "" writes no section, otherwise "## Why on hold" follows // "## Out of scope". WhyOnHold string + // TicketProvider, TicketID, and TicketURL are the optional ticket link, + // stored as given; "" leaves a field unset (a valueless key), so every + // new record names all three, the way it names pr:. + TicketProvider, TicketID, TicketURL string } // ChangeRecord serializes r as a canonical brand-new proposed change record. @@ -76,6 +80,9 @@ func ChangeRecord(r NewChangeRecord) ([]byte, error) { {Name: "branch_prefix", Value: optionalStringValue(r.BranchPrefix)}, {Name: "branch", Value: document.Null()}, {Name: "pr", Value: document.Null()}, + {Name: domain.TicketFieldProvider, Value: optionalStringValue(r.TicketProvider)}, + {Name: domain.TicketFieldID, Value: optionalStringValue(r.TicketID)}, + {Name: domain.TicketFieldURL, Value: optionalStringValue(r.TicketURL)}, {Name: "blocked_by", Value: document.Null()}, {Name: "reconciled", Value: document.Bool(false)}, } diff --git a/internal/render/record_test.go b/internal/render/record_test.go index ac474586d..87c5d0d5b 100644 --- a/internal/render/record_test.go +++ b/internal/render/record_test.go @@ -387,3 +387,21 @@ func TestChangeRecordHold(t *testing.T) { } } } + +func TestChangeRecordTicketFields(t *testing.T) { + got, err := render.ChangeRecord(render.NewChangeRecord{ + ID: 1, Slug: "s", Title: "T", Type: "feat", Priority: "medium", Created: goldenDate, + Why: "w", WhatChanges: "c", OutOfScope: "oos", + TicketProvider: "jira", TicketID: "CLOUD-123", TicketURL: "https://tickets.example.com/browse/CLOUD-123", + }) + if err != nil { + t.Fatalf("ChangeRecord: %v", err) + } + if _, err := document.Parse(got); err != nil { + t.Fatalf("document.Parse: %v\n%s", err, got) + } + want := "pr:\nticket_provider: 'jira'\nticket_id: 'CLOUD-123'\nticket_url: 'https://tickets.example.com/browse/CLOUD-123'\nblocked_by:\n" + if !strings.Contains(string(got), want) { + t.Fatalf("ticket lines missing or out of order:\n%s", got) + } +} diff --git a/internal/render/testdata/records/change.golden.md b/internal/render/testdata/records/change.golden.md index 1967c10f9..543f82f8f 100644 --- a/internal/render/testdata/records/change.golden.md +++ b/internal/render/testdata/records/change.golden.md @@ -21,6 +21,9 @@ hold: branch_prefix: branch: pr: +ticket_provider: +ticket_id: +ticket_url: blocked_by: reconciled: false --- From 7623a13a9b0c1462863c086cad7842bf3bcefb5b Mon Sep 17 00:00:00 2001 From: Daniel Hanold Date: Mon, 9 Nov 2026 18:11:44 -0500 Subject: [PATCH 05/12] feat(app): accept a ticket link on change.create --- internal/app/change_create.go | 28 ++++++-- internal/app/change_create_test.go | 99 +++++++++++++++++++++++++++++ internal/app/finding_codes.go | 11 ++++ internal/app/finding_codes_test.go | 3 + internal/app/schema_test.go | 6 ++ internal/app/ticket_request.go | 60 +++++++++++++++++ internal/app/ticket_request_test.go | 75 ++++++++++++++++++++++ 7 files changed, 278 insertions(+), 4 deletions(-) create mode 100644 internal/app/ticket_request.go create mode 100644 internal/app/ticket_request_test.go diff --git a/internal/app/change_create.go b/internal/app/change_create.go index 4f039e2f5..0eb7c628d 100644 --- a/internal/app/change_create.go +++ b/internal/app/change_create.go @@ -75,6 +75,12 @@ type ChangeCreateRequest struct { // HoldReason is the optional "## Why on hold" section body, accepted only // with Hold true in the same request. HoldReason string `json:"hold_reason,omitempty"` + // TicketProvider, TicketID, and TicketURL are the optional ticket link: + // all three together or none, each checked by domain.ValidateTicket and + // stored exactly as given. + TicketProvider string `json:"ticket_provider,omitempty"` + TicketID string `json:"ticket_id,omitempty"` + TicketURL string `json:"ticket_url,omitempty"` } // ChangeCreateResult is the protocol-v1 document `change create` returns. It @@ -158,6 +164,11 @@ type changeCreatePayload struct { // AcceptanceCriteria is omitempty and blank-normalized so a request without // it digests exactly as before the field existed and an older retry replays. AcceptanceCriteria string `json:"acceptance_criteria,omitempty"` + // The ticket keys are omitempty so a request without a ticket link digests + // exactly as before the fields existed and an older retry still replays. + TicketProvider string `json:"ticket_provider,omitempty"` + TicketID string `json:"ticket_id,omitempty"` + TicketURL string `json:"ticket_url,omitempty"` } func changeCreateSemanticPayload(req ChangeCreateRequest) changeCreatePayload { @@ -180,6 +191,9 @@ func changeCreateSemanticPayload(req ChangeCreateRequest) changeCreatePayload { HoldReason: req.HoldReason, AcceptanceCriteria: normalizedAcceptanceCriteria(req), + TicketProvider: req.TicketProvider, + TicketID: req.TicketID, + TicketURL: req.TicketURL, } } @@ -420,6 +434,7 @@ func validateChangeCreateShape(req ChangeCreateRequest) []StatusFinding { } } boundAuthored(&findings, "acceptance_criteria", req.AcceptanceCriteria) + findings = append(findings, ticketRequestFindings(req.TicketProvider, req.TicketID, req.TicketURL)...) return findings } @@ -634,6 +649,9 @@ func (o changeCreateOp) Plan(ctx context.Context, st transaction.AttemptState) ( AcceptanceCriteria: normalizedAcceptanceCriteria(o.req), Hold: requestHeld(o.req), WhyOnHold: o.req.HoldReason, + TicketProvider: o.req.TicketProvider, + TicketID: o.req.TicketID, + TicketURL: o.req.TicketURL, }) if err != nil { return transaction.MutationPlan{}, transaction.OperationResult{}, fmt.Errorf("change create: serializing record: %w", err) @@ -645,8 +663,9 @@ func (o changeCreateOp) Plan(ctx context.Context, st transaction.AttemptState) ( // render the board (which must reflect the new change) and to resolve the new // record's ADR references to their paths. It is built only when something // consumes it. + fillArtifacts := len(o.req.ADRs) > 0 || ticketRequestComplete(o.req.TicketProvider, o.req.TicketID, o.req.TicketURL) var candidate domain.Snapshot - if o.inline || len(o.req.ADRs) > 0 { + if o.inline || fillArtifacts { candidate, err = buildCandidateSnapshot(o.eff, st.State.Documents, recordBytes, activePath) if err != nil { return transaction.MutationPlan{}, transaction.OperationResult{}, err @@ -654,10 +673,11 @@ func (o changeCreateOp) Plan(ctx context.Context, st transaction.AttemptState) ( } // Fill the artifact block. A freshly created change has no spec/plan/results, - // so the only possible row is ADRs; when there are none the serializer's empty - // block is already correct. + // so the only possible rows are ADRs and Ticket (shape validation already + // guaranteed a complete ticket link is valid); when there are neither the + // serializer's empty block is already correct. finalBytes := recordBytes - if len(o.req.ADRs) > 0 { + if fillArtifacts { c, out := candidate.Change(newID) if out != domain.LookupFound { return transaction.MutationPlan{}, transaction.OperationResult{}, fmt.Errorf("change create: new record %04d absent from candidate snapshot", int(newID)) diff --git a/internal/app/change_create_test.go b/internal/app/change_create_test.go index d4b772100..6bb55f209 100644 --- a/internal/app/change_create_test.go +++ b/internal/app/change_create_test.go @@ -1044,3 +1044,102 @@ func TestChangeCreateDigestUnchangedWithoutAcceptanceCriteria(t *testing.T) { t.Error("a non-blank acceptance_criteria must change the digest") } } + +func TestChangeCreateTicketShape(t *testing.T) { + req := validChangeCreateRequest() + req.TicketID = "CLOUD-123" + if !hasFindingCode(validateChangeCreateShape(req), string(FCPartialTicket)) { + t.Errorf("a lone ticket_id must emit %s", FCPartialTicket) + } + req.TicketProvider = "jira" + req.TicketURL = testTicketURL + for _, f := range validateChangeCreateShape(req) { + if strings.Contains(f.Code, "ticket") { + t.Errorf("a valid ticket link emitted %s: %s", f.Code, f.Message) + } + } +} + +func TestChangeCreatePlanLinkedRecord(t *testing.T) { + files := map[string]string{ + "docs/changes/active/0001-first.md": fixtureChange(1, "first"), + } + op := baseOp([]string{}) + op.req.TicketProvider = "jira" + op.req.TicketID = "CLOUD-123" + op.req.TicketURL = testTicketURL + plan, opRes := planFor(t, files, op) + if opRes.Refused { + t.Fatalf("unexpected refusal: %v", opRes.Findings) + } + var recordBytes []byte + for _, f := range plan.Files { + if strings.HasSuffix(string(f.Path), "0002-add-a-widget.md") { + recordBytes = f.Bytes + } + } + if recordBytes == nil { + t.Fatal("new record not planned") + } + body := string(recordBytes) + for _, line := range []string{ + "ticket_provider: 'jira'", + "ticket_id: 'CLOUD-123'", + "ticket_url: '" + testTicketURL + "'", + "| Ticket | [CLOUD-123](" + testTicketURL + ") |", + } { + if !strings.Contains(body, line) { + t.Errorf("record missing %q:\n%s", line, body) + } + } +} + +func TestChangeCreateTicketDigestCompatible(t *testing.T) { + // legacyPayload is changeCreatePayload as it stood before the ticket fields. + type legacyPayload struct { + Title string `json:"title"` + Type string `json:"type"` + Priority string `json:"priority"` + Why string `json:"why"` + WhatChanges string `json:"what_changes"` + OutOfScope string `json:"out_of_scope"` + DependsOn []int `json:"depends_on"` + StackedOn *int `json:"stacked_on"` + Related []int `json:"related"` + DiscoveredFrom []int `json:"discovered_from"` + ADRs []int `json:"adrs"` + AutoGroomable *bool `json:"auto_groomable,omitempty"` + BranchPrefix string `json:"branch_prefix,omitempty"` + Deliverable string `json:"deliverable,omitempty"` + Hold bool `json:"hold,omitempty"` + HoldReason string `json:"hold_reason,omitempty"` + AcceptanceCriteria string `json:"acceptance_criteria,omitempty"` + } + req := validChangeCreateRequest() + req.AcceptanceCriteria = "- x" + legacy := legacyPayload{ + Title: req.Title, Type: req.Type, Priority: req.Priority, + Why: req.Why, WhatChanges: req.WhatChanges, OutOfScope: req.OutOfScope, + AcceptanceCriteria: req.AcceptanceCriteria, + } + want, err := json.Marshal(legacy) + if err != nil { + t.Fatalf("marshal legacy: %v", err) + } + got, err := json.Marshal(changeCreateSemanticPayload(req)) + if err != nil { + t.Fatalf("marshal: %v", err) + } + if string(got) != string(want) { + t.Errorf("payload without ticket fields = %s, want the pre-field %s", got, want) + } + linked := req + linked.TicketProvider, linked.TicketID, linked.TicketURL = "jira", "CLOUD-123", testTicketURL + withTicket, err := json.Marshal(changeCreateSemanticPayload(linked)) + if err != nil { + t.Fatalf("marshal: %v", err) + } + if string(withTicket) == string(want) { + t.Error("a ticket link must change the digest payload") + } +} diff --git a/internal/app/finding_codes.go b/internal/app/finding_codes.go index 3caf88c25..f3fb2cecb 100644 --- a/internal/app/finding_codes.go +++ b/internal/app/finding_codes.go @@ -181,6 +181,13 @@ const ( // usable as the "## Acceptance criteria" section body. FCInvalidAcceptanceCriteria FindingCode = "invalid-acceptance_criteria" + // Ticket link request findings (change.create): the three ticket fields + // come together or not at all, and each must pass domain.ValidateTicket. + FCPartialTicket FindingCode = "partial-ticket" + FCInvalidTicketProvider FindingCode = "invalid-ticket-provider" + FCInvalidTicketID FindingCode = "invalid-ticket-id" + FCInvalidTicketURL FindingCode = "invalid-ticket-url" + // Install-maintenance findings. collection-pending is the reason an explicit // `install collect` reports and the warning code an automatic post-install // collection surfaces when a version tree could not be reclaimed; the primary @@ -339,6 +346,9 @@ var AllFindingCodes = []FindingCode{ FCInvalidStackedOn, FindingCode("invalid-successor-id"), FCInvalidTargetID, + FCInvalidTicketID, + FCInvalidTicketProvider, + FCInvalidTicketURL, FCInvalidTitle, FCInvalidTopics, FCInvalidType, @@ -356,6 +366,7 @@ var AllFindingCodes = []FindingCode{ FCNotRetitleable, FCNothingToReEnable, FCParseFailed, + FCPartialTicket, FCPathMismatch, FindingCode("pr-recorded"), FCPrepareLocalStateUnknown, diff --git a/internal/app/finding_codes_test.go b/internal/app/finding_codes_test.go index d11b1b98d..b508f883f 100644 --- a/internal/app/finding_codes_test.go +++ b/internal/app/finding_codes_test.go @@ -226,6 +226,8 @@ func TestShapeValidatorCodesAreRegistered(t *testing.T) { emitted = append(emitted, validateChangeCreateShape(ChangeCreateRequest{BranchPrefix: "a/b"})...) emitted = append(emitted, validateChangeCreateShape(ChangeCreateRequest{Title: "a\nb"})...) emitted = append(emitted, validateChangeCreateShape(ChangeCreateRequest{AcceptanceCriteria: "x\n## H\n"})...) + emitted = append(emitted, validateChangeCreateShape(ChangeCreateRequest{TicketID: "X-1"})...) + emitted = append(emitted, validateChangeCreateShape(ChangeCreateRequest{TicketProvider: "JIRA", TicketID: " ", TicketURL: "x"})...) emitted = append(emitted, validateADRRecordShape(adrContent)...) emitted = append(emitted, validateADRReplaceShape(ADRReplaceRequest{Target: ADRTarget{ID: 0}, Successor: adrContent})...) emitted = append(emitted, validateLearningRecordShape(LearningRecordRequest{Topics: []string{""}})...) @@ -274,6 +276,7 @@ func TestShapeValidatorCodesAreRegistered(t *testing.T) { FCInvalidPRNumber, FCInvalidAttempt, FCEmptyHead, FCInvalidPriority, FCUnknownPriority, FCInvalidHold, FCHoldReasonWithoutHold, FCInvalidHoldReason, FCInvalidAcceptanceCriteria, + FCPartialTicket, FCInvalidTicketProvider, FCInvalidTicketID, FCInvalidTicketURL, } for _, c := range floor { if !seen[string(c)] { diff --git a/internal/app/schema_test.go b/internal/app/schema_test.go index d1b6ef31e..ba7faa1db 100644 --- a/internal/app/schema_test.go +++ b/internal/app/schema_test.go @@ -159,6 +159,7 @@ func TestReflectDescriptorChangeCreateRequest(t *testing.T) { "why", "what_changes", "acceptance_criteria", "out_of_scope", "depends_on", "stacked_on", "related", "discovered_from", "adrs", "auto_groomable", "branch_prefix", "hold", "hold_reason", + "ticket_provider", "ticket_id", "ticket_url", } if !reflect.DeepEqual(keys, want) { t.Fatalf("keys = %v, want %v", keys, want) @@ -193,6 +194,11 @@ func TestReflectDescriptorChangeCreateRequest(t *testing.T) { if f := fieldByKey(t, d, "acceptance_criteria"); f.Required || f.Repeated || f.Type != "string" { t.Errorf("acceptance_criteria = %+v, want optional non-repeated string", f) } + for _, k := range []string{"ticket_provider", "ticket_id", "ticket_url"} { + if f := fieldByKey(t, d, k); f.Required || f.Repeated || f.Type != "string" { + t.Errorf("%s = %+v, want optional non-repeated string", k, f) + } + } // Required set per Task 4's tags. wantRequired := map[string]bool{ diff --git a/internal/app/ticket_request.go b/internal/app/ticket_request.go new file mode 100644 index 000000000..6159535be --- /dev/null +++ b/internal/app/ticket_request.go @@ -0,0 +1,60 @@ +package app + +import ( + "fmt" + "strings" + + "github.com/danielhanold/docket/internal/domain" +) + +// ticketRequestFindings checks a request's ticket link: the three fields come +// together or not at all, and a complete set must pass domain.ValidateTicket. +// A field counts as given when it is non-empty. No field given yields nil; one +// or two given yields a single partial-ticket finding naming the missing keys; +// all three given yields one finding per failing field, in +// domain.TicketFields order. +func ticketRequestFindings(provider, id, url string) []StatusFinding { + values := map[string]string{ + domain.TicketFieldProvider: provider, + domain.TicketFieldID: id, + domain.TicketFieldURL: url, + } + var missing []string + for _, key := range domain.TicketFields { + if values[key] == "" { + missing = append(missing, key) + } + } + switch len(missing) { + case len(domain.TicketFields): + return nil + case 0: + default: + return []StatusFinding{{ + Code: string(FCPartialTicket), + Severity: string(domain.SeverityError), + Message: fmt.Sprintf("a ticket link needs all of %s together; missing %s", + strings.Join(domain.TicketFields, ", "), strings.Join(missing, ", ")), + }} + } + + codes := map[string]FindingCode{ + domain.TicketFieldProvider: FCInvalidTicketProvider, + domain.TicketFieldID: FCInvalidTicketID, + domain.TicketFieldURL: FCInvalidTicketURL, + } + var findings []StatusFinding + for _, p := range domain.ValidateTicket(domain.Ticket{Provider: provider, ID: id, URL: url}) { + findings = append(findings, StatusFinding{ + Code: string(codes[p.Field]), + Severity: string(domain.SeverityError), + Message: fmt.Sprintf("%s must be %s", p.Field, p.Rule), + }) + } + return findings +} + +// ticketRequestComplete reports whether all three ticket fields are given. +func ticketRequestComplete(provider, id, url string) bool { + return provider != "" && id != "" && url != "" +} diff --git a/internal/app/ticket_request_test.go b/internal/app/ticket_request_test.go new file mode 100644 index 000000000..e7cae6296 --- /dev/null +++ b/internal/app/ticket_request_test.go @@ -0,0 +1,75 @@ +package app + +import ( + "reflect" + "strings" + "testing" +) + +const testTicketURL = "https://tickets.example.com/browse/CLOUD-123" + +func ticketCodes(findings []StatusFinding) []string { + var codes []string + for _, f := range findings { + codes = append(codes, f.Code) + } + return codes +} + +func TestTicketRequestFindings(t *testing.T) { + cases := []struct { + name string + provider, id, url string + want []string + }{ + {"none", "", "", "", nil}, + {"missing id", "jira", "", testTicketURL, []string{string(FCPartialTicket)}}, + {"missing url", "jira", "CLOUD-123", "", []string{string(FCPartialTicket)}}, + {"only url", "", "", testTicketURL, []string{string(FCPartialTicket)}}, + {"valid", "jira", "CLOUD-123", testTicketURL, nil}, + {"bad provider", "JIRA", "CLOUD-123", testTicketURL, []string{string(FCInvalidTicketProvider)}}, + {"blank id", "jira", " ", testTicketURL, []string{string(FCInvalidTicketID)}}, + {"relative url", "jira", "CLOUD-123", "/browse/X", []string{string(FCInvalidTicketURL)}}, + {"all bad", "JIRA", " ", "x", []string{string(FCInvalidTicketProvider), string(FCInvalidTicketID), string(FCInvalidTicketURL)}}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + got := ticketRequestFindings(tc.provider, tc.id, tc.url) + if codes := ticketCodes(got); !reflect.DeepEqual(codes, tc.want) { + t.Fatalf("codes = %v, want %v", codes, tc.want) + } + for _, f := range got { + if f.Severity != "error" { + t.Errorf("finding %q severity = %q, want error", f.Code, f.Severity) + } + if f.Message == "" { + t.Errorf("finding %q has an empty message", f.Code) + } + } + }) + } +} + +func TestTicketRequestFindingsNameTheKeys(t *testing.T) { + partial := ticketRequestFindings("jira", "", "") + if len(partial) != 1 || !strings.Contains(partial[0].Message, "ticket_id") || !strings.Contains(partial[0].Message, "ticket_url") { + t.Errorf("partial-ticket message must name the missing keys: %+v", partial) + } + if strings.Contains(partial[0].Message, "ticket_provider is missing") { + t.Errorf("partial-ticket message names a given key as missing: %q", partial[0].Message) + } + for _, f := range ticketRequestFindings("JIRA", " ", "x") { + var key string + switch f.Code { + case string(FCInvalidTicketProvider): + key = "ticket_provider" + case string(FCInvalidTicketID): + key = "ticket_id" + case string(FCInvalidTicketURL): + key = "ticket_url" + } + if !strings.Contains(f.Message, key) { + t.Errorf("finding %q message %q does not name %s", f.Code, f.Message, key) + } + } +} From 4469a56b7c28dec99059cc1e145837979e835d6d Mon Sep 17 00:00:00 2001 From: Daniel Hanold Date: Mon, 9 Nov 2026 18:19:30 -0500 Subject: [PATCH 06/12] feat(app): add change.link-ticket to link, replace, and unlink a ticket --- internal/app/change_link_ticket.go | 408 ++++++++++++++++++ .../change_link_ticket_integration_test.go | 75 ++++ internal/app/change_link_ticket_test.go | 340 +++++++++++++++ internal/app/finding_codes.go | 11 + internal/app/schema_registry.go | 1 + internal/app/schema_revision_test.go | 2 +- internal/app/schema_tags_test.go | 3 + internal/app/schema_vocab.go | 4 + internal/app/schema_vocab_test.go | 1 + internal/app/shadow_test.go | 1 + internal/cli/change.go | 8 +- internal/cli/change_test.go | 5 +- internal/cli/install.go | 1 + 13 files changed, 856 insertions(+), 4 deletions(-) create mode 100644 internal/app/change_link_ticket.go create mode 100644 internal/app/change_link_ticket_integration_test.go create mode 100644 internal/app/change_link_ticket_test.go diff --git a/internal/app/change_link_ticket.go b/internal/app/change_link_ticket.go new file mode 100644 index 000000000..f5c83dd7d --- /dev/null +++ b/internal/app/change_link_ticket.go @@ -0,0 +1,408 @@ +package app + +import ( + "context" + "encoding/json" + "fmt" + "path" + "strings" + + "github.com/danielhanold/docket/internal/config" + "github.com/danielhanold/docket/internal/document" + "github.com/danielhanold/docket/internal/domain" + "github.com/danielhanold/docket/internal/gitcli" + "github.com/danielhanold/docket/internal/render" + "github.com/danielhanold/docket/internal/repository/transaction" +) + +// This file is `change link-ticket`: the operation that links one change to +// one ticket in an outside ticket system, replaces that link, or clears it. +// A ticket link is three frontmatter fields stored exactly as given — +// ticket_provider, ticket_id, and ticket_url — and the op never contacts the +// ticket system; it only records what the caller sends. +// +// The request pins the exact record revision, like the lifecycle ops. It runs +// in one of two modes: +// +// - link: all three fields, each passing domain.ValidateTicket. A record +// with no ticket fields is linked. A record already carrying this exact +// link is a no-op (already-linked). A record carrying a different link, +// or ticket fields that do not form a valid link, is refused +// (already-linked-elsewhere) unless the request says replace: true. +// Replace happens only on an explicit request. A human may make that +// request in plain words ("point it at CLOUD-2 instead"), but an agent +// never sets replace on its own initiative to get past the refusal. +// - unlink: unlink: true and no ticket field. Every ticket key the record +// carries is set to an empty value (an absent key is never inserted); a +// record with no ticket values is a no-op (nothing-to-unlink). +// +// Status never refuses: a done or killed record in the archive is linked the +// same way as an active one. Each write also refreshes updated:, re-renders +// the artifact block (its Ticket row), and the inline board. + +// OperationChangeLinkTicket is the operation key `change link-ticket` records +// in its result envelope and its transaction trailer. +const OperationChangeLinkTicket = "change.link-ticket" + +// The closed disposition set `change link-ticket` reports. +const ( + // LinkTicketDispLinked: a record with no ticket fields was linked. + LinkTicketDispLinked = "linked" + // LinkTicketDispAlreadyLinked: the record already carries exactly this + // link; nothing was written. + LinkTicketDispAlreadyLinked = "already-linked" + // LinkTicketDispReplaced: an existing link (or a broken set of ticket + // fields) was replaced on an explicit replace request. + LinkTicketDispReplaced = "replaced" + // LinkTicketDispUnlinked: the record's ticket fields were cleared. + LinkTicketDispUnlinked = "unlinked" + // LinkTicketDispNothingToUnlink: the record carries no ticket value; + // nothing was written. + LinkTicketDispNothingToUnlink = "nothing-to-unlink" +) + +// ChangeLinkTicketRequest is the closed, caller-supplied request for one +// link, replace, or unlink. Path and Revision pin the exact submitted record. +// A ticket field counts as given when it is non-empty. +type ChangeLinkTicketRequest struct { + ChangeID int `json:"change_id" docket:"required"` + Path string `json:"path" docket:"required"` + Revision string `json:"revision" docket:"required"` + TicketProvider string `json:"ticket_provider,omitempty"` + TicketID string `json:"ticket_id,omitempty"` + TicketURL string `json:"ticket_url,omitempty"` + Replace bool `json:"replace,omitempty"` + Unlink bool `json:"unlink,omitempty"` +} + +// ChangeLinkTicketResult is the protocol-v1 document `change link-ticket` +// returns. Findings is present on every path (marshalled as [] never null). +type ChangeLinkTicketResult struct { + Envelope + ID int `json:"id,omitempty" docket:"success-only"` + Disposition string `json:"disposition,omitempty" docket:"enum=link_ticket_dispositions"` + Revision string `json:"committed_revision,omitempty" docket:"success-only"` + Findings []StatusFinding `json:"findings"` +} + +// HumanText renders one line on an applied or no-op result; otherwise the +// operation and result, followed by each finding's message on its own +// indented line. +func (r ChangeLinkTicketResult) HumanText() string { + switch r.Result { + case ResultApplied, ResultNoOp: + line := fmt.Sprintf("%s: change %04d %s", r.Operation, r.ID, r.Disposition) + if r.Revision != "" { + line += " — " + r.Revision + } + return line + default: + var b strings.Builder + fmt.Fprintf(&b, "%s: %s", r.Operation, r.Result) + for _, f := range r.Findings { + if f.Message != "" { + b.WriteString("\n " + f.Message) + } + } + return b.String() + } +} + +// newChangeLinkTicketResult stamps the envelope and normalizes Findings so the +// array marshals as [] on every path. +func newChangeLinkTicketResult(result Result, r ChangeLinkTicketResult) ChangeLinkTicketResult { + r.Envelope = NewEnvelope(OperationChangeLinkTicket, result) + if r.Findings == nil { + r.Findings = []StatusFinding{} + } + return r +} + +// changeLinkTicketReceipt is the canonical receipt persisted with a +// link-ticket commit. Field order is alphabetical for the engine's +// canonical-form validator. +type changeLinkTicketReceipt struct { + Disposition string `json:"disposition"` + ID int `json:"id"` + Op string `json:"op"` +} + +// validateLinkTicketRequest runs the request checks that need no repository, +// in order, stopping at the first group that finds anything: the pinned +// identity, the unlink/ticket-field conflict, an empty link request, then the +// ticket fields themselves. +func validateLinkTicketRequest(req ChangeLinkTicketRequest) []StatusFinding { + if findings := validateLifecycleShape("change_id", req.ChangeID, req.Path, req.Revision); len(findings) > 0 { + return findings + } + anyField := req.TicketProvider != "" || req.TicketID != "" || req.TicketURL != "" + if req.Unlink { + if anyField || req.Replace { + return []StatusFinding{lifecycleFinding(FCUnlinkWithTicket, + "unlink clears the ticket link, so it takes no ticket field and no replace")} + } + return nil + } + if !anyField { + return []StatusFinding{lifecycleFinding(FCEmptyTicketRequest, + "send ticket_provider, ticket_id, and ticket_url to link a ticket, or unlink: true to clear the link")} + } + return ticketRequestFindings(req.TicketProvider, req.TicketID, req.TicketURL) +} + +// ChangeLinkTicket validates the request, pins authoritative context, and +// drives one exact-revision transaction that links, replaces, or clears the +// change's ticket link. Every failure that predates the transaction (a bad +// request, a github board surface) returns without an engine call. +func ChangeLinkTicket(ctx context.Context, deps PlanningDeps, repoDir string, req ChangeLinkTicketRequest) ChangeLinkTicketResult { + if findings := validateLinkTicketRequest(req); len(findings) > 0 { + return newChangeLinkTicketResult(ResultInvalidInput, ChangeLinkTicketResult{Findings: findings}) + } + + pin, err := deps.Reader.PinContext(ctx, repoDir) + if err != nil { + result, reason := classifyStatusError(ctx, err) + return newChangeLinkTicketResult(result, ChangeLinkTicketResult{Findings: []StatusFinding{lifecycleFinding(FindingCode(reason), err.Error())}}) + } + eff := pin.Config.Effective + + inline, err := resolveBoardSurface(eff) + if err != nil { + if pe, ok := asPlanningError(err); ok { + return newChangeLinkTicketResult(pe.Result, ChangeLinkTicketResult{Findings: []StatusFinding{lifecycleFinding(FindingCode(pe.Reason), pe.Message)}}) + } + return newChangeLinkTicketResult(ResultInternalError, ChangeLinkTicketResult{Findings: []StatusFinding{lifecycleFinding(FindingCode(ReasonStatusInternalError), err.Error())}}) + } + + repo, err := deps.Client.Discover(ctx, gitcli.DiscoverOptions{InvocationPath: repoDir}) + if err != nil { + result, reason := classifyStatusError(ctx, classifyGitFailure(err)) + return newChangeLinkTicketResult(result, ChangeLinkTicketResult{Findings: []StatusFinding{lifecycleFinding(FindingCode(reason), err.Error())}}) + } + + op := changeLinkTicketOp{ + changeID: req.ChangeID, + path: req.Path, + ticket: domain.Ticket{Provider: req.TicketProvider, ID: req.TicketID, URL: req.TicketURL}, + replace: req.Replace, + unlink: req.Unlink, + eff: eff, + clock: deps.Clock, + inline: inline, + link: linkContextOf(pin), + changesDir: eff.ChangesDir.Value, + } + res, execErr := deps.Engine.Execute(ctx, transaction.Request{ + Repository: repo, + Remote: metadataRemote(pin.Layout), + TargetRef: metadataRef(pin.Layout), + Expected: []transaction.EntityExpectation{{ + Path: gitcli.RepoPath(req.Path), + Revision: transaction.ExpectedRevision{Kind: transaction.RevisionBlob, ObjectID: gitcli.ObjectID(req.Revision)}, + }}, + Loader: newPlanningLoader(eff), + Scope: changeScope(req.ChangeID, req.Path, false), + Operation: op, + }) + return linkTicketResultFromOutcome(req, res, execErr) +} + +// linkTicketResultFromOutcome folds a transaction outcome into the result +// document. An applied result takes its disposition from the receipt; a no-op +// (the only empty plans are already-linked and nothing-to-unlink) takes it +// from the request's mode; a refusal is state-shaped and shows each +// refusal's own sentence. +func linkTicketResultFromOutcome(req ChangeLinkTicketRequest, res transaction.Result, execErr error) ChangeLinkTicketResult { + result, _ := mapOutcome(res, execErr, ResultInvalidState) + + out := ChangeLinkTicketResult{Findings: findingsToStatus(res.Findings)} + for i, f := range res.Findings { + if msg := f.Detail["message"]; msg != "" { + out.Findings[i].Message = msg + } + } + switch result { + case ResultApplied: + out.ID = req.ChangeID + var rec changeLinkTicketReceipt + if len(res.Receipt) > 0 && json.Unmarshal(res.Receipt, &rec) == nil { + out.ID = rec.ID + out.Disposition = rec.Disposition + } + out.Revision = string(res.AppliedCommit) + case ResultNoOp: + out.ID = req.ChangeID + out.Disposition = LinkTicketDispAlreadyLinked + if req.Unlink { + out.Disposition = LinkTicketDispNothingToUnlink + } + } + r := newChangeLinkTicketResult(result, out) + r.Failure = failureStatus(res, execErr) + return r +} + +// changeLinkTicketOp is the SemanticOperation the engine drives per attempt. +// Every field is fixed before the transaction; the decision whether to write +// re-runs from the attempt's own fresh state. +type changeLinkTicketOp struct { + changeID int + path string + ticket domain.Ticket + replace bool + unlink bool + eff config.Effective + clock transaction.Clock + inline bool + link render.LinkContext + changesDir string +} + +func (o changeLinkTicketOp) Key() transaction.OperationKey { + return transaction.OperationKey(OperationChangeLinkTicket) +} + +// Plan decides from the attempt's snapshot whether the request writes, and +// with which disposition, then writes the ticket fields, the refreshed +// updated date, the re-rendered artifact block, and the inline board. +func (o changeLinkTicketOp) Plan(ctx context.Context, st transaction.AttemptState) (transaction.MutationPlan, transaction.OperationResult, error) { + c, out := st.State.Snapshot.Change(domain.ChangeID(o.changeID)) + if out != domain.LookupFound { + return refuseLifecycle(FCNotFound, fmt.Sprintf("change %04d is not present in the current corpus", o.changeID)) + } + if c.Path() != o.path { + return refuseLifecycle(FCPathMismatch, + fmt.Sprintf("change %04d's record is at %q, not the requested %q", o.changeID, c.Path(), o.path)) + } + src, ok := st.State.Sources[c.Path()] + if !ok { + return refuseLifecycle(FCPathMismatch, + fmt.Sprintf("no record source loaded at %q for change %04d", c.Path(), o.changeID)) + } + + var ( + disposition string + values map[string]document.Value + ) + if o.unlink { + if !c.HasTicketFields() { + return o.noOpPlan(LinkTicketDispNothingToUnlink) + } + doc, err := document.Parse(src) + if err != nil { + return transaction.MutationPlan{}, transaction.OperationResult{}, fmt.Errorf("link ticket: parsing record: %w", err) + } + values = map[string]document.Value{} + for _, key := range domain.TicketFields { + if _, present := doc.Field(key); present { + values[key] = document.Null() + } + } + disposition = LinkTicketDispUnlinked + } else { + current, linked := c.Ticket() + switch { + case linked && current == o.ticket: + return o.noOpPlan(LinkTicketDispAlreadyLinked) + case linked || c.HasTicketFields(): + if !o.replace { + return refuseLifecycle(FCAlreadyLinkedElsewhere, alreadyLinkedElsewhereMessage(o.changeID, current, linked)) + } + disposition = LinkTicketDispReplaced + default: + disposition = LinkTicketDispLinked + } + values = map[string]document.Value{ + domain.TicketFieldProvider: document.String(o.ticket.Provider), + domain.TicketFieldID: document.String(o.ticket.ID), + domain.TicketFieldURL: document.String(o.ticket.URL), + } + } + + // Each field gets its own parse/apply cycle: inserted fields would + // otherwise collide at the pre-fence insertion point (see + // changeRelinkOp.Plan). + intermediate := src + for _, key := range domain.TicketFields { + v, ok := values[key] + if !ok { + continue + } + var err error + intermediate, err = upsertFieldBytes(intermediate, key, v) + if err != nil { + return transaction.MutationPlan{}, transaction.OperationResult{}, fmt.Errorf("link ticket: patching %s: %w", key, err) + } + } + intermediate, err := upsertFieldBytes(intermediate, "updated", document.String(o.clock.Now().UTC().Format("2006-01-02"))) + if err != nil { + return transaction.MutationPlan{}, transaction.OperationResult{}, fmt.Errorf("link ticket: stamping updated: %w", err) + } + + candidate, err := buildGroomCandidate(o.eff, st.State.Documents, c.Path(), intermediate) + if err != nil { + return transaction.MutationPlan{}, transaction.OperationResult{}, err + } + gc, gout := candidate.Change(domain.ChangeID(o.changeID)) + if gout != domain.LookupFound { + return transaction.MutationPlan{}, transaction.OperationResult{}, fmt.Errorf("link ticket: mutated record %04d absent from candidate snapshot", o.changeID) + } + body, err := render.ArtifactBlockContent(gc, candidate, o.link) + if err != nil { + return refuseLifecycle(FCArtifactRenderFailed, err.Error()) + } + doc2, err := document.Parse(intermediate) + if err != nil { + return transaction.MutationPlan{}, transaction.OperationResult{}, fmt.Errorf("link ticket: reparsing patched record: %w", err) + } + var ps document.PatchSet + ps.ReplaceBlock("artifacts", body) + finalBytes, err := doc2.Apply(ps) + if err != nil { + return transaction.MutationPlan{}, transaction.OperationResult{}, fmt.Errorf("link ticket: writing artifact block: %w", err) + } + + files := []transaction.FileMutation{ + {Path: gitcli.RepoPath(c.Path()), Kind: transaction.MutationReplace, Bytes: finalBytes}, + } + if o.inline { + boardPath := path.Join(o.changesDir, "BOARD.md") + if err := includeBoard(ctx, st.Tree, boardPath, candidate, boardUnrenderable(st.State, o.changesDir), boardPresentation(o.eff), &files); err != nil { + return transaction.MutationPlan{}, transaction.OperationResult{}, fmt.Errorf("link ticket: %w", err) + } + } + + return o.plan(files, disposition) +} + +// noOpPlan is the empty plan the engine reports as a no-op. It writes no file, +// but the engine still validates the plan, which needs a commit subject and a +// receipt. +func (o changeLinkTicketOp) noOpPlan(disposition string) (transaction.MutationPlan, transaction.OperationResult, error) { + return o.plan(nil, disposition) +} + +// plan assembles the mutation plan for files under disposition: its receipt +// and its commit subject. +func (o changeLinkTicketOp) plan(files []transaction.FileMutation, disposition string) (transaction.MutationPlan, transaction.OperationResult, error) { + receipt, err := json.Marshal(changeLinkTicketReceipt{Disposition: disposition, ID: o.changeID, Op: OperationChangeLinkTicket}) + if err != nil { + return transaction.MutationPlan{}, transaction.OperationResult{}, fmt.Errorf("link ticket: encoding receipt: %w", err) + } + return transaction.MutationPlan{ + Files: files, + CommitSubject: fmt.Sprintf("change %04d ticket %s", o.changeID, disposition), + Receipt: receipt, + }, transaction.OperationResult{}, nil +} + +// alreadyLinkedElsewhereMessage explains a refused link over an existing one +// and the only way past it: a replace the human asked for. +func alreadyLinkedElsewhereMessage(id int, current domain.Ticket, linked bool) string { + what := "ticket fields that do not form a valid link" + if linked { + what = fmt.Sprintf("a link to ticket %s (%s)", current.ID, current.URL) + } + return fmt.Sprintf("change %04d already carries %s. To replace it, send the request again with replace: true — "+ + "but only when the human asked for the replacement, never on your own initiative.", id, what) +} diff --git a/internal/app/change_link_ticket_integration_test.go b/internal/app/change_link_ticket_integration_test.go new file mode 100644 index 000000000..5a7db62c4 --- /dev/null +++ b/internal/app/change_link_ticket_integration_test.go @@ -0,0 +1,75 @@ +//go:build integration + +package app + +// Real-git end-to-end test for change.link-ticket, run by +// tests/test_go_integration_app_recordops.sh (prefix ^TestIntegrationRecordOps). + +import ( + "context" + "strings" + "testing" +) + +func TestIntegrationRecordOpsChangeLinkTicketEndToEnd(t *testing.T) { + requireRealGit(t) + recPath := groomPath(7, "widget") + archived := "docs/changes/archive/2026-10-01-0008-gadget.md" + repo := newWorkingRepo(t, map[string]string{ + recPath: lifecycleChange(7, "widget", "in-progress"), + archived: lifecycleChange(8, "gadget", "done"), + }) + node := planningDepsFor(t, repo.invocation) + link := func(id int, p, revision string, unlink bool) ChangeLinkTicketResult { + req := ChangeLinkTicketRequest{ChangeID: id, Path: p, Revision: revision, Unlink: unlink} + if !unlink { + req.TicketProvider, req.TicketID, req.TicketURL = "jira", "CLOUD-123", ticketTestURL + } + return ChangeLinkTicket(context.Background(), node.deps, node.dir, req) + } + + // Link: applied, linked, exactly one new metadata commit. + tip0 := originTip(t, repo.origin, "docket") + rev0 := blobRevisionAt(t, repo.origin, "docket", recPath) + res := link(7, recPath, rev0, false) + if res.Result != ResultApplied || res.Disposition != LinkTicketDispLinked { + t.Fatalf("link = %q %q (findings %v), want applied linked", res.Result, res.Disposition, res.Findings) + } + tip1 := originTip(t, repo.origin, "docket") + if parent := runGit(t, repo.origin, "rev-parse", tip1+"^"); parent != tip0 { + t.Errorf("link did not advance the metadata branch by exactly one commit: %s^ = %s, want %s", tip1, parent, tip0) + } + if rec, _ := originFile(t, repo.origin, "docket", recPath); !strings.Contains(rec, "ticket_id: 'CLOUD-123'") { + t.Errorf("linked record on origin lacks the ticket:\n%s", rec) + } + + // The same link again at the new revision: no-op, tip unchanged. + rev1 := blobRevisionAt(t, repo.origin, "docket", recPath) + res = link(7, recPath, rev1, false) + if res.Result != ResultNoOp || res.Disposition != LinkTicketDispAlreadyLinked { + t.Fatalf("repeat link = %q %q (findings %v), want no-op already-linked; failure %+v", res.Result, res.Disposition, res.Findings, res.Failure) + } + if got := originTip(t, repo.origin, "docket"); got != tip1 { + t.Errorf("a no-op moved the metadata branch %s -> %s", tip1, got) + } + + // The old revision is stale. + if res = link(7, recPath, rev0, false); res.Result != ResultContended { + t.Fatalf("stale-revision link = %q (findings %v), want contended", res.Result, res.Findings) + } + + // Unlink. + res = link(7, recPath, rev1, true) + if res.Result != ResultApplied || res.Disposition != LinkTicketDispUnlinked { + t.Fatalf("unlink = %q %q (findings %v), want applied unlinked", res.Result, res.Disposition, res.Findings) + } + + // An archived done record links the same way. + res = link(8, archived, blobRevisionAt(t, repo.origin, "docket", archived), false) + if res.Result != ResultApplied || res.Disposition != LinkTicketDispLinked { + t.Fatalf("archived link = %q %q (findings %v), want applied linked", res.Result, res.Disposition, res.Findings) + } + if rec, _ := originFile(t, repo.origin, "docket", archived); !strings.Contains(rec, "| Ticket | [CLOUD-123](") { + t.Errorf("archived record on origin lacks the Ticket row:\n%s", rec) + } +} diff --git a/internal/app/change_link_ticket_test.go b/internal/app/change_link_ticket_test.go new file mode 100644 index 000000000..037be3ba3 --- /dev/null +++ b/internal/app/change_link_ticket_test.go @@ -0,0 +1,340 @@ +package app + +import ( + "context" + "encoding/json" + "strings" + "testing" + + "github.com/danielhanold/docket/internal/domain" + "github.com/danielhanold/docket/internal/render" + "github.com/danielhanold/docket/internal/repository/transaction" +) + +const ( + ticketTestURL = "https://tickets.example.com/browse/CLOUD-123" + ticketTestURL2 = "https://tickets.example.com/browse/CLOUD-2" +) + +// ticketLines renders the three ticket frontmatter lines for a fixture. +func ticketLines(provider, id, url string) string { + return "ticket_provider: '" + provider + "'\nticket_id: '" + id + "'\nticket_url: '" + url + "'\n" +} + +// withTicketLines splices lines into a lifecycleChange record's frontmatter. +func withTicketLines(rec, lines string) string { + return strings.Replace(rec, "trivial: false\n", "trivial: false\n"+lines, 1) +} + +func linkTicketOpFor(surfaces []string, id int, recPath string, t domain.Ticket, replace, unlink bool) changeLinkTicketOp { + return changeLinkTicketOp{ + changeID: id, + path: recPath, + ticket: t, + replace: replace, + unlink: unlink, + eff: planningTestConfig(surfaces), + clock: testClock(), + inline: len(surfaces) > 0 && surfaces[0] == "inline", + link: render.LinkContext{MetadataBranch: "main"}, + changesDir: "docs/changes", + } +} + +// linkTicketPlanFor runs one Plan over files, through the same loader the +// lifecycle harness uses. +func linkTicketPlanFor(t *testing.T, files map[string]string, op changeLinkTicketOp) (transaction.MutationPlan, transaction.OperationResult) { + t.Helper() + tree := newFakeTree(files) + before, err := newPlanningLoader(op.eff).Load(context.Background(), tree) + if err != nil { + t.Fatalf("loader.Load: %v", err) + } + if before.Report.HasErrors() { + t.Fatalf("before-state has errors: %v", before.Report.Findings()) + } + plan, opRes, err := op.Plan(context.Background(), transaction.AttemptState{Base: tree.Revision(), State: before, Tree: tree}) + if err != nil { + t.Fatalf("Plan: %v", err) + } + return plan, opRes +} + +func linkTicketReceipt(t *testing.T, plan transaction.MutationPlan) changeLinkTicketReceipt { + t.Helper() + var rec changeLinkTicketReceipt + if err := json.Unmarshal(plan.Receipt, &rec); err != nil { + t.Fatalf("decoding receipt %q: %v", plan.Receipt, err) + } + if rec.Op != OperationChangeLinkTicket { + t.Errorf("receipt op = %q", rec.Op) + } + return rec +} + +var cloud123 = domain.Ticket{Provider: "jira", ID: "CLOUD-123", URL: ticketTestURL} + +func TestChangeLinkTicketRejectsBadShapeWithoutEngineCall(t *testing.T) { + id := func(r ChangeLinkTicketRequest) ChangeLinkTicketRequest { + r.ChangeID, r.Path, r.Revision = 7, groomPath(7, "widget"), blobV + return r + } + cases := []struct { + name string + req ChangeLinkTicketRequest + codes []string + }{ + {"empty request", ChangeLinkTicketRequest{}, []string{"invalid-change_id", "empty-path", "empty-revision"}}, + {"no fields", id(ChangeLinkTicketRequest{}), []string{"empty-request"}}, + {"unlink with id", id(ChangeLinkTicketRequest{Unlink: true, TicketID: "CLOUD-1"}), []string{"unlink-with-ticket"}}, + {"unlink with replace", id(ChangeLinkTicketRequest{Unlink: true, Replace: true}), []string{"unlink-with-ticket"}}, + {"two fields", id(ChangeLinkTicketRequest{TicketProvider: "jira", TicketID: "CLOUD-1"}), []string{"partial-ticket"}}, + {"bad url", id(ChangeLinkTicketRequest{TicketProvider: "jira", TicketID: "CLOUD-1", TicketURL: "javascript:alert(1)"}), []string{"invalid-ticket-url"}}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + res := ChangeLinkTicket(context.Background(), PlanningDeps{}, "", c.req) + if res.Result != ResultInvalidInput { + t.Fatalf("result = %q, want invalid-input", res.Result) + } + var got []string + for _, f := range res.Findings { + got = append(got, f.Code) + } + if strings.Join(got, ",") != strings.Join(c.codes, ",") { + t.Errorf("codes = %v, want %v", got, c.codes) + } + }) + } +} + +func TestLinkTicketPlanLinks(t *testing.T) { + recPath := groomPath(7, "widget") + files := map[string]string{ + recPath: lifecycleChange(7, "widget", "in-progress"), + "docs/changes/BOARD.md": "# Backlog\n\nold\n", + } + plan, opRes := linkTicketPlanFor(t, files, linkTicketOpFor([]string{"inline"}, 7, recPath, cloud123, false, false)) + if opRes.Refused { + t.Fatalf("unexpected refusal: %v", opRes.Findings) + } + assertPlanPaths(t, plan, map[string]transaction.MutationKind{ + recPath: transaction.MutationReplace, + "docs/changes/BOARD.md": transaction.MutationReplace, + }) + rec := lifecycleRecordBytes(t, plan, recPath) + for _, want := range []string{ + "ticket_provider: 'jira'", "ticket_id: 'CLOUD-123'", "ticket_url: '" + ticketTestURL + "'", + "updated: '2026-08-16'", "| Ticket | [CLOUD-123](" + ticketTestURL + ") |", + } { + if !strings.Contains(rec, want) { + t.Errorf("record lacks %q:\n%s", want, rec) + } + } + if got := linkTicketReceipt(t, plan).Disposition; got != LinkTicketDispLinked { + t.Errorf("receipt disposition = %q, want linked", got) + } + if plan.CommitSubject != "change 0007 ticket linked" { + t.Errorf("commit subject = %q", plan.CommitSubject) + } +} + +func TestLinkTicketPlanInsertsMissingKeys(t *testing.T) { + recPath := groomPath(7, "widget") + files := map[string]string{recPath: lifecycleChange(7, "widget", "in-progress")} + plan, opRes := linkTicketPlanFor(t, files, linkTicketOpFor(nil, 7, recPath, cloud123, false, false)) + if opRes.Refused { + t.Fatalf("unexpected refusal: %v", opRes.Findings) + } + after := newFakeTree(map[string]string{recPath: lifecycleRecordBytes(t, plan, recPath)}) + state, err := newPlanningLoader(planningTestConfig(nil)).Load(context.Background(), after) + if err != nil { + t.Fatalf("reload: %v", err) + } + if fs := state.Report.Findings(); len(fs) != 0 { + t.Errorf("reloaded record has findings: %v", fs) + } + c, out := state.Snapshot.Change(domain.ChangeID(7)) + if out != domain.LookupFound { + t.Fatalf("change 7 not found after reload") + } + if got, ok := c.Ticket(); !ok || got != cloud123 { + t.Errorf("Ticket() = %+v, %v; want %+v", got, ok, cloud123) + } +} + +func TestLinkTicketPlanSameLinkIsAlreadyLinked(t *testing.T) { + assertSameLinkNoOp(t, false) +} + +func TestLinkTicketPlanReplaceSameIsAlreadyLinked(t *testing.T) { + assertSameLinkNoOp(t, true) +} + +func assertSameLinkNoOp(t *testing.T, replace bool) { + t.Helper() + recPath := groomPath(7, "widget") + files := map[string]string{ + recPath: withTicketLines(lifecycleChange(7, "widget", "in-progress"), ticketLines("jira", "CLOUD-123", ticketTestURL)), + } + plan, opRes := linkTicketPlanFor(t, files, linkTicketOpFor(nil, 7, recPath, cloud123, replace, false)) + if opRes.Refused { + t.Fatalf("refused: %v", opRes.Findings) + } + assertValidNoOpPlan(t, plan, LinkTicketDispAlreadyLinked) +} + +// assertValidNoOpPlan checks an empty plan the engine will accept as a no-op: +// no files, but a commit subject and a receipt naming the disposition. +func assertValidNoOpPlan(t *testing.T, plan transaction.MutationPlan, disposition string) { + t.Helper() + if len(plan.Files) != 0 { + t.Errorf("planned %v, want an empty plan", planPaths(plan)) + } + if plan.CommitSubject == "" { + t.Error("empty plan has no commit subject; the engine rejects it") + } + if got := linkTicketReceipt(t, plan).Disposition; got != disposition { + t.Errorf("no-op receipt disposition = %q, want %q", got, disposition) + } +} + +func cloud1Record() string { + return withTicketLines(lifecycleChange(7, "widget", "in-progress"), + ticketLines("jira", "CLOUD-1", "https://tickets.example.com/browse/CLOUD-1")) +} + +var cloud2 = domain.Ticket{Provider: "jira", ID: "CLOUD-2", URL: ticketTestURL2} + +func TestLinkTicketPlanDifferentLinkRefused(t *testing.T) { + recPath := groomPath(7, "widget") + plan, opRes := linkTicketPlanFor(t, map[string]string{recPath: cloud1Record()}, + linkTicketOpFor(nil, 7, recPath, cloud2, false, false)) + if !opRes.Refused || !hasDomainFindingCode(opRes.Findings, "already-linked-elsewhere") { + t.Fatalf("refused=%v findings=%v; want already-linked-elsewhere", opRes.Refused, opRes.Findings) + } + if len(plan.Files) != 0 { + t.Errorf("a refusal planned files %v", planPaths(plan)) + } + msg := opRes.Findings[0].Detail["message"] + if !strings.Contains(msg, "replace: true") || !strings.Contains(msg, "human") { + t.Errorf("message does not name replace: true on the human's request: %q", msg) + } +} + +func TestLinkTicketPlanReplace(t *testing.T) { + recPath := groomPath(7, "widget") + plan, opRes := linkTicketPlanFor(t, map[string]string{recPath: cloud1Record()}, + linkTicketOpFor(nil, 7, recPath, cloud2, true, false)) + if opRes.Refused { + t.Fatalf("refused: %v", opRes.Findings) + } + rec := lifecycleRecordBytes(t, plan, recPath) + if !strings.Contains(rec, "ticket_id: 'CLOUD-2'") || strings.Contains(rec, "CLOUD-1") { + t.Errorf("record not replaced:\n%s", rec) + } + if got := linkTicketReceipt(t, plan).Disposition; got != LinkTicketDispReplaced { + t.Errorf("receipt disposition = %q, want replaced", got) + } +} + +func TestLinkTicketPlanPartialRecordNeedsReplace(t *testing.T) { + recPath := groomPath(7, "widget") + files := map[string]string{ + recPath: withTicketLines(lifecycleChange(7, "widget", "in-progress"), "ticket_id: 'CLOUD-9'\n"), + } + _, opRes := linkTicketPlanFor(t, files, linkTicketOpFor(nil, 7, recPath, cloud123, false, false)) + if !opRes.Refused || !hasDomainFindingCode(opRes.Findings, "already-linked-elsewhere") { + t.Fatalf("partial record without replace: refused=%v findings=%v", opRes.Refused, opRes.Findings) + } + plan, opRes := linkTicketPlanFor(t, files, linkTicketOpFor(nil, 7, recPath, cloud123, true, false)) + if opRes.Refused { + t.Fatalf("partial record with replace refused: %v", opRes.Findings) + } + if got := linkTicketReceipt(t, plan).Disposition; got != LinkTicketDispReplaced { + t.Errorf("receipt disposition = %q, want replaced", got) + } + rec := lifecycleRecordBytes(t, plan, recPath) + if !strings.Contains(rec, "| Ticket | [CLOUD-123](") || strings.Contains(rec, "CLOUD-9") { + t.Errorf("record not a valid CLOUD-123 link:\n%s", rec) + } +} + +func TestLinkTicketPlanUnlink(t *testing.T) { + recPath := groomPath(7, "widget") + files := map[string]string{ + recPath: withTicketLines(lifecycleChange(7, "widget", "in-progress"), ticketLines("jira", "CLOUD-123", ticketTestURL)), + } + plan, opRes := linkTicketPlanFor(t, files, linkTicketOpFor(nil, 7, recPath, domain.Ticket{}, false, true)) + if opRes.Refused { + t.Fatalf("refused: %v", opRes.Findings) + } + rec := lifecycleRecordBytes(t, plan, recPath) + for _, want := range []string{"\nticket_provider:\n", "\nticket_id:\n", "\nticket_url:\n"} { + if !strings.Contains(rec, want) { + t.Errorf("record lacks valueless %q:\n%s", strings.TrimSpace(want), rec) + } + } + if strings.Contains(rec, "| Ticket |") || strings.Contains(rec, "CLOUD-123") { + t.Errorf("unlinked record still carries the ticket:\n%s", rec) + } + if got := linkTicketReceipt(t, plan).Disposition; got != LinkTicketDispUnlinked { + t.Errorf("receipt disposition = %q, want unlinked", got) + } +} + +func TestLinkTicketPlanUnlinkNothingToUnlink(t *testing.T) { + recPath := groomPath(7, "widget") + for name, lines := range map[string]string{ + "absent": "", + "valueless": "ticket_provider:\nticket_id:\nticket_url:\n", + } { + t.Run(name, func(t *testing.T) { + files := map[string]string{recPath: withTicketLines(lifecycleChange(7, "widget", "in-progress"), lines)} + plan, opRes := linkTicketPlanFor(t, files, linkTicketOpFor(nil, 7, recPath, domain.Ticket{}, false, true)) + if opRes.Refused { + t.Fatalf("refused: %v", opRes.Findings) + } + assertValidNoOpPlan(t, plan, LinkTicketDispNothingToUnlink) + }) + } +} + +func TestLinkTicketPlanArchivedDone(t *testing.T) { + recPath := "docs/changes/archive/2026-10-01-0007-widget.md" + files := map[string]string{recPath: lifecycleChange(7, "widget", "done")} + plan, opRes := linkTicketPlanFor(t, files, linkTicketOpFor(nil, 7, recPath, cloud123, false, false)) + if opRes.Refused { + t.Fatalf("refused: %v", opRes.Findings) + } + assertPlanPaths(t, plan, map[string]transaction.MutationKind{recPath: transaction.MutationReplace}) + if rec := lifecycleRecordBytes(t, plan, recPath); !strings.Contains(rec, "| Ticket | [CLOUD-123](") { + t.Errorf("archived record lacks the Ticket row:\n%s", rec) + } +} + +func TestLinkTicketPlanPathMismatch(t *testing.T) { + recPath := groomPath(7, "widget") + files := map[string]string{recPath: lifecycleChange(7, "widget", "in-progress")} + _, opRes := linkTicketPlanFor(t, files, linkTicketOpFor(nil, 7, groomPath(7, "other"), cloud123, false, false)) + if !opRes.Refused || !hasDomainFindingCode(opRes.Findings, "path-mismatch") { + t.Fatalf("refused=%v findings=%v; want path-mismatch", opRes.Refused, opRes.Findings) + } +} + +func TestLinkTicketResultHumanText(t *testing.T) { + applied := newChangeLinkTicketResult(ResultApplied, ChangeLinkTicketResult{ID: 7, Disposition: LinkTicketDispLinked, Revision: "abc123"}) + if got, want := applied.HumanText(), "change.link-ticket: change 0007 linked — abc123"; got != want { + t.Errorf("applied = %q, want %q", got, want) + } + noop := newChangeLinkTicketResult(ResultNoOp, ChangeLinkTicketResult{ID: 7, Disposition: LinkTicketDispAlreadyLinked}) + if got, want := noop.HumanText(), "change.link-ticket: change 0007 already-linked"; got != want { + t.Errorf("no-op = %q, want %q", got, want) + } + refused := newChangeLinkTicketResult(ResultInvalidState, ChangeLinkTicketResult{Findings: []StatusFinding{ + {Code: string(FCAlreadyLinkedElsewhere), Message: "change 0007 already carries a link."}, + }}) + if got, want := refused.HumanText(), "change.link-ticket: invalid-state\n change 0007 already carries a link."; got != want { + t.Errorf("refused = %q, want %q", got, want) + } +} diff --git a/internal/app/finding_codes.go b/internal/app/finding_codes.go index f3fb2cecb..cd78e2861 100644 --- a/internal/app/finding_codes.go +++ b/internal/app/finding_codes.go @@ -188,6 +188,14 @@ const ( FCInvalidTicketID FindingCode = "invalid-ticket-id" FCInvalidTicketURL FindingCode = "invalid-ticket-url" + // change.link-ticket findings: unlink takes no ticket field and no replace; + // a link request names at least one ticket field; and a record already + // carrying a different link (or broken ticket fields) is replaced only on + // an explicit replace request. + FCUnlinkWithTicket FindingCode = "unlink-with-ticket" + FCEmptyTicketRequest FindingCode = "empty-request" + FCAlreadyLinkedElsewhere FindingCode = "already-linked-elsewhere" + // Install-maintenance findings. collection-pending is the reason an explicit // `install collect` reports and the warning code an automatic post-install // collection surfaces when a version tree could not be reclaimed; the primary @@ -249,6 +257,7 @@ const ( var AllFindingCodes = []FindingCode{ FindingCode("adr-not-accepted"), FCAgentCacheTTLDropped, + FCAlreadyLinkedElsewhere, FindingCode("ambiguous-adr"), FindingCode("ambiguous-change"), FCArtifactMissing, @@ -292,6 +301,7 @@ var AllFindingCodes = []FindingCode{ FCEmptyReason, FCEmptyReconcileLogEntry, FCEmptyReport, + FCEmptyTicketRequest, FCEmptyRevise, FCEmptyRevision, FCEmptySpecMarkdown, @@ -387,6 +397,7 @@ var AllFindingCodes = []FindingCode{ FCUnknownOperation, FCUnknownPriority, FCUnknownType, + FCUnlinkWithTicket, } // invalidIDCodeByKey selects the id-shape finding code for a lifecycle request diff --git a/internal/app/schema_registry.go b/internal/app/schema_registry.go index 52531e554..8b626a995 100644 --- a/internal/app/schema_registry.go +++ b/internal/app/schema_registry.go @@ -58,6 +58,7 @@ var operationBindings = []OperationBinding{ {ID: "change.groom", Request: ChangeGroomRequest{}, Result: ChangeGroomResult{}}, // ChangeGroom {ID: "change.halt", Request: ChangeHaltInput{}, Result: HaltResult{}}, // ChangeHalt {ID: "change.kill", Request: ChangeKillRequest{}, Result: ChangeKillResult{}}, // ChangeKill + {ID: "change.link-ticket", Request: ChangeLinkTicketRequest{}, Result: ChangeLinkTicketResult{}}, // ChangeLinkTicket {ID: "change.mark-implemented", Request: nil, Result: ChangeLifecycleResult{}}, // ChangeMarkImplemented {ID: "change.reconcile", Request: ChangeReconcileRequest{}, Result: ChangeReconcileResult{}}, // ChangeReconcile {ID: "change.relink", Request: nil, Result: RelinkResult{}}, // Relink diff --git a/internal/app/schema_revision_test.go b/internal/app/schema_revision_test.go index 1cdc4b5b2..005fbdc02 100644 --- a/internal/app/schema_revision_test.go +++ b/internal/app/schema_revision_test.go @@ -42,7 +42,7 @@ func TestSchemaRevisionKeys(t *testing.T) { "adr.supersede REQ target.revision", "adr.supersede REQ successor.change.revision", "change.block REQ revision", "change.complete REQ revision", "change.defer REQ revision", "change.groom REQ revision", "change.groom REQ spec_revision", - "change.kill REQ revision", "change.reconcile REQ revision", + "change.kill REQ revision", "change.link-ticket REQ revision", "change.reconcile REQ revision", "change.revive REQ revision", "change.unblock REQ revision", "context.finalize RES candidates.revision", "context.finalize RES candidates.pr.revision", "context.implementation RES context.change.revision", "context.implementation RES context.spec.revision", diff --git a/internal/app/schema_tags_test.go b/internal/app/schema_tags_test.go index 8fe52cbfa..592bfe8fc 100644 --- a/internal/app/schema_tags_test.go +++ b/internal/app/schema_tags_test.go @@ -58,6 +58,9 @@ func TestRequiredTagMatchesValidator(t *testing.T) { {"change.unblock", ChangeUnblockRequest{}, func() []StatusFinding { return ChangeUnblock(context.Background(), PlanningDeps{}, "", ChangeUnblockRequest{}).Findings }}, + {"change.link-ticket", ChangeLinkTicketRequest{}, func() []StatusFinding { + return ChangeLinkTicket(context.Background(), PlanningDeps{}, "", ChangeLinkTicketRequest{}).Findings + }}, {"change.revive", ChangeReviveRequest{}, func() []StatusFinding { return ChangeRevive(context.Background(), PlanningDeps{}, "", ChangeReviveRequest{}).Findings }}, diff --git a/internal/app/schema_vocab.go b/internal/app/schema_vocab.go index 19622b581..7027cb2d7 100644 --- a/internal/app/schema_vocab.go +++ b/internal/app/schema_vocab.go @@ -133,6 +133,10 @@ func SchemaVocabularies(effects []string) map[string]Vocabulary { }} // The conflict-resolver report's closed disposition set (ResolverReport, // the request finalize.rebase-continue and finalize.rebase-abort decode). + v["link_ticket_dispositions"] = Vocabulary{Members: []string{ + LinkTicketDispLinked, LinkTicketDispAlreadyLinked, LinkTicketDispReplaced, + LinkTicketDispUnlinked, LinkTicketDispNothingToUnlink, + }} v["resolver_dispositions"] = Vocabulary{Members: []string{ ResolverResolved, ResolverStuck, }} diff --git a/internal/app/schema_vocab_test.go b/internal/app/schema_vocab_test.go index cb7ffe50a..e400e9a82 100644 --- a/internal/app/schema_vocab_test.go +++ b/internal/app/schema_vocab_test.go @@ -175,6 +175,7 @@ func TestVocabularyConstCompleteness(t *testing.T) { {vocab: "publish_dispositions", byPrefix: "PublishDisp"}, {vocab: "sync_dispositions", byPrefix: "SyncDisp"}, {vocab: "cancel_dispositions", byPrefix: "CancelDisposition"}, + {vocab: "link_ticket_dispositions", byPrefix: "LinkTicketDisp"}, {vocab: "resolver_dispositions", byPrefix: "Resolver"}, } diff --git a/internal/app/shadow_test.go b/internal/app/shadow_test.go index 09a22007c..1e14aaa9b 100644 --- a/internal/app/shadow_test.go +++ b/internal/app/shadow_test.go @@ -71,6 +71,7 @@ func TestEnvelopeNotShadowed(t *testing.T) { {"change.defer", newChangeLifecycleResult(OperationChangeDefer, ResultApplied, ChangeLifecycleResult{})}, {"change.unblock", newChangeLifecycleResult(OperationChangeUnblock, ResultApplied, ChangeLifecycleResult{})}, {"change.revive", newChangeLifecycleResult(OperationChangeRevive, ResultApplied, ChangeLifecycleResult{})}, + {"change.link-ticket", newChangeLinkTicketResult(ResultApplied, ChangeLinkTicketResult{})}, {"change.kill", newChangeKillResult(ResultApplied, ChangeKillResult{})}, {"change.complete", newChangeCompleteResult(ResultApplied, ChangeCompleteResult{})}, {"learning.record", newLearningResult(OperationLearningRecord, ResultApplied, LearningResult{})}, diff --git a/internal/cli/change.go b/internal/cli/change.go index 4233d705e..077d292fe 100644 --- a/internal/cli/change.go +++ b/internal/cli/change.go @@ -96,6 +96,12 @@ func newChangeCommand(setResult func(app.OperationResult)) *cobra.Command { setResult(app.ChangeComplete(c.Context(), deps, repoDir, req)) }, EffectMetadataWrite) + linkTicket := changeSubcommand("change", "link-ticket", + "Link a change to a ticket, replace that link on request, or clear it, from a JSON request", + func(c *cobra.Command, deps app.PlanningDeps, repoDir string, req app.ChangeLinkTicketRequest) { + setResult(app.ChangeLinkTicket(c.Context(), deps, repoDir, req)) + }, EffectMetadataWrite) + claim := changeIDRevisionSubcommand("claim", "Claim a build-ready change at an exact revision, moving it to in-progress", func(c *cobra.Command, deps app.PlanningDeps, repoDir string, req app.ChangeClaimRequest) { @@ -144,7 +150,7 @@ func newChangeCommand(setResult func(app.OperationResult)) *cobra.Command { relink := newRelinkSubcommand(setResult) - changeCmd.AddCommand(create, groom, block, deferCmd, unblock, revive, kill, complete, claim, reconcile, attachPlan, attachResults, halt, resumeHalted, markImplemented, relink) + changeCmd.AddCommand(create, groom, block, deferCmd, unblock, revive, kill, complete, linkTicket, claim, reconcile, attachPlan, attachResults, halt, resumeHalted, markImplemented, relink) return changeCmd } diff --git a/internal/cli/change_test.go b/internal/cli/change_test.go index 47e9f36aa..d2180b4d2 100644 --- a/internal/cli/change_test.go +++ b/internal/cli/change_test.go @@ -26,7 +26,7 @@ func runCLIStdin(t *testing.T, stdin string, args ...string) (stdout, stderr str // flag and a --repo-dir flag, and the bare group reports a missing command. func TestChangeCommandsRegistered(t *testing.T) { root := captureTree(t) - for _, sub := range []string{"create", "groom", "block", "defer", "unblock", "revive", "kill", "complete"} { + for _, sub := range []string{"create", "groom", "block", "defer", "unblock", "revive", "kill", "complete", "link-ticket"} { cmd, _, err := root.Find([]string{"change", sub}) if err != nil || cmd == nil || cmd.Name() != sub { t.Fatalf("change %s not registered: cmd=%v err=%v", sub, cmd, err) @@ -87,6 +87,7 @@ func TestChangeCommandsReachOperation(t *testing.T) { {"revive", "change.revive"}, {"kill", "change.kill"}, {"complete", "change.complete"}, + {"link-ticket", "change.link-ticket"}, } for _, c := range cases { out, errS, code := runCLIStdin(t, `{}`, "change", c.sub, "--request", "-", "--repo-dir", testsupport.TempDir(t), "--json") @@ -139,7 +140,7 @@ func TestChangeRequestFileMissing(t *testing.T) { // never installed assets), so they are not refused on a machine with no // installation. func TestChangeCommandsAssetIndependent(t *testing.T) { - for _, key := range []string{"change", "change create", "change groom", "change block", "change defer", "change unblock", "change revive", "change kill", "change complete", "change claim", "change reconcile"} { + for _, key := range []string{"change", "change create", "change groom", "change block", "change defer", "change unblock", "change revive", "change kill", "change complete", "change link-ticket", "change claim", "change reconcile"} { if !assetIndependent[key] { t.Errorf("%q is not registered asset-independent", key) } diff --git a/internal/cli/install.go b/internal/cli/install.go index e66ff3b1a..fcb66f3e5 100644 --- a/internal/cli/install.go +++ b/internal/cli/install.go @@ -44,6 +44,7 @@ var assetIndependent = map[string]bool{ "change revive": true, "change kill": true, "change complete": true, + "change link-ticket": true, "change claim": true, "change reconcile": true, "change attach-plan": true, From d6ca80f5222032f829a36a4e3f3baa9f11954812 Mon Sep 17 00:00:00 2001 From: Daniel Hanold Date: Mon, 9 Nov 2026 18:22:11 -0500 Subject: [PATCH 07/12] feat(app): expose a linked ticket in the implementation context --- internal/app/implementation_context.go | 22 ++++++++ internal/app/implementation_context_test.go | 62 +++++++++++++++++++++ internal/app/status_test.go | 45 +++++++++++++++ 3 files changed, 129 insertions(+) diff --git a/internal/app/implementation_context.go b/internal/app/implementation_context.go index 37aac7e20..65a9406c3 100644 --- a/internal/app/implementation_context.go +++ b/internal/app/implementation_context.go @@ -63,6 +63,27 @@ type ContextEntitySummary struct { Type string `json:"type,omitempty"` Priority string `json:"priority,omitempty"` Deliverable string `json:"deliverable,omitempty"` + // Ticket is the selected change's ticket link, set only when Change.Ticket + // reports a complete, valid link; any other ticket state is omitted. + Ticket *ContextTicket `json:"ticket,omitempty"` +} + +// contextTicket returns the change's ticket link for the context summary, or +// nil when Change.Ticket reports the change as not linked. +func contextTicket(c domain.Change) *ContextTicket { + t, ok := c.Ticket() + if !ok { + return nil + } + return &ContextTicket{Provider: t.Provider, ID: t.ID, URL: t.URL} +} + +// ContextTicket is a change's linked ticket: the three stored values, exactly +// as recorded. +type ContextTicket struct { + Provider string `json:"provider"` + ID string `json:"id"` + URL string `json:"url"` } // ContextEntity is one document the bundle carries: its canonical repo-relative @@ -316,6 +337,7 @@ func ContextImplementation(ctx context.Context, deps PlanningDeps, repoDir strin Type: selected.Type(), Priority: selected.RawPriority(), Deliverable: deliverableText(selected), + Ticket: contextTicket(selected), }, }, Spec: specEntity, diff --git a/internal/app/implementation_context_test.go b/internal/app/implementation_context_test.go index c4bbd76b8..371c7ee8e 100644 --- a/internal/app/implementation_context_test.go +++ b/internal/app/implementation_context_test.go @@ -799,3 +799,65 @@ func TestContextImplementationRefusesOtherNonProposedStatuses(t *testing.T) { }) } } + +// ticketContext returns the bundle for change 11 carrying the given extra +// frontmatter, failing the test unless the operation applied. +func ticketContext(t *testing.T, extra string) *ImplementationContext { + t.Helper() + specPath := "docs/changes/specs/spec-alpha.md" + fake := &fakeReader{ + pin: docketPin(t), + corpus: []StatusBlob{changeBlob(11, "alpha", "feat", "high", "spec: "+specPath+"\n"+extra)}, + artifactData: map[string]StatusArtifact{ + sourceMetadata + "|" + specPath: {Found: true, Revision: "specblob-alpha", Data: []byte("# Spec Alpha\n")}, + }, + } + got := ContextImplementation(context.Background(), contextDeps(fake), "", ImplementationContextRequest{ID: 11}) + if got.Result != ResultApplied || got.Context == nil || got.Context.Change.Summary == nil { + t.Fatalf("result=%q reason=%q message=%q", got.Result, got.Reason, got.Message) + } + return got.Context +} + +// TestContextImplementationCarriesTicket: a change with a valid ticket link +// carries all three stored values in its summary, under the "ticket" JSON key. +func TestContextImplementationCarriesTicket(t *testing.T) { + b := ticketContext(t, "ticket_provider: jira\nticket_id: CLOUD-123\nticket_url: 'https://tickets.example.com/browse/CLOUD-123'\n") + want := &ContextTicket{Provider: "jira", ID: "CLOUD-123", URL: "https://tickets.example.com/browse/CLOUD-123"} + if !reflect.DeepEqual(b.Change.Summary.Ticket, want) { + t.Fatalf("summary ticket = %+v, want %+v", b.Change.Summary.Ticket, want) + } + raw, err := json.Marshal(b.Change.Summary) + if err != nil { + t.Fatalf("marshal: %v", err) + } + if !strings.Contains(string(raw), `"ticket":{"provider":"jira","id":"CLOUD-123","url":"https://tickets.example.com/browse/CLOUD-123"}`) { + t.Errorf("summary JSON lacks the ticket object: %s", raw) + } +} + +// TestContextImplementationOmitsInvalidTicket: a partial set, an invalid +// complete set, and no ticket fields at all each leave the summary's ticket +// nil, and the JSON carries no "ticket" key. +func TestContextImplementationOmitsInvalidTicket(t *testing.T) { + cases := map[string]string{ + "partial": "ticket_provider: jira\nticket_id: CLOUD-123\n", + "invalid-url": "ticket_provider: jira\nticket_id: CLOUD-123\nticket_url: 'javascript:x'\n", + "absent": "", + } + for name, extra := range cases { + t.Run(name, func(t *testing.T) { + b := ticketContext(t, extra) + if b.Change.Summary.Ticket != nil { + t.Errorf("summary ticket = %+v, want nil", b.Change.Summary.Ticket) + } + raw, err := json.Marshal(b.Change.Summary) + if err != nil { + t.Fatalf("marshal: %v", err) + } + if strings.Contains(string(raw), `"ticket"`) { + t.Errorf("summary JSON carries a ticket key: %s", raw) + } + }) + } +} diff --git a/internal/app/status_test.go b/internal/app/status_test.go index 249db5537..acd467e17 100644 --- a/internal/app/status_test.go +++ b/internal/app/status_test.go @@ -746,3 +746,48 @@ func TestStatusLegacyTrivialRecordReadsNeedsGrooming(t *testing.T) { t.Errorf("legacy trivial row = readiness %q, ready %v; want needs-grooming, false", row.Readiness, row.Ready) } } + +// TestStatusReportsTicketLinkInvalid: a change carrying a partial ticket set +// raises one warning-severity ticket-link-invalid finding, adds no error +// finding, and is still listed. +func TestStatusReportsTicketLinkInvalid(t *testing.T) { + fake := &fakeReader{ + pin: docketPin(t), + corpus: []StatusBlob{ + changeBlob(61, "partial", "feat", "high", "ticket_provider: jira\nticket_id: CLOUD-123\n"), + }, + facts: domain.NewBranchFacts(nil), + } + got := Status(context.Background(), fake, StatusOptions{}) + if got.Result != ResultApplied { + t.Fatalf("result = %q, want applied; message=%q", got.Result, got.Message) + } + found := 0 + for _, f := range got.Findings { + if f.Code != "ticket-link-invalid" { + continue + } + found++ + if f.Severity != "warning" { + t.Errorf("ticket-link-invalid severity = %q, want warning", f.Severity) + } + if f.Identity != "0061" { + t.Errorf("ticket-link-invalid identity = %q, want 0061", f.Identity) + } + } + if found != 1 { + t.Errorf("ticket-link-invalid findings = %d, want 1: %+v", found, got.Findings) + } + if got.Summary.ErrorFindings != 0 { + t.Errorf("error findings = %d, want 0: %+v", got.Summary.ErrorFindings, got.Findings) + } + listed := false + for _, c := range got.Changes { + if c.ID == 61 { + listed = true + } + } + if !listed { + t.Errorf("change 61 not listed: %+v", got.Changes) + } +} From 25cc9443123e6c40c5eb31f4aa0d655d2b457236 Mon Sep 17 00:00:00 2001 From: Daniel Hanold Date: Mon, 9 Nov 2026 18:27:35 -0500 Subject: [PATCH 08/12] feat(config): add the per-repository tickets settings --- .docket.example.yml | 41 ++++++++- docs/reference/config-keys.md | 8 ++ internal/app/config.go | 8 ++ internal/app/config_test.go | 63 +++++++++++++ internal/assets/embedded/manifest.json | 6 +- .../assets/embedded/tree/.docket.example.yml | 41 ++++++++- internal/config/config.go | 20 +++++ internal/config/decode_test.go | 25 ++++++ internal/config/defaults.go | 12 +++ internal/config/defaults_test.go | 8 ++ internal/config/fixtures_test.go | 8 ++ internal/config/resolve.go | 8 ++ internal/config/resolve_test.go | 88 +++++++++++++++++++ internal/config/schema.go | 41 +++++++++ internal/config/schema_test.go | 23 ++++- internal/config/setting_paths_test.go | 8 +- internal/repoguard/docket_yml_tickets_test.go | 67 ++++++++++++++ 17 files changed, 468 insertions(+), 7 deletions(-) create mode 100644 internal/repoguard/docket_yml_tickets_test.go diff --git a/.docket.example.yml b/.docket.example.yml index edbcdf3e6..9ab9ccef8 100644 --- a/.docket.example.yml +++ b/.docket.example.yml @@ -21,7 +21,7 @@ # ── Copying this file ───────────────────────────────────────────────────────────────────── # Safe to copy: copied verbatim as `.docket.yml`, it behaves exactly like having no file, because # every active value below is the built-in default. Copy only the keys you want to change. -# For `.docket.local.yml` or the global config, copy only `scope: any layer` keys: the four +# For `.docket.local.yml` or the global config, copy only `scope: any layer` keys: the # `scope: repo-only` keys are ignored with a warning there. # # ── Scope tags ──────────────────────────────────────────────────────────────────────────── @@ -244,6 +244,45 @@ board: change_types: [chore, docs, feat, fix, refactor, perf] +# ═══ Tickets ══════════════════════════════════════════════════════════════════════════════ + +# tickets — the ticket system this repository's changes link to. Linking a change to a ticket +# keeps the two together: the change shows the ticket in its artifacts, and the pull request +# docket opens names it. `provider` names the tool (jira, linear, …), `site` names where it lives +# (tickets.example.com), and `project` names where new tickets go. Each is a single line; empty +# (the default) means not set. +# +# What `project` means, and what kind of ticket each tool creates, depends on the tool: +# +# | Tool | `project` means | Ticket types | +# |----------------|------------------|----------------------------------------------| +# | Jira | project | issue type (Story, Task, Bug) | +# | Azure DevOps | project | work item type | +# | GitLab | project | issue type | +# | GitHub Issues | repository | issue type, where the organization has them | +# | Shortcut | team | story type | +# | Linear | team | none (labels) | +# | Asana / Trello | project / board | none | +# +# The `auto` switches let docket act on a linked ticket on its own after each event: a change is +# created, its spec is written, its pull request opens, its pull request merges, or its results +# are complete. All are off by default. +# +# These settings belong to the repository: a value in the global config or `.docket.local.yml` is +# ignored with a warning. +# scope: repo-only (shared-setting guarded) +tickets: + provider: "" + site: "" + project: "" + auto: + change_created: false + spec_written: false + pr_opened: false + pr_merged: false + results_completed: false + + # ═══ Agent harnesses & agent models ═══════════════════════════════════════════════════════ # agent_harnesses — which harnesses this repository's dispatch surfaces are installed for. It has diff --git a/docs/reference/config-keys.md b/docs/reference/config-keys.md index adab380f0..e025fb689 100644 --- a/docs/reference/config-keys.md +++ b/docs/reference/config-keys.md @@ -57,6 +57,14 @@ Each key has one scope: | `board.section_order` | `[in-progress, built, blocked, groomed, proposed, deferred]` | any layer | the order of the board's sections | | `board.sorting.
.by` / `.direction` | `updated` / `desc` | any layer | how each board section is sorted | | `change_types` | `[chore, docs, feat, fix, refactor, perf]` | any layer | the types a change can be classified as | +| `tickets.provider` | `""` (unset) | repo-only | the ticket system this repository's changes link to (jira, linear, …) | +| `tickets.site` | `""` (unset) | repo-only | where that ticket system lives | +| `tickets.project` | `""` (unset) | repo-only | where new tickets go (a project, team, repository, or board, by tool) | +| `tickets.auto.change_created` | `false` | repo-only | whether docket acts on the linked ticket when a change is created | +| `tickets.auto.spec_written` | `false` | repo-only | whether docket acts on the linked ticket when a change's spec is written | +| `tickets.auto.pr_opened` | `false` | repo-only | whether docket acts on the linked ticket when a change's pull request opens | +| `tickets.auto.pr_merged` | `false` | repo-only | whether docket acts on the linked ticket when a change's pull request merges | +| `tickets.auto.results_completed` | `false` | repo-only | whether docket acts on the linked ticket when a change's results are complete | | `agent_harnesses` | none | any layer | the dispatch opt-in (below) | | `agents...model` / `.effort` | the built-in table | global-only | model and effort pins for docket's agents | diff --git a/internal/app/config.go b/internal/app/config.go index eb86e368c..d02a29d9b 100644 --- a/internal/app/config.go +++ b/internal/app/config.go @@ -273,6 +273,14 @@ func effectiveLines(eff *config.Effective) []effectiveLine { } lines = append(lines, leafLine("change_types", listValue(eff.ChangeTypes.Value), eff.ChangeTypes.Provenance), + leafLine("tickets.provider", textValue(eff.Tickets.Provider.Value), eff.Tickets.Provider.Provenance), + leafLine("tickets.site", textValue(eff.Tickets.Site.Value), eff.Tickets.Site.Provenance), + leafLine("tickets.project", textValue(eff.Tickets.Project.Value), eff.Tickets.Project.Provenance), + leafLine("tickets.auto.change_created", strconv.FormatBool(eff.Tickets.Auto.ChangeCreated.Value), eff.Tickets.Auto.ChangeCreated.Provenance), + leafLine("tickets.auto.spec_written", strconv.FormatBool(eff.Tickets.Auto.SpecWritten.Value), eff.Tickets.Auto.SpecWritten.Provenance), + leafLine("tickets.auto.pr_opened", strconv.FormatBool(eff.Tickets.Auto.PROpened.Value), eff.Tickets.Auto.PROpened.Provenance), + leafLine("tickets.auto.pr_merged", strconv.FormatBool(eff.Tickets.Auto.PRMerged.Value), eff.Tickets.Auto.PRMerged.Provenance), + leafLine("tickets.auto.results_completed", strconv.FormatBool(eff.Tickets.Auto.ResultsCompleted.Value), eff.Tickets.Auto.ResultsCompleted.Provenance), ) return append(lines, agentLines(eff.Agents)...) } diff --git a/internal/app/config_test.go b/internal/app/config_test.go index b0aba2f36..b7291de74 100644 --- a/internal/app/config_test.go +++ b/internal/app/config_test.go @@ -899,3 +899,66 @@ func TestConfigDiagnosticsAgentCacheTTLSurface(t *testing.T) { } } } + +// TestConfigDiagnosticsTicketsSurface pins that DiagnosticConfig lists every +// tickets.* setting with its effective value, on both halves: the reflected +// `effective` JSON and the hand-maintained human block, after change_types. +func TestConfigDiagnosticsTicketsSurface(t *testing.T) { + def := DiagnosticConfig(sparseSources(), mainCtx(), false).HumanText() + for _, want := range []string{ + "tickets.provider = (unset) [built-in]", + "tickets.site = (unset) [built-in]", + "tickets.project = (unset) [built-in]", + "tickets.auto.change_created = false [built-in]", + "tickets.auto.spec_written = false [built-in]", + "tickets.auto.pr_opened = false [built-in]", + "tickets.auto.pr_merged = false [built-in]", + "tickets.auto.results_completed = false [built-in]", + } { + if !strings.Contains(def, want) { + t.Errorf("default inspection lacks %q:\n%s", want, def) + } + } + if ct, tp := strings.Index(def, "change_types = "), strings.Index(def, "tickets.provider = "); ct < 0 || tp < ct { + t.Errorf("tickets.provider (%d) must follow change_types (%d):\n%s", tp, ct, def) + } + + src := []config.Source{{Layer: config.LayerRepository, Name: ".docket.yml", Data: []byte( + "tickets:\n provider: jira\n site: tickets.example.com\n project: CLOUD\n" + + " auto:\n change_created: true\n spec_written: true\n pr_opened: true\n" + + " pr_merged: true\n results_completed: true\n")}} + r := DiagnosticConfig(src, mainCtx(), false) + if r.Effective == nil { + t.Fatalf("no effective document:\n%s", r.HumanText()) + } + tk := r.Effective.Tickets + if tk.Provider.Value != "jira" || tk.Site.Value != "tickets.example.com" || tk.Project.Value != "CLOUD" || + !tk.Auto.ChangeCreated.Value || !tk.Auto.SpecWritten.Value || !tk.Auto.PROpened.Value || + !tk.Auto.PRMerged.Value || !tk.Auto.ResultsCompleted.Value { + t.Errorf("effective tickets = %+v, want every declared value", tk) + } + text := r.HumanText() + for _, want := range []string{ + "tickets.provider = jira [repository .docket.yml:2]", + "tickets.site = tickets.example.com", + "tickets.project = CLOUD", + "tickets.auto.change_created = true", + "tickets.auto.spec_written = true", + "tickets.auto.pr_opened = true", + "tickets.auto.pr_merged = true", + "tickets.auto.results_completed = true", + } { + if !strings.Contains(text, want) { + t.Errorf("inspection lacks %q:\n%s", want, text) + } + } + raw, err := json.Marshal(r.Effective) + if err != nil { + t.Fatal(err) + } + for _, want := range []string{`"tickets":`, `"provider":`, `"auto":`, `"change_created":`, `"results_completed":`} { + if !strings.Contains(string(raw), want) { + t.Errorf("effective JSON lacks %s: %s", want, raw) + } + } +} diff --git a/internal/assets/embedded/manifest.json b/internal/assets/embedded/manifest.json index 9dd420b23..8d6459a41 100644 --- a/internal/assets/embedded/manifest.json +++ b/internal/assets/embedded/manifest.json @@ -1,14 +1,14 @@ { "format_version": 1, "asset_protocol": 1, - "asset_set_id": "sha256:d7f5d56a646a8b930ad3d8cd7d127a20a04b14caf23f2f33fb74f8d75863c53a", + "asset_set_id": "sha256:b16a8a0452290b69b9608c22f0187de0ce892618264880bef098ae6618e82265", "entries": [ { "path": ".docket.example.yml", "role": "config-schema", "mode": 420, - "size": 21573, - "sha256": "b9c4126443fbd3fff300def014b4cf0204e972bad0e33d4e7d32ca14ca99e824" + "size": 23718, + "sha256": "1ac775ba16836d65ded899f0ca7f2611dcc9fe28b1d3676b058cb1b54b827bb1" }, { "path": "agents/docket-adr.md", diff --git a/internal/assets/embedded/tree/.docket.example.yml b/internal/assets/embedded/tree/.docket.example.yml index edbcdf3e6..9ab9ccef8 100644 --- a/internal/assets/embedded/tree/.docket.example.yml +++ b/internal/assets/embedded/tree/.docket.example.yml @@ -21,7 +21,7 @@ # ── Copying this file ───────────────────────────────────────────────────────────────────── # Safe to copy: copied verbatim as `.docket.yml`, it behaves exactly like having no file, because # every active value below is the built-in default. Copy only the keys you want to change. -# For `.docket.local.yml` or the global config, copy only `scope: any layer` keys: the four +# For `.docket.local.yml` or the global config, copy only `scope: any layer` keys: the # `scope: repo-only` keys are ignored with a warning there. # # ── Scope tags ──────────────────────────────────────────────────────────────────────────── @@ -244,6 +244,45 @@ board: change_types: [chore, docs, feat, fix, refactor, perf] +# ═══ Tickets ══════════════════════════════════════════════════════════════════════════════ + +# tickets — the ticket system this repository's changes link to. Linking a change to a ticket +# keeps the two together: the change shows the ticket in its artifacts, and the pull request +# docket opens names it. `provider` names the tool (jira, linear, …), `site` names where it lives +# (tickets.example.com), and `project` names where new tickets go. Each is a single line; empty +# (the default) means not set. +# +# What `project` means, and what kind of ticket each tool creates, depends on the tool: +# +# | Tool | `project` means | Ticket types | +# |----------------|------------------|----------------------------------------------| +# | Jira | project | issue type (Story, Task, Bug) | +# | Azure DevOps | project | work item type | +# | GitLab | project | issue type | +# | GitHub Issues | repository | issue type, where the organization has them | +# | Shortcut | team | story type | +# | Linear | team | none (labels) | +# | Asana / Trello | project / board | none | +# +# The `auto` switches let docket act on a linked ticket on its own after each event: a change is +# created, its spec is written, its pull request opens, its pull request merges, or its results +# are complete. All are off by default. +# +# These settings belong to the repository: a value in the global config or `.docket.local.yml` is +# ignored with a warning. +# scope: repo-only (shared-setting guarded) +tickets: + provider: "" + site: "" + project: "" + auto: + change_created: false + spec_written: false + pr_opened: false + pr_merged: false + results_completed: false + + # ═══ Agent harnesses & agent models ═══════════════════════════════════════════════════════ # agent_harnesses — which harnesses this repository's dispatch surfaces are installed for. It has diff --git a/internal/config/config.go b/internal/config/config.go index c61c5b63a..72169cd60 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -135,6 +135,7 @@ type Effective struct { BoardSurfaces Value[[]string] `json:"board_surfaces"` Board Board `json:"board"` ChangeTypes Value[[]string] `json:"change_types"` + Tickets Tickets `json:"tickets"` // AgentHarnesses is the repository's explicit parent-facing dispatch opt-in. // Write authority for repository surfaces exists iff it is Explicit AND its // provenance is the repository or repository-local layer; a global-layer @@ -145,6 +146,25 @@ type Effective struct { Agents AgentsTable `json:"agents"` } +// Tickets names the repository's ticket system and where new tickets go, plus +// the per-event automation switches. Every leaf is repository-only. +type Tickets struct { + Provider Value[string] `json:"provider"` + Site Value[string] `json:"site"` + Project Value[string] `json:"project"` + Auto TicketsAuto `json:"auto"` +} + +// TicketsAuto holds the switches that let docket act on a linked ticket on +// its own after each event. All default off. +type TicketsAuto struct { + ChangeCreated Value[bool] `json:"change_created"` + SpecWritten Value[bool] `json:"spec_written"` + PROpened Value[bool] `json:"pr_opened"` + PRMerged Value[bool] `json:"pr_merged"` + ResultsCompleted Value[bool] `json:"results_completed"` +} + type Finalize struct { Gate Value[string] `json:"gate"` // local|off (ci/both classify deferred-active) TestCommand Value[string] `json:"test_command"` // "" == unconfigured (legacy `auto` resolves away) diff --git a/internal/config/decode_test.go b/internal/config/decode_test.go index 516b0cf47..aa4fc4687 100644 --- a/internal/config/decode_test.go +++ b/internal/config/decode_test.go @@ -139,6 +139,29 @@ func decodeAcceptanceCases() []decodeCase { block: "change_types:\n - feat\n - fix\n", flow: "change_types: [feat, fix]\n", value: []string{"feat", "fix"}}, + {row: "tickets.provider", path: "tickets.provider", + block: "tickets:\n provider: jira\n", flow: "tickets: {provider: jira}\n", value: "jira"}, + {row: "tickets.site", path: "tickets.site", + block: "tickets:\n site: tickets.example.com\n", + flow: "tickets: {site: tickets.example.com}\n", value: "tickets.example.com"}, + {row: "tickets.project", path: "tickets.project", + block: "tickets:\n project: CLOUD\n", flow: "tickets: {project: CLOUD}\n", value: "CLOUD"}, + {row: "tickets.auto.change_created", path: "tickets.auto.change_created", + block: "tickets:\n auto:\n change_created: true\n", + flow: "tickets: {auto: {change_created: true}}\n", value: true}, + {row: "tickets.auto.spec_written", path: "tickets.auto.spec_written", + block: "tickets:\n auto:\n spec_written: true\n", + flow: "tickets: {auto: {spec_written: true}}\n", value: true}, + {row: "tickets.auto.pr_opened", path: "tickets.auto.pr_opened", + block: "tickets:\n auto:\n pr_opened: true\n", + flow: "tickets: {auto: {pr_opened: true}}\n", value: true}, + {row: "tickets.auto.pr_merged", path: "tickets.auto.pr_merged", + block: "tickets:\n auto:\n pr_merged: true\n", + flow: "tickets: {auto: {pr_merged: true}}\n", value: true}, + {row: "tickets.auto.results_completed", path: "tickets.auto.results_completed", + block: "tickets:\n auto:\n results_completed: true\n", + flow: "tickets: {auto: {results_completed: true}}\n", value: true}, + {row: "auto_capture.enabled", path: "auto_capture.enabled", block: "auto_capture:\n enabled: true\n", flow: "auto_capture: {enabled: true}\n", value: true}, @@ -339,6 +362,8 @@ func TestDecodeRejections(t *testing.T) { {"duplicate change type", "change_types: [feat, feat]\n", CodeInvalidValue, "change_types", SeverityError}, {"reserved change type", "change_types: [all]\n", CodeInvalidValue, "change_types", SeverityError}, {"bad token pattern", "change_types: [Feat]\n", CodeInvalidValue, "change_types", SeverityError}, + {"unknown tickets key", "tickets:\n provder: jira\n", CodeUnknownKey, "tickets.provder", SeverityError}, + {"unknown tickets auto switch", "tickets:\n auto:\n pr_closed: true\n", CodeUnknownKey, "tickets.auto.pr_closed", SeverityError}, {"obsolete scalar auto_capture true", "auto_capture: true\n", CodeInvalidValue, "auto_capture", SeverityError}, {"obsolete scalar auto_capture false", "auto_capture: false\n", CodeInvalidValue, "auto_capture", SeverityError}, {"interior node as scalar", "finalize: local\n", CodeInvalidType, "finalize", SeverityError}, diff --git a/internal/config/defaults.go b/internal/config/defaults.go index d375b3bc2..589fdce2f 100644 --- a/internal/config/defaults.go +++ b/internal/config/defaults.go @@ -57,6 +57,18 @@ func builtinEffective() Effective { Sorting: builtinBoardSorting(), }, ChangeTypes: builtinValue([]string{"chore", "docs", "feat", "fix", "refactor", "perf"}), + Tickets: Tickets{ + Provider: builtinValue(""), + Site: builtinValue(""), + Project: builtinValue(""), + Auto: TicketsAuto{ + ChangeCreated: builtinValue(false), + SpecWritten: builtinValue(false), + PROpened: builtinValue(false), + PRMerged: builtinValue(false), + ResultsCompleted: builtinValue(false), + }, + }, // No built-in default: an absent agent_harnesses is the touch-nothing // state, so the built-in value is a nil list that stays non-explicit. AgentHarnesses: builtinValue([]string(nil)), diff --git a/internal/config/defaults_test.go b/internal/config/defaults_test.go index 7307795a3..9661de5a6 100644 --- a/internal/config/defaults_test.go +++ b/internal/config/defaults_test.go @@ -176,6 +176,14 @@ func TestBuiltinEffectiveMatchesRegistryDefaults(t *testing.T) { "gate_observation_budget": eff.GateObservation.Value, "board_surfaces": eff.BoardSurfaces.Value, "change_types": eff.ChangeTypes.Value, + "tickets.provider": eff.Tickets.Provider.Value, + "tickets.site": eff.Tickets.Site.Value, + "tickets.project": eff.Tickets.Project.Value, + "tickets.auto.change_created": eff.Tickets.Auto.ChangeCreated.Value, + "tickets.auto.spec_written": eff.Tickets.Auto.SpecWritten.Value, + "tickets.auto.pr_opened": eff.Tickets.Auto.PROpened.Value, + "tickets.auto.pr_merged": eff.Tickets.Auto.PRMerged.Value, + "tickets.auto.results_completed": eff.Tickets.Auto.ResultsCompleted.Value, } // The board presentation block mirrors the registry the same way: the // section-order list and every per-section sort leaf, keyed and walked by diff --git a/internal/config/fixtures_test.go b/internal/config/fixtures_test.go index ac05c656a..d479590c8 100644 --- a/internal/config/fixtures_test.go +++ b/internal/config/fixtures_test.go @@ -187,6 +187,14 @@ func TestFixtureSparseDefaults(t *testing.T) { {"gate_observation_budget", eff.GateObservation.Explicit, eff.GateObservation.Provenance.Layer}, {"board_surfaces", eff.BoardSurfaces.Explicit, eff.BoardSurfaces.Provenance.Layer}, {"change_types", eff.ChangeTypes.Explicit, eff.ChangeTypes.Provenance.Layer}, + {"tickets.provider", eff.Tickets.Provider.Explicit, eff.Tickets.Provider.Provenance.Layer}, + {"tickets.site", eff.Tickets.Site.Explicit, eff.Tickets.Site.Provenance.Layer}, + {"tickets.project", eff.Tickets.Project.Explicit, eff.Tickets.Project.Provenance.Layer}, + {"tickets.auto.change_created", eff.Tickets.Auto.ChangeCreated.Explicit, eff.Tickets.Auto.ChangeCreated.Provenance.Layer}, + {"tickets.auto.spec_written", eff.Tickets.Auto.SpecWritten.Explicit, eff.Tickets.Auto.SpecWritten.Provenance.Layer}, + {"tickets.auto.pr_opened", eff.Tickets.Auto.PROpened.Explicit, eff.Tickets.Auto.PROpened.Provenance.Layer}, + {"tickets.auto.pr_merged", eff.Tickets.Auto.PRMerged.Explicit, eff.Tickets.Auto.PRMerged.Provenance.Layer}, + {"tickets.auto.results_completed", eff.Tickets.Auto.ResultsCompleted.Explicit, eff.Tickets.Auto.ResultsCompleted.Provenance.Layer}, } { if leaf.explicit { t.Errorf("%s: Explicit is true with no configuration file present", leaf.path) diff --git a/internal/config/resolve.go b/internal/config/resolve.go index a9e9fdfcc..6bb458d47 100644 --- a/internal/config/resolve.go +++ b/internal/config/resolve.go @@ -330,6 +330,14 @@ func (r *resolution) assemble(byLayer map[LayerKind]map[string]leafDecl) (Effect eff.Board.Sorting[s] = srt } set(assign(&eff.ChangeTypes, r.declared, "change_types")) + set(assign(&eff.Tickets.Provider, r.declared, "tickets.provider")) + set(assign(&eff.Tickets.Site, r.declared, "tickets.site")) + set(assign(&eff.Tickets.Project, r.declared, "tickets.project")) + set(assign(&eff.Tickets.Auto.ChangeCreated, r.declared, "tickets.auto.change_created")) + set(assign(&eff.Tickets.Auto.SpecWritten, r.declared, "tickets.auto.spec_written")) + set(assign(&eff.Tickets.Auto.PROpened, r.declared, "tickets.auto.pr_opened")) + set(assign(&eff.Tickets.Auto.PRMerged, r.declared, "tickets.auto.pr_merged")) + set(assign(&eff.Tickets.Auto.ResultsCompleted, r.declared, "tickets.auto.results_completed")) set(assign(&eff.AgentHarnesses, r.declared, "agent_harnesses")) if len(errs) > 0 { return eff, errs[0] diff --git a/internal/config/resolve_test.go b/internal/config/resolve_test.go index 18f11400d..61641c12f 100644 --- a/internal/config/resolve_test.go +++ b/internal/config/resolve_test.go @@ -4,6 +4,7 @@ import ( "errors" "fmt" "reflect" + "strings" "testing" ) @@ -102,6 +103,22 @@ func effectiveLeaf(t *testing.T, eff Effective, path string) (any, Provenance, b return eff.BoardSurfaces.Value, eff.BoardSurfaces.Provenance, eff.BoardSurfaces.Explicit case "change_types": return eff.ChangeTypes.Value, eff.ChangeTypes.Provenance, eff.ChangeTypes.Explicit + case "tickets.provider": + return eff.Tickets.Provider.Value, eff.Tickets.Provider.Provenance, eff.Tickets.Provider.Explicit + case "tickets.site": + return eff.Tickets.Site.Value, eff.Tickets.Site.Provenance, eff.Tickets.Site.Explicit + case "tickets.project": + return eff.Tickets.Project.Value, eff.Tickets.Project.Provenance, eff.Tickets.Project.Explicit + case "tickets.auto.change_created": + return eff.Tickets.Auto.ChangeCreated.Value, eff.Tickets.Auto.ChangeCreated.Provenance, eff.Tickets.Auto.ChangeCreated.Explicit + case "tickets.auto.spec_written": + return eff.Tickets.Auto.SpecWritten.Value, eff.Tickets.Auto.SpecWritten.Provenance, eff.Tickets.Auto.SpecWritten.Explicit + case "tickets.auto.pr_opened": + return eff.Tickets.Auto.PROpened.Value, eff.Tickets.Auto.PROpened.Provenance, eff.Tickets.Auto.PROpened.Explicit + case "tickets.auto.pr_merged": + return eff.Tickets.Auto.PRMerged.Value, eff.Tickets.Auto.PRMerged.Provenance, eff.Tickets.Auto.PRMerged.Explicit + case "tickets.auto.results_completed": + return eff.Tickets.Auto.ResultsCompleted.Value, eff.Tickets.Auto.ResultsCompleted.Provenance, eff.Tickets.Auto.ResultsCompleted.Explicit } t.Fatalf("effectiveLeaf: %q is not an Effective leaf", path) return nil, Provenance{}, false @@ -618,6 +635,77 @@ func guardCases() []guardCase { {"github_project", "github_project: {owner: acme, number: 7}\n", "github_project: auto\n", githubProject{Owner: "acme", Number: 7}}, {"terminal_publish", "terminal_publish: true\n", "terminal_publish: false\n", true}, + {"tickets.provider", "tickets:\n provider: jira\n", "tickets:\n provider: linear\n", "jira"}, + {"tickets.site", "tickets:\n site: tickets.example.com\n", "tickets:\n site: other.example.com\n", "tickets.example.com"}, + {"tickets.project", "tickets:\n project: CLOUD\n", "tickets:\n project: OPS\n", "CLOUD"}, + {"tickets.auto.change_created", "tickets:\n auto: {change_created: true}\n", "tickets:\n auto: {change_created: false}\n", true}, + {"tickets.auto.spec_written", "tickets:\n auto: {spec_written: true}\n", "tickets:\n auto: {spec_written: false}\n", true}, + {"tickets.auto.pr_opened", "tickets:\n auto: {pr_opened: true}\n", "tickets:\n auto: {pr_opened: false}\n", true}, + {"tickets.auto.pr_merged", "tickets:\n auto: {pr_merged: true}\n", "tickets:\n auto: {pr_merged: false}\n", true}, + {"tickets.auto.results_completed", "tickets:\n auto: {results_completed: true}\n", "tickets:\n auto: {results_completed: false}\n", true}, + } +} + +// TestTicketsKeysRepoOnly: the ticket settings belong to the repository. A +// machine layer (global or repository-local) declaring one is warned about +// per key and leaves the built-in value in force; the committed layer's +// declaration resolves with repository provenance and blocks nothing. +func TestTicketsKeysRepoOnly(t *testing.T) { + const doc = "tickets:\n provider: jira\n auto:\n pr_opened: true\n" + for _, build := range []func(string) Source{srcG, srcL} { + src := build(doc) + t.Run(string(src.Layer), func(t *testing.T) { + snap := mustSnapshot(t, src) + ignored := diagPathSet(snap, CodeSharedSettingIgnored) + for _, p := range []string{"tickets.provider", "tickets.auto.pr_opened"} { + if !ignored[p] { + t.Errorf("%s declared in the %s layer produced no shared-setting-ignored warning", p, src.Layer) + } + } + for _, d := range snap.Diagnostics { + if d.Code == CodeSharedSettingIgnored && d.Severity != SeverityWarning { + t.Errorf("%s: severity %q, want warning", d.Path, d.Severity) + } + } + eff := snap.Effective + if eff.Tickets.Provider.Value != "" || eff.Tickets.Provider.Explicit { + t.Errorf("tickets.provider = %q (explicit %v), want the built-in \"\"", eff.Tickets.Provider.Value, eff.Tickets.Provider.Explicit) + } + if eff.Tickets.Auto.PROpened.Value || eff.Tickets.Auto.PROpened.Explicit { + t.Errorf("tickets.auto.pr_opened = %v (explicit %v), want the built-in false", eff.Tickets.Auto.PROpened.Value, eff.Tickets.Auto.PROpened.Explicit) + } + }) + } + + snap := mustSnapshot(t, srcR(doc)) + eff := snap.Effective + if eff.Tickets.Provider.Value != "jira" || eff.Tickets.Provider.Provenance.Layer != LayerRepository { + t.Errorf("tickets.provider = %q from %q, want jira from the repository layer", eff.Tickets.Provider.Value, eff.Tickets.Provider.Provenance.Layer) + } + if !eff.Tickets.Auto.PROpened.Value || eff.Tickets.Auto.PROpened.Provenance.Layer != LayerRepository { + t.Errorf("tickets.auto.pr_opened = %v from %q, want true from the repository layer", eff.Tickets.Auto.PROpened.Value, eff.Tickets.Auto.PROpened.Provenance.Layer) + } + if !PreflightMutation(snap).Allowed { + t.Errorf("preflight blocked a repository declaring ticket settings: %v", blockerPaths(snap)) + } +} + +// TestTicketsStringSingleLine: a ticket string setting is one line; a value +// carrying a line break is rejected rather than stored. +func TestTicketsStringSingleLine(t *testing.T) { + for _, doc := range []string{ + "tickets:\n site: \"a\\nb\"\n", + "tickets:\n project: \"a\\rb\"\n", + "tickets:\n provider: \"jira\\n\"\n", + } { + _, diags := decodeDoc(t, doc) + if len(diags) != 1 || diags[0].Code != CodeInvalidValue { + t.Errorf("%q: want one %s diagnostic, got %+v", doc, CodeInvalidValue, diags) + continue + } + if !strings.Contains(diags[0].Message, "must be a single line") { + t.Errorf("%q: message %q does not say the value must be a single line", doc, diags[0].Message) + } } } diff --git a/internal/config/schema.go b/internal/config/schema.go index 738e7d577..4f5462feb 100644 --- a/internal/config/schema.go +++ b/internal/config/schema.go @@ -382,6 +382,30 @@ func buildRegistry() []pathSpec { reserved: reservedChangeTypes, })}, + // The ticket settings: which ticket system a repository links to, where + // new tickets go, and the per-event automation switches. All belong to + // the repository, so a machine layer's declaration is ignored with a + // warning. + {path: "tickets.provider", kind: kindString, def: "", + merge: mergeScalar, scope: scopeRepoOnly, disp: dispSupported, + validate: singleLineStringLeaf()}, + {path: "tickets.site", kind: kindString, def: "", + merge: mergeScalar, scope: scopeRepoOnly, disp: dispSupported, + validate: singleLineStringLeaf()}, + {path: "tickets.project", kind: kindString, def: "", + merge: mergeScalar, scope: scopeRepoOnly, disp: dispSupported, + validate: singleLineStringLeaf()}, + {path: "tickets.auto.change_created", kind: kindBool, def: false, + merge: mergeScalar, scope: scopeRepoOnly, disp: dispSupported, validate: boolLeaf()}, + {path: "tickets.auto.spec_written", kind: kindBool, def: false, + merge: mergeScalar, scope: scopeRepoOnly, disp: dispSupported, validate: boolLeaf()}, + {path: "tickets.auto.pr_opened", kind: kindBool, def: false, + merge: mergeScalar, scope: scopeRepoOnly, disp: dispSupported, validate: boolLeaf()}, + {path: "tickets.auto.pr_merged", kind: kindBool, def: false, + merge: mergeScalar, scope: scopeRepoOnly, disp: dispSupported, validate: boolLeaf()}, + {path: "tickets.auto.results_completed", kind: kindBool, def: false, + merge: mergeScalar, scope: scopeRepoOnly, disp: dispSupported, validate: boolLeaf()}, + // 25-26: auto capture. The subset check against effective change_types // cannot run here — it is cross-leaf, so resolution owns it. {path: "auto_capture.enabled", kind: kindBool, def: false, @@ -593,6 +617,23 @@ func stringLeaf(nonEmpty, spaceFree, relPath bool) leafValidator { } } +// singleLineStringLeaf is stringLeaf with no other constraint, except that the +// value must be one line: a carriage return or line feed is rejected. +func singleLineStringLeaf() leafValidator { + base := stringLeaf(false, false, false) + return func(src Source, path string, n *yaml.Node) (any, []Diagnostic) { + v, diags := base(src, path, n) + if diags != nil { + return nil, diags + } + if strings.ContainsAny(n.Value, "\r\n") { + return nil, []Diagnostic{leafDiag(src, path, CodeInvalidValue, n, + "must be a single line")} + } + return v, nil + } +} + // relPathDiag enforces the directory-setting rule: relative, already clean, // and with no parent segment. `docs/../etc` is rejected on the clean test // rather than resolved, so what the file says is what the tool uses. diff --git a/internal/config/schema_test.go b/internal/config/schema_test.go index 1bfb2da15..7a8040401 100644 --- a/internal/config/schema_test.go +++ b/internal/config/schema_test.go @@ -38,7 +38,11 @@ func TestRegistryPathSetMatchesV092(t *testing.T) { "board.sorting.proposed.by", "board.sorting.proposed.direction", "board.sorting.deferred.by", "board.sorting.deferred.direction", "github_project", "terminal_publish", "auto_groom", - "change_types", "auto_capture.enabled", "auto_capture.types", + "change_types", + "tickets.provider", "tickets.site", "tickets.project", + "tickets.auto.change_created", "tickets.auto.spec_written", "tickets.auto.pr_opened", + "tickets.auto.pr_merged", "tickets.auto.results_completed", + "auto_capture.enabled", "auto_capture.types", "dummy_mode.enabled", "dummy_mode.persona", "dummy_mode.surfaces", "agent_harnesses", "skills.brainstorm", "skills.plan", "skills.build", "skills.review", "skills.finish", @@ -83,6 +87,9 @@ func TestRegistryRepoOnlySet(t *testing.T) { "integration_branch", "changes_dir", "adrs_dir", "results_dir", "github_project", "terminal_publish", + "tickets.provider", "tickets.site", "tickets.project", + "tickets.auto.change_created", "tickets.auto.spec_written", "tickets.auto.pr_opened", + "tickets.auto.pr_merged", "tickets.auto.results_completed", } wantLocalOnly := []string{"runtime.bash"} @@ -139,6 +146,14 @@ func TestRegistryDefaults(t *testing.T) { "terminal_publish": false, "auto_groom": false, "change_types": []string{"chore", "docs", "feat", "fix", "refactor", "perf"}, + "tickets.provider": "", + "tickets.site": "", + "tickets.project": "", + "tickets.auto.change_created": false, + "tickets.auto.spec_written": false, + "tickets.auto.pr_opened": false, + "tickets.auto.pr_merged": false, + "tickets.auto.results_completed": false, "auto_capture.enabled": false, "auto_capture.types": "all", "dummy_mode.enabled": false, @@ -386,6 +401,12 @@ func TestLeafValidators(t *testing.T) { {"change types reserved untyped", "change_types", "[untyped]", nil, CodeInvalidValue}, {"change types bad pattern", "change_types", "[Feat]", nil, CodeInvalidValue}, {"change types leading dash", "change_types", "[-feat]", nil, CodeInvalidValue}, + {"tickets provider ok", "tickets.provider", "jira", "jira", ""}, + {"tickets site empty ok", "tickets.site", `""`, "", ""}, + {"tickets project with space ok", "tickets.project", `"Cloud Team"`, "Cloud Team", ""}, + {"tickets site not a string", "tickets.site", "[a]", nil, CodeInvalidType}, + {"tickets auto bool", "tickets.auto.pr_opened", "true", true, ""}, + {"tickets auto not a bool", "tickets.auto.pr_merged", "yes-please", nil, CodeInvalidType}, // scalar-or-list. {"auto_capture types all", "auto_capture.types", "all", "all", ""}, diff --git a/internal/config/setting_paths_test.go b/internal/config/setting_paths_test.go index 43cf6ebd5..9e98c720f 100644 --- a/internal/config/setting_paths_test.go +++ b/internal/config/setting_paths_test.go @@ -13,7 +13,10 @@ import ( // the leaves a machine layer may not declare and a visibility switch never // carries out of the local file. func TestRepoOnlyPaths(t *testing.T) { - want := []string{"integration_branch", "changes_dir", "adrs_dir", "results_dir", "github_project", "terminal_publish"} + want := []string{"integration_branch", "changes_dir", "adrs_dir", "results_dir", "github_project", "terminal_publish", + "tickets.provider", "tickets.site", "tickets.project", + "tickets.auto.change_created", "tickets.auto.spec_written", "tickets.auto.pr_opened", + "tickets.auto.pr_merged", "tickets.auto.results_completed"} got := RepoOnlyPaths() if len(got) != len(want) { t.Fatalf("RepoOnlyPaths() = %v, want %v", got, want) @@ -52,6 +55,9 @@ func TestSettingPathsSupportSplit(t *testing.T) { "gate_observation_budget", "board_surfaces", "board.section_order", "change_types", "agent_harnesses", + "tickets.provider", "tickets.site", "tickets.project", + "tickets.auto.change_created", "tickets.auto.spec_written", "tickets.auto.pr_opened", + "tickets.auto.pr_merged", "tickets.auto.results_completed", "agents.*.*.model", "agents.*.*.effort", "agents.*.*.cache_ttl", } for _, s := range BoardSectionTokens { diff --git a/internal/repoguard/docket_yml_tickets_test.go b/internal/repoguard/docket_yml_tickets_test.go new file mode 100644 index 000000000..c36cec007 --- /dev/null +++ b/internal/repoguard/docket_yml_tickets_test.go @@ -0,0 +1,67 @@ +package repoguard + +import ( + "fmt" + "slices" + "testing" + + "go.yaml.in/yaml/v3" +) + +// topLevelKeys returns the keys of a YAML document's top-level mapping, in +// document order. It parses the document rather than matching lines, so a +// block mapping and a flow mapping are read alike and a commented-out key is +// not a key. An empty document has no keys. +func topLevelKeys(b []byte) ([]string, error) { + var doc yaml.Node + if err := yaml.Unmarshal(b, &doc); err != nil { + return nil, err + } + if doc.Kind == 0 || len(doc.Content) == 0 { + return nil, nil + } + root := doc.Content[0] + if root.Kind != yaml.MappingNode { + return nil, fmt.Errorf("top level is not a mapping (kind %d)", root.Kind) + } + keys := make([]string, 0, len(root.Content)/2) + for i := 0; i+1 < len(root.Content); i += 2 { + keys = append(keys, root.Content[i].Value) + } + return keys, nil +} + +// TestDocketYMLDeclaresNoTicketsKey: docket's own repository is never linked +// to a ticket system, so its committed .docket.yml must not carry a tickets +// block. The ticket settings are exercised in another repository. +func TestDocketYMLDeclaresNoTicketsKey(t *testing.T) { + keys, err := topLevelKeys([]byte(readRepoFile(t, ".docket.yml"))) + if err != nil { + t.Fatalf("parsing .docket.yml: %v", err) + } + if slices.Contains(keys, "tickets") { + t.Errorf(".docket.yml declares a top-level tickets key; docket's own configuration must never carry one") + } +} + +// TestTopLevelKeysSeesTickets is the in-suite mutation proof for the guard +// above: the helper finds a tickets key in block and flow spelling, and does +// not mistake a commented-out one for a declaration. +func TestTopLevelKeysSeesTickets(t *testing.T) { + for _, tc := range []struct { + doc string + want bool + }{ + {"tickets:\n provider: jira\n", true}, + {"tickets: {provider: jira}\n", true}, + {"finalize:\n gate: local\n# tickets:\n", false}, + } { + keys, err := topLevelKeys([]byte(tc.doc)) + if err != nil { + t.Fatalf("%q: %v", tc.doc, err) + } + if got := slices.Contains(keys, "tickets"); got != tc.want { + t.Errorf("%q: found tickets = %v, want %v (keys %v)", tc.doc, got, tc.want, keys) + } + } +} From 44cac9593f32685d816320077026f3fe2a13fc32 Mon Sep 17 00:00:00 2001 From: Daniel Hanold Date: Mon, 9 Nov 2026 18:30:17 -0500 Subject: [PATCH 09/12] docs(skills): document ticket links and the PR ticket line --- internal/assets/embedded/manifest.json | 10 +++++----- .../tree/skills/docket-convention/SKILL.md | 14 +++++++++++++ .../skills/docket-implement-next/SKILL.md | 4 ++-- internal/cli/open.go | 2 +- internal/cli/open_test.go | 15 ++++++++++++++ internal/repoguard/budgets_test.go | 4 ++-- internal/repoguard/prose_contracts_test.go | 20 ++++++++++++++++++- skills/docket-convention/SKILL.md | 14 +++++++++++++ skills/docket-implement-next/SKILL.md | 4 ++-- 9 files changed, 74 insertions(+), 13 deletions(-) diff --git a/internal/assets/embedded/manifest.json b/internal/assets/embedded/manifest.json index 8d6459a41..ba2882df4 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:b16a8a0452290b69b9608c22f0187de0ce892618264880bef098ae6618e82265", + "asset_set_id": "sha256:32bd9f5aa56f95f3e92aacd08e4e95f2a471b9ae91cf1c20ccca13afecd0e1fd", "entries": [ { "path": ".docket.example.yml", @@ -322,8 +322,8 @@ "path": "skills/docket-convention/SKILL.md", "role": "skill", "mode": 420, - "size": 53140, - "sha256": "b433182ecb64c7d8bea9d8566b01bd6189510acdbfbce2ef36ea05d9ac9192f5" + "size": 54347, + "sha256": "94f362932340a28e8a36cf9ce9e5fac5a9932f11b7d86d4e1aa44b58ad6cbf12" }, { "path": "skills/docket-convention/references/agent-layer.md", @@ -385,8 +385,8 @@ "path": "skills/docket-implement-next/SKILL.md", "role": "skill", "mode": 420, - "size": 60475, - "sha256": "dbe62d791bde8851e9f5a1e0683a5a6f0acf4cf82eb50b751ce379e6a5c44f06" + "size": 60524, + "sha256": "63fb2fb741677a23ef5207f2fbe0babea56f4b9abced0f800a3ff088bb8b248d" }, { "path": "skills/docket-implement-next/references/edge-paths.md", diff --git a/internal/assets/embedded/tree/skills/docket-convention/SKILL.md b/internal/assets/embedded/tree/skills/docket-convention/SKILL.md index a7c600349..4414f9ca3 100644 --- a/internal/assets/embedded/tree/skills/docket-convention/SKILL.md +++ b/internal/assets/embedded/tree/skills/docket-convention/SKILL.md @@ -189,6 +189,9 @@ hold: # `true` keeps a groomed change out of autonomous buil branch_prefix: # optional one unqualified branch-path component; overrides at mint, consumed only at claim, inert once branch: is populated branch: # minted / (or /) name, set on claim; sole feature-head source of truth after, never reconstructed; branch itself created at build (step 4) pr: # set when the PR is opened +ticket_provider: # the ticket system of the linked ticket (jira, linear, …); the three ticket fields are written together by change.link-ticket +ticket_id: # the ticket's id as that system shows it (CLOUD-123) +ticket_url: # the ticket's web address blocked_by: # free text; set only when status: blocked reconciled: false # set true after the just-in-time reconcile pass --- @@ -198,6 +201,17 @@ reconciled: false # set true after the just-in-time reconcile pass the sole source of truth for that relationship — the parent-side link is derived at render time — and is never copied into `related:` or `depends_on:`. +**Ticket link.** A change links to a ticket in the team's ticket system through all three fields — +`ticket_provider:`, `ticket_id:`, and `ticket_url:` — or none. The `change.link-ticket` operation +(request file: `change_id`, `path`, `revision`, then either the three fields or `unlink: true`) +links in any status, archived changes included, and re-renders `## Artifacts` with a Ticket row. +Re-linking the same ticket writes nothing. A link to a different ticket is refused unless the +request carries `replace: true`. A human's plain-words request ("switch it to CLOUD-456", "this is +actually CLOUD-456") is that explicit replace request, and the agent sends `replace: true` for it; +an agent must never replace a link on its own initiative. `change.create` accepts the same three +fields. A hand-edited partial or invalid set counts as not linked and is reported as the warning +`ticket-link-invalid`, never a block. + **Closed-out plans and results are frozen build records.** Once a change is closed out, its `plan:` and `results:` files are never hand-edited again — not to correct a stale line reference, not to update a superseded instruction. The only later write re-stamps the generated `docket:backlink` block, done by diff --git a/internal/assets/embedded/tree/skills/docket-implement-next/SKILL.md b/internal/assets/embedded/tree/skills/docket-implement-next/SKILL.md index 4b70dc207..8ff93c256 100644 --- a/internal/assets/embedded/tree/skills/docket-implement-next/SKILL.md +++ b/internal/assets/embedded/tree/skills/docket-implement-next/SKILL.md @@ -142,9 +142,9 @@ The results artifact is **required for every implemented change** — there is n **Publish the feature head.** The `workspace.publish` operation with `--id --head ` inspects the owned workspace and pushes the exact head through the landed non-forcing publication, returning the verified remote head. It refuses when the reinspected head differs from `--head`; a divergent remote ref is `contended`, unknown post-effect state is `unknown` (reprobe on retry) — neither forces, and no PR opens here. -**PR-body assembly.** The PR body carries no build-evidence block. In a private repository the authored title and body follow the private-repository writing rule: no `#` reference, no change id in the title, and `pr.publish` publishes the body verbatim, with no back-link line and no links block. +**PR-body assembly.** The PR body carries no build-evidence block. In a private repository the authored title and body follow the private-repository writing rule: no change id in the title, and `pr.publish` publishes the body verbatim, with no back-link line and no links block. -**Best-effort PR→issue reference.** If the change carries an `issue:` value, add a plain `#` reference to the PR body — but **never `Closes #N`**, so merging the PR never auto-closes the referenced issue. Skip silently when `issue:` is unset — the reference is a one-time courtesy, not a build gate. +**Ticket line.** When the implementation context's `change.summary.ticket` is present, the authored PR body carries one plain line, `Ticket: []()`, with that ticket's `id` and `url`; otherwise it carries none. The line goes in a private repository too: a ticket link is not docket machinery, and `pr.publish`'s leak check scans it with the rest of the body. Never a build gate. **PR-body back-link.** `pr.publish` renders and upserts a **back-link line** pointing home to the change on the metadata branch — a first body line of the shape `↩ Change — ` linking to the change file on `docket` (built with the same blob-or-bare-path logic) — plus a Docket-owned links block pointing at the plan and results files on the metadata branch; never author either in the body. diff --git a/internal/cli/open.go b/internal/cli/open.go index 691ce3fb1..39e616d0d 100644 --- a/internal/cli/open.go +++ b/internal/cli/open.go @@ -58,7 +58,7 @@ 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 <date>-<type>-<name>.md, type one of issue, spec, plan, or +The copy is named <date>-<type>-<name>.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 diff --git a/internal/cli/open_test.go b/internal/cli/open_test.go index a079f1bd1..3cf00aaf1 100644 --- a/internal/cli/open_test.go +++ b/internal/cli/open_test.go @@ -125,3 +125,18 @@ func TestOpenCLIExportDepsWiring(t *testing.T) { t.Fatalf("GOOS %q (want %q), HomeDir set %v, Getwd set %v", d.GOOS, runtime.GOOS, d.HomeDir != nil, d.Getwd != nil) } } + +// 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) + } +} diff --git a/internal/repoguard/budgets_test.go b/internal/repoguard/budgets_test.go index ed992bea6..5c0b4d697 100644 --- a/internal/repoguard/budgets_test.go +++ b/internal/repoguard/budgets_test.go @@ -199,7 +199,7 @@ var skillBudgets = []skillBudget{ {"docket-build/references/gate-driver.md", 138, 1552}, // 0502 review: the raw-verb section names finalize's repaired-head re-gate (137/1546 -> 138/1552); 0502: "loop" means /loop only (137/1550 -> 137/1546); 0502: finalize's repaired-head re-gate is a direct caller (136/1523 -> 137/1550); 0502: the gate-execution intro reference is deleted (138/1555 -> 136/1523); 0502: renamed from gate-caller-loop.md; 0497: +halted-gate tree-survives finding relay (134/1510 -> 138/1555); 0491: the run id is retired (134/1513 -> 134/1510); 0490: the admission section describes the supervisor-held worktree lock; launch-unconfirmed is no longer a refusal (136/1511 -> 134/1513); 0488 review fix: finalize reaches the driver only through finalize.rebase; task-era handoff clauses dropped (word ceiling 1504 -> 1511); 0488 review: start row carries --change-id (word ceiling 1491 -> 1504); 0488: worker-scope/takeover/acknowledge rows and the parent-takeover section removed; callers are the full-suite gates (175/1872 -> 136/1491); 0467: +prepare-scope --run-id and scope-inherited start run id (word ceiling 1826 -> 1872); 0375: +worktree-admission section (word ceiling 1750 -> 1826) {"docket-build/references/task-routing.md", 50, 500}, {"docket-build-task/SKILL.md", 173, 1695}, // 0532: the private-repository writing rule and visibility hand-off (168/1640 -> 173/1695); 0531: the metadata worktree and remote come from the repository.prepare context (168/1637 -> 168/1640); 0488: scoped drive protocol replaced by direct foreground tests under timeout; three outcomes (211/2235 -> 168/1637); 0467 review fix: +the repair re-run run-id exception (206/2183 -> 211/2235); 0467: +the run id rides on the scope, never the bundle (204/2151 -> 206/2183); 0459: +post-handoff continuation never acknowledges or reuses the transferred scope (188/1964 -> 204/2151); 0405: sequential-drive receipt and acknowledgement; 0420: shell-safe capture; 0375: worktree-busy-not-a-retry rule (179/1842 -> 188/1964) - {"docket-convention/SKILL.md", 356, 7352}, // 0582: acceptance criteria section and proposal order (353/7259 -> 356/7352); 0578: docket-export joins the inline skills (353/7257 -> 353/7259); 0575: reclaim and the claim lease are retired (361/7377 -> 353/7257); 0360: claimed_at is stamped by claim, reconcile, and resume-halted; a halt no longer claims a refreshed lease (361/7381 -> 361/7377); 0573: trivial retired (362/7411 -> 361/7381); 0560: the hold manifest field, its selection rule, the ## Why on hold section, and the auto-groomer's hold write (360/7331 -> 362/7411); 0565: a kill refuses on built stacked descendants; the killed-parent board text and exits table (360/7317 -> 360/7331); 0568: deferred is entered only from proposed (363/7317 -> 360/7317); 0559: the manifest lists deliverable; done means a merged PR or a completed results artifact; archive dates and change.complete (361/7276 -> 363/7317); 0533: editing visibility never moves a repository; repository.set-visibility does (361/7263 -> 361/7276); 0532: the private-repository writing rule and visibility hand-off (359/7160 -> 361/7263); 0531 review: skills say "the metadata branch", naming `docket` once for shared mode (359/7155 -> 359/7160); 0531: the metadata worktree and remote come from the repository.prepare context (357/7062 -> 359/7155); 0530: plan, results, and build evidence live on the docket branch — the plan-writer's one metadata operation, the attach operations as file-backlink writers, relative same-branch links, and the new ## Build evidence record section (357/7026 -> 357/7062); 0529 review: the backlink block names its PR-body writers beside artifact.backlink, one shared renderer (357/7004 -> 357/7026); 0515: the repair sign-off is retired; a green repair merges (357/7007 -> 357/7004); 0502 rebase onto 0510: kept the backlog-match follow-up clause in the results-artifact paragraph (357/7004 -> 357/7007); 0502 review: the review-tier dispatch is the controller's own (357/6995 -> 357/7004); 0502: configuration read paths corrected — operations read .docket.yml from origin's default-branch tip, the repository setup operations from the primary worktree (357/6959 -> 357/6995); 0502: "loop" means /loop only (357/7036 -> 357/7037); 0502: one metadata layout — the docket branch and the .docket/ worktree (357/7035 -> 357/7036); 0502: agent layer names user-level wrappers and global-only pins (357/7024 -> 357/7035); 0502: typed operations replace the Bash-era script names; ## Run halted facts corrected (359/7092 -> 357/7024); 0502: terminal publish, the learnings cap, and the repository auto_groom default are deleted (362/7256 -> 359/7092); 0502: the auto-capture export paragraph is deleted (370/7334 -> 362/7256); 0502: the configuration contract rewritten from the schema (371/7488 -> 370/7334); 0502: fixed role skills; halt posture (372/7660 -> 371/7488); 0502: record blocks mirror the renderers (367/7619 -> 372/7660); 0502: the dummy-mode shared definition is deleted (390/7848 -> 367/7619); 0410: +required-results lifecycle prose; 0399: +schema request/result contract prose; 0388: +sync-integration prose (see note above); 0502: drop change citations and Go v1 narration (357/7037 -> 357/6958); 0502: the harness adapter is named without a docket source path (357/6958 -> 357/6959) + {"docket-convention/SKILL.md", 370, 7527}, // 0583: the three ticket manifest fields and the Ticket link paragraph (356/7352 -> 370/7527); 0582: acceptance criteria section and proposal order (353/7259 -> 356/7352); 0578: docket-export joins the inline skills (353/7257 -> 353/7259); 0575: reclaim and the claim lease are retired (361/7377 -> 353/7257); 0360: claimed_at is stamped by claim, reconcile, and resume-halted; a halt no longer claims a refreshed lease (361/7381 -> 361/7377); 0573: trivial retired (362/7411 -> 361/7381); 0560: the hold manifest field, its selection rule, the ## Why on hold section, and the auto-groomer's hold write (360/7331 -> 362/7411); 0565: a kill refuses on built stacked descendants; the killed-parent board text and exits table (360/7317 -> 360/7331); 0568: deferred is entered only from proposed (363/7317 -> 360/7317); 0559: the manifest lists deliverable; done means a merged PR or a completed results artifact; archive dates and change.complete (361/7276 -> 363/7317); 0533: editing visibility never moves a repository; repository.set-visibility does (361/7263 -> 361/7276); 0532: the private-repository writing rule and visibility hand-off (359/7160 -> 361/7263); 0531 review: skills say "the metadata branch", naming `docket` once for shared mode (359/7155 -> 359/7160); 0531: the metadata worktree and remote come from the repository.prepare context (357/7062 -> 359/7155); 0530: plan, results, and build evidence live on the docket branch — the plan-writer's one metadata operation, the attach operations as file-backlink writers, relative same-branch links, and the new ## Build evidence record section (357/7026 -> 357/7062); 0529 review: the backlink block names its PR-body writers beside artifact.backlink, one shared renderer (357/7004 -> 357/7026); 0515: the repair sign-off is retired; a green repair merges (357/7007 -> 357/7004); 0502 rebase onto 0510: kept the backlog-match follow-up clause in the results-artifact paragraph (357/7004 -> 357/7007); 0502 review: the review-tier dispatch is the controller's own (357/6995 -> 357/7004); 0502: configuration read paths corrected — operations read .docket.yml from origin's default-branch tip, the repository setup operations from the primary worktree (357/6959 -> 357/6995); 0502: "loop" means /loop only (357/7036 -> 357/7037); 0502: one metadata layout — the docket branch and the .docket/ worktree (357/7035 -> 357/7036); 0502: agent layer names user-level wrappers and global-only pins (357/7024 -> 357/7035); 0502: typed operations replace the Bash-era script names; ## Run halted facts corrected (359/7092 -> 357/7024); 0502: terminal publish, the learnings cap, and the repository auto_groom default are deleted (362/7256 -> 359/7092); 0502: the auto-capture export paragraph is deleted (370/7334 -> 362/7256); 0502: the configuration contract rewritten from the schema (371/7488 -> 370/7334); 0502: fixed role skills; halt posture (372/7660 -> 371/7488); 0502: record blocks mirror the renderers (367/7619 -> 372/7660); 0502: the dummy-mode shared definition is deleted (390/7848 -> 367/7619); 0410: +required-results lifecycle prose; 0399: +schema request/result contract prose; 0388: +sync-integration prose (see note above); 0502: drop change citations and Go v1 narration (357/7037 -> 357/6958); 0502: the harness adapter is named without a docket source path (357/6958 -> 357/6959) // 0154: docket-convention/github-board-mirror.md removed — the GitHub mirror is // retired (unsupported, mutation-blocking); its budget row is deleted with it. {"docket-convention/references/agent-layer.md", 214, 1991}, // 0578: docket-export joins the inline skills (214/1989 -> 214/1991); 0552: the user-level settings.json also carries the finalize allow rules (212/1951 -> 214/1990); 0546: the per-agent cache_ttl pin, its shipped 1h default, and the machine-wide controls docket leaves unset (168/1593 -> 212/1951); 0538: init and repository.configure-harnesses set agent_harnesses; repository.check reports harnesses-unset (164/1553 -> 168/1593); 0535: a private repository's instructions file and its user-level triggers (148/1419 -> 164/1553); 0502: rewritten around user-level wrappers and global-only pins (202/2346 -> 148/1419); 0502: the legacy agents-file migration clause is deleted (202/2349 -> 202/2346) @@ -210,7 +210,7 @@ var skillBudgets = []skillBudget{ {"docket-finalize-change/SKILL.md", 242, 6269}, // 0571: the children-retarget-required closeout bullet is deleted; root-archived names who is carried (243/6254 -> 242/6269); 0567: step 10 cleans each carried_ids child after the root (243/6191 -> 243/6254); 0551: step 1 checks the change out into its own workspace first (241/6033 -> 243/6191); 0532 review: both finalize gate dispatches carry the Visibility payload line (239/6020 -> 241/6033); 0532: the private-repository writing rule and visibility hand-off (239/6000 -> 239/6020); 0529 review: the PR-backlink repoint is a best-effort follow-up after the archive push, for root-archived descendants too (239/5984 -> 239/6000); 0529: close-out repoints the merged PR description's backlink; pr-backlink-pending is a retryable warning (239/5936 -> 239/5984); 0525 review: workspace-remnant rides any finished-workspace disposition and is named in the final report; branch-rules-unavailable comes only from the probing run (239/5910 -> 239/5936); 0525: plan-gated merges carry branch-rules-unavailable into closeout notes; cleanup reports workspace-remnant and names what blocked a workspace (239/5820 -> 239/5910); 0515 review: the refused-notes fallback names every dropped note in the final report (238/5809 -> 239/5820); 0515 review: a repair whose run halts before closeout is named in finalize.block and carried into a later closeout (238/5708 -> 238/5809); 0515: the repair sign-off is retired; a green repair merges (238/5808 -> 238/5708); 0517: the repaired-head evidence.record carries --owner finalize and records finalize.test_command (238/5790 -> 238/5808); 0502 review: clear-block re-reads the revision after the block lands (238/5771 -> 238/5790); 0502: repair sign-off records finalize.block before publishing the repaired head (238/5733 -> 238/5771); 0502: "loop" means /loop only (238/5729 -> 238/5733); 0502: repair sign-off is the human running finalize.clear-block (238/5666 -> 238/5729); 0502: the repaired head is re-gated through the gate driver (236/5568 -> 238/5666); 0502: the dummy-mode paragraph is deleted (238/5641 -> 236/5568); 0455: +record-invalid refusal (structural scope, findings remedy, merged-outside-docket precedence) in step 8 (word ceiling 5520 -> 5647); 0442: +post-publication base-advance guidance (word ceiling 5421 -> 5520); de-duplicated the shared forward-rebase mechanic against the 0438 unpublished-case paragraph (reclaimed 57 words), but the distinct published-refresh facts plus the retained 0438 guidance cannot fit the old ceiling without deleting required guidance; 0411: +reconciliation-write recovery exception paragraph in the resolver loop (ceilings 238/5232 -> 239/5421); 0413: +generated-bundle mixed-conflict handoff sentence in the resolver-loop block (word ceiling 5200 -> 5232); 0419: +repair-attempt budget payload line and rewired repair contract (line ceiling 236 -> 238); 0393: +exact payload, marker, and direct-dispatch lines atop 0349/0410 (see note above) {"docket-finalize-change/references/gate-failure.md", 162, 2107}, // 0571: the children-retarget-required closeout halt is deleted (162/2111 -> 162/2107); 0532 review: the gate-agent payload names Visibility (161/2109 -> 162/2111); 0515 review: the refused-notes fallback names every dropped note in the final report (160/2098 -> 161/2109); 0515 review: a repair whose run halts before closeout is named in finalize.block and carried into a later closeout (153/2005 -> 160/2098); 0515: the repair sign-off is retired; a green repair merges (160/2086 -> 153/2005); 0517: the repaired-head evidence.record carries --owner finalize (159/2081 -> 160/2086); 0502 review: clear-block re-reads the revision after the block lands (157/2062 -> 159/2081); 0502: repair sign-off records finalize.block before publishing the repaired head (155/2028 -> 157/2062); 0502: the embedded-bundle rule is conditioned on docket's own repository (155/2024 -> 155/2028); 0502: "loop" means /loop only (155/2027 -> 155/2024); 0502: repair sign-off is the human running finalize.clear-block; the marker lifecycle names what removes it (154/2013 -> 155/2027); 0502: the repaired head is re-gated through the gate driver (148/1937 -> 154/2013); 0497: +wait-for-the-leftover-group sentence (146/1901 -> 148/1937); 0493: the gate relaunch is retired (145/1892 -> 146/1901); 0491: the run id is retired (145/1894 -> 145/1892); 0490: the shared-slot note became the shared worktree-lock note (147/1901 -> 145/1894); 0411: +reconciliation-write exception section and abort-set carve-out (ceilings 135/1472 -> 147/1901); 0413: +conflicted_paths-lists-authored-only rule in the resolver-report section (line ceiling 133 -> 135, word ceiling 1465 -> 1472); 0419: +repair-attempt budget payload and rewired repair contract prose (word ceiling 1450 -> 1465); 0349: +reserve-before-dispatch resolver protocol prose; 0375: +worktree-slot note for the scopeless finalize gate (120/1300 -> 133/1450) {"docket-groom-next/SKILL.md", 77, 2310}, // 0573: trivial retired; the brainstorm is told the artifact is always a spec (78/2377 -> 77/2310); 0560 review: a revise that sets or lifts a hold changes the row's readiness (78/2370 -> 78/2377); 0560: the Step-4 hold paragraph (76/2282 -> 78/2370); 0559: the Step-4 deliverable, type, and branch_prefix paragraph (78/2215 -> 76/2282); 0550: the Step-4 reprioritize paragraph and the stub-edit priority route (76/2141 -> 78/2215); 0532: the private-repository writing rule and visibility hand-off (76/2109 -> 76/2141); 0531: the metadata worktree and remote come from the repository.prepare context (76/2102 -> 76/2109); 0502 rebase onto 0509: carried the edit-a-stub revise route and groom-exit-scoped STOPs (76/2012 -> 76/2102); 0502: "loop" means /loop only (76/2011 -> 76/2012); 0502: one metadata layout — the docket branch and the .docket/ worktree (76/2010 -> 76/2011); 0502: selection bands key on auto_groomable itself (76/2009 -> 76/2010); 0502: invoke superpowers:brainstorming by name (76/2037 -> 76/2009); 0502: the dummy-mode pointer is deleted (78/2080 -> 76/2037); 0461: +Step-4 retitle paragraph (title on change.groom; lines 77 -> 78, words 1996 -> 2081); +not-retitleable refusal code (2081 -> 2082); 0382: +typed rearm exit (word ceiling 1889 -> 1996); 0445: +revise route for already-groomed explicit ids (Step 1) and the fifth Step-4 exit (word ceiling 1650 -> 1813); +spec_version pin for a spec-body revise (1813 -> 1849); +revise spec_markdown excludes the backlink block (1849 -> 1850); +revise in the description and the revise contended/board clauses (1850 -> 1889) - {"docket-implement-next/SKILL.md", 226, 8806}, // 0575: reclaim and the claim lease are retired (226/8841 -> 226/8806); review: Step 7 names the Step 6 evidence file instead of verified bytes (226/8835 -> 226/8841); 0360 step wording: the PR-body rules moved in from edge-paths.md (which fell 222 words) plus the minimal reconcile request, evidence block file, and ADR producing-change pass-through; the raise is that moved text, compressed (220/8590 -> 226/8835); 0360: local revision lookups, no claim refreshes, fewer re-syncs; the line raise is the new standalone Revision lookups paragraph every post-claim write keys on, words fell (218/8612 -> 220/8590); 0573: trivial retired (218/8637 -> 218/8612); 0570: the --selection claim sentence and the run-next driver rule (218/8555 -> 218/8637); 0560 review: on the named path on-hold also qualifies at the Step-1 confirm (218/8548 -> 218/8555); 0560: on-hold joins the readiness vocabulary and skip reasons; a held change is built when named (218/8518 -> 218/8548); 0559: the results-artifact ending pointer, postcondition row, and advanced meaning (215/8411 -> 218/8518); 0532: the private-repository writing rule and visibility hand-off (212/8282 -> 215/8411); 0531: the metadata worktree and remote come from the repository.prepare context (216/8443 -> 212/8282); 0517: evidence.record reads the gate command from build configuration (216/8438 -> 216/8443); 0502 rebase onto 0510: carried the Step 6.5 Backlog match paragraph and verdict pointers (214/8039 -> 216/8438); 0502 review: the controller dispatches the review tier wrapper; the skill dispatches nothing (214/8023 -> 214/8039); 0502: "loop" means /loop only (214/8058 -> 214/8057); 0502: one metadata layout — the docket branch and the .docket/ worktree (214/8042 -> 214/8058); 0502: the review payload names the resolved build.gate value; build_gate spellings become build.gate (214/8020 -> 214/8042); 0502: change.reclaim replaces reclaim-claims; the claim removes a leftover ## Run halted (214/8009 -> 214/8020); 0502: terminal-publication narration is deleted (214/8037 -> 214/8009); 0502: the severity floor is read as review.min_fix_severity through diagnostic.config (214/8034 -> 214/8037); 0502: the fixed role skills replace the $SKILL_* sites (214/8257 -> 214/8034); 0502: the dummy-mode paragraph and PR-body clause are deleted (216/8356 -> 214/8257); 0497: +Step 5 halted-build evidence kept verbatim in ## Run halted (216/8325 -> 216/8356); 0498 review: checkpoint (ii) persist wording (8320 -> 8325); 0498: +Step 6.5 review-findings homes, condensation exception, Human-actions class rule (214/8161 -> 216/8320); 0491: the run id is retired (214/8183 -> 214/8161); 0488 review: build-owned starts carry --change-id/--run-context (word ceiling 8162 -> 8183); 0488: run context and run id name only build-owned starts (word ceiling 8175 -> 8162); 0467 review fix: +the repair worker's post-fix re-run is a build-owned start (word ceiling 8165 -> 8175); 0467: +run id threaded to prepare-scope and build-owned starts (word ceiling 8080 -> 8165); 0455: +pr.publish record-invalid refusal clause (word ceiling 8025 -> 8080); 0448: +named-invocation branch; bounded own-dependency closeout moved to edge-paths.md (ceilings 210/7716 -> 214/8270 -> 214/8025); 0393: +exact payload, marker, and direct-dispatch lines atop 0410/0354/0376; 0375: +run-tracker resume pointer (word ceiling 7530 -> 7547); 0440: reader-first results prose; 0502: drop change citations and Go v1 narration (214/8057 -> 214/8023) + {"docket-implement-next/SKILL.md", 226, 8813}, // 0583: the PR-body Ticket line replaces the issue reference (226/8806 -> 226/8813); 0575: reclaim and the claim lease are retired (226/8841 -> 226/8806); review: Step 7 names the Step 6 evidence file instead of verified bytes (226/8835 -> 226/8841); 0360 step wording: the PR-body rules moved in from edge-paths.md (which fell 222 words) plus the minimal reconcile request, evidence block file, and ADR producing-change pass-through; the raise is that moved text, compressed (220/8590 -> 226/8835); 0360: local revision lookups, no claim refreshes, fewer re-syncs; the line raise is the new standalone Revision lookups paragraph every post-claim write keys on, words fell (218/8612 -> 220/8590); 0573: trivial retired (218/8637 -> 218/8612); 0570: the --selection claim sentence and the run-next driver rule (218/8555 -> 218/8637); 0560 review: on the named path on-hold also qualifies at the Step-1 confirm (218/8548 -> 218/8555); 0560: on-hold joins the readiness vocabulary and skip reasons; a held change is built when named (218/8518 -> 218/8548); 0559: the results-artifact ending pointer, postcondition row, and advanced meaning (215/8411 -> 218/8518); 0532: the private-repository writing rule and visibility hand-off (212/8282 -> 215/8411); 0531: the metadata worktree and remote come from the repository.prepare context (216/8443 -> 212/8282); 0517: evidence.record reads the gate command from build configuration (216/8438 -> 216/8443); 0502 rebase onto 0510: carried the Step 6.5 Backlog match paragraph and verdict pointers (214/8039 -> 216/8438); 0502 review: the controller dispatches the review tier wrapper; the skill dispatches nothing (214/8023 -> 214/8039); 0502: "loop" means /loop only (214/8058 -> 214/8057); 0502: one metadata layout — the docket branch and the .docket/ worktree (214/8042 -> 214/8058); 0502: the review payload names the resolved build.gate value; build_gate spellings become build.gate (214/8020 -> 214/8042); 0502: change.reclaim replaces reclaim-claims; the claim removes a leftover ## Run halted (214/8009 -> 214/8020); 0502: terminal-publication narration is deleted (214/8037 -> 214/8009); 0502: the severity floor is read as review.min_fix_severity through diagnostic.config (214/8034 -> 214/8037); 0502: the fixed role skills replace the $SKILL_* sites (214/8257 -> 214/8034); 0502: the dummy-mode paragraph and PR-body clause are deleted (216/8356 -> 214/8257); 0497: +Step 5 halted-build evidence kept verbatim in ## Run halted (216/8325 -> 216/8356); 0498 review: checkpoint (ii) persist wording (8320 -> 8325); 0498: +Step 6.5 review-findings homes, condensation exception, Human-actions class rule (214/8161 -> 216/8320); 0491: the run id is retired (214/8183 -> 214/8161); 0488 review: build-owned starts carry --change-id/--run-context (word ceiling 8162 -> 8183); 0488: run context and run id name only build-owned starts (word ceiling 8175 -> 8162); 0467 review fix: +the repair worker's post-fix re-run is a build-owned start (word ceiling 8165 -> 8175); 0467: +run id threaded to prepare-scope and build-owned starts (word ceiling 8080 -> 8165); 0455: +pr.publish record-invalid refusal clause (word ceiling 8025 -> 8080); 0448: +named-invocation branch; bounded own-dependency closeout moved to edge-paths.md (ceilings 210/7716 -> 214/8270 -> 214/8025); 0393: +exact payload, marker, and direct-dispatch lines atop 0410/0354/0376; 0375: +run-tracker resume pointer (word ceiling 7530 -> 7547); 0440: reader-first results prose; 0502: drop change citations and Go v1 narration (214/8057 -> 214/8023) {"docket-implement-next/references/edge-paths.md", 99, 1044}, // 0575: reclaim and the claim lease are retired (99/1051 -> 99/1044); 0360: the PR-body assembly section moved into SKILL.md Step 7 (109/1273 -> 99/1051); 0360: the resume results load needs no extra re-sync (109/1276 -> 109/1273); 0571: the stack-base refusal names its true reason (109/1265 -> 109/1276); 0532: the private-repository writing rule and visibility hand-off (109/1226 -> 109/1265); 0531: the metadata worktree and remote come from the repository.prepare context (118/1499 -> 109/1226); 0502: one metadata layout — the docket branch and the .docket/ worktree (118/1507 -> 118/1509); 0502: run.verify replaces verify-run (118/1505 -> 118/1507); 0502: terminal-publication narration is deleted (118/1513 -> 118/1505); 0502: the deferred results-only permit clause is deleted (118/1546 -> 118/1513); 0502: no custom plan location (118/1547 -> 118/1546); 0491: the run id is retired (118/1554 -> 118/1547); 0410: +resume/recovery + required-results reconciliation; 0375: +run-tracker resume refusals (78/1091 -> 93/1261); 0448: +named own-dependency closeout moved from SKILL.md (93/1261 -> 118/1554); 0502: drop change citations and Go v1 narration (118/1509 -> 118/1499) {"docket-implement-next/references/fix-pass.md", 189, 1954}, // 0360: halts no longer claim a refreshed lease (189/1963 -> 189/1954); 0532: the private-repository writing rule and visibility hand-off (187/1943 -> 189/1963); 0502 rebase onto 0510: carried the backlog-verdict pointer for reported findings (186/1929 -> 187/1943); 0502: "loop" means /loop only (190/1962 -> 190/1967); 0502: undispatchable fix worker halts (192/1991 -> 190/1962); 0502: renamed from fix-loop.md; 0498 review: results-file antecedent (1989 -> 1991); 0498: +review-findings condensation at final consolidation (190/1958 -> 192/1989); 0410: +findings-to-results checkpoint linkage (see note above); 0502: drop change citations and Go v1 narration (190/1967 -> 186/1929) {"docket-implement-next/references/results-artifact.md", 76, 737}, // 0360: no claim refreshes; change.complete pins a locally looked-up revision (79/765 -> 76/737); 0573: trivial retired (79/775 -> 79/765); 0559: new — the results-artifact ending (no plan, build, or PR; review, complete, clean up) diff --git a/internal/repoguard/prose_contracts_test.go b/internal/repoguard/prose_contracts_test.go index 9a92564c3..f460ddf66 100644 --- a/internal/repoguard/prose_contracts_test.go +++ b/internal/repoguard/prose_contracts_test.go @@ -556,7 +556,6 @@ var proseContracts = []proseContract{ "passes the producing change as `{id, path, revision}`", "one at a time, each with a fresh lookup", "`git diff --shortstat <effective base>...HEAD`", - "**Best-effort PR→issue reference.**", "**PR-body back-link.**", }, absent: []string{ @@ -566,6 +565,25 @@ var proseContracts = []proseContract{ "git diff --shortstat origin/<integration_branch>...HEAD", "Before assembling it, **read `references/edge-paths.md` now (blocking)**", }}, + // change 0583 — a change links to a ticket through three stored fields; the + // PR body carries a Ticket line from the implementation context, and the + // retired `issue:` field and its `#<issue>` reference are gone. + {sentinel: "change_0583_ticket_link", file: "skills/docket-implement-next/SKILL.md", + present: []string{ + "**Ticket line.**", + "`change.summary.ticket`", + "`Ticket: [<id>](<url>)`", + }, + absent: []string{"`issue:`", "#<issue>", "PR→issue"}}, + {sentinel: "change_0583_ticket_link", file: "skills/docket-convention/SKILL.md", + present: []string{ + "change.link-ticket", + "`ticket_provider:`", + "`ticket_url:`", + "`replace: true`", + "never replace a link on its own initiative", + "`ticket-link-invalid`", + }}, {sentinel: "change_0360_step_wording", file: "skills/docket-implement-next/references/edge-paths.md", absent: []string{"## PR-body assembly (Step 7)", "Step 7's PR-body assembly"}}, {sentinel: "change_0360_step_wording", file: "skills/docket-adr/SKILL.md", diff --git a/skills/docket-convention/SKILL.md b/skills/docket-convention/SKILL.md index a7c600349..4414f9ca3 100644 --- a/skills/docket-convention/SKILL.md +++ b/skills/docket-convention/SKILL.md @@ -189,6 +189,9 @@ hold: # `true` keeps a groomed change out of autonomous buil branch_prefix: # optional one unqualified branch-path component; overrides <type> at mint, consumed only at claim, inert once branch: is populated branch: # minted <type>/<slug> (or <branch_prefix>/<slug>) name, set on claim; sole feature-head source of truth after, never reconstructed; branch itself created at build (step 4) pr: # set when the PR is opened +ticket_provider: # the ticket system of the linked ticket (jira, linear, …); the three ticket fields are written together by change.link-ticket +ticket_id: # the ticket's id as that system shows it (CLOUD-123) +ticket_url: # the ticket's web address blocked_by: # free text; set only when status: blocked reconciled: false # set true after the just-in-time reconcile pass --- @@ -198,6 +201,17 @@ reconciled: false # set true after the just-in-time reconcile pass the sole source of truth for that relationship — the parent-side link is derived at render time — and is never copied into `related:` or `depends_on:`. +**Ticket link.** A change links to a ticket in the team's ticket system through all three fields — +`ticket_provider:`, `ticket_id:`, and `ticket_url:` — or none. The `change.link-ticket` operation +(request file: `change_id`, `path`, `revision`, then either the three fields or `unlink: true`) +links in any status, archived changes included, and re-renders `## Artifacts` with a Ticket row. +Re-linking the same ticket writes nothing. A link to a different ticket is refused unless the +request carries `replace: true`. A human's plain-words request ("switch it to CLOUD-456", "this is +actually CLOUD-456") is that explicit replace request, and the agent sends `replace: true` for it; +an agent must never replace a link on its own initiative. `change.create` accepts the same three +fields. A hand-edited partial or invalid set counts as not linked and is reported as the warning +`ticket-link-invalid`, never a block. + **Closed-out plans and results are frozen build records.** Once a change is closed out, its `plan:` and `results:` files are never hand-edited again — not to correct a stale line reference, not to update a superseded instruction. The only later write re-stamps the generated `docket:backlink` block, done by diff --git a/skills/docket-implement-next/SKILL.md b/skills/docket-implement-next/SKILL.md index 4b70dc207..8ff93c256 100644 --- a/skills/docket-implement-next/SKILL.md +++ b/skills/docket-implement-next/SKILL.md @@ -142,9 +142,9 @@ The results artifact is **required for every implemented change** — there is n **Publish the feature head.** The `workspace.publish` operation with `--id <id> --head <feature head>` inspects the owned workspace and pushes the exact head through the landed non-forcing publication, returning the verified remote head. It refuses when the reinspected head differs from `--head`; a divergent remote ref is `contended`, unknown post-effect state is `unknown` (reprobe on retry) — neither forces, and no PR opens here. -**PR-body assembly.** The PR body carries no build-evidence block. In a private repository the authored title and body follow the private-repository writing rule: no `#<issue>` reference, no change id in the title, and `pr.publish` publishes the body verbatim, with no back-link line and no links block. +**PR-body assembly.** The PR body carries no build-evidence block. In a private repository the authored title and body follow the private-repository writing rule: no change id in the title, and `pr.publish` publishes the body verbatim, with no back-link line and no links block. -**Best-effort PR→issue reference.** If the change carries an `issue:` value, add a plain `#<issue>` reference to the PR body — but **never `Closes #N`**, so merging the PR never auto-closes the referenced issue. Skip silently when `issue:` is unset — the reference is a one-time courtesy, not a build gate. +**Ticket line.** When the implementation context's `change.summary.ticket` is present, the authored PR body carries one plain line, `Ticket: [<id>](<url>)`, with that ticket's `id` and `url`; otherwise it carries none. The line goes in a private repository too: a ticket link is not docket machinery, and `pr.publish`'s leak check scans it with the rest of the body. Never a build gate. **PR-body back-link.** `pr.publish` renders and upserts a **back-link line** pointing home to the change on the metadata branch — a first body line of the shape `↩ Change <padded-id> — <title>` linking to the change file on `docket` (built with the same blob-or-bare-path logic) — plus a Docket-owned links block pointing at the plan and results files on the metadata branch; never author either in the body. From c241796e42aa2f95d0f905aa7ea01744c0a6e361 Mon Sep 17 00:00:00 2001 From: Daniel Hanold <danny@danielhanold.com> Date: Mon, 9 Nov 2026 18:44:13 -0500 Subject: [PATCH 10/12] fix(app): let link-ticket replace and unlink rewrite an unsupported-shape ticket value Review finding: replace: true and unlink: true failed with a plain unsupported-patch-shape error when a hand-edited ticket value was a mapping, block scalar, or multi-line scalar, so the ticket-link-invalid remedy could not be followed. Such an entry is now first reduced to a valueless key line in place, which the field patcher then fills. --- internal/app/change_link_ticket.go | 28 ++++++++- internal/app/change_link_ticket_test.go | 76 +++++++++++++++++++++++++ 2 files changed, 103 insertions(+), 1 deletion(-) diff --git a/internal/app/change_link_ticket.go b/internal/app/change_link_ticket.go index f5c83dd7d..6fd927013 100644 --- a/internal/app/change_link_ticket.go +++ b/internal/app/change_link_ticket.go @@ -1,6 +1,7 @@ package app import ( + "bytes" "context" "encoding/json" "fmt" @@ -329,7 +330,7 @@ func (o changeLinkTicketOp) Plan(ctx context.Context, st transaction.AttemptStat continue } var err error - intermediate, err = upsertFieldBytes(intermediate, key, v) + intermediate, err = rewriteTicketFieldBytes(intermediate, key, v) if err != nil { return transaction.MutationPlan{}, transaction.OperationResult{}, fmt.Errorf("link ticket: patching %s: %w", key, err) } @@ -375,6 +376,31 @@ func (o changeLinkTicketOp) Plan(ctx context.Context, st transaction.AttemptStat return o.plan(files, disposition) } +// rewriteTicketFieldBytes upserts one ticket field into src. A hand-edited +// ticket value the field patcher cannot edit in place — a mapping, a block +// scalar, a multi-line scalar — is rewritten whole: its entry lines are first +// reduced to a valueless "key:" line at the same position, which the patcher +// then fills with v. Replace and unlink clear whatever is present, so the +// ticket-link-invalid remedy works on every shape the decoder accepts. +func rewriteTicketFieldBytes(src []byte, key string, v document.Value) ([]byte, error) { + doc, err := document.Parse(src) + if err != nil { + return nil, err + } + if f, ok := doc.Field(key); ok && f.Shape == document.ShapeUnsupported { + ending := "\n" + if bytes.HasSuffix(src[f.Entry.Start:f.Entry.End], []byte("\r\n")) { + ending = "\r\n" + } + cleared := make([]byte, 0, len(src)) + cleared = append(cleared, src[:f.Entry.Start]...) + cleared = append(cleared, key+":"+ending...) + cleared = append(cleared, src[f.Entry.End:]...) + src = cleared + } + return upsertFieldBytes(src, key, v) +} + // noOpPlan is the empty plan the engine reports as a no-op. It writes no file, // but the engine still validates the plan, which needs a commit subject and a // receipt. diff --git a/internal/app/change_link_ticket_test.go b/internal/app/change_link_ticket_test.go index 037be3ba3..ff12c844e 100644 --- a/internal/app/change_link_ticket_test.go +++ b/internal/app/change_link_ticket_test.go @@ -338,3 +338,79 @@ func TestLinkTicketResultHumanText(t *testing.T) { t.Errorf("refused = %q, want %q", got, want) } } + +// unsupportedTicketURLShapes are hand-edited ticket_url values the decoder +// accepts as a ticket-link-invalid warning but the field patcher cannot edit +// in place: a mapping, a block scalar, and a multi-line plain scalar. +var unsupportedTicketURLShapes = map[string]string{ + "mapping": "ticket_url: {a: b}\n", + "block-mapping": "ticket_url:\n a: b\n", + "block-scalar": "ticket_url: |\n https://tickets.example.com/browse/OLD-1\n more\n", + "multi-line-scalar": "ticket_url: https://tickets.example.com/browse/OLD-1\n continued\n", +} + +// unsupportedTicketRecord carries provider and id plus one unsupported +// ticket_url entry, followed by a field the rewrite must leave untouched. +func unsupportedTicketRecord(urlLines string) string { + return withTicketLines(lifecycleChange(7, "widget", "in-progress"), + "ticket_provider: 'jira'\nticket_id: 'OLD-1'\n"+urlLines) +} + +func TestLinkTicketPlanReplaceOverUnsupportedShape(t *testing.T) { + recPath := groomPath(7, "widget") + for name, urlLines := range unsupportedTicketURLShapes { + t.Run(name, func(t *testing.T) { + files := map[string]string{recPath: unsupportedTicketRecord(urlLines)} + plan, opRes := linkTicketPlanFor(t, files, linkTicketOpFor(nil, 7, recPath, cloud123, true, false)) + if opRes.Refused { + t.Fatalf("refused: %v", opRes.Findings) + } + if got := linkTicketReceipt(t, plan).Disposition; got != LinkTicketDispReplaced { + t.Errorf("receipt disposition = %q, want replaced", got) + } + rec := lifecycleRecordBytes(t, plan, recPath) + if !strings.Contains(rec, "\nticket_url: '"+ticketTestURL+"'\n") || + !strings.Contains(rec, "| Ticket | [CLOUD-123](") { + t.Errorf("record not a valid CLOUD-123 link:\n%s", rec) + } + for _, gone := range []string{"OLD-1", "a: b", "continued", "more"} { + if strings.Contains(rec, gone) { + t.Errorf("record still carries %q from the old entry:\n%s", gone, rec) + } + } + if strings.Count(rec, "ticket_url:") != 1 { + t.Errorf("record carries ticket_url more than once:\n%s", rec) + } + }) + } +} + +func TestLinkTicketPlanUnlinkOverUnsupportedShape(t *testing.T) { + recPath := groomPath(7, "widget") + for name, urlLines := range unsupportedTicketURLShapes { + t.Run(name, func(t *testing.T) { + files := map[string]string{recPath: unsupportedTicketRecord(urlLines)} + plan, opRes := linkTicketPlanFor(t, files, linkTicketOpFor(nil, 7, recPath, domain.Ticket{}, false, true)) + if opRes.Refused { + t.Fatalf("refused: %v", opRes.Findings) + } + if got := linkTicketReceipt(t, plan).Disposition; got != LinkTicketDispUnlinked { + t.Errorf("receipt disposition = %q, want unlinked", got) + } + rec := lifecycleRecordBytes(t, plan, recPath) + for _, want := range []string{"\nticket_provider:\n", "\nticket_id:\n", "\nticket_url:\n"} { + if !strings.Contains(rec, want) { + t.Errorf("record lacks valueless %q:\n%s", strings.TrimSpace(want), rec) + } + } + for _, gone := range []string{"OLD-1", "a: b", "continued", "more", "| Ticket |"} { + if strings.Contains(rec, gone) { + t.Errorf("unlinked record still carries %q:\n%s", gone, rec) + } + } + if strings.Count(rec, "ticket_url:") != 1 { + t.Errorf("record carries ticket_url more than once:\n%s", rec) + } + }) + } +} From ab351133ccc51e52dc77e4d3ca4747dd6f83bdb6 Mon Sep 17 00:00:00 2001 From: Daniel Hanold <danny@danielhanold.com> Date: Mon, 9 Nov 2026 18:45:27 -0500 Subject: [PATCH 11/12] docs(config): say the tickets settings have no effect yet Review finding: the tickets block in .docket.example.yml and the tickets.* rows in docs/reference/config-keys.md described docket acting on linked tickets, but no command reads any tickets.* key and linking a change accepts any provider. State current behaviour instead: the settings have no effect today, and a change's ticket is whatever its link records. --- .docket.example.yml | 18 +++++++++-------- docs/reference/config-keys.md | 20 +++++++++++-------- internal/assets/embedded/manifest.json | 6 +++--- .../assets/embedded/tree/.docket.example.yml | 18 +++++++++-------- 4 files changed, 35 insertions(+), 27 deletions(-) diff --git a/.docket.example.yml b/.docket.example.yml index 9ab9ccef8..db74ff7cd 100644 --- a/.docket.example.yml +++ b/.docket.example.yml @@ -246,11 +246,13 @@ change_types: [chore, docs, feat, fix, refactor, perf] # ═══ Tickets ══════════════════════════════════════════════════════════════════════════════ -# tickets — the ticket system this repository's changes link to. Linking a change to a ticket -# keeps the two together: the change shows the ticket in its artifacts, and the pull request -# docket opens names it. `provider` names the tool (jira, linear, …), `site` names where it lives -# (tickets.example.com), and `project` names where new tickets go. Each is a single line; empty -# (the default) means not set. +# tickets — the ticket system this repository's changes link to. `provider` names the tool +# (jira, linear, …), `site` names where it lives (tickets.example.com), and `project` names where +# new tickets go. Each is a single line; empty (the default) means not set. +# +# No docket command reads these settings yet, so setting them has no effect today. Linking a +# change to a ticket does not consult them either: the ticket a change links to, and its tool, +# are whatever that change's link records. # # What `project` means, and what kind of ticket each tool creates, depends on the tool: # @@ -264,9 +266,9 @@ change_types: [chore, docs, feat, fix, refactor, perf] # | Linear | team | none (labels) | # | Asana / Trello | project / board | none | # -# The `auto` switches let docket act on a linked ticket on its own after each event: a change is -# created, its spec is written, its pull request opens, its pull request merges, or its results -# are complete. All are off by default. +# The `auto` switches name five events: a change is created, its spec is written, its pull +# request opens, its pull request merges, or its results are complete. All are off by default, +# and like the settings above, docket does not act on them yet. # # These settings belong to the repository: a value in the global config or `.docket.local.yml` is # ignored with a warning. diff --git a/docs/reference/config-keys.md b/docs/reference/config-keys.md index e025fb689..7f8e39305 100644 --- a/docs/reference/config-keys.md +++ b/docs/reference/config-keys.md @@ -57,17 +57,21 @@ Each key has one scope: | `board.section_order` | `[in-progress, built, blocked, groomed, proposed, deferred]` | any layer | the order of the board's sections | | `board.sorting.<section>.by` / `.direction` | `updated` / `desc` | any layer | how each board section is sorted | | `change_types` | `[chore, docs, feat, fix, refactor, perf]` | any layer | the types a change can be classified as | -| `tickets.provider` | `""` (unset) | repo-only | the ticket system this repository's changes link to (jira, linear, …) | -| `tickets.site` | `""` (unset) | repo-only | where that ticket system lives | -| `tickets.project` | `""` (unset) | repo-only | where new tickets go (a project, team, repository, or board, by tool) | -| `tickets.auto.change_created` | `false` | repo-only | whether docket acts on the linked ticket when a change is created | -| `tickets.auto.spec_written` | `false` | repo-only | whether docket acts on the linked ticket when a change's spec is written | -| `tickets.auto.pr_opened` | `false` | repo-only | whether docket acts on the linked ticket when a change's pull request opens | -| `tickets.auto.pr_merged` | `false` | repo-only | whether docket acts on the linked ticket when a change's pull request merges | -| `tickets.auto.results_completed` | `false` | repo-only | whether docket acts on the linked ticket when a change's results are complete | +| `tickets.provider` | `""` (unset) | repo-only | the ticket system this repository's changes link to (jira, linear, …); no effect yet | +| `tickets.site` | `""` (unset) | repo-only | where that ticket system lives; no effect yet | +| `tickets.project` | `""` (unset) | repo-only | where new tickets go (a project, team, repository, or board, by tool); no effect yet | +| `tickets.auto.change_created` | `false` | repo-only | a switch for when a change is created; no effect yet | +| `tickets.auto.spec_written` | `false` | repo-only | a switch for when a change's spec is written; no effect yet | +| `tickets.auto.pr_opened` | `false` | repo-only | a switch for when a change's pull request opens; no effect yet | +| `tickets.auto.pr_merged` | `false` | repo-only | a switch for when a change's pull request merges; no effect yet | +| `tickets.auto.results_completed` | `false` | repo-only | a switch for when a change's results are complete; no effect yet | | `agent_harnesses` | none | any layer | the dispatch opt-in (below) | | `agents.<harness>.<agent>.model` / `.effort` | the built-in table | global-only | model and effort pins for docket's agents | +**`tickets`** settings are accepted and checked, but no docket command reads them yet, so setting +them has no effect today. Linking a change to a ticket does not consult them: the ticket a change +links to, and its tool, are whatever that change's link records. + **`agent_harnesses`** opts a repository in to docket's parent-facing dispatch surfaces: the managed block in `CLAUDE.md` / `AGENTS.md` and, for Cursor, `.cursor/rules/docket-dispatch.mdc`. It takes `claude`, `codex`, `cursor`, and `opencode`. While it is absent, `docket install` touches diff --git a/internal/assets/embedded/manifest.json b/internal/assets/embedded/manifest.json index ba2882df4..19a08700e 100644 --- a/internal/assets/embedded/manifest.json +++ b/internal/assets/embedded/manifest.json @@ -1,14 +1,14 @@ { "format_version": 1, "asset_protocol": 1, - "asset_set_id": "sha256:32bd9f5aa56f95f3e92aacd08e4e95f2a471b9ae91cf1c20ccca13afecd0e1fd", + "asset_set_id": "sha256:5e75da008ab533c7f27e6d80bd06bd60337e8ceb494642bd94ac660d3bab067c", "entries": [ { "path": ".docket.example.yml", "role": "config-schema", "mode": 420, - "size": 23718, - "sha256": "1ac775ba16836d65ded899f0ca7f2611dcc9fe28b1d3676b058cb1b54b827bb1" + "size": 23821, + "sha256": "935b3626d0228caebe341ab1704376e84d631a0712f026f5ba9a25bbdca72cb6" }, { "path": "agents/docket-adr.md", diff --git a/internal/assets/embedded/tree/.docket.example.yml b/internal/assets/embedded/tree/.docket.example.yml index 9ab9ccef8..db74ff7cd 100644 --- a/internal/assets/embedded/tree/.docket.example.yml +++ b/internal/assets/embedded/tree/.docket.example.yml @@ -246,11 +246,13 @@ change_types: [chore, docs, feat, fix, refactor, perf] # ═══ Tickets ══════════════════════════════════════════════════════════════════════════════ -# tickets — the ticket system this repository's changes link to. Linking a change to a ticket -# keeps the two together: the change shows the ticket in its artifacts, and the pull request -# docket opens names it. `provider` names the tool (jira, linear, …), `site` names where it lives -# (tickets.example.com), and `project` names where new tickets go. Each is a single line; empty -# (the default) means not set. +# tickets — the ticket system this repository's changes link to. `provider` names the tool +# (jira, linear, …), `site` names where it lives (tickets.example.com), and `project` names where +# new tickets go. Each is a single line; empty (the default) means not set. +# +# No docket command reads these settings yet, so setting them has no effect today. Linking a +# change to a ticket does not consult them either: the ticket a change links to, and its tool, +# are whatever that change's link records. # # What `project` means, and what kind of ticket each tool creates, depends on the tool: # @@ -264,9 +266,9 @@ change_types: [chore, docs, feat, fix, refactor, perf] # | Linear | team | none (labels) | # | Asana / Trello | project / board | none | # -# The `auto` switches let docket act on a linked ticket on its own after each event: a change is -# created, its spec is written, its pull request opens, its pull request merges, or its results -# are complete. All are off by default. +# The `auto` switches name five events: a change is created, its spec is written, its pull +# request opens, its pull request merges, or its results are complete. All are off by default, +# and like the settings above, docket does not act on them yet. # # These settings belong to the repository: a value in the global config or `.docket.local.yml` is # ignored with a warning. From b7897978c7bfe5c2cdc78885c8b294e6ef4e0805 Mon Sep 17 00:00:00 2001 From: Daniel Hanold <danny@danielhanold.com> Date: Mon, 9 Nov 2026 18:46:24 -0500 Subject: [PATCH 12/12] fix(app): address link-ticket review findings - Move link_ticket_dispositions above the conflict-resolver comment and give it its own comment, so that comment describes resolver_dispositions again. - Add TestLinkTicketPlanFillsEmptyKeys: linking a record that already carries the three valueless ticket keys yields linked with all three values written. --- internal/app/change_link_ticket_test.go | 27 +++++++++++++++++++++++++ internal/app/schema_vocab.go | 5 +++-- 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/internal/app/change_link_ticket_test.go b/internal/app/change_link_ticket_test.go index ff12c844e..ff354fe48 100644 --- a/internal/app/change_link_ticket_test.go +++ b/internal/app/change_link_ticket_test.go @@ -139,6 +139,33 @@ func TestLinkTicketPlanLinks(t *testing.T) { } } +// TestLinkTicketPlanFillsEmptyKeys links a record already carrying the three +// valueless ticket keys, the shape change.create and unlink produce. +func TestLinkTicketPlanFillsEmptyKeys(t *testing.T) { + recPath := groomPath(7, "widget") + body := strings.Replace(lifecycleChange(7, "widget", "in-progress"), + "status: in-progress\n", "status: in-progress\nticket_provider:\nticket_id:\nticket_url:\n", 1) + if !strings.Contains(body, "ticket_id:\n") { + t.Fatalf("fixture lacks empty ticket keys:\n%s", body) + } + files := map[string]string{recPath: body} + plan, opRes := linkTicketPlanFor(t, files, linkTicketOpFor(nil, 7, recPath, cloud123, false, false)) + if opRes.Refused { + t.Fatalf("unexpected refusal: %v", opRes.Findings) + } + rec := lifecycleRecordBytes(t, plan, recPath) + for _, want := range []string{ + "ticket_provider: 'jira'", "ticket_id: 'CLOUD-123'", "ticket_url: '" + ticketTestURL + "'", + } { + if strings.Count(rec, want) != 1 { + t.Errorf("record should carry %q exactly once:\n%s", want, rec) + } + } + if got := linkTicketReceipt(t, plan).Disposition; got != LinkTicketDispLinked { + t.Errorf("receipt disposition = %q, want linked", got) + } +} + func TestLinkTicketPlanInsertsMissingKeys(t *testing.T) { recPath := groomPath(7, "widget") files := map[string]string{recPath: lifecycleChange(7, "widget", "in-progress")} diff --git a/internal/app/schema_vocab.go b/internal/app/schema_vocab.go index 7027cb2d7..538c50965 100644 --- a/internal/app/schema_vocab.go +++ b/internal/app/schema_vocab.go @@ -131,12 +131,13 @@ func SchemaVocabularies(effects []string) map[string]Vocabulary { CancelDispositionCancelled, CancelDispositionAlreadyCancelled, CancelDispositionPending, CancelDispositionRefused, }} - // The conflict-resolver report's closed disposition set (ResolverReport, - // the request finalize.rebase-continue and finalize.rebase-abort decode). + // The change.link-ticket receipt's closed disposition set. v["link_ticket_dispositions"] = Vocabulary{Members: []string{ LinkTicketDispLinked, LinkTicketDispAlreadyLinked, LinkTicketDispReplaced, LinkTicketDispUnlinked, LinkTicketDispNothingToUnlink, }} + // The conflict-resolver report's closed disposition set (ResolverReport, + // the request finalize.rebase-continue and finalize.rebase-abort decode). v["resolver_dispositions"] = Vocabulary{Members: []string{ ResolverResolved, ResolverStuck, }}