Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions docs/reference/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,9 @@ Each line is a pointer: the command, what its verbs govern, and where to read th
(implemented with a PR, or a completed results artifact); also reset the count of implement-next
halts in a row (`docket run reset-halts`).
Verbs: `docket run --help`.
- **`docket schema`** — emit request/result payload schemas and allowed values (read-only,
repository-independent). Verbs: `docket schema --help`.
- **`docket schema [<id>]`** — emit request/result payload schemas and allowed values (read-only,
repository-independent). Narrow it to one operation by giving its id positionally or via
`--operation`. Verbs: `docket schema --help`.
- **`docket status`** — report backlog status, readiness, selection, and repository health
(read-only). Verbs: `docket status --help`.
- **`docket uninstall`** — remove recorded harness integrations while retaining the CLI and
Expand Down
16 changes: 9 additions & 7 deletions docs/reference/glossary.md
Original file line number Diff line number Diff line change
Expand Up @@ -527,17 +527,17 @@ docket finalize cleanup --id 412
### Claim / claim lease / reclaim

A **claim** is the moment a change is picked up for building; it records which branch will carry
the work and when it was taken. The **claim lease** is a timestamp on a claim (`claimed_at:`);
when it expires with no branch behind it, the change goes back to the queue. **Reclaim** is that
the work and when it was taken. The **claim lease** is a timestamp on a claim (`claimed_at:`),
stamped at claim and re-stamped at reconcile and resume-halted; when it expires with no branch
behind it, the change goes back to the queue. **Reclaim** is that
return trip (`in-progress → proposed`), logged in `## Reclaim log`.

**Used for:** making sure an abandoned build never holds a change forever. A claim that already
has a feature branch or a workspace (real work) is never reclaimed. Grooming never takes a claim.

```sh
docket change claim --id 412 --revision <v>
docket change refresh-claim --id 412 --revision <v> # extend the lease at a phase boundary
docket change reclaim --id 412 --revision <v> # refuses with lease-not-expired if still live
docket change claim --id 412 --revision <v>
docket change reclaim --id 412 --revision <v> # refuses with lease-not-expired if still live
```

Config: `reclaim.lease_ttl` (hours) and `reclaim.auto`.
Expand Down Expand Up @@ -848,7 +848,9 @@ The build and finalize gates both run the whole suite. The page that covers them
### Implementation context

The read-only bundle implement-next assembles before claiming: the selected change, its readiness,
and what it needs to proceed.
and what it needs to proceed. Read by id, it also serves the run's own `in-progress` change (after
the claim, or on a resume), reporting `claim_eligible: false` with the record's current revision
and recorded branch.

```sh
docket context implementation --id 412 --json
Expand Down Expand Up @@ -2122,7 +2124,7 @@ below.
|---|---|---|
| `block_dispositions` | `recorded` `already-recorded` `cleared` `nothing-to-clear` `unknown` `contended` `refused` `failed` | `finalize block`, `finalize clear-block` |
| `cancel_dispositions` | `cancelled` `already-cancelled` `cancellation-pending` `refused` | `run cancel` |
| `claim_dispositions` | `applied` `already-claimed` `contended` `failed` `run-context-invalid` `run-context-conflict` | `change claim`, `change refresh-claim` |
| `claim_dispositions` | `applied` `already-claimed` `contended` `failed` `run-context-invalid` `run-context-conflict` | `change claim` |
| `cleanup_dispositions` | `cleaned` `already-clean` `pending` `retained` `children-retarget-required` `rebase-scratch-cleared` | `finalize cleanup`, `gate cleanup` |
| `closeout_dispositions` | `done-archived` `stacked-merged` `root-archived` `already-closed-out` `contended` `blocked` `unknown` `failed` | `finalize closeout` |
| `complete_dispositions` | `completed` `already-completed` `contended` `failed` | `change complete` |
Expand Down

Large diffs are not rendered by default.

3 changes: 2 additions & 1 deletion internal/app/adr_ops.go
Original file line number Diff line number Diff line change
Expand Up @@ -454,7 +454,8 @@ func validateADRReferences(relatesTo []int, snap domain.Snapshot) []domain.Findi
Severity: domain.SeverityError,
Entity: domain.EntityRef{Kind: domain.EntityADR},
Field: "relates_to",
Detail: map[string]string{"reference": fmt.Sprintf("%d", id)},
Related: []domain.EntityRef{{Kind: domain.EntityADR, ID: id}},
Detail: map[string]string{"lookup": "absent"},
})
}
}
Expand Down
11 changes: 11 additions & 0 deletions internal/app/adr_ops_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"github.com/danielhanold/docket/internal/render"
"github.com/danielhanold/docket/internal/reposetup"
"github.com/danielhanold/docket/internal/repository/transaction"
"strings"
"testing"
Expand Down Expand Up @@ -185,6 +186,16 @@ func TestADRRecordPlanRefusesDanglingRelatesTo(t *testing.T) {
if !hasDomainFindingCode(opRes.Findings, "adr-dangling-reference") {
t.Errorf("missing adr-dangling-reference finding: %v", opRes.Findings)
}
// The rendered text names the missing ADR, never a placeholder change.
for _, f := range opRes.Findings {
if f.Code != "adr-dangling-reference" {
continue
}
msg := explainValidation(f, reposetup.RecordLocator{Checkout: ".docket"}).Message
if !strings.Contains(msg, "ADR 0999") || strings.Contains(msg, "change 0000") {
t.Errorf("dangling relates_to message does not name ADR 0999: %q", msg)
}
}
}

func TestADRRecordPlanRecordContent(t *testing.T) {
Expand Down
160 changes: 43 additions & 117 deletions internal/app/change_claim.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,14 @@ import (
"github.com/danielhanold/docket/internal/repository/transaction"
)

// This file is the `change claim` and `change refresh-claim` planning
// operations: two exact-revision metadata transitions that land a change's claim
// fields and every affected v1-owned derived view (the change record's owned
// lifecycle fields, its refreshed updated date, its re-rendered artifact block,
// and the inline board) as one validated atomic transaction. The domain owns
// legality: domain.Claim and domain.RefreshClaim decide whether the current
// status may take the transition and yield the exact FieldChanges to apply.
// This file is the `change claim` planning operation: an exact-revision
// metadata transition that lands a change's claim fields and every affected
// v1-owned derived view (the change record's owned lifecycle fields, its
// refreshed updated date, its re-rendered artifact block, and the inline board)
// as one validated atomic transaction. The domain owns legality: domain.Claim
// decides whether the current status may take the transition and yields the
// exact FieldChanges to apply. The lease is re-stamped only by claim,
// change.reconcile, and change.resume-halted.
//
// Claim additionally re-proves eligibility INSIDE the transaction against the
// attempt's own fresh snapshot — proposed, uniquely identified, build-ready,
Expand All @@ -35,17 +36,12 @@ import (
// Claim carries an idempotency key derived from its own (id, revision) request so
// a lost response replays the original applied receipt as `already-claimed`
// rather than allocating a second claim; a foreign edit that moved the record
// fails the exact-revision expectation as `contended`. Refresh is a small
// non-keyed exact-revision transaction — a revision mismatch is `contended`, which
// instructs the caller to stop, never to overwrite a newer record. Neither
// operation clears or steals an expired claim; reclaim is 0316.
// fails the exact-revision expectation as `contended`. A claim never clears or
// steals an expired claim; reclaim is 0316.

// The operation keys the two claim transitions record in their result envelopes
// and transaction trailers.
const (
OperationChangeClaim = "change.claim"
OperationChangeRefreshClaim = "change.refresh-claim"
)
// OperationChangeClaim is the operation key the claim transition records in its
// result envelope and transaction trailer.
const OperationChangeClaim = "change.claim"

// The closed set of claim dispositions a result may carry. `applied` is a fresh
// claim; `already-claimed` is an idempotent replay of this exact request's own
Expand All @@ -71,9 +67,9 @@ const (
ClaimDispositionRunContextConflict = "run-context-conflict"
)

// ChangeClaimRequest is the closed, caller-supplied request for one claim or
// refresh-claim. ID names the change; Revision pins the exact submitted record
// blob (the revision the authoritative context read reported).
// ChangeClaimRequest is the closed, caller-supplied request for one claim. ID
// names the change; Revision pins the exact submitted record blob (the revision
// the authoritative context read reported).
type ChangeClaimRequest struct {
ID int `json:"id" docket:"required"`
Revision string `json:"revision" docket:"required"`
Expand Down Expand Up @@ -126,11 +122,11 @@ type claimDigestPayload struct {
RunContextHash string `json:"gate_context_hash"`
}

// ChangeClaimResult is the protocol-v1 document `change claim` and
// `change refresh-claim` return. It embeds the envelope; the claim fields are
// populated on a successful apply or an idempotent replay, Disposition carries
// the closed claim disposition, and Findings carries every refusal or validation
// diagnostic (marshalled as [] never null).
// ChangeClaimResult is the protocol-v1 document `change claim` returns. It
// embeds the envelope; the claim fields are populated on a successful apply or
// an idempotent replay, Disposition carries the closed claim disposition, and
// Findings carries every refusal or validation diagnostic (marshalled as []
// never null).
type ChangeClaimResult struct {
Envelope
ID int `json:"id,omitempty"`
Expand Down Expand Up @@ -326,62 +322,9 @@ func ChangeClaim(ctx context.Context, deps PlanningDeps, repoDir string, req Cha
return out
}

// ChangeRefreshClaim validates the request, pins authoritative context, and
// drives one small non-keyed exact-revision transaction that re-stamps the
// change's claimed_at (plus its refreshed updated date and derived views) and
// nothing else. It requires the change to still be in-progress at the exact
// submitted revision; a mismatch is `contended`, which stops the run rather than
// overwriting a newer record.
func ChangeRefreshClaim(ctx context.Context, deps PlanningDeps, repoDir string, req ChangeClaimRequest) ChangeClaimResult {
findings := dropFindingCode(validateLifecycleShape("id", req.ID, "", req.Revision), FCEmptyPath)
if len(findings) > 0 {
return newChangeClaimResult(OperationChangeRefreshClaim, ResultInvalidInput, ChangeClaimResult{Findings: findings})
}

pin, eff, inline, repo, pre := claimPreflight(ctx, deps, repoDir, OperationChangeRefreshClaim)
if pre != nil {
return *pre
}

// Resolve the record's current path (the request carries only id + revision).
// Refresh consults no branch facts — it re-proves nothing about readiness —
// so the resolved facts are discarded.
recPath, _, _, terr := resolveClaimTarget(ctx, deps, pin, eff, req.ID, OperationChangeRefreshClaim)
if terr != nil {
return *terr
}

op := changeClaimOp{
opKey: OperationChangeRefreshClaim,
changeID: req.ID,
refresh: true,
eff: eff,
clock: deps.Clock,
ttlHours: eff.Reclaim.LeaseTTL.Value,
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(recPath),
Revision: transaction.ExpectedRevision{Kind: transaction.RevisionBlob, ObjectID: gitcli.ObjectID(req.Revision)},
}},
Loader: newPlanningLoader(eff),
Scope: changeScope(req.ID, recPath, false),
Operation: op,
})

return claimResultFromOutcome(OperationChangeRefreshClaim, res, execErr)
}

// claimPreflight performs the shared pre-transaction plumbing both claim
// transitions need: pin context, check the board surface, and discover the
// repository. It returns a non-nil result pointer for any preflight failure.
// claimPreflight performs the pre-transaction plumbing a claim needs: pin
// context, check the board surface, and discover the repository. It returns a
// non-nil result pointer for any preflight failure.
func claimPreflight(ctx context.Context, deps PlanningDeps, repoDir, opKey string) (
pin StatusPin, eff config.Effective, inline bool, repo gitcli.Repository, refusal *ChangeClaimResult) {

Expand Down Expand Up @@ -578,14 +521,13 @@ func decodeChangeClaimReceipt(b []byte) (changeClaimReceipt, bool) {
return rec, true
}

// changeClaimOp is the SemanticOperation the engine drives per attempt for both
// claim and refresh-claim. Every field is fixed before the transaction; the
// state-dependent work (the eligibility re-proof, the domain gate, field
// patching, rendering) re-runs from the attempt's own fresh state.
// changeClaimOp is the SemanticOperation the engine drives per attempt for a
// claim. Every field is fixed before the transaction; the state-dependent work
// (the eligibility re-proof, the domain gate, field patching, rendering) re-runs
// from the attempt's own fresh state.
type changeClaimOp struct {
opKey string
changeID int
refresh bool
facts domain.BranchFacts
eff config.Effective
clock transaction.Clock
Expand All @@ -594,18 +536,17 @@ type changeClaimOp struct {
link render.LinkContext
changesDir string
// runContextHash is the hashed run context this claim is bound to (""
// for an ungated claim or a refresh). It is folded into the committed claim
// for an ungated claim). It is folded into the committed claim
// receipt as the durable ownership proof (change 0407); the raw token never
// reaches this struct.
runContextHash string
// selection is the normalized claim selection ("" = unknown, and always ""
// for a refresh), folded into the committed claim receipt.
// selection is the normalized claim selection ("" = unknown), folded into the committed claim receipt.
selection string
}

func (o changeClaimOp) Key() transaction.OperationKey { return transaction.OperationKey(o.opKey) }

// Plan re-proves eligibility (claim only) against the attempt's fresh snapshot,
// Plan re-proves eligibility against the attempt's fresh snapshot,
// gates the transition through the domain action, patches the owned claim fields
// plus the refreshed updated date, applies any domain-owned section removals,
// re-renders the artifact block, and assembles the closed plan: the mutated
Expand All @@ -622,26 +563,16 @@ func (o changeClaimOp) Plan(ctx context.Context, st transaction.AttemptState) (t
return refuseLifecycle(FindingCode(reason), fmt.Sprintf("change %04d is not a single record in the current corpus", o.changeID))
}

var result domain.ActionResult
if o.refresh {
r, fail := domain.RefreshClaim(c, o.clock.Now())
if fail != nil {
return refuseLifecyclePolicy(fail)
}
result = r
} else {
// In-transaction re-proof: proposed, uniquely identified, build-ready, and
// a resolved effective base — all from the attempt's own fresh snapshot.
// Stripping this line lets an ineligible change be claimed on stale facts;
// the refusal table mutation-tests exactly that.
if fail := domain.ClaimEligibility(snap, c, o.facts); fail != nil {
return refuseLifecyclePolicy(fail)
}
r, fail := domain.Claim(c, o.clock.Now())
if fail != nil {
return refuseLifecyclePolicy(fail)
}
result = r
// In-transaction re-proof: proposed, uniquely identified, build-ready, and
// a resolved effective base — all from the attempt's own fresh snapshot.
// Stripping this line lets an ineligible change be claimed on stale facts;
// the refusal table mutation-tests exactly that.
if fail := domain.ClaimEligibility(snap, c, o.facts); fail != nil {
return refuseLifecyclePolicy(fail)
}
result, fail := domain.Claim(c, o.clock.Now())
if fail != nil {
return refuseLifecyclePolicy(fail)
}

src, ok := st.State.Sources[c.Path()]
Expand Down Expand Up @@ -705,10 +636,8 @@ func (o changeClaimOp) Plan(ctx context.Context, st transaction.AttemptState) (t
}

if o.inline {
// A refresh re-stamps only claimed_at and the updated date — neither is
// board-visible — so includeBoard's declare-only-when-changed shape can
// render byte-identical to the committed board and correctly declare no
// board mutation.
// includeBoard declares a board mutation only when the re-render differs
// from the committed board.
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("change claim: %w", err)
Expand All @@ -731,9 +660,6 @@ func (o changeClaimOp) Plan(ctx context.Context, st transaction.AttemptState) (t
}

subject := fmt.Sprintf("change %04d claimed", o.changeID)
if o.refresh {
subject = fmt.Sprintf("change %04d claim refreshed", o.changeID)
}
return transaction.MutationPlan{
Files: files,
CommitSubject: subject,
Expand Down
34 changes: 0 additions & 34 deletions internal/app/change_claim_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import (
"path"
"strings"
"testing"
"time"
)

// TestIntegrationRecordOpsClaimTransactionTargetsPinnedMetadataLayout pins the
Expand Down Expand Up @@ -315,7 +314,6 @@ func TestIntegrationRecordOpsChangeClaimUnrelatedInvalidRecordProgress(t *testin
unrelatedBrokenPath: unrelatedBrokenBytes,
})
node := planningDepsFor(t, repo.invocation)
later := planningDepsForClock(t, repo.invocation, fixedClock{t: time.Date(2026, 8, 17, 12, 0, 0, 0, time.UTC)})
ctx := context.Background()

claim := ChangeClaim(ctx, node.deps, node.dir, ChangeClaimRequest{ID: id, Revision: blobRevisionAt(t, repo.origin, "docket", recPath)})
Expand All @@ -342,14 +340,6 @@ func TestIntegrationRecordOpsChangeClaimUnrelatedInvalidRecordProgress(t *testin
if !strings.Contains(board, "| `"+unrelatedBrokenPath+"` | unclosed-frontmatter |") {
t.Errorf("board lacks the repair notice naming the unrelated record:\n%s", board)
}

refresh := ChangeRefreshClaim(ctx, later.deps, later.dir, ChangeClaimRequest{ID: id, Revision: blobRevisionAt(t, repo.origin, "docket", recPath)})
if refresh.Result != ResultApplied {
t.Fatalf("refresh-claim beside an unrelated unparseable record = %q (disposition %q findings %v), want applied",
refresh.Result, refresh.Disposition, refresh.Findings)
}
assertAppliedSurfacesUnrelated(t, refresh)
assertUnrelatedBrokenIntact(t, repo)
}

// TestIntegrationRecordOpsChangeClaimUnrelatedDependentsOfBrokenProgress is the canonical real-world
Expand Down Expand Up @@ -448,30 +438,6 @@ func TestIntegrationRecordOpsChangeClaimUnrelatedInvalidRecordRefusals(t *testin
}
}

func TestIntegrationRecordOpsChangeRefreshClaimUnrelatedInvalidRecordRefusals(t *testing.T) {
requireRealGit(t)
const id = 3
recPath := groomPath(id, "widget")
src := lifecycleChange(id, "widget", "in-progress")
for _, c := range unrelatedRefusalCases(t, id, recPath, src, lifecycleChange(id, "dupe", "in-progress")) {
t.Run(c.name, func(t *testing.T) {
repo := newWorkingRepo(t, c.files)
node := planningDepsFor(t, repo.invocation)
tip := originTip(t, repo.origin, "docket")

res := ChangeRefreshClaim(context.Background(), node.deps, node.dir,
ChangeClaimRequest{ID: id, Revision: blobRevisionAt(t, repo.origin, "docket", recPath)})
if res.Result == ResultApplied {
t.Fatalf("refresh-claim applied despite %s; want a refusal", c.name)
}
assertRefusalBeyondUnrelated(t, res.Disposition, res.Findings)
if got := originTip(t, repo.origin, "docket"); got != tip {
t.Errorf("a refused refresh-claim moved the metadata branch %s -> %s", tip, got)
}
})
}
}

// TestIntegrationRecordOpsClaimResumeContextRefusedBeforeReserve: a `run start --resume` start pre-binds
// the resumed change as AttributedID and never gets a claim binding (change 0463).
// A claim under that context, for the resumed change itself or for any other change,
Expand Down
Loading
Loading