From 271c5d46e611c62fefd315a166f6f538507a1fa6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Kova=C4=BE?= Date: Thu, 6 Aug 2026 08:45:42 +0200 Subject: [PATCH] Extract and rename Phyllary workflow facade --- .clerk | 2 - .github/workflows/delivery-gate.yml | 17 +- .gitignore | 2 +- .phyllary | 2 + .stow-local-ignore | 4 +- AGENTS.md | 20 +- CONTEXT-MAP.md | 3 +- bin/bd.test.sh | 4 +- bin/clerk | 71 - bin/nextdelivery | 11 - claude-code/settings.json | 14 +- clerk/CONTEXT.md | 82 - .../0015-clerk-opaque-workflow-verb-facade.md | 246 --- ...ed-backlog-location-and-merge-gate-axes.md | 79 - .../0018-clerk-compound-impediment-reducer.md | 91 - .../adr/0019-project-gate-adapter-contract.md | 59 - clerk/docs/project-gate.md | 52 - ...-07-24-project-gate-acceptance-verifier.md | 64 - clerk/project-gate.json | 4 - clerk/src/clerk/__init__.py | 5 - clerk/src/clerk/__main__.py | 6 - clerk/src/clerk/cli.py | 192 -- clerk/src/clerk/commands.py | 1759 ----------------- clerk/src/clerk/doctor.py | 179 -- clerk/src/clerk/glean.py | 345 ---- clerk/src/clerk/manifest.py | 56 - clerk/src/clerk/output.py | 36 - clerk/src/clerk/ownership.py | 57 - clerk/src/clerk/proc.py | 47 - clerk/src/clerk/project_gate.py | 413 ---- clerk/src/clerk/reconciliation.py | 331 ---- clerk/src/clerk/roster.py | 257 --- clerk/src/clerk/work_graph.py | 434 ---- ...sable-scripts-as-config-bin-executables.md | 4 +- docs/agents/domain.md | 13 +- docs/agents/issue-tracker.md | 104 +- docs/agents/pi-setup-survey.md | 2 +- docs/agents/triage-labels.md | 16 +- mise/config.toml | 4 +- {clerk => phyllary}/project-gate | 17 +- phyllary/project-gate.json | 4 + .../.gitignore | 0 .../index.ts | 30 +- tests/clerk/backlog-read.bats | 296 --- tests/clerk/backlog-resolve.bats | 113 -- tests/clerk/claim.bats | 442 ----- tests/clerk/clerk-bundles.bats | 136 -- tests/clerk/core.bats | 587 ------ tests/clerk/cutover.bats | 75 - tests/clerk/finish-sync.bats | 365 ---- tests/clerk/gate-submit.bats | 271 --- tests/clerk/glean.bats | 544 ----- tests/clerk/helpers.bash | 13 - tests/clerk/hermetic.bats | 28 - tests/clerk/inbox-graph.bats | 326 --- tests/clerk/inbox.bats | 1021 ---------- tests/clerk/release-return.bats | 508 ----- tests/clerk_python/test_core_contracts.py | 202 -- tests/clerk_python/test_graph_mutations.py | 261 --- tests/clerk_python/test_ownership.py | 81 - tests/clerk_python/test_proof.py | 36 - tests/clerk_python/test_read_queries.py | 280 --- tests/clerk_python/test_ready_drop.py | 717 ------- tests/clerk_python/test_text_mutations.py | 218 -- tests/clerk_python/test_work_graph.py | 156 -- tests/phyllary/project-gate.bats | 41 + umbel/CONTEXT.md | 30 +- umbel/bundles/clerk-delivery-base.md | 38 - umbel/bundles/clerk-discovery.md | 42 - umbel/bundles/phyllary-delivery-base.md | 38 + ...rs.md => phyllary-delivery-superpowers.md} | 14 +- umbel/bundles/phyllary-discovery.md | 42 + ...ate-acceptance-proof-and-judgment-loops.md | 36 +- umbel/hooks/local/clerk-session-start/HOOK.md | 12 - umbel/hooks/local/clerk-session-start/seed.md | 30 - .../local/phyllary-session-start/HOOK.md | 12 + .../local/phyllary-session-start/seed.md | 30 + .../session-start | 10 +- .../SKILL.md | 22 +- 79 files changed, 338 insertions(+), 11873 deletions(-) delete mode 100644 .clerk create mode 100644 .phyllary delete mode 100755 bin/clerk delete mode 100755 bin/nextdelivery delete mode 100644 clerk/CONTEXT.md delete mode 100644 clerk/docs/adr/0015-clerk-opaque-workflow-verb-facade.md delete mode 100644 clerk/docs/adr/0017-tier-retired-backlog-location-and-merge-gate-axes.md delete mode 100644 clerk/docs/adr/0018-clerk-compound-impediment-reducer.md delete mode 100644 clerk/docs/adr/0019-project-gate-adapter-contract.md delete mode 100644 clerk/docs/project-gate.md delete mode 100644 clerk/docs/research/2026-07-24-project-gate-acceptance-verifier.md delete mode 100644 clerk/project-gate.json delete mode 100644 clerk/src/clerk/__init__.py delete mode 100644 clerk/src/clerk/__main__.py delete mode 100644 clerk/src/clerk/cli.py delete mode 100644 clerk/src/clerk/commands.py delete mode 100644 clerk/src/clerk/doctor.py delete mode 100644 clerk/src/clerk/glean.py delete mode 100644 clerk/src/clerk/manifest.py delete mode 100644 clerk/src/clerk/output.py delete mode 100644 clerk/src/clerk/ownership.py delete mode 100644 clerk/src/clerk/proc.py delete mode 100644 clerk/src/clerk/project_gate.py delete mode 100644 clerk/src/clerk/reconciliation.py delete mode 100644 clerk/src/clerk/roster.py delete mode 100644 clerk/src/clerk/work_graph.py rename {clerk => phyllary}/project-gate (53%) create mode 100644 phyllary/project-gate.json rename pi/agent/extensions/{clerk-implement => phyllary-implement}/.gitignore (100%) rename pi/agent/extensions/{clerk-implement => phyllary-implement}/index.ts (59%) delete mode 100644 tests/clerk/backlog-read.bats delete mode 100644 tests/clerk/backlog-resolve.bats delete mode 100644 tests/clerk/claim.bats delete mode 100644 tests/clerk/clerk-bundles.bats delete mode 100644 tests/clerk/core.bats delete mode 100644 tests/clerk/cutover.bats delete mode 100644 tests/clerk/finish-sync.bats delete mode 100644 tests/clerk/gate-submit.bats delete mode 100644 tests/clerk/glean.bats delete mode 100644 tests/clerk/helpers.bash delete mode 100644 tests/clerk/hermetic.bats delete mode 100644 tests/clerk/inbox-graph.bats delete mode 100644 tests/clerk/inbox.bats delete mode 100644 tests/clerk/release-return.bats delete mode 100644 tests/clerk_python/test_core_contracts.py delete mode 100644 tests/clerk_python/test_graph_mutations.py delete mode 100644 tests/clerk_python/test_ownership.py delete mode 100644 tests/clerk_python/test_proof.py delete mode 100644 tests/clerk_python/test_read_queries.py delete mode 100644 tests/clerk_python/test_ready_drop.py delete mode 100644 tests/clerk_python/test_text_mutations.py delete mode 100644 tests/clerk_python/test_work_graph.py create mode 100644 tests/phyllary/project-gate.bats delete mode 100644 umbel/bundles/clerk-delivery-base.md delete mode 100644 umbel/bundles/clerk-discovery.md create mode 100644 umbel/bundles/phyllary-delivery-base.md rename umbel/bundles/{clerk-delivery-superpowers.md => phyllary-delivery-superpowers.md} (69%) create mode 100644 umbel/bundles/phyllary-discovery.md delete mode 100644 umbel/hooks/local/clerk-session-start/HOOK.md delete mode 100644 umbel/hooks/local/clerk-session-start/seed.md create mode 100644 umbel/hooks/local/phyllary-session-start/HOOK.md create mode 100644 umbel/hooks/local/phyllary-session-start/seed.md rename umbel/hooks/local/{clerk-session-start => phyllary-session-start}/session-start (62%) rename umbel/skills/local/{clerk-presort => phyllary-presort}/SKILL.md (81%) diff --git a/.clerk b/.clerk deleted file mode 100644 index fabd45c..0000000 --- a/.clerk +++ /dev/null @@ -1,2 +0,0 @@ -backlog: bd -project-gate: clerk/project-gate.json diff --git a/.github/workflows/delivery-gate.yml b/.github/workflows/delivery-gate.yml index 043afb2..356f10b 100644 --- a/.github/workflows/delivery-gate.yml +++ b/.github/workflows/delivery-gate.yml @@ -24,18 +24,7 @@ jobs: - name: Install system checks run: | sudo apt-get update - sudo apt-get install -y bats shellcheck jq parallel - - - name: Set up Go for pinned bd install - uses: actions/setup-go@v5 - with: - go-version: stable - - - name: Install bd 1.0.4 - run: | - go install github.com/steveyegge/beads/cmd/bd@ce242a879 - sudo install -m 0755 "$(go env GOPATH)/bin/bd" /usr/local/bin/bd - bd --version | grep 'bd version 1.0.4' + sudo apt-get install -y bats shellcheck jq - name: project-gate run: | @@ -44,6 +33,6 @@ jobs: --arg branch "${GITHUB_HEAD_REF}" \ --arg commit "$head" \ --arg worktree "$GITHUB_WORKSPACE" \ - '{work: {id: "pull-request", title: "Pull request validation", acceptance_criteria: "Project-gate CI validation"}, delivery: {branch: $branch, starting_commit: $commit, worktree: $worktree}, submission_owner: "clerk"}') - printf '%s\n' "$request" | clerk/project-gate run | tee result.json + '{work: {id: "pull-request", title: "Pull request validation", acceptance_criteria: "Project-gate CI validation"}, delivery: {branch: $branch, starting_commit: $commit, worktree: $worktree}, submission_owner: "phyllary"}') + printf '%s\n' "$request" | phyllary/project-gate run | tee result.json jq -e --arg head "$head" '.status == "passed" and .assessed_commit == $head' result.json diff --git a/.gitignore b/.gitignore index 56f1377..36f8a38 100644 --- a/.gitignore +++ b/.gitignore @@ -53,7 +53,7 @@ pi/agent/extensions/*/* # project config is ever wanted — see the claude-code/* block above. .claude/ -# clerk: provisioned delivery worktrees live under the checkout; the branches and +# phyllary: provisioned delivery worktrees live under the checkout; the branches and # commits are tracked by git refs, not by recursively staging worktree contents. .worktrees/ diff --git a/.phyllary b/.phyllary new file mode 100644 index 0000000..e63585f --- /dev/null +++ b/.phyllary @@ -0,0 +1,2 @@ +backlog: bd +project-gate: phyllary/project-gate.json diff --git a/.stow-local-ignore b/.stow-local-ignore index 0aeb5ff..741d0c3 100644 --- a/.stow-local-ignore +++ b/.stow-local-ignore @@ -16,8 +16,8 @@ tmp_config.json ^docs$ ^\.local$ ^\.repo-visibility$ -^\.clerk$ -^clerk$ +^\.phyllary$ +^phyllary$ ^tests$ ^\.umbel-bundle$ ^\.worktrees$ diff --git a/AGENTS.md b/AGENTS.md index 208acbc..8f1715c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -4,31 +4,31 @@ Personal dotfiles repo. ## Agent workflow -Use **Clerk** (`clerk`) as the workflow facade for this repo. +Use **Phyllary** (`phyllary`) as the workflow facade for this repo. -- Capture raw work with `clerk capture`. -- Inspect/refine work with `clerk inbox ...`. -- Pick up and deliver ready work with `clerk backlog ...`. -- Run `clerk doctor` when setup or the next workflow step is unclear. +- Capture raw work with `phyllary capture`. +- Inspect/refine work with `phyllary inbox ...`. +- Pick up and deliver ready work with `phyllary backlog ...`. +- Run `phyllary doctor` when setup or the next workflow step is unclear. -Runtime instructions should speak Clerk verbs only. Operator-only docs under `docs/agents/` +Runtime instructions should speak Phyllary verbs only. Operator-only docs under `docs/agents/` may describe lower-level storage details for maintenance. ## Domain docs -Multi-context; see `CONTEXT-MAP.md` for the documented Umbel and Clerk contexts and their ADRs. +See `CONTEXT-MAP.md` for the local Umbel and external Phyllary contexts and their ADRs. See `docs/agents/domain.md`. ## Agent skills ### Issue tracker -Work is tracked through Clerk, not an external issue tracker. Use `clerk capture`, -`clerk inbox ...`, and `clerk backlog ...`. See `docs/agents/issue-tracker.md`. +Work is tracked through Phyllary, not an external issue tracker. Use `phyllary capture`, +`phyllary inbox ...`, and `phyllary backlog ...`. See `docs/agents/issue-tracker.md`. ### Triage labels -The canonical triage roles map to Clerk inbox/backlog dispositions, not tracker labels. See +The canonical triage roles map to Phyllary inbox/backlog dispositions, not tracker labels. See `docs/agents/triage-labels.md`. ### Domain docs diff --git a/CONTEXT-MAP.md b/CONTEXT-MAP.md index ad45fef..c99b9dc 100644 --- a/CONTEXT-MAP.md +++ b/CONTEXT-MAP.md @@ -5,5 +5,4 @@ local reference to another context is useful navigation, not a shared glossary o - [**Umbel**](umbel/CONTEXT.md) — the discovery and delivery workflow, its tracks, bundles, and judgment loops. -- [**Clerk**](clerk/CONTEXT.md) — the workflow-verb facade application, its Work model, delivery - lifecycle, manifest, and Project-gate boundary. +- [**Phyllary**](https://github.com/vessux/phyllary/blob/main/CONTEXT.md) — the external workflow-verb facade application, its Work model, delivery lifecycle, manifest, and Project-gate boundary. diff --git a/bin/bd.test.sh b/bin/bd.test.sh index c1af36e..36bd615 100755 --- a/bin/bd.test.sh +++ b/bin/bd.test.sh @@ -2,8 +2,8 @@ # bin/bd.test.sh — hermetic tests for the bin/bd shim's shared-server bootstrap fix # (dotfiles-). Follows the ccstatusline/umbel-segment.test.sh convention: a standalone, # non-bats companion script next to the file it tests (exit 0 = all pass), NOT currently wired -# into clerk/project-gate (which only runs `bats tests/clerk` — see that file's `bats -# tests/clerk && shellcheck -S error bin/*`). Run directly: ./bin/bd.test.sh +# into phyllary/project-gate (which only runs `shellcheck -S error bin/*`). Run directly: +# ./bin/bd.test.sh # # Two layers, matching the two halves of the fix: # 1. Direct unit tests of the two new helper functions, via SOURCING bin/bd — exactly what diff --git a/bin/clerk b/bin/clerk deleted file mode 100755 index ad33ecf..0000000 --- a/bin/clerk +++ /dev/null @@ -1,71 +0,0 @@ -#!/usr/bin/env bash -# clerk public launcher: resolve this checkout and hand off to stdlib Python. -set -uo pipefail - -clerk_error() { - printf 'clerk: %s\n' "$1" >&2 - if [ "$#" -gt 1 ]; then - shift - printf ' %s\n' "$@" >&2 - fi -} - -source_path=${BASH_SOURCE[0]} -while [ -L "$source_path" ]; do - source_dir=${source_path%/*} - [ "$source_dir" != "$source_path" ] || source_dir=. - if ! source_dir=$(cd -P -- "$source_dir" 2>/dev/null && pwd); then - clerk_error "cannot resolve launcher directory — cd into the dotfiles checkout, then rerun 'clerk doctor'" - exit 4 - fi - if ! target=$(readlink "$source_path" 2>/dev/null); then - clerk_error "cannot resolve launcher symlink — cd into the dotfiles checkout, then rerun 'clerk doctor'" - exit 4 - fi - case "$target" in - /*) source_path=$target ;; - *) source_path=$source_dir/$target ;; - esac -done - -bin_dir=${source_path%/*} -[ "$bin_dir" != "$source_path" ] || bin_dir=. -if ! bin_dir=$(cd -P -- "$bin_dir" 2>/dev/null && pwd); then - clerk_error "cannot resolve launcher directory — cd into the dotfiles checkout, then rerun 'clerk doctor'" - exit 4 -fi -if ! repo_root=$(cd -P -- "$bin_dir/.." 2>/dev/null && pwd); then - clerk_error "cannot resolve dotfiles checkout — cd into the dotfiles checkout, then rerun 'clerk doctor'" - exit 4 -fi - -python_src=$repo_root/clerk/src - -find_python() { - local candidate - for candidate in "${CLERK_PYTHON:-}" python3 python; do - [ -n "$candidate" ] || continue - command -v -- "$candidate" >/dev/null 2>&1 || continue - if "$candidate" - <<'PY' >/dev/null 2>&1 -import sys -raise SystemExit(0 if sys.version_info >= (3, 11) else 1) -PY - then - printf '%s\n' "$candidate" - return 0 - fi - done - return 1 -} - -if ! python_bin=$(find_python); then - clerk_error "Python 3.11 or newer is required to run Clerk" \ - "install Python 3.11+ or set CLERK_PYTHON to its path" \ - "then run 'clerk doctor' if setup is still unclear" - exit 4 -fi - -PYTHONDONTWRITEBYTECODE=1 \ -PYTHONPATH="$python_src${PYTHONPATH:+:$PYTHONPATH}" \ -CLERK_REPO_ROOT="$repo_root" \ -exec "$python_bin" -m clerk "$@" diff --git a/bin/nextdelivery b/bin/nextdelivery deleted file mode 100755 index 7cab827..0000000 --- a/bin/nextdelivery +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env bash -# Compatibility shim for the retired ready-pool lister. The live workflow facade is Clerk; -# keep this executable only so old shell muscle memory gets routed to the supported verb. -set -uo pipefail - -if [ "$#" -ne 0 ]; then - printf "nextdelivery: retired; use 'clerk backlog next' (or 'clerk doctor' for setup)\n" >&2 - exit 2 -fi - -exec clerk backlog next diff --git a/claude-code/settings.json b/claude-code/settings.json index 1fc6d14..325b5ef 100644 --- a/claude-code/settings.json +++ b/claude-code/settings.json @@ -5,13 +5,13 @@ "includeCoAuthoredBy": false, "permissions": { "allow": [ - "Bash(clerk capture:*)", - "Bash(clerk inbox list)", - "Bash(clerk inbox show:*)", - "Bash(clerk inbox dups:*)", - "Bash(clerk backlog next)", - "Bash(clerk backlog show:*)", - "Bash(clerk backlog claim:*)" + "Bash(phyllary capture:*)", + "Bash(phyllary inbox list)", + "Bash(phyllary inbox show:*)", + "Bash(phyllary inbox dups:*)", + "Bash(phyllary backlog next)", + "Bash(phyllary backlog show:*)", + "Bash(phyllary backlog claim:*)" ], "defaultMode": "auto" }, diff --git a/clerk/CONTEXT.md b/clerk/CONTEXT.md deleted file mode 100644 index 1bc8a93..0000000 --- a/clerk/CONTEXT.md +++ /dev/null @@ -1,82 +0,0 @@ -# Clerk — Workflow-verb facade - -Clerk is an independently understandable application context. It presents the workflow verbs that -clients use while hiding the backend and delivery mechanics behind that command boundary. - -## Language - -**Clerk**: -The opaque workflow-verb facade. Clients state a workflow verb and author judgment; Clerk performs -the deterministic mechanism and owns its public CLI contract, manifest, reconciliation, and backend -binding. -_Avoid_: wrapper, dispatcher, helper - -**Work**: -One Clerk-managed unit of discovery or delivery. A Work item carries its title, body, Acceptance -criteria when refined, and its place in the Work graph. -_Avoid_: task, ticket, issue - -**Work graph**: -The parent/child and sibling-blocking relationships among Work. Graph state determines whether ready -Work is pickable; it is not a backend-specific tracker graph. -_Avoid_: queue, tracker graph - -**Inbox**: -Clerk's refinement collection: Work that is not yet ready. Inbox verbs shape, relate, and promote -Work without exposing the backing store. -_Avoid_: tracker inbox - -**Backlog**: -Clerk's delivery collection: refinement-complete Work. A Backlog item may be waiting rather than -pickable when graph state has open children or blockers. -_Avoid_: queue - -**Work graph adapter**: -The backend binding behind Clerk's verb facade. It translates backend records and edges into Work, -owns ready/pickable/waiting and parent/child invariants, and exposes graph operations to command -handlers without leaking backend command shapes. -_Avoid_: tracker helper, command-handler graph logic - -**Claim**: -The atomic acquisition of one pickable Work item for delivery. A Claim creates the canonical delivery -branch/worktree and is distinct from a planning claim or an assignee. -_Avoid_: assignment, lock - -**Planning claim**: -A temporary Inbox ownership marker that keeps a planning item out of the Frontier. It has no delivery -branch, worktree, or delivery lifecycle semantics. -_Avoid_: Claim - -**Project gate**: -A project-owned validation policy invoked at the delivery handoff. It may be a one-shot command, an -asynchronous service, or a stronger independent verifier; Clerk does not own its tools, models, -prompts, evidence, artifacts, or criterion-to-test policy. -_Avoid_: Clerk gate, delivery-gate - -**Project gate adapter**: -The project-owned command boundary that translates Clerk's Gate request to a Project gate. `run` is -required; `status` is required only after a pending run. The minimum adapter is a synchronous -transform shim around a project command. -_Avoid_: plugin, integration - -**Project gate configuration**: -Committed project-owned configuration referenced by `.clerk`. Clerk resolves it and the adapter from -trusted default-branch content; its absence fails submission closed. -_Avoid_: Clerk policy - -**Gate request**: -One structured stdin document from Clerk to an adapter, carrying Work identity, full Acceptance -criteria, delivery branch/commit/worktree, and Submission ownership. -_Avoid_: adapter arguments - -**Gate result**: -One JSON document emitted by an adapter. It has `status`, `summary`, and `assessed_commit`; a pending -result additionally has opaque `run.id`. It is a valid verdict, unlike a non-zero adapter operational -failure. -_Avoid_: tool log - -**Submission ownership**: -The selected owner of the post-validation delivery handoff. `clerk` means Clerk hands off the assessed -worktree head after a pass; `project-gate` means the adapter owns refs, push/PR/CI, and lifecycle -reporting. -_Avoid_: mode diff --git a/clerk/docs/adr/0015-clerk-opaque-workflow-verb-facade.md b/clerk/docs/adr/0015-clerk-opaque-workflow-verb-facade.md deleted file mode 100644 index 9cd3d7e..0000000 --- a/clerk/docs/adr/0015-clerk-opaque-workflow-verb-facade.md +++ /dev/null @@ -1,246 +0,0 @@ ---- -status: accepted ---- - -# Clerk: an opaque workflow-verb facade owns the public workflow contract - -Workflow mechanism (claim atomicity, sync discipline, finish sequencing) lived in seed prose and -auto-memories that agents re-read, re-obey, and eventually skip (dotfiles-b6r); fixes landed as -more prose (y7m, ys5, the skip-worktree/dirty-checkout memory cluster). We move every menial, -deterministic step behind **`clerk`** — a single dispatcher in repo `bin/`, stowed like the `bd` -shim — and the agent speaks workflow verbs. The split is **judgment vs paperwork**: the agent -decides *which* verb and authors anything requiring judgment (PR bodies, promotion titles, return -reasons); the clerk executes mechanism exactly, in code that cannot drift from itself. - -The durable decision is the **facade contract**, not ownership of every primitive forever. Clerk is -allowed — expected — to orchestrate existing substrates (`bd`, `gh`, git refs, GitHub Actions, -branch protection) and to swap or delegate those substrates later. What bundles and agents depend -on is the verb grammar, exit/output contracts, and idempotent reconciliation behaviour. - -This clarification is deliberately made before the dotfiles cutover: the concurrent Umbel overhaul -may reorganise bundle application, but it must not accidentally make bundles the owners of Clerk's -state machine or make Clerk depend on Umbel internals. - -## Boundary contract - -### Clerk public contract - -The public contract is the `clerk` CLI: its verb roster, argument shapes, exit-code taxonomy, -prescriptive output, `.clerk` marker interpretation, and the idempotency promised by `doctor`, -`claim`, `release`, `return`, `submit`, `gate`, `finish`, `sync`, and `glean`. Tests assert this -contract at the command boundary. Callers may rely on successful mutations being self-verified -before a success line is printed, and on repeated reconciliation converging rather than duplicating -work. - -The public `bin/clerk` launcher invokes the self-contained, stdlib-only Python 3.11+ -implementation. It remains the compatibility boundary: callers invoke the same executable and rely -on the same verb grammar, exit-code taxonomy, prescriptive output, manifest handling, mutation -verification, delivery-gate behaviour, and reconciliation semantics. Compatibility is proven at the -public CLI contract, especially command-boundary tests, not by preserving implementation internals. - -### Umbel bundle contract - -Umbel bundles are **clients of Clerk**, not generators of Clerk. A bundle may: - -- include Clerk-facing operating prose (short seed text, session loop, keys); -- install a thin SessionStart hook that injects those rules and kicks `clerk glean`; -- choose which skills compose around the Clerk loop; -- tell the operator to run `clerk doctor` when setup is missing. - -A bundle must not: - -- parse or write backend state directly (`bd`, GitHub issue labels, claim branches) when a Clerk - verb exists; -- parse `.clerk` itself instead of calling Clerk; -- synthesize a different `clerk` implementation during bundle application; -- encode branch/worktree/finish mechanics in seed prose as a parallel workflow. - -Umbel apply remains idempotent over bundle pins, generated hook config, and injected text. Per-repo -workflow state (`.clerk`, open claims, worktrees, PRs, transcript watermarks) is Clerk/repo state, -not bundle state. Rollback is therefore re-pinning the old bundle generation; it must not require -rewinding Clerk's already-reconciled operational state. - -### Manifest contract - -`.clerk` is the repo-local manifest v0 owned by the Clerk/repo boundary (ADR 0017). Bundles may -assume Clerk can dispatch once `clerk doctor` is green; they do not own the marker schema. Schema -changes are handled as Clerk compatibility work: accept old valid manifests, diagnose ambiguous -ones, and have `doctor` prescribe or perform safe migrations. - -### Change budget - -Small changes: seed wording, bundle composition, skill lists, prompt text, and hook text that still -calls the same Clerk verbs. - -Medium changes: adding manifest keys, changing labels/states behind an existing verb, changing PR -body proof schema, or adding a backend binding while preserving the verb contract. - -Large changes: changing the claim lock/worktree model, removing PRs as the convergence point, -changing merge semantics in a way that invalidates finish's PR-state model, or changing the public -verb grammar. Large changes require a focused grill before delivery resumes. - -## Decision - -- **Clerk is a facade over primitives, not a new substrate monopoly.** The workflow needed a stable - command boundary because prose/config discipline was the failing layer; it did not require - reimplementing every underlying capability. Existing primitives remain first-choice internals - where they match the contract. -- **Implementation language is not the contract.** The CLI contract above survives the completed - stdlib-only Python 3.11+ port. The public command remains the launcher and contract boundary. -- **The Work graph adapter is the Python backend seam.** Command handlers ask it for Work graph and - Backlog operations rather than encoding backend edge shapes or pickability. The adapter owns the - ready/pickable/waiting split, including the rule that a ready parent with an open direct child is - not pickable. It computes the full bd-backed graph from an unlimited snapshot, avoiding serial - per-candidate detail calls. Remaining Python-port slices use this adapter for Work state, - graph mutations, and delivery lifecycle transitions instead of adding command-local bd logic. -- **Umbel bundles consume Clerk; they do not own it.** The bundle layer provides operating rules and - hook wiring. Clerk owns workflow mechanism and repo-local state. -- **Grammar is noun-scoped by collection (place)**: `inbox` (refinement views over non-ready work) - and `backlog` (refinement-complete ready work). Ready and pickable are intentionally split: - `inbox ready` records that refinement is complete, while backlog verbs compute whether the Work - graph makes that unit claimable/resolvable now. Object-type nouns break under promote=flow; - ID-shape dispatch couples to backend token formats — both rejected in the session-1 stress test - (epic dotfiles-dft). -- **Verb roster**: `capture "" [--stdin|--type <type>|--impediment|--parent <id>|--blocked-by <id>]`; - `inbox list|show|dups|ready|drop|pregrill|children|frontier|blockers|blocked|parent|dep|claim|release|note|update|resolve`; - `backlog next|show|waiting|claim|release|resolve|return|proof|submit|gate|finish`; `sync`; `doctor`; `glean`. -- **Opacity (hard ban, layered)**: skills, bundles, hooks, seeds, and injected instructions never - name beads/`bd` — the backing store is the clerk's private business. Agent *runtime* discovery of - `bd` is tolerated (reads harmless; writes self-punishing — they reintroduce solved bugs like the - stale close ADR 0013 fixed) and signals a missing verb (an Impediment). The unattended tier will - make the ban structural via the permission allowlist (dotfiles-220). Raw `bd` grooming - (`dep`/`update`/`epic`) stays legal only in operator docs and live human sessions; the first - *skill* needing grooming vocabulary is the trigger to mint the clerk verb. -- **One keyless binary, four callers**: agent in attended session; agent in job (clerk detects job - context itself — absorbs the BD_SHIM_SYNC seed clauses); **no agent at all** — the - authorship-free verbs (`sync`, `doctor`) are schedulable as a plain systemd timer, zero tokens; - human terminal (`clerk backlog next` is `nextdelivery`'s successor as a first-class human - surface; `--explain` prints underlying commands + ADR pointer). -- **Three keys, zero verb ACLs** — autonomy is dialed at boundaries the human controls, never in - clerk code: (K1) merge key = review-required branch protection (ADR 0016); (K2) initiation key = - the human starts sessions; (K3) in-session key = harness permission allowlist (reads, `capture`, - `claim` free; `submit`/`finish` prompt-gated initially). -- **Three loops, three owners**: inner (red check → fix → push → `finish`) agent-owned in-session; - session loop (claim → build → submit → finish) owned by the bundle's operating rules; outer loop - (launching unattended sessions) **deferred to a future epic** — this epic is attended-first, - unattended-ready. -- **Hook roster = one hook**: SessionStart (seed-inject + kick `clerk glean`). A Stop-hook claim - guard was rejected (fires every turn mid-build; no honest mount point) — the `sync` sweep is the - sole abandonment net. A SessionEnd glean hook was rejected (doesn't fire on crashes/kills — - leaky exactly on messy sessions). -- **`clerk glean` is a watermark sweep**: per-transcript-file line-offset watermark (offsets, not - timestamps: exactly-once, no gaps), spawns the judgment fork per unharvested chunk, advances the - watermark only after captures file successfully, `flock`-guarded single instance, fully async. - Cursor state in `~/.local/state/clerk/`. -- **Reconciler (`finish`/`sync`)**: one stateless function, two schedulers — finish-eager as the - delivery session's last act, sync-sweep over all open claims (absorbs dotfiles-dnq stale-claim - reclaim). **The sweep never authors** — it executes authorship-free phases and files reports for - judgment-needing states. `finish` is non-blocking by default (`--watch` opt-in wraps - `gh pr checks --watch`); it detects merge via **PR state only, never ancestry** (squash orphans - branch commits). `submit` is once per unit; iteration repeats `finish`. -- **Merge method = squash**: one unit = one PR = one commit, unit id in the subject, criteria - evidence in the body — `git log` is the delivery record glean audits. -- **Offline claim = attended-only degraded mode**: proceed with a quantified LOCAL-ONLY warning; - the canonical branch is the CAS at reconnect (second push rejected → collision detected, never - silent). Job contexts refuse offline claims. -- **Operational contracts (every verb, asserted verbatim in bats — including the failure paths).** - Surfaced by the small-model delivery experiment on unit dotfiles-dft.1 (History), where two - independent implementations both passed all seven acceptance criteria yet diverged on behaviours - the criteria never pinned — the signature of an underspecified contract, not a coding slip: - - **Exit-code taxonomy, one meaning each**: `0` success; `1` `doctor` found problems (below); - `2` usage error / unknown verb / bad-or-missing id (roster or corrected invocation printed); - `3` a known verb not implemented in this generation; `4` `.clerk` unresolvable (missing / - invalid / not in a git repo); `5` a backend command (`bd`/`gh`) failed or a mutation could not - be confirmed; `6` a delivery-gate ran successfully and found one or more failed proof classes. - Dispatch distinguishes unknown (`2`) from not-yet-implemented (`3`) — a grammar - error is not a generation gap; and a broken backend (`5`) from a caller who named a - non-existent unit (`2`) — "the tracker is down" is not "you passed a bad id". `1` is scoped to - `doctor`'s health check; every other verb signals operational failure through `5`, never `1`. - - **`doctor` is a health check, not a diagnostic that always succeeds**: it exits `0` iff every - check passes and non-zero (`1`) if any fails. This is the contract the zero-token systemd-timer - caller depends on — a timer can only alert on a non-zero exit; a `doctor` that always exits `0` - is silent on exactly the failures it exists to catch. - - **Mutations self-verify before reporting success**: any state-changing action (`doctor --fix` - writing `.clerk`, `claim` creating the branch/worktree, `capture` filing) confirms its effect - landed before printing a success line, and on failure exits non-zero with a prescriptive - message — it never prints `[ ok ]` / "written" over a failed write. A false success dead-ends - the dispatch → `doctor` → dispatch recovery loop. - - **Error text is prompt engineering**: every refusal prescribes the next verb, names the - resolved path where one is at issue, and (for usage errors) shows the corrected invocation. - Printed output is load-bearing — the agent's next action follows it. - - **Output discipline**: 16-color ANSI only (30–37 / 90–97, bold/reset; never `38;5` / `38;2`). - Colour is suppressed when the stream is not a TTY or `NO_COLOR` is set — the refusal / roster / - `doctor` strings are parsed downstream and must never carry escape sequences into a pipe or log. - -## Considered options - -- **Adopt beads formulas/molecules or Gas Town** (verified: local `bd` 1.0.4 ships - `formula`/`cook`/`mol`/`gate`/`merge-slot`; zero formulas in use) — rejected: formulas define the - *shape of work* (bead-DAG templates), not mechanism; Gas Town is a multi-agent runtime whose - Refinery replaces the trust fabric with its own merge queue, killing the gh backlog dispatch and - the branch-protection gate bet. Steals taken instead: `bd ready` ≈ private `backlog next`; - `bd --readonly` wraps clerk read verbs (structural fork read-only); `bd gate`/`merge-slot` noted - as future serialization primitives. Re-evaluate Gas Town only if the end-state becomes - multi-agent fleets; opacity keeps `gt` adoptable as a binding later. -- **Five top-level commands instead of a dispatcher** — rejected: `sync`/`doctor` are too generic - for PATH; `--explain` and doctor version-parity want one entry point. -- **Umbel-derived or flow-family names** — rejected: umbel is a delivery mechanism, not a sibling - project; `deskflow` collides with the Synergy fork; "task"/"workflow" pollute agent priors - (harness Task tools, `gh workflow`). `clerk` is the English word fusing desk + menial labor. -- **Role→backend manifest now** — deferred until a third binding exists; dispatch is two hardcoded - presets riding the `.clerk` marker (ADR 0017). Interface now, generality lazily (ADR 0010). - -## Consequences - -- **The bundle generation is re-authored, not migrated**: new `clerk-discovery`, - `clerk-delivery-base`, `clerk-delivery-superpowers` speak clerk from birth; the old generation - (three workflow manifests + personal variants, `delivery-base-ruleset` hook, both tier seeds, - presort skill) is **frozen as-is** and retired later. Freeze boundary is wording, not tooling — - wording-neutral tools (grill-with-docs, plannotator, tuidriver, glean mechanics) are shared. - Cutover is per-repo re-pin; rollback is re-pinning the old bundle. -- Pre-sort's successor is decision-free with one write verb (`inbox pregrill`, ADR 0016); the - inbox noun definition (open minus `stage:ready`) moves from skill prose into clerk code. The Work - graph can span inbox and backlog: `capture --parent` may target a non-closed promoted parent, and - `backlog waiting` shows ready items held out of `backlog next` by open blockers or open children. -- `nextdelivery` and its dead `umbel adopt` hint dissolve (`clerk backlog next` / `clerk doctor`); - `land` and the dirty-shared-checkout hazard class dissolve with worktree-per-claim; the - delivery-finish memory cluster (user-pushes-main, worktree-discard, skip-worktree, dirty-checkout) - retires — enforced by structure instead of remembered (dotfiles-w0x). -- `CLAUDE.md`'s "issues live in beads" line is Layer-1 text and becomes clerk wording; - `docs/agents/issue-tracker.md` remains the one operator doc allowed to name beads. - -## History - -- 2026-08-05: The Python implementation assumed every public verb path after the complete - Refinement/delivery soak. The legacy Bash implementation and force-legacy override were removed; - the command-boundary and Python suites now cover the retained public contract. -- 2026-07-25: Python backend clarification added for dotfiles-9urv.17. Work graph invariants and - substrate-specific graph operations live behind the Work graph adapter seam; remaining port - slices use that seam as their backend boundary. -- 2026-07-23: Python-port clarification added for epic dotfiles-9urv. Clerk began moving from - Bash to stdlib-only Python 3.11+ behind the existing public command. Compatibility was judged at - the public CLI contract and command boundary, not by retaining shell internals. -- 2026-07-11: design pause before dotfiles cutover clarified the boundary contract: Clerk's durable - asset is the CLI facade over primitives, not a permanent bespoke substrate; Bash is the v0 - implementation, not the language contract; Umbel bundles consume Clerk and own only operating - prose/hook wiring, while Clerk/repo state owns `.clerk`, claims, worktrees, PR reconciliation, and - transcript watermarks. -- 2026-07-06: operational-contracts bullet added (exit-code taxonomy, `doctor`-as-health-check, - mutation-self-verify, non-TTY/`NO_COLOR` output discipline). Surfaced by the small-model delivery - experiment on unit dotfiles-dft.1 — a fable baseline and a sonnet-implement/haiku-verify arm both - passed all seven acceptance criteria and shellcheck, yet diverged on `doctor`'s exit code - (health-check `1` vs always-`0`) and one shipped a `doctor --fix` that printed success over a - failed write. When two competent implementations of one spec diverge on a load-bearing behaviour, - the spec underspecified a *contract* — so it is written down here rather than left to per-unit - criteria (which cannot enumerate every failure path). The neutral referee confirmed both - behaviours; the cost/quality data and the resulting model-tier policy live in the epic - dotfiles-dft experiment note. -- 2026-07-07: taxonomy extended with exit `5` (a backend command failed, or a mutation could not be - confirmed) and not-found folded into `2` (a non-existent id is a bad-id usage error, like a - missing one). Surfaced delivering unit dotfiles-dft.2 (the inbox verbs are the first to invoke - `bd`/`gh`): the review caught backend failures returning `1`, which collides with `doctor`'s `1`. - Same contracts-not-instances move as the row above — decided once here, not per verb. -- 2026-07-09: taxonomy extended with exit `6` for delivery-gate proof failures. The command and - environment are valid in this case, so folding red proof classes into usage error `2` would erase - the signal later automation needs to distinguish "invoke clerk differently" from "delivery is not - mergeable yet" (ADR 0016 dotfiles-dft.4 amendment). diff --git a/clerk/docs/adr/0017-tier-retired-backlog-location-and-merge-gate-axes.md b/clerk/docs/adr/0017-tier-retired-backlog-location-and-merge-gate-axes.md deleted file mode 100644 index d424760..0000000 --- a/clerk/docs/adr/0017-tier-retired-backlog-location-and-merge-gate-axes.md +++ /dev/null @@ -1,79 +0,0 @@ ---- -status: accepted ---- - -# Tier retired: backlog-location and merge-gate are independent axes; `.clerk` is the manifest v0 - -The public/private "tier" conflated two independent policies, and this repo falsified the wording -itself: its `.repo-visibility` marker says `private` while the GitHub remote is public — tier was -always policy, never a remote fact. The real axes are **backlog location** (where the ready pool -lives: `bd stage:ready` vs `gh` issues `ready-for-agent`) and **merge gate** (the autonomy dial: -review-required vs auto-merge-on-green). They get opposite storage treatments on one principle — -**policy lives where its enforcement lives**. - -## Decision - -- **Backlog location = a committed marker, `.clerk`, at the repo root** — dispatch must be - deterministic and offline-capable. One key for now (`backlog: bd|gh`), and the file is the - **manifest v0**: when a third binding arrives (jira/linear/gt; promote and claim styles), roles - become new keys in an existing file, not a migration (ADR 0010's interface-now instinct; - ADR 0015's presets ride this key). `.clerk` is read and repaired through Clerk; Umbel bundles - may require a green `clerk doctor`, but they do not parse or generate the marker themselves. -- **The marker is strict, and ambiguity is refused, never resolved.** A valid `.clerk` is a single - directive line (surrounding whitespace and `#`-comment lines tolerated). More than one directive, - or trailing non-comment content, makes it *invalid* — the parser does not take first-match-wins. - An ambiguous manifest is a `doctor`-diagnosed fault, not a silent backend choice (dotfiles-dft.1 - experiment: a lenient parser accepted `backlog: bd` + `backlog: gh` and silently dispatched to - `bd`). -- **Merge gate = never a marker.** The gate *is* branch protection + auto-merge settings — - server-enforced, so the reconciler reads it live (`gh api`) at exactly the phases that need the - remote anyway. A committed copy could only ever lie; `.repo-visibility` is the proof. - "Attended"/"unattended" survive as *descriptions* of a repo's observed gate posture, never - stored state. -- **Claim unifies across backends**: every claim creates the canonical `delivery/<id>` branch — - the universal lock at the remote (first push wins); a bd-backed backlog adds the status - transition as the online fast path. (CONTEXT.md's Claim entry updated accordingly.) - -This ADR **supersedes-in-part**: - -- **ADR 0004** (private-tier decision record) — its decisions stand; read its "private tier" as - "bd-backed backlog, review-required gate". -- **ADR 0011** (public delivery claim: canonical branch is the lock) — its mechanism is *promoted* - from public-tier-specific to the universal claim lock on both backends. - -Per the frozen-generation ruling (ADR 0015), neither old ADR is reworded in place; the old bundle -generation and `.repo-visibility` keep speaking tier until retired — the two markers coexist -during cutover, each generation reading only its own. - -## Consequences - -- `nextdelivery` has dissolved into `clerk backlog next` + `clerk doctor`. Its remaining `bin/` - executable is only a compatibility shim for old muscle memory; it no longer reads the retired - marker or prints the old setup hint. Clerk owns ready-pool dispatch and `.clerk` provisioning. -- Seeds in the new generation barely mention the axes at all: dispatch is the clerk's business, - and the gate is discovered live, so the graduated-autonomy ladder is a per-repo platform - setting, not seed prose. -- At cutover this repo's `.clerk` says `backlog: bd` — unchanged behavior under retired - vocabulary. - -## History - -- 2026-07-11: dotfiles committed `.clerk` with `backlog: bd`; `nextdelivery` became a - compatibility shim over `clerk backlog next`, and its old setup hint was replaced by - `clerk doctor`. -- 2026-07-11: clarified the Umbel/Clerk boundary before dotfiles cutover: `.clerk` is the - repo-local manifest that Clerk reads and repairs, while bundles are clients that may require a - green `clerk doctor` but must not parse or generate the marker. This coordinates the concurrent - Umbel overhaul with the Clerk cutover. -- 2026-07-09: the `nextdelivery` Consequences bullet was rewritten to drop the false claim - that it was a `zsh/.zshenv` function and to state its current form instead. `nextdelivery` - was ported from a `.zshenv` zsh function to a `bin/` executable (ADR 0001, repo-root), so it - is reachable by pi's `/bin/bash` tool shell and yazi, not only zsh. The bullet had also - implied the `clerk backlog next` migration was done; it isn't — `nextdelivery` still reads - `.repo-visibility` and this repo has no `.clerk` yet. The *intended* migration target now - reads as `bin/nextdelivery` dissolving into `clerk backlog next` + `clerk doctor`. -- 2026-07-06: strict-marker clause added (ambiguous / multi-directive `.clerk` is invalid, not - first-match-wins). The dotfiles-dft.1 small-model experiment shipped a lenient parser that - accepted two conflicting directives and silently picked the first; "one key" always implied a - single directive, now stated so the contract is testable. Marker-format details otherwise - unchanged. diff --git a/clerk/docs/adr/0018-clerk-compound-impediment-reducer.md b/clerk/docs/adr/0018-clerk-compound-impediment-reducer.md deleted file mode 100644 index d415995..0000000 --- a/clerk/docs/adr/0018-clerk-compound-impediment-reducer.md +++ /dev/null @@ -1,91 +0,0 @@ ---- -status: accepted ---- - -# `clerk compound` — a read-only longitudinal reduce over the Impediment corpus (Gap B) - -Glean (ADR 0012) files per-session `type:impediment` beads — Gap A. Cross-session -recurring-friction detection was scoped out as **Gap B** (dotfiles-8vq), to be modelled on -`plannotator/compound`'s longitudinal map-reduce. The corpus now exists (50+ Impediment beads). -This ADR fixes what Gap B is and, deliberately, what it is not. - -## Context - -Three facts constrain the design: - -1. **The corpus is a bd custom type, and it is prose.** The live producer (`clerk glean`, dft.6, - fired by the SessionStart hook) files `bd create --type impediment`; the ADR-0012 `/glean` - skill would file a `type:impediment` *label*, but it is not installed. Either way the bead - carries only a title + free-text body — the structured signals `extract.py` computes - (`error_class`, `retry_count`, tool, cost) are not persisted onto it. -2. **The loop map already routes impediments to fixes.** ADR 0016: glean → inbox → Pre-sort - clusters (via dups) → grill lands the cluster as one compounded unit → gated edit. Pre-sort - already dedups the *open inbox* source-agnostically (dotfiles-o1o). So a Gap-B step that - *files* compounded units would collide with Pre-sort and risk inbox flood. -3. **Remediation is a grill decision** (ADR 0012): glean deliberately leaves the fix open, because - choosing which instruction to change has more than one defensible answer. - -## Decision - -**`clerk compound`** — a clerk verb, the *reduce* sibling to `clerk glean`'s *harvest*, read-only -and ephemeral. - -- **A clerk verb, not a skill.** Its whole input is the bd Impediment corpus; a skill querying bd - would break the opacity ruling (ADR 0015). Glean hit the same fork and became a verb. Bash owns - the deterministic parts (query `--type impediment`, tolerate the label variant, group, count - recurrence, read status + dates); a reduce fork owns the judgment (name the friction classes from - the prose bodies, recommend one instruction/skill/tool change per class), returning a JSON - clustering that the deterministic half then counts, ranks, and renders. The fork is invoked - through a stubbable env seam (`CLERK_COMPOUND_REDUCE_CMD`, defaulting to `claude -p`) mirroring - glean's `CLERK_GLEAN_JUDGMENT_CMD`, so the acceptance tests pin the deterministic assembly against - a canned clustering rather than the non-deterministic model. One fork for the current corpus; - map-reduce batching only if it grows (the ADR 0010 instinct). -- **Read-only — the defining invariant.** It files no Capture, closes none, relabels none. It is - **Pre-sort's longitudinal cousin** (a read-only, ephemeral proposal), not Glean's write-fork. The - Impediment beads are already the persistent record; Compound only analyzes them. -- **Consumes beads, not transcripts.** No transcript re-scan — that would ignore the human triage - the beads carry, re-do glean's per-session work, and stand up a third transcript parser (ADR 0010 - gates sharing even the two existing ones). It reduces over the prose bodies, exactly as - `plannotator/compound` reduces over prose denial reasons. -- **Ranks by recurrence; flags recency, not fix-linkage.** Recurrence count is the primary rank key - (token-cost is inconsistent prose — a qualitative secondary at most). "Did the fix stick?" is a - recurrence-*recency* heuristic (recent occurrences = live; quiet-since-a-date = possibly - resolved), **not** a claim that a fix shipped: beads do not link to the delivery unit that fixed - them. -- **Ephemeral output.** A terse ranked agenda to stdout (16-color ANSI, capability-gated); anything - richer to an uncommitted state path (`~/.local/state/clerk/`), never a committed worklog (the - no-worklog rule; clear of the dotfiles-l1d committed-KB tension). The human reads the agenda and - grills the top class; the fix is a normal gated delivery unit. - -The loop closes without a meta-bead layer: grill a class → deliver the gated fix → the now-closed -Impediments plus the ADR/instruction change are the durable trace → the next `clerk compound` run -sees the recency shift. - -**Naming.** `clerk compound` names the *compound-engineering* discipline this verb performs. It is -distinct from the dormant, vendored `plannotator/compound` *skill*, which reduces the human's -plan-rejection feedback to improve planning (not agent friction). Convention: the tool is always -written `plannotator/compound`, the verb always `clerk compound`. (`clerk reduce` was the runner-up -— it names the member's role rather than the family — and is kept as a rename option.) - -## Considered options - -- **Re-scan transcripts for structured signal** — rejected: discards the human triage in the beads, - re-does glean's work, and duplicates the ADR-0010-gated parser. -- **Auto-file a compounded grill unit per class** (Glean's write-fork) — rejected: overlaps - Pre-sort's clustering, risks inbox flood, and makes a "worth fixing" call that is a grill decision. -- **A skill, modelled on `plannotator/compound`** — rejected: it would name bd, breaking the opacity - ruling. -- **True fix-linkage in v1** — deferred: needs a persisted fix-link/close-reason (a - glean-enrichment change + back-fill of existing prose beads). Earned when the recency heuristic - proves insufficient, not before. - -## Consequences - -- New clerk verb `clerk compound`; deterministic bash + one `claude -p` reduce fork. -- v1 reports recurrence + a recency signal. True fix-linkage and glean structured-field enrichment - are a deferred follow-up capture. -- `umbel/CONTEXT.md` gains the **Compound** term (disambiguated from `plannotator/compound`). -- Acceptance criteria pin the read-only invariant, corpus selection, and the empty-corpus exit path - as tests (the dotfiles-dft contract-divergence lesson: contracts two implementations could - reasonably decide oppositely must be written down, not left to delivery). -- Tracked as dotfiles-8vq (stage:ready). diff --git a/clerk/docs/adr/0019-project-gate-adapter-contract.md b/clerk/docs/adr/0019-project-gate-adapter-contract.md deleted file mode 100644 index 1365b3e..0000000 --- a/clerk/docs/adr/0019-project-gate-adapter-contract.md +++ /dev/null @@ -1,59 +0,0 @@ ---- -status: accepted ---- - -# Project-gate adapter contract: project policy outside Clerk - -## Context - -Umbel ADR 0016 established that Acceptance criteria are authored during Refinement and that the -implementer does not write its own exam. Its former Project-gate amendments described the Clerk -mechanism that hands delivery to project validation. That mechanism is now a Clerk decision; Umbel -continues to own the discovery/delivery judgment loop and Acceptance-criteria craft. - -Clerk must remain portable across projects. It cannot make this repository's test commands, proof -format, models, prompts, evidence retention, or independent-review policy universal. Equally, a -project must not need a daemon, artifact store, or agent merely to transform a synchronous test -command into a Clerk verdict. - -## Decision - -- A `.clerk` manifest references required, committed Project-gate configuration and adapter content. - Clerk resolves both from trusted default-branch content. Missing, unreadable, malformed, or - out-of-repository configuration fails submission closed; a delivery branch cannot supply the - adapter that grades itself. -- A Project-gate adapter implements required `run`. Clerk sends one structured stdin Gate request - containing Work identity/title/full Acceptance criteria, delivery branch/starting commit/worktree, - and Submission ownership. The adapter writes exactly one Gate result JSON to stdout. Tool output, - logs, details, evidence, and artifacts remain project policy. -- A result has `status` (`passed`, `failed`, or `pending`), `summary`, and actual - `assessed_commit`. `pending` additionally requires an opaque `run.id`. Terminal results may carry - an ID but do not require one. A valid failed check exits zero with `status: failed`; a broken or - unavailable adapter/configuration, or malformed output, exits non-zero as an operational error. -- `status` is conditional: only an adapter whose `run` returned `pending` must implement it. Clerk - retains the Claim/worktree for pending or failed results and gives the run ID back to `status` for - reconciliation. A later submission starts a new run. -- `passed` means only that the selected Project-gate policy passed for `assessed_commit`. Clerk does - not require or interpret individual criterion verdicts, independent verification, evidence, - artifacts, or criterion-to-test mappings. The Work and, where present, its PR remain the - Acceptance-criteria record. -- `submission_owner: clerk` is the minimum/default path. A passing adapter may advance the delivery - head, but must leave its assessed commit checked out in the supplied worktree; Clerk hands off only - that current head. `submission_owner: project-gate` is an opt-in for adapters that own changed - refs, push/PR/CI, and lifecycle reporting. - -## Consequences - -- The adoption floor is a committed config and a small project-owned synchronous transform shim. - Generic bootstrap automation is separate work; Clerk must not guess a project's validation policy. -- Projects may layer stronger verification—per-criterion ledgers, independently contextualized - reviewers, durable evidence, or asynchronous runs—without expanding Clerk's universal contract. -- Clerk persists only its generic Gate-run metadata and relays generic results. It remains the - workflow facade, not a validation-policy runtime. - -## Related decisions - -- Umbel ADR 0016 retains Acceptance-criteria and judgment-loop policy, and links here for the - Clerk-owned Project-gate contract. -- Clerk ADR 0015 defines the opaque workflow-verb facade; Clerk ADR 0017 defines `.clerk` as its - manifest. diff --git a/clerk/docs/project-gate.md b/clerk/docs/project-gate.md deleted file mode 100644 index 0a910ec..0000000 --- a/clerk/docs/project-gate.md +++ /dev/null @@ -1,52 +0,0 @@ -# Project-gate configuration - -`clerk backlog submit <id>` is validated by a required Project gate. Clerk reads the -configuration and adapter from the trusted default branch, never from the delivery -branch. - -`.clerk` keeps the normal backend binding and names a repository-relative JSON config: - -```text -backlog: bd -project-gate: clerk/project-gate.json -``` - -The config names a repository-relative executable adapter and its handoff owner: - -```json -{"adapter":"clerk/project-gate","submission_owner":"clerk"} -``` - -`submission_owner` defaults to `clerk`; `project-gate` is the explicit opt-in. -Both paths must stay inside the repository. Missing, unreadable, or malformed trusted -content stops submission as an operational error. - -## Adapter protocol - -Clerk runs the trusted adapter as `adapter run`, writing one JSON request to stdin: - -```json -{ - "work":{"id":"dotfiles-abc","title":"…","acceptance_criteria":"…"}, - "delivery":{"branch":"delivery/abc","starting_commit":"<sha>","worktree":"<path>"}, - "submission_owner":"clerk" -} -``` - -The adapter writes exactly one JSON Gate result to stdout. Every result has `status` -(`passed`, `failed`, or `pending`), `summary`, and `assessed_commit`. A `pending` -result additionally has `run.id`. Failed checks are a valid zero-exit `failed` result; -non-zero execution and malformed output are operational errors. - -Pending metadata is retained with the Claim. `clerk backlog gate <id>` invokes -`adapter status` only for that pending run, supplying the saved request plus -`{"run":{"id":"…"}}`; another `submit` always begins a fresh `run`. - -For Clerk-owned handoff, a passing `assessed_commit` must be the current supplied -worktree head before Clerk pushes and opens the PR. A Project-gate-owned passed result -must include `{"delivery":{"status":"completed"}}`; Clerk then records the Work -closed and does not create refs or PRs. - -The adapter owns all project-specific validation, logs, evidence, artifact, and -independent-review policy. Dotfiles' `clerk/project-gate` is the intentionally small -synchronous transform of `bats tests/clerk` and `shellcheck -S error bin/*`. diff --git a/clerk/docs/research/2026-07-24-project-gate-acceptance-verifier.md b/clerk/docs/research/2026-07-24-project-gate-acceptance-verifier.md deleted file mode 100644 index fba56b6..0000000 --- a/clerk/docs/research/2026-07-24-project-gate-acceptance-verifier.md +++ /dev/null @@ -1,64 +0,0 @@ -# Project-gate Acceptance-criteria verification research - -**Question:** Must Clerk impose an independent Acceptance-criteria verifier, durable evidence, and executable-test mapping on every Project gate? - -**Finding:** No. The primary sources support trusted project-controlled gate configuration, isolated validation workspaces, optional intent/evidence/reviewer loops, and head-specific results. They do not establish a universal Acceptance-criteria verification policy. Requiring one would turn Clerk's portable boundary into a policy-owning gate and make simple synchronous test adoption unnecessarily stateful. - -**Decision reached in the `dotfiles-9urv.18` Refinement grill:** Clerk owns the Work's Acceptance criteria and transports them to the Project gate, but a `passed` Gate result means only that **the selected Project-gate policy passed** for the assessed commit. The project decides whether that policy includes an independent verifier, per-criterion ledger, executable-test mapping, evidence, artifacts, reviewer model, prompts, budget, or asynchronous state. - -Clerk ADR 0019 records the resulting contract. - -## What the sources establish - -### Trusted project control plane - -`no-mistakes` treats shell commands and agent selection as executable control fields: it reads them from the fetched default branch rather than the submitted branch and aborts when that trusted copy cannot be read or parsed. This supports the settled Clerk boundary: `.clerk` references a committed Project-gate configuration and adapter resolved from trusted default-branch content. The delivery branch cannot replace the adapter that validates it. - -This is a control-plane rule, not a rule about the tools the adapter may invoke in the supplied delivery worktree. The Project gate owns those tools and their privileges. - -### Independent review and evidence are useful optional gate capabilities - -`no-mistakes` demonstrates a higher-assurance Project-gate design: disposable worktrees, an explicit user intent treated as authoritative acceptance context, separate reviewer/fixer sessions, and an evidence-oriented test step that asks for end-user-visible proof and reports insufficient evidence. Its own configuration deliberately permits a targeted deterministic test command or agent-selected targeted tests; broad regression belongs to its remote CI stage. - -That is useful evidence for a project which chooses an independent verifier. It is not a reason for Clerk to require one. A project whose gate is simply `bats tests/clerk` needs only a small adapter which converts the command outcome into the generic Gate result. - -### A passing result must identify what was actually assessed - -GitHub's required-check behavior is commit-specific: an earlier commit's successful result does not satisfy a check for a newer head. A Project gate can legitimately advance the head while repairing or rebasing, however, so the generic rule cannot require it to assess the commit named at the start of a run. - -The portable invariant is instead that a result identifies its actual `assessed_commit`. For Clerk-owned submission, Clerk may proceed only when that commit is the head it will hand off from the supplied delivery worktree. A Project-gate-owned submission reports its own changed ref and lifecycle; Clerk does not impose a Git implementation on it. - -### Ephemeral runs do not require artifact persistence - -A synchronous tool invocation can produce a terminal pass/fail result and disappear. No universal artifact store, durable test transcript, or run database follows from the existence of Clerk. Artifact generation, retention, and evidence URLs are Project-gate policy. - -Only a Project gate which returns `pending` needs to keep enough of its own run state to answer a later `status` request. This is an implication of its chosen asynchronous behavior, not a base adoption cost. If it cannot answer, the adapter has an operational failure; Clerk does not store the gate's state for it. - -## Resulting minimum contract - -The minimum Project-gate adapter is a project-owned transform shim. - -| Situation | Adapter requirement | Clerk behavior | -| --- | --- | --- | -| Synchronous project check | Required `run` reads one Gate request and writes one terminal result JSON to stdout. | Records/relays the result and, with Clerk-owned submission, hands off only the assessed current worktree head. | -| A check reports failure | Exit `0` with `status: "failed"`. | Retains Claim/worktree for delivery to repair or rerun. | -| Adapter/configuration cannot execute, or output is malformed | Non-zero exit. | Reports an operational error, distinct from an honest failed verdict. | -| Asynchronous gate | `run` may return `pending` and must include `run.id`; it then implements `status`. | Retains Claim/worktree and reconciles that run through `status`. | - -Every result has `status`, `summary`, and `assessed_commit`. A `run.id` is required only for `pending`; terminal runs may supply one for their own purposes. The adapter controls details and logs: stdout is exactly one result JSON, while raw tool output can be captured, discarded, sent to stderr, or included as project-selected details. Clerk does not parse it. - -A project can layer a stricter verifier on this contract. For example, it may require an independently gathered verdict for every criterion; executable criteria may require committed focused tests, while UI/CLI behavior may require end-to-end evidence. Those are valuable Project-gate policies, but are not Clerk fields or baseline requirements. - -## Adoption consequence - -Project-gate configuration remains required and missing configuration fails submission closed: Clerk must not silently invent validation policy. The adoption floor is nevertheless only committed configuration plus a small adapter. Generic Adoption/bootstrap automation is intentionally separate work, filed as Clerk capture `dotfiles-1vfp`, because a generic tool cannot choose a project's test commands or evidence policy without violating this boundary. - -## Primary sources - -1. [Clerk ADR 0019, “Project-gate adapter contract: project policy outside Clerk”](../adr/0019-project-gate-adapter-contract.md). Records the Project-gate boundary resulting from this research; Umbel ADR 0016 separately owns Acceptance-criteria craft and the judgment loop. -2. [`kunchenguid/no-mistakes` gate model at commit `88dc204f933bbccee5fd144f2fa1e74cb52704c2`](https://github.com/kunchenguid/no-mistakes/blob/88dc204f933bbccee5fd144f2fa1e74cb52704c2/docs/src/content/docs/concepts/gate-model.md). Documents disposable worktrees, a fixed validation pipeline, asynchronous daemon state, and the distinction between pipeline mechanics and project configuration. -3. [`no-mistakes` repository configuration reference at the same commit](https://github.com/kunchenguid/no-mistakes/blob/88dc204f933bbccee5fd144f2fa1e74cb52704c2/docs/src/content/docs/reference/repo-config.md). Establishes default-branch loading for executable control fields and describes targeted test commands and optional evidence storage. -4. [`no-mistakes` agent guide at the same commit](https://github.com/kunchenguid/no-mistakes/blob/88dc204f933bbccee5fd144f2fa1e74cb52704c2/docs/src/content/docs/guides/agents.md). Documents separate reviewer/fixer sessions, explicit intent as acceptance context, evidence-oriented tests, and a non-degrading gate when its chosen agent is unavailable. -5. [`no-mistakes` test-step source at the same commit](https://github.com/kunchenguid/no-mistakes/blob/88dc204f933bbccee5fd144f2fa1e74cb52704c2/internal/pipeline/steps/test.go). Shows its project-selected evidence policy: focused tests, end-user evidence where possible, and an honest warning when proof is unavailable. -6. [GitHub Docs: Troubleshooting required status checks](https://docs.github.com/en/pull-requests/how-tos/merge-and-close-pull-requests/troubleshooting-required-status-checks). Establishes commit-specific required check behavior. -7. [GitHub Docs: Secure use of `pull_request_target`](https://docs.github.com/en/actions/reference/security/securely-using-pull_request_target). Warns against checking out and executing untrusted pull-request code in a privileged context. diff --git a/clerk/project-gate.json b/clerk/project-gate.json deleted file mode 100644 index b94197b..0000000 --- a/clerk/project-gate.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "adapter": "clerk/project-gate", - "submission_owner": "clerk" -} diff --git a/clerk/src/clerk/__init__.py b/clerk/src/clerk/__init__.py deleted file mode 100644 index 1d09dec..0000000 --- a/clerk/src/clerk/__init__.py +++ /dev/null @@ -1,5 +0,0 @@ -"""Stdlib-only Clerk implementation shell.""" - -__all__ = ["__version__"] - -__version__ = "0.1.0" diff --git a/clerk/src/clerk/__main__.py b/clerk/src/clerk/__main__.py deleted file mode 100644 index a36e335..0000000 --- a/clerk/src/clerk/__main__.py +++ /dev/null @@ -1,6 +0,0 @@ -"""Module entrypoint for the public Clerk launcher.""" - -from .cli import main - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/clerk/src/clerk/cli.py b/clerk/src/clerk/cli.py deleted file mode 100644 index 97300a7..0000000 --- a/clerk/src/clerk/cli.py +++ /dev/null @@ -1,192 +0,0 @@ -"""Clerk Python switchboard entrypoint.""" - -from __future__ import annotations - -import os -import sys -from collections.abc import Sequence -from pathlib import Path - -from . import __version__ -from .commands import ClerkExit, MUTATION_HANDLERS, QUERY_HANDLERS, run_mutation, run_query -from .doctor import repo_root, run_doctor -from .glean import run_glean -from .manifest import ManifestStatus, read_manifest -from .proc import CommandRunner -from .project_gate import cmd_backlog_gate, cmd_backlog_proof, cmd_backlog_submit -from .reconciliation import RECONCILIATION_VERBS, run_reconciliation -from .roster import EXPLAIN_TEXT, NOUN_VERBS, ROSTER_LINES, TOP_LEVEL_VERBS, roster_text, verb_label - -PYTHON_QUERY_VERBS: frozenset[tuple[str, ...]] = frozenset(QUERY_HANDLERS) -PYTHON_MUTATION_VERBS: frozenset[tuple[str, ...]] = frozenset(MUTATION_HANDLERS) -PYTHON_PROJECT_GATE_VERBS: frozenset[tuple[str, ...]] = frozenset( - {("backlog", "proof"), ("backlog", "submit"), ("backlog", "gate")} -) - -def _print_roster(*, stream) -> None: - stream.write(roster_text()) - - -def _usage(message: str) -> int: - print(message, file=sys.stderr) - return 2 - - -def _unknown(label: str) -> int: - print(f"clerk: unknown verb '{label}'", file=sys.stderr) - _print_roster(stream=sys.stderr) - return 2 - - -def _split_control_flags(argv: Sequence[str]) -> tuple[list[str], bool, bool]: - explain = False - help_ = False - args: list[str] = [] - for arg in argv: - if arg == "--explain": - explain = True - elif arg in {"--help", "-h"}: - help_ = True - else: - args.append(arg) - return args, explain, help_ - - -def _parse_verb(args: Sequence[str]) -> tuple[tuple[str, ...] | None, list[str], int | None]: - if not args: - return None, [], None - - first = args[0] - if first in TOP_LEVEL_VERBS: - return (first,), list(args[1:]), None - - if first in NOUN_VERBS: - if len(args) == 1: - print(f"clerk: '{first}' needs a verb", file=sys.stderr) - _print_roster(stream=sys.stderr) - return None, [], 2 - subverb = args[1] - if subverb not in NOUN_VERBS[first]: - return None, [], _unknown(" ".join(args)) - return (first, subverb), list(args[2:]), None - - return None, [], _unknown(first) - - -def _explain(path: tuple[str, ...]) -> int: - text = EXPLAIN_TEXT.get(verb_label(path)) - if text is None: - return _unknown(verb_label(path)) - print("\n".join(text)) - return 0 - - -def _manifest_context(path: tuple[str, ...]) -> tuple[Path, str] | int: - # The delivery gate is intentionally backend-marker-free so CI can run it in - # checkout states that precede Clerk cutover. - if path == ("backlog", "gate"): - root = repo_root() - if root is None: - print( - "clerk: not inside a git repository — cd into the target repo, then rerun 'clerk backlog gate'", - file=sys.stderr, - ) - return 4 - return root, "" - - root = repo_root() - if root is None: - print( - "clerk: not inside a git repository — cd into the target repo, then run 'clerk doctor'", - file=sys.stderr, - ) - return 4 - - manifest_path = root / ".clerk" - manifest = read_manifest(manifest_path) - if manifest.status is ManifestStatus.OK: - assert manifest.backend is not None - return root, manifest.backend - if manifest.status is ManifestStatus.MISSING: - print(f"clerk: missing .clerk marker at {manifest_path} — run 'clerk doctor' to provision it", file=sys.stderr) - return 4 - print(f"clerk: invalid .clerk marker at {manifest_path} — run 'clerk doctor' to diagnose it", file=sys.stderr) - return 4 - - -def main(argv: Sequence[str] | None = None) -> int: - """Dispatch public Clerk argv to its Python command handlers.""" - - original_args = list(sys.argv[1:] if argv is None else argv) - args, explain, help_ = _split_control_flags(original_args) - - if not args: - if explain: - return _usage("clerk: --explain needs a verb — e.g. 'clerk --explain backlog claim'") - if help_: - print(f"clerk {__version__} — workflow verb facade (ADR 0015)") - for line in ROSTER_LINES: - print(line) - return 0 - print("clerk: missing verb", file=sys.stderr) - _print_roster(stream=sys.stderr) - return 2 - - if args[0] in {"--version", "-V"}: - print(f"clerk {__version__}") - return 0 - - path, remaining, parse_exit = _parse_verb(args) - if parse_exit is not None: - return parse_exit - if path is None: - return _usage("clerk: missing verb") - - if explain or help_: - return _explain(path) - - if path == ("doctor",): - return run_doctor(remaining) - - if path in PYTHON_QUERY_VERBS: - context = _manifest_context(path) - if isinstance(context, int): - return context - root, backend = context - return run_query(path, backend, root, remaining) - - if path in PYTHON_MUTATION_VERBS: - context = _manifest_context(path) - if isinstance(context, int): - return context - root, backend = context - return run_mutation(path, backend, root, remaining) - - if path in PYTHON_PROJECT_GATE_VERBS: - context = _manifest_context(path) - if isinstance(context, int): - return context - root, backend = context - try: - if path == ("backlog", "proof"): - return cmd_backlog_proof(backend, root, remaining, CommandRunner()) - handler = cmd_backlog_submit if path == ("backlog", "submit") else cmd_backlog_gate - return handler(backend, root, remaining, CommandRunner(), os.environ) - except ClerkExit as exc: - return exc.code - - if path in RECONCILIATION_VERBS: - context = _manifest_context(path) - if isinstance(context, int): - return context - root, backend = context - return run_reconciliation(path, backend, root, remaining) - - if path == ("glean",): - context = _manifest_context(path) - if isinstance(context, int): - return context - root, backend = context - return run_glean(backend, root, remaining) - - return _unknown(verb_label(path)) diff --git a/clerk/src/clerk/commands.py b/clerk/src/clerk/commands.py deleted file mode 100644 index 516141b..0000000 --- a/clerk/src/clerk/commands.py +++ /dev/null @@ -1,1759 +0,0 @@ -"""Python-owned Clerk command implementations.""" - -from __future__ import annotations - -import hashlib -import json -import os -import re -import shutil -import sys -from collections.abc import Mapping, Sequence -from datetime import datetime, timezone -from pathlib import Path -from typing import Any - -from .output import Palette -from .proc import CommandResult, CommandRunner -from .work_graph import ( - BdWorkGraphAdapter, - Work, - WorkGraph, - WorkGraphBackendError, - has_acceptance_criteria, - has_blocker as _has_block_edge, - has_open_blockers, - has_open_children, - is_active_inbox as _is_active_inbox, - is_nonclosed_work as _is_nonclosed_work, - is_open_inbox as _is_open_inbox, - is_ready_promoted as _is_ready_promoted, - parent_id, - shares_parent, -) - -_PREGRILL_RE = re.compile(r"clerk-pregrill: ([0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z)") - -# C-e (acceptance-criteria detection, `inbox ready`): presence of a structural section only; -# never a quality judgment. A markdown heading (any '#' depth) or a bare -# "Acceptance Criteria[:]" line counts; prose that merely mentions the phrase does not. -_ACCEPTANCE_SECTION_RE = re.compile( - r"^#{1,6}\s*acceptance criteria|^acceptance criteria:?\s*$", - re.IGNORECASE | re.MULTILINE, -) - - -def has_acceptance_criteria_section(combined: str) -> bool: - """Whether the combined description+design prose carries an Acceptance Criteria section.""" - return _ACCEPTANCE_SECTION_RE.search(combined or "") is not None - - -class ClerkExit(Exception): - def __init__(self, code: int) -> None: - self.code = code - - -def usage(message: str) -> None: - print(message, file=sys.stderr) - raise ClerkExit(2) - - -def backend_fail(message: str) -> None: - print(f"clerk: {message}", file=sys.stderr) - print(" run 'clerk doctor' to check the backend", file=sys.stderr) - raise ClerkExit(5) - - -def _emit_stderr(result: CommandResult) -> None: - if result.stderr: - print(result.stderr, end="", file=sys.stderr) - - -def _json_from_result(result: CommandResult, message: str) -> Any: - _emit_stderr(result) - if result.returncode != 0: - backend_fail(message) - try: - return json.loads(result.stdout or "null") - except json.JSONDecodeError: - backend_fail(message) - - -def _bd_issue_json_or_usage(runner: CommandRunner, id_: str, verb: str, hint: str = "'clerk inbox list' shows open units") -> dict[str, Any]: - result = runner.run(["bd", "show", id_, "--readonly", "--json"]) - if result.returncode != 0 and not result.stdout.strip(): - usage(f"{verb}: {id_} not found — check the id ({hint})") - try: - data = json.loads(result.stdout or "null") - except json.JSONDecodeError: - backend_fail(f"{verb.removeprefix('clerk ')} failed — bd show did not return valid JSON for {id_}") - if not isinstance(data, list) or not data: - usage(f"{verb}: {id_} not found — check the id ({hint})") - obj = data[0] - if not isinstance(obj, dict): - backend_fail(f"{verb.removeprefix('clerk ')} failed — bd show did not return an issue object for {id_}") - return obj - - -def _bd_issue_json_or_backend(runner: CommandRunner, id_: str, message: str) -> dict[str, Any]: - result = runner.run(["bd", "show", id_, "--readonly", "--json"]) - _emit_stderr(result) - if result.returncode != 0: - backend_fail(message) - try: - data = json.loads(result.stdout or "null") - except json.JSONDecodeError: - backend_fail(message) - if not isinstance(data, list) or not data or not isinstance(data[0], dict): - backend_fail(message) - return data[0] - - -def _pregrill_epoch(value: str) -> int | None: - try: - dt = datetime.strptime(value, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc) - except (TypeError, ValueError): - return None - return int(dt.timestamp()) - - -def _pregrill_marker(notes: str, updated_at: str, env: Mapping[str, str]) -> str: - matches = _PREGRILL_RE.findall(notes or "") - if not matches: - return "absent" - note_epoch = _pregrill_epoch(matches[-1]) - updated_epoch = _pregrill_epoch(updated_at or "") - if note_epoch is None or updated_epoch is None: - return "stale" - try: - tolerance = int(env.get("CLERK_PREGRILL_STALE_TOLERANCE_S", "10")) - except ValueError: - tolerance = 10 - return "stale" if updated_epoch - note_epoch > tolerance else "present" - - -def _dump_json(value: Any, *, pretty: bool) -> str: - if pretty: - return json.dumps(value, ensure_ascii=False, indent=2) + "\n" - return json.dumps(value, ensure_ascii=False, separators=(",", ":")) + "\n" - - -def _success(message: str, env: Mapping[str, str]) -> None: - palette = Palette.from_env(env) - print(f"{palette.green}clerk:{palette.reset} {message}") - - -def _body_guard(updated_at: str, body: str) -> str: - # Match legacy command-substitution behavior: trailing newlines are stripped before - # hashing the guarded body, while embedded newlines remain significant. - guard_body = body.rstrip("\n") - return hashlib.sha256(updated_at.encode() + b"\0" + guard_body.encode()).hexdigest() - - -def _read_stdin_trimmed() -> str: - return sys.stdin.read().rstrip("\n") - - -def _read_file_trimmed(path: str, verb: str, *, body: bool = False) -> str: - file_path = Path(path) - if not file_path.is_file(): - if body: - usage(f"{verb}: body file not found: {path}") - usage(f"{verb}: file not found: {path}") - return file_path.read_text().rstrip("\n") - - -def _read_nonempty_text_arg(verb: str, argv: Sequence[str]) -> str: - input_source = "stdin" - file = "" - input_seen = False - args = list(argv) - i = 0 - while i < len(args): - arg = args[i] - if arg == "--file": - if i + 1 >= len(args): - usage(f"{verb}: --file needs a path") - if input_seen: - usage(f"{verb}: choose only one input source") - input_source = "file" - input_seen = True - file = args[i + 1] - i += 2 - elif arg == "--stdin": - if input_seen: - usage(f"{verb}: choose only one input source") - input_source = "stdin" - input_seen = True - i += 1 - else: - usage(f"{verb}: unknown argument '{arg}'") - text = _read_file_trimmed(file, verb) if input_source == "file" else _read_stdin_trimmed() - if not re.search(r"\S", text): - usage(f"{verb}: note text must be non-empty") - return text - - -def _status_labels(obj: Mapping[str, Any]) -> dict[str, Any]: - return {"status": obj.get("status"), "labels": obj.get("labels")} - - -def _bd_custom_types_csv(runner: CommandRunner) -> str: - result = runner.run(["bd", "config", "get", "types.custom"]) - current = result.stdout.strip() if result.returncode == 0 else "" - if "(not set)" in current: - return "" - return current - - -def _bd_ensure_impediment_type(runner: CommandRunner) -> None: - current = _bd_custom_types_csv(runner) - values = [value.strip() for value in current.split(",") if value.strip()] - if "impediment" in values: - return - next_value = "impediment" if not current else f"{current},impediment" - runner.run(["bd", "config", "set", "types.custom", next_value]) - - -def _clerk_type_valid(runner: CommandRunner, type_: str) -> bool: - if type_ in {"bug", "feature", "task", "epic", "chore", "decision"}: - return True - if type_ == "impediment": - return True - return type_ in [value.strip() for value in _bd_custom_types_csv(runner).split(",")] - - -def _build_pregrill_note(ts: str, decisions: Sequence[str], premises: Sequence[str], criteria: Sequence[str]) -> str: - lines = [f"clerk-pregrill: {ts}", "Open decisions:"] - lines.extend([f"- {decision}" for decision in decisions] or ["- (none)"]) - lines.append("Premises:") - if premises: - for premise in premises: - if "|" in premise: - text, verification = premise.split("|", 1) - else: - text, verification = premise, "not yet specified" - lines.append(f"- {text} (verify: {verification})") - else: - lines.append("- (none)") - lines.append("Draft acceptance criteria:") - lines.extend([f"- {criterion}" for criterion in criteria] or ["- (none)"]) - return "\n".join(lines) - - -def _utc_timestamp() -> str: - return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") - - -def _returned_short_from_id(id_: str) -> str: - token = id_[1:] if id_.startswith("#") else id_ - return token.split("-", 1)[1] if "-" in token else token - - -def _git(runner: CommandRunner, root: Path, args: Sequence[str]) -> CommandResult: - return runner.run(["git", "-C", str(root), *args]) - - -def _primary_repo_root(runner: CommandRunner, root: Path) -> Path: - result = _git(runner, root, ["rev-parse", "--path-format=absolute", "--git-common-dir"]) - if result.returncode != 0: - return root - common = result.stdout.strip() - if common.endswith("/.git"): - return Path(common).parent - return root - - -def _show_ref(runner: CommandRunner, root: Path, ref: str) -> bool: - return _git(runner, root, ["show-ref", "--verify", "--quiet", ref]).returncode == 0 - - -def _returned_attempt_refs(runner: CommandRunner, root: Path, id_: str) -> tuple[bool, bool]: - if not (root / ".git").exists(): - return False, False - main_root = _primary_repo_root(runner, root) - short = _returned_short_from_id(id_) - return ( - _show_ref(runner, main_root, f"refs/heads/returned/{short}"), - _show_ref(runner, main_root, f"refs/remotes/origin/returned/{short}"), - ) - - -def returned_attempt_banner(runner: CommandRunner, root: Path, short: str, id_: str, dispose_hint: str) -> None: - main_root = _primary_repo_root(runner, root) - local_present, remote_present = _returned_attempt_refs(runner, root, id_) - if not local_present and not remote_present: - return - if local_present and remote_present: - presence = "local+origin" - elif local_present: - presence = "local" - else: - presence = "origin" - ref = f"returned/{short}" if local_present else f"origin/returned/{short}" - behind_result = _git(runner, main_root, ["rev-list", "--count", f"{ref}..main"]) - behind = behind_result.stdout.strip() if behind_result.returncode == 0 and behind_result.stdout.strip() else "?" - subject_result = _git(runner, main_root, ["log", "-1", "--format=%s", ref]) - subject = subject_result.stdout.rstrip("\n") if subject_result.returncode == 0 and subject_result.stdout else "(unknown subject)" - print(f"\nclerk: returned attempt: returned/{short} ({presence}; {behind} commit(s) behind main)") - print(f" subject: {subject}") - if dispose_hint == "backlog claim": - print(f" reuse via: clerk backlog claim {id_} --from-returned") - print(f" fresh via: clerk backlog claim {id_} --fresh --returned keep|discard") - else: - print(f" dispose via: clerk {dispose_hint} {id_} --returned keep|discard") - - -def _planning_holder_refusal(verb: str, root: Path, obj: Mapping[str, Any], runner: CommandRunner, env: Mapping[str, str]) -> None: - # Allows unclaimed items or items claimed by the current actor; refuses (exit 5) - # anything held by a different actor. Matches legacy `planning_holder_refusal`. - holder = str(obj.get("assignee") or "") - if not holder: - return - me = _claim_current_actor(runner, root, env) - if holder == me: - return - print(f"clerk: {verb} refused — {obj.get('id')} is claimed by {holder}", file=sys.stderr) - raise ClerkExit(5) - - -def _returned_branch_exists(runner: CommandRunner, root: Path, short: str) -> bool: - if not (root / ".git").exists(): - return False - main_root = _primary_repo_root(runner, root) - if _show_ref(runner, main_root, f"refs/heads/returned/{short}"): - return True - return _show_ref(runner, main_root, f"refs/remotes/origin/returned/{short}") - - -def _delivery_branch_exists(runner: CommandRunner, root: Path, short: str) -> bool: - if not (root / ".git").exists(): - return False - main_root = _primary_repo_root(runner, root) - return _show_ref(runner, main_root, f"refs/heads/delivery/{short}") or _show_ref(runner, main_root, f"refs/remotes/origin/delivery/{short}") - - -def _for_each_ref(runner: CommandRunner, main_root: Path, patterns: Sequence[str]) -> list[str]: - result = _git(runner, main_root, ["for-each-ref", "--format=%(refname:short)", *patterns]) - if result.returncode != 0: - return [] - return [line.strip() for line in result.stdout.splitlines() if line.strip()] - - -def _dispose_returned(runner: CommandRunner, root: Path, short: str, env: Mapping[str, str]) -> bool: - # Delete the canonical `returned/<short>` ref plus any archived `returned/<short>-*` - # siblings from both the local and origin refs, mirroring legacy `dispose_returned`. - # Returns True when fully disposed; False when the remote delete was deferred to the - # next `clerk sync` because the repository was offline. - main_root = _primary_repo_root(runner, root) - local_refs = _for_each_ref(runner, main_root, [f"refs/heads/returned/{short}", f"refs/heads/returned/{short}-*"]) - remote_refs_present = _for_each_ref(runner, main_root, [f"refs/remotes/origin/returned/{short}", f"refs/remotes/origin/returned/{short}-*"]) - if not local_refs and not remote_refs_present: - return True - for ref in local_refs: - result = _git(runner, main_root, ["branch", "-D", ref]) - if result.returncode != 0: - backend_fail(f"returned disposition failed — could not delete local {ref}") - fetch_env = {**env, "GIT_TERMINAL_PROMPT": "0"} - fetch_result = runner.run(["git", "-C", str(main_root), "fetch", "origin"], env=fetch_env) - del fetch_env - if fetch_result.returncode != 0: - print( - f"clerk: OFFLINE - returned/{short} and archives deleted locally only; the remote branch delete is deferred to sync (clerk sync will finish it at the next reconnect).", - file=sys.stderr, - ) - return False - remote_refs = _for_each_ref(runner, main_root, [f"refs/remotes/origin/returned/{short}", f"refs/remotes/origin/returned/{short}-*"]) - for ref in remote_refs: - branch = ref.removeprefix("origin/") - result = _git(runner, main_root, ["push", "origin", "--delete", branch]) - if result.returncode != 0: - backend_fail(f"returned disposition failed — could not delete origin {branch}") - _git(runner, main_root, ["update-ref", "-d", f"refs/remotes/origin/{branch}"]) - return True - - -def _handle_returned_disposition(verb: str, root: Path, short: str, disposition: str, runner: CommandRunner, env: Mapping[str, str]) -> None: - if not disposition: - if _returned_branch_exists(runner, root, short): - usage(f"clerk {verb}: returned/{short} exists — choose --returned keep or --returned discard") - return - if disposition == "keep": - return - if disposition == "discard": - _dispose_returned(runner, root, short, env) - return - usage(f"clerk {verb}: --returned must be keep or discard") - - -def cmd_inbox_list(_backend: str, _root: Path, argv: Sequence[str], runner: CommandRunner, env: Mapping[str, str]) -> int: - limit = "" - args = list(argv) - i = 0 - while i < len(args): - arg = args[i] - if arg == "--limit": - if i + 1 >= len(args): - usage("clerk inbox list: --limit needs a value — usage: clerk inbox list [--limit <n>]") - value = args[i + 1] - if not value.isdigit(): - usage("clerk inbox list: --limit must be a non-negative integer") - limit = value - i += 2 - else: - usage(f"clerk inbox list: unknown argument '{arg}' — usage: clerk inbox list [--limit <n>]") - bd_args = ["bd", "list", "--status", "open", "--exclude-label", "stage:ready", "--readonly", "--json"] - if limit: - bd_args.extend(["--limit", limit]) - data = _json_from_result(runner.run(bd_args), "inbox list failed — bd list did not succeed") - if not isinstance(data, list): - backend_fail("inbox list failed — bd list did not return an issue list") - print(f"Inbox (open, not ready) — {len(data)} item(s):") - if not data: - print(" (empty)") - return 0 - for item in data: - if not isinstance(item, dict): - backend_fail("inbox list failed — bd list did not return issue objects") - marker = _pregrill_marker(str(item.get("notes") or ""), str(item.get("updated_at") or ""), env) - print(f" {item.get('id', '')} [pregrill:{marker}] {item.get('title', '')}") - return 0 - - -def cmd_inbox_show(_backend: str, root: Path, argv: Sequence[str], runner: CommandRunner, _env: Mapping[str, str]) -> int: - if not argv: - usage("clerk inbox show: missing id — usage: clerk inbox show <id> [--json|--pretty]") - id_ = argv[0] - json_mode = False - pretty = False - for arg in argv[1:]: - if arg == "--json": - json_mode = True - elif arg == "--pretty": - json_mode = True - pretty = True - else: - usage(f"clerk inbox show: unknown argument '{arg}' — usage: clerk inbox show <id> [--json|--pretty]") - if json_mode: - obj = _bd_issue_json_or_usage(runner, id_, "clerk inbox show") - updated = str(obj.get("updated_at") or "") - body = str(obj.get("description") or "") - # Legacy computes this through jq -r inside command substitution, so trailing - # newlines are stripped for the guard even though the rendered body stays intact. - guard_body = body.rstrip("\n") - guard = _body_guard(updated, guard_body) - rendered = { - "id": obj.get("id"), - "title": obj.get("title"), - "status": obj.get("status"), - "type": obj.get("issue_type"), - "assignee": obj.get("assignee") or "", - "labels": obj.get("labels") or [], - "parent": obj.get("parent") if obj.get("parent") is not None else None, - "body": body, - "body_guard": guard, - "notes": obj.get("notes") or "", - "design": obj.get("design") or "", - "acceptance": obj.get("acceptance_criteria") or "", - "created_at": obj.get("created_at"), - "updated_at": obj.get("updated_at"), - } - print(_dump_json(rendered, pretty=pretty), end="") - return 0 - _bd_issue_json_or_usage(runner, id_, "clerk inbox show") - result = runner.run(["bd", "show", id_, "--readonly"]) - _emit_stderr(result) - if result.returncode != 0: - backend_fail(f"inbox show failed — bd show did not succeed for {id_}") - print(result.stdout, end="") - returned_attempt_banner(runner, root, _returned_short_from_id(id_), id_, "inbox ready|drop") - return 0 - - -def cmd_inbox_dups(_backend: str, _root: Path, _argv: Sequence[str], runner: CommandRunner, _env: Mapping[str, str]) -> int: - data = _json_from_result(runner.run(["bd", "find-duplicates", "--readonly", "--json"]), "inbox dups failed — bd find-duplicates did not succeed") - if not isinstance(data, dict): - backend_fail("inbox dups failed — bd find-duplicates did not return an object") - count = data.get("count") or 0 - print(f"Duplicate candidates — {count} pair(s):") - if count == 0: - print(" (none)") - return 0 - for pair in data.get("pairs") or []: - print( - f" {pair.get('issue_a_id')} \"{pair.get('issue_a_title')}\" ~ " - f"{pair.get('issue_b_id')} \"{pair.get('issue_b_title')}\" (score: {pair.get('similarity')})" - ) - return 0 - - -def _claim_conflict(message: str) -> None: - print(message, file=sys.stderr) - raise ClerkExit(5) - - -def _graph_usage_text(kind: str) -> str: - target = "parent" if kind in {"children", "frontier"} else "id" - display = "<parent>" if target == "parent" else "<id>" - return f"clerk inbox {kind} {display} [--pretty]" - - -def _parse_graph_query_args(kind: str, argv: Sequence[str]) -> tuple[str, bool]: - if not argv: - if kind in {"children", "frontier"}: - usage(f"clerk inbox {kind}: missing parent id — usage: {_graph_usage_text(kind)}") - usage(f"clerk inbox {kind}: missing id — usage: {_graph_usage_text(kind)}") - id_ = argv[0] - pretty = False - for arg in argv[1:]: - if arg == "--pretty": - pretty = True - else: - usage(f"clerk inbox {kind}: unknown argument '{arg}' — usage: {_graph_usage_text(kind)}") - return id_, pretty - - -def _graph_item(item: Work) -> dict[str, Any]: - obj = item.raw - return { - "id": item.id, - "title": item.title, - "status": item.status, - "type": obj.get("issue_type"), - "assignee": item.assignee, - "labels": list(item.labels), - "parent": item.parent or None, - "created_at": obj.get("created_at"), - "updated_at": obj.get("updated_at"), - } - - -def _bd_graph(runner: CommandRunner, kind: str) -> WorkGraph: - try: - return BdWorkGraphAdapter(runner).load() - except WorkGraphBackendError as exc: - _emit_stderr(exc.result) - backend_fail(f"inbox {kind} failed — {exc}") - - -def _graph_work_or_usage(graph: WorkGraph, id_: str, kind: str) -> Work: - item = graph.get(id_) - if item is None: - usage(f"clerk inbox {kind}: {id_} not found — check the id ('clerk inbox list' shows open units)") - return item - - -def cmd_inbox_children(_backend: str, _root: Path, argv: Sequence[str], runner: CommandRunner, _env: Mapping[str, str]) -> int: - id_, pretty = _parse_graph_query_args("children", argv) - graph = _bd_graph(runner, "children") - parent = _graph_work_or_usage(graph, id_, "children") - rendered = {"parent": _graph_item(parent), "items": [_graph_item(item) for item in graph.children(parent)]} - print(_dump_json(rendered, pretty=pretty), end="") - return 0 - - -def cmd_inbox_blockers(_backend: str, _root: Path, argv: Sequence[str], runner: CommandRunner, _env: Mapping[str, str]) -> int: - id_, pretty = _parse_graph_query_args("blockers", argv) - graph = _bd_graph(runner, "blockers") - item = _graph_work_or_usage(graph, id_, "blockers") - rendered = {"item": _graph_item(item), "items": [_graph_item(blocker) for blocker in graph.blockers(item)]} - print(_dump_json(rendered, pretty=pretty), end="") - return 0 - - -def cmd_inbox_blocked(_backend: str, _root: Path, argv: Sequence[str], runner: CommandRunner, _env: Mapping[str, str]) -> int: - id_, pretty = _parse_graph_query_args("blocked", argv) - graph = _bd_graph(runner, "blocked") - item = _graph_work_or_usage(graph, id_, "blocked") - rendered = {"item": _graph_item(item), "items": [_graph_item(blocked) for blocked in graph.blocked_by(item)]} - print(_dump_json(rendered, pretty=pretty), end="") - return 0 - - -def cmd_inbox_frontier(_backend: str, _root: Path, argv: Sequence[str], runner: CommandRunner, _env: Mapping[str, str]) -> int: - id_, pretty = _parse_graph_query_args("frontier", argv) - graph = _bd_graph(runner, "frontier") - parent = _graph_work_or_usage(graph, id_, "frontier") - if parent.status == "closed": - usage(f"clerk inbox frontier: {id_} must be a non-closed Work graph parent") - rendered = {"parent": _graph_item(parent), "items": [_graph_item(item) for item in graph.frontier(parent)]} - print(_dump_json(rendered, pretty=pretty), end="") - return 0 - - -def cmd_backlog_next(backend: str, root: Path, _argv: Sequence[str], runner: CommandRunner, _env: Mapping[str, str]) -> int: - if backend == "bd": - try: - pickable = BdWorkGraphAdapter(runner).backlog().pickable - except WorkGraphBackendError as exc: - _emit_stderr(exc.result) - backend_fail(f"backlog next failed — {exc}") - print(f"Backlog (ready) — {len(pickable)} item(s):") - if not pickable: - print(" (empty)") - return 0 - for item in pickable: - marker = "returned" if any(_returned_attempt_refs(runner, root, item.id)) else "ready" - print(f" {item.id} {marker} {item.title}") - return 0 - data = _json_from_result(runner.run(["gh", "issue", "list", "--label", "ready-for-agent", "--json", "number,title"]), "backlog next failed — gh issue list did not succeed") - if not isinstance(data, list): - backend_fail("backlog next failed — gh issue list did not return an issue list") - print(f"Backlog (ready) — {len(data)} item(s):") - if not data: - print(" (empty)") - return 0 - for item in data: - if not isinstance(item, dict): - backend_fail("backlog next failed — gh issue list did not return issue objects") - print(f" #{item.get('number')} ready {item.get('title', '')}") - return 0 - - -def cmd_backlog_waiting(backend: str, _root: Path, _argv: Sequence[str], runner: CommandRunner, _env: Mapping[str, str]) -> int: - if backend == "bd": - try: - waiting = BdWorkGraphAdapter(runner).backlog().waiting - except WorkGraphBackendError as exc: - _emit_stderr(exc.result) - backend_fail(f"backlog waiting failed — {exc}") - print(f"Backlog waiting — {len(waiting)} item(s):") - if not waiting: - print(" (empty)") - return 0 - for item in waiting: - print(f" {item.work.id} blockers:{item.blocker_count} children:{item.child_count} {item.work.title}") - return 0 - print("Backlog waiting — 0 item(s):\n (empty)") - return 0 - - -def cmd_backlog_resolve(backend: str, root: Path, argv: Sequence[str], runner: CommandRunner, env: Mapping[str, str]) -> int: - if not argv: - usage("clerk backlog resolve: missing id — usage: clerk backlog resolve <id> [--returned keep|discard] [--file <path>|--stdin]") - id_ = argv[0] - returned_disposition = "" - input_args: list[str] = [] - args = list(argv[1:]) - i = 0 - while i < len(args): - arg = args[i] - if arg == "--returned": - if i + 1 >= len(args): - usage("clerk backlog resolve: --returned needs keep or discard") - returned_disposition = args[i + 1] - i += 2 - elif arg == "--file": - if i + 1 >= len(args): - usage("clerk backlog resolve: --file needs a path") - input_args.extend(args[i:i + 2]) - i += 2 - elif arg == "--stdin": - input_args.append(arg) - i += 1 - else: - usage(f"clerk backlog resolve: unknown argument '{arg}' — usage: clerk backlog resolve <id> [--returned keep|discard] [--file <path>|--stdin]") - if returned_disposition not in {"", "keep", "discard"}: - usage("clerk backlog resolve: --returned must be keep or discard") - if backend != "bd": - print("clerk: 'backlog resolve (gh)' is not yet implemented in this generation (see dotfiles-dft epic)", file=sys.stderr) - raise ClerkExit(3) - - adapter = BdWorkGraphAdapter(runner) - try: - graph = adapter.load() - except WorkGraphBackendError as exc: - _emit_stderr(exc.result) - backend_fail(f"backlog resolve failed — {exc}") - item = graph.resolve(id_) - if item is None: - usage(f"clerk backlog resolve: {id_} not found — check the id ('clerk backlog next' shows ready units)") - if not has_acceptance_criteria(item.raw): - usage(f"clerk backlog resolve: {item.id} has no 'Acceptance Criteria' section — it needs a grill pass before no-code resolution") - - reasons = list(graph.pickability_reasons(item)) - short = _returned_short_from_id(item.id) - if _delivery_branch_exists(runner, root, short): - reasons.append(f"claimed by delivery/{short}") - if reasons: - usage(f"clerk backlog resolve: {item.id} is not pickable — {', '.join(reasons)}") - _handle_returned_disposition("backlog resolve", root, short, returned_disposition, runner, env) - - text = _read_nonempty_text_arg("clerk backlog resolve", input_args) - note = f"clerk-backlog-resolution: {_utc_timestamp()}\n{text}" - result = adapter.append_notes(item.id, note) - _emit_stderr(result) - if result.returncode != 0: - backend_fail(f"backlog resolve failed — could not append resolution note for {item.id}") - result = adapter.close(item.id, "resolved without delivery") - _emit_stderr(result) - if result.returncode != 0: - backend_fail(f"backlog resolve failed — bd close did not succeed for {item.id}") - try: - after = adapter.inspect(item.id) - except WorkGraphBackendError as exc: - _emit_stderr(exc.result) - backend_fail(f"backlog resolve failed — {item.id} was not confirmed closed as resolved without delivery") - if str(after.get("status") or "") != "closed" or str(after.get("close_reason") or "") != "resolved without delivery": - backend_fail(f"backlog resolve failed — {item.id} was not confirmed closed as resolved without delivery") - if note not in str(after.get("notes") or ""): - backend_fail(f"backlog resolve failed — resolution note was not confirmed for {item.id}") - _success(f"resolved {item.id} without delivery", env) - return 0 - - -def cmd_backlog_show(backend: str, root: Path, argv: Sequence[str], runner: CommandRunner, _env: Mapping[str, str]) -> int: - if not argv: - usage("clerk backlog show: missing id — usage: clerk backlog show <id>") - id_ = argv[0] - if backend == "bd": - _bd_issue_json_or_usage(runner, id_, "clerk backlog show", "'clerk backlog next' shows open units") - result = runner.run(["bd", "show", id_, "--readonly"]) - _emit_stderr(result) - if result.returncode != 0: - backend_fail(f"backlog show failed — bd show did not succeed for {id_}") - print(result.stdout, end="") - else: - result = runner.run(["gh", "issue", "view", id_]) - _emit_stderr(result) - if result.returncode != 0: - if "not found" in result.stderr.lower(): - usage(f"clerk backlog show: {id_} not found — check the id ('clerk backlog next' shows open units)") - backend_fail(f"backlog show failed — gh issue view did not succeed for {id_}") - print(result.stdout, end="") - returned_attempt_banner(runner, root, _returned_short_from_id(id_), id_, "backlog claim") - return 0 - - -def cmd_capture(backend: str, _root: Path, argv: Sequence[str], runner: CommandRunner, env: Mapping[str, str]) -> int: - if not argv: - usage('clerk capture: missing title — usage: clerk capture "<title>" [--stdin|--type <type>|--impediment|--parent <id>|--blocked-by <id>]') - title = argv[0] - use_stdin = False - use_impediment = False - issue_type = "" - parent = "" - blockers: list[str] = [] - args = list(argv[1:]) - i = 0 - while i < len(args): - arg = args[i] - if arg == "--stdin": - use_stdin = True - i += 1 - elif arg == "--impediment": - use_impediment = True - i += 1 - elif arg == "--type": - if i + 1 >= len(args): - usage("clerk capture: --type needs a value") - issue_type = args[i + 1] - i += 2 - elif arg == "--parent": - if i + 1 >= len(args): - usage("clerk capture: --parent needs a Work graph id") - parent = args[i + 1] - i += 2 - elif arg == "--blocked-by": - if i + 1 >= len(args): - usage("clerk capture: --blocked-by needs a Work graph sibling id") - blockers.append(args[i + 1]) - i += 2 - else: - usage(f'clerk capture: unknown argument \'{arg}\' — usage: clerk capture "<title>" [--stdin|--type <type>|--impediment|--parent <id>|--blocked-by <id>]') - - if use_impediment and issue_type: - usage("clerk capture: --impediment is compatibility sugar for --type impediment; do not combine them") - if use_impediment: - issue_type = "impediment" - if issue_type and not _clerk_type_valid(runner, issue_type): - usage(f"clerk capture: invalid --type '{issue_type}' — use a canonical core type or configure types.custom") - if blockers and not parent: - usage("clerk capture: --blocked-by requires --parent so the new dependency edge is sibling-only") - - if backend not in {"bd", "gh"}: - backend_fail(f"capture failed — unsupported backend {backend}") - if issue_type == "impediment": - _bd_ensure_impediment_type(runner) - if parent: - parent_json = _bd_issue_json_or_usage(runner, parent, "clerk capture") - if not _is_nonclosed_work(parent_json): - usage(f"clerk capture: --parent {parent} must name a non-closed Work graph item") - for blocker in blockers: - blocker_json = _bd_issue_json_or_usage(runner, blocker, "clerk capture") - if not _is_nonclosed_work(blocker_json): - usage(f"clerk capture: --blocked-by {blocker} must name a non-closed Work graph item") - if parent and parent_id(blocker_json) != parent: - usage(f"clerk capture: --blocked-by {blocker} must be a sibling under {parent}") - - graph = BdWorkGraphAdapter(runner) - result = graph.create( - title, - use_stdin=use_stdin, - issue_type=issue_type, - parent=parent, - blockers=tuple(blockers), - ) - _emit_stderr(result) - if result.returncode != 0: - backend_fail(f'capture failed — bd create did not succeed for "{title}"') - id_ = result.stdout.strip() - seen = _bd_issue_json_or_backend(runner, id_, f"capture failed — {id_} was not confirmed after creation") - if seen.get("id") != id_: - backend_fail(f"capture failed — {id_} was not confirmed after creation") - if _is_ready_promoted(seen): - result = graph.remove_ready_label(id_) - _emit_stderr(result) - if result.returncode != 0: - backend_fail(f"capture failed — {id_} could not be restored to the Inbox") - seen = _bd_issue_json_or_backend(runner, id_, f"capture failed — {id_} was not confirmed after restoring it to the Inbox") - if seen.get("id") != id_ or _is_ready_promoted(seen): - backend_fail(f"capture failed — {id_} remained ready after creation") - suffix = " (type: impediment)" if issue_type == "impediment" else "" - _success(f"filed {id_}{suffix}", env) - return 0 - - -def _claim_current_actor(runner: CommandRunner, root: Path, env: Mapping[str, str]) -> str: - if env.get("BEADS_ACTOR"): - return str(env["BEADS_ACTOR"]) - result = _git(runner, root, ["config", "user.name"]) - name = result.stdout.strip() if result.returncode == 0 else "" - return name or str(env.get("USER") or "") - - -def cmd_inbox_parent(_backend: str, _root: Path, argv: Sequence[str], runner: CommandRunner, env: Mapping[str, str]) -> int: - if not argv: - usage("clerk inbox parent: usage: clerk inbox parent set <child> <parent> | clerk inbox parent clear <child>") - action = argv[0] - drop = False - if action == "set": - if len(argv) < 3: - usage("clerk inbox parent set: usage: clerk inbox parent set <child> <parent> [--drop-invalid-deps]") - child, parent = argv[1], argv[2] - rest = list(argv[3:]) - elif action == "clear": - if len(argv) < 2: - usage("clerk inbox parent clear: usage: clerk inbox parent clear <child> [--drop-invalid-deps]") - child, parent = argv[1], "" - rest = list(argv[2:]) - else: - usage("clerk inbox parent: usage: clerk inbox parent set <child> <parent> | clerk inbox parent clear <child>") - for arg in rest: - if arg == "--drop-invalid-deps": - drop = True - else: - usage(f"clerk inbox parent {action}: unknown argument '{arg}'") - - adapter = BdWorkGraphAdapter(runner) - child_json = _bd_issue_json_or_usage(runner, child, f"clerk inbox parent {action}") - if not _is_open_inbox(child_json): - usage(f"clerk inbox parent {action}: {child} must be an open inbox item") - if parent: - parent_json = _bd_issue_json_or_usage(runner, parent, "clerk inbox parent set") - if not _is_open_inbox(parent_json): - usage(f"clerk inbox parent set: {parent} must be an open inbox parent") - try: - cycle = adapter.parent_cycle_would_form(child, parent) - except WorkGraphBackendError as exc: - _emit_stderr(exc.result) - backend_fail(f"inbox parent set failed — {exc}") - if cycle: - usage(f"clerk inbox parent set: refusing parent cycle ({child} under {parent})") - - try: - invalid = adapter.invalid_blockers_for_parent_move(child, parent, child_json) - except WorkGraphBackendError as exc: - _emit_stderr(exc.result) - backend_fail(f"inbox parent {action} failed — {exc}") - if invalid and not drop: - usage(f"clerk inbox parent {action}: move would leave non-sibling dependency edges — rerun with --drop-invalid-deps to remove them") - for dependent, blocker in invalid: - result = adapter.remove_blocker(dependent, blocker) - _emit_stderr(result) - if result.returncode != 0: - backend_fail(f"inbox parent {action} failed — could not drop invalid dependency {dependent} -> {blocker}") - - result = adapter.set_parent(child, parent) - _emit_stderr(result) - if result.returncode != 0: - backend_fail(f"inbox parent {action} failed — bd update --parent did not succeed for {child}") - after_child = _bd_issue_json_or_backend(runner, child, f"inbox parent {action} failed — parent was not confirmed for {child}") - actual = parent_id(after_child) - if actual != parent: - backend_fail(f"inbox parent {action} failed — parent was not confirmed for {child}") - for dependent, blocker in invalid: - dependent_json = after_child if dependent == child else _bd_issue_json_or_backend( - runner, - dependent, - f"inbox parent {action} failed — dropped invalid dependency was not confirmed for {dependent} -> {blocker}", - ) - if _has_block_edge(dependent_json, blocker): - backend_fail(f"inbox parent {action} failed — dropped invalid dependency was not confirmed for {dependent} -> {blocker}") - _success(f"parent set {child} -> {parent}" if parent else f"parent cleared {child}", env) - return 0 - - -def cmd_inbox_dep(_backend: str, _root: Path, argv: Sequence[str], runner: CommandRunner, env: Mapping[str, str]) -> int: - if not argv: - usage("clerk inbox dep: usage: clerk inbox dep add <child> <blocker> | clerk inbox dep remove <child> <blocker>") - action = argv[0] - if action not in {"add", "remove"} or len(argv) < 3: - usage(f"clerk inbox dep {action}: usage: clerk inbox dep {action} <child> <blocker>" if action in {"add", "remove"} else "clerk inbox dep: usage: clerk inbox dep add <child> <blocker> | clerk inbox dep remove <child> <blocker>") - child, blocker = argv[1], argv[2] - if len(argv) > 3: - usage(f"clerk inbox dep {action}: unknown argument '{argv[3]}'") - if child == blocker: - usage(f"clerk inbox dep {action}: an item cannot block itself") - adapter = BdWorkGraphAdapter(runner) - child_json = _bd_issue_json_or_usage(runner, child, f"clerk inbox dep {action}") - blocker_json = _bd_issue_json_or_usage(runner, blocker, f"clerk inbox dep {action}") - if not _is_open_inbox(child_json): - usage(f"clerk inbox dep {action}: {child} must be an open inbox item") - if _is_ready_promoted(blocker_json): - usage(f"clerk inbox dep {action}: {blocker} must be an inbox item, not a ready/promoted item") - if not shares_parent(child_json, blocker_json): - usage(f"clerk inbox dep {action}: dependency edges are sibling-only; {child} and {blocker} must share the same immediate parent") - - if action == "add": - try: - cycle = adapter.dependency_path_exists(blocker, child) - except WorkGraphBackendError as exc: - _emit_stderr(exc.result) - backend_fail(f"inbox dep add failed — {exc}") - if cycle: - usage(f"clerk inbox dep add: refusing dependency cycle ({child} blocked by {blocker})") - result = adapter.add_blocker(child, blocker) - _emit_stderr(result) - if result.returncode != 0: - backend_fail(f"inbox dep add failed — bd dep add did not succeed for {child} <- {blocker}") - after = _bd_issue_json_or_backend(runner, child, f"inbox dep add failed — edge was not confirmed for {child} <- {blocker}") - if not _has_block_edge(after, blocker): - backend_fail(f"inbox dep add failed — edge was not confirmed for {child} <- {blocker}") - _success(f"dependency added {child} blocked-by {blocker}", env) - else: - result = adapter.remove_blocker(child, blocker) - _emit_stderr(result) - if result.returncode != 0: - backend_fail(f"inbox dep remove failed — bd dep remove did not succeed for {child} <- {blocker}") - after = _bd_issue_json_or_backend(runner, child, f"inbox dep remove failed — edge still exists for {child} <- {blocker}") - if _has_block_edge(after, blocker): - backend_fail(f"inbox dep remove failed — edge still exists for {child} <- {blocker}") - _success(f"dependency removed {child} blocked-by {blocker}", env) - return 0 - - -def cmd_inbox_claim(_backend: str, root: Path, argv: Sequence[str], runner: CommandRunner, env: Mapping[str, str]) -> int: - if not argv: - usage("clerk inbox claim: missing id — usage: clerk inbox claim <id>") - id_ = argv[0] - if len(argv) > 1: - usage(f"clerk inbox claim: unknown argument '{argv[1]}' — usage: clerk inbox claim <id>") - obj = _bd_issue_json_or_usage(runner, id_, "clerk inbox claim") - if not _is_active_inbox(obj): - usage(f"clerk inbox claim: {id_} must be an open inbox item (not ready/promoted/closed)") - holder = str(obj.get("assignee") or "") - if holder: - me = _claim_current_actor(runner, root, env) - if holder == me: - _success(f"{id_} already claimed by you", env) - return 0 - _claim_conflict(f"clerk: inbox claim refused — {id_} is already claimed by {holder}") - if not _is_open_inbox(obj): - usage(f"clerk inbox claim: {id_} must be an open inbox item (not already in progress)") - if has_open_blockers(obj): - usage(f"clerk inbox claim: {id_} has open blockers — claim an unblocked frontier item") - if has_open_children(obj): - usage(f"clerk inbox claim: {id_} has open children — claim a leaf item, not its parent") - me = _claim_current_actor(runner, root, env) - result = runner.run(["bd", "update", id_, "--claim"]) - _emit_stderr(result) - if result.returncode != 0: - latest = _bd_issue_json_or_usage(runner, id_, "clerk inbox claim") - holder = str(latest.get("assignee") or "") - if holder and holder != me: - _claim_conflict(f"clerk: inbox claim refused — {id_} is already claimed by {holder}") - backend_fail(f"inbox claim failed — bd update --claim did not succeed for {id_}") - check = str(_bd_issue_json_or_backend(runner, id_, f"inbox claim failed — {id_} was not confirmed claimed by {me}").get("assignee") or "") - if check != me: - backend_fail(f"inbox claim failed — {id_} was not confirmed claimed by {me}") - _success(f"claimed {id_}", env) - return 0 - - -def cmd_inbox_release(_backend: str, root: Path, argv: Sequence[str], runner: CommandRunner, env: Mapping[str, str]) -> int: - if not argv: - usage("clerk inbox release: missing id — usage: clerk inbox release <id>") - id_ = argv[0] - if len(argv) > 1: - usage(f"clerk inbox release: unknown argument '{argv[1]}' — usage: clerk inbox release <id>") - obj = _bd_issue_json_or_usage(runner, id_, "clerk inbox release") - me = _claim_current_actor(runner, root, env) - holder = str(obj.get("assignee") or "") - if not holder: - _success(f"{id_} is not claimed — nothing to release", env) - return 0 - if holder != me: - _claim_conflict(f"clerk: inbox release refused — {id_} is claimed by {holder}") - result = runner.run(["bd", "update", id_, "--status", "open", "--assignee", ""]) - _emit_stderr(result) - if result.returncode != 0: - backend_fail(f"inbox release failed — bd update --status open --assignee did not succeed for {id_}") - check = str(_bd_issue_json_or_backend(runner, id_, f"inbox release failed — {id_} was not confirmed unclaimed").get("assignee") or "") - if check: - backend_fail(f"inbox release failed — {id_} was not confirmed unclaimed") - _success(f"released {id_}", env) - return 0 - - -def cmd_inbox_resolve(_backend: str, root: Path, argv: Sequence[str], runner: CommandRunner, env: Mapping[str, str]) -> int: - if not argv: - usage("clerk inbox resolve: missing id — usage: clerk inbox resolve <id> [--file <path>|--stdin]") - id_ = argv[0] - obj = _bd_issue_json_or_usage(runner, id_, "clerk inbox resolve") - if not _is_active_inbox(obj): - usage(f"clerk inbox resolve: {id_} must be an open inbox item (not ready/promoted/closed)") - holder = str(obj.get("assignee") or "") - if holder: - me = _claim_current_actor(runner, root, env) - if holder != me: - _claim_conflict(f"clerk: inbox resolve refused — {id_} is claimed by {holder}") - if has_open_blockers(obj): - usage(f"clerk inbox resolve: {id_} has open blockers — resolve blockers first") - if has_open_children(obj): - usage(f"clerk inbox resolve: {id_} has open children — resolve or reparent children first") - text = _read_nonempty_text_arg("clerk inbox resolve", argv[1:]) - ts = _utc_timestamp() - note = f"clerk-resolution: {ts}\n{text}" - result = runner.run(["bd", "update", id_, "--append-notes", note]) - _emit_stderr(result) - if result.returncode != 0: - backend_fail(f"inbox resolve failed — could not append resolution note for {id_}") - result = runner.run(["bd", "close", id_, "--reason", "resolved"]) - _emit_stderr(result) - if result.returncode != 0: - backend_fail(f"inbox resolve failed — bd close did not succeed for {id_}") - after = _bd_issue_json_or_backend(runner, id_, f"inbox resolve failed — {id_} was not confirmed closed") - status = str(after.get("status") or "") - if status != "closed": - backend_fail(f"inbox resolve failed — {id_} was not confirmed closed") - if note not in str(after.get("notes") or ""): - backend_fail(f"inbox resolve failed — resolution note was not confirmed for {id_}") - _success(f"resolved {id_}", env) - return 0 - - -def cmd_inbox_pregrill(_backend: str, _root: Path, argv: Sequence[str], runner: CommandRunner, env: Mapping[str, str]) -> int: - if not argv: - usage('clerk inbox pregrill: missing id — usage: clerk inbox pregrill <id> [--decision "<text>"]... [--premise "<text>|<verification>"]... [--criterion "<text>"]...') - id_ = argv[0] - decisions: list[str] = [] - premises: list[str] = [] - criteria: list[str] = [] - args = list(argv[1:]) - i = 0 - while i < len(args): - arg = args[i] - if arg == "--decision": - if i + 1 >= len(args): - usage("clerk inbox pregrill: --decision needs a value") - decisions.append(args[i + 1]) - i += 2 - elif arg == "--premise": - if i + 1 >= len(args): - usage("clerk inbox pregrill: --premise needs a value") - premises.append(args[i + 1]) - i += 2 - elif arg == "--criterion": - if i + 1 >= len(args): - usage("clerk inbox pregrill: --criterion needs a value") - criteria.append(args[i + 1]) - i += 2 - else: - usage(f"clerk inbox pregrill: unknown argument '{arg}'") - before = _bd_issue_json_or_usage(runner, id_, "clerk inbox pregrill") - status_labels_before = _status_labels(before) - ts = _utc_timestamp() - note = _build_pregrill_note(ts, decisions, premises, criteria) - result = runner.run(["bd", "update", id_, "--append-notes", note]) - _emit_stderr(result) - if result.returncode != 0: - backend_fail(f"inbox pregrill failed — bd update --append-notes did not succeed for {id_}") - after = _bd_issue_json_or_backend(runner, id_, f"inbox pregrill failed — {id_} status/labels changed (not state-neutral)") - if status_labels_before != _status_labels(after): - backend_fail(f"inbox pregrill failed — {id_} status/labels changed (not state-neutral)") - _success(f"pregrilled {id_} (dated {ts})", env) - return 0 - - -def cmd_inbox_note(_backend: str, _root: Path, argv: Sequence[str], runner: CommandRunner, env: Mapping[str, str]) -> int: - if not argv: - usage("clerk inbox note: missing id — usage: clerk inbox note <id> [--file <path>|--stdin]") - id_ = argv[0] - _bd_issue_json_or_usage(runner, id_, "clerk inbox note") - text = _read_nonempty_text_arg("clerk inbox note", argv[1:]) - before = _bd_issue_json_or_usage(runner, id_, "clerk inbox note") - status_labels_before = _status_labels(before) - result = runner.run(["bd", "update", id_, "--append-notes", text]) - _emit_stderr(result) - if result.returncode != 0: - backend_fail(f"inbox note failed — bd update --append-notes did not succeed for {id_}") - after = _bd_issue_json_or_backend(runner, id_, f"inbox note failed — {id_} state changed while appending note") - if status_labels_before != _status_labels(after): - backend_fail(f"inbox note failed — {id_} state changed while appending note") - _success(f"noted {id_}", env) - return 0 - - -def cmd_inbox_update(_backend: str, _root: Path, argv: Sequence[str], runner: CommandRunner, env: Mapping[str, str]) -> int: - if not argv: - usage("clerk inbox update: missing id — usage: clerk inbox update <id> [--title <title>] [--type <type>] [--body-file <path>|--stdin --body-guard <guard>]") - id_ = argv[0] - title = "" - type_ = "" - body_file = "" - guard = "" - have_body = False - use_stdin = False - args = list(argv[1:]) - i = 0 - while i < len(args): - arg = args[i] - if arg == "--title": - if i + 1 >= len(args): - usage("clerk inbox update: --title needs a value") - title = args[i + 1] - i += 2 - elif arg == "--type": - if i + 1 >= len(args): - usage("clerk inbox update: --type needs a value") - type_ = args[i + 1] - i += 2 - elif arg == "--body-file": - if i + 1 >= len(args): - usage("clerk inbox update: --body-file needs a path") - if have_body: - usage("clerk inbox update: choose only one of --stdin or --body-file") - body_file = args[i + 1] - have_body = True - i += 2 - elif arg == "--stdin": - if have_body: - usage("clerk inbox update: choose only one of --stdin or --body-file") - use_stdin = True - have_body = True - i += 1 - elif arg == "--body-guard": - if i + 1 >= len(args): - usage("clerk inbox update: --body-guard needs a value from clerk inbox show --json") - guard = args[i + 1] - i += 2 - else: - usage(f"clerk inbox update: unknown argument '{arg}'") - if not title and not type_ and not have_body: - usage("clerk inbox update: nothing to update") - if type_ and not _clerk_type_valid(runner, type_): - usage(f"clerk inbox update: invalid --type '{type_}' — use a canonical core type or configure types.custom") - if type_ == "impediment": - _bd_ensure_impediment_type(runner) - - obj = _bd_issue_json_or_usage(runner, id_, "clerk inbox update") - update_args = ["bd", "update", id_] - if title: - update_args.extend(["--title", title]) - if type_: - update_args.extend(["--type", type_]) - body = "" - if have_body: - if not guard: - usage("clerk inbox update: replacing the body requires --body-guard from clerk inbox show --json") - current_guard = _body_guard(str(obj.get("updated_at") or ""), str(obj.get("description") or "")) - if guard != current_guard: - usage("clerk inbox update: stale body guard — rerun clerk inbox show --json and retry") - body = _read_stdin_trimmed() if use_stdin else _read_file_trimmed(body_file, "clerk inbox update", body=True) - update_args.extend(["--description", body, "--allow-empty-description"]) - result = runner.run(update_args) - _emit_stderr(result) - if result.returncode != 0: - backend_fail(f"inbox update failed — bd update did not succeed for {id_}") - after = _bd_issue_json_or_backend(runner, id_, f"inbox update failed — {id_} was not confirmed updated") - if title and after.get("title") != title: - backend_fail(f"inbox update failed — {id_} was not confirmed updated") - if type_ and after.get("issue_type") != type_: - backend_fail(f"inbox update failed — {id_} was not confirmed updated") - if have_body and str(after.get("description") or "").rstrip("\n") != body: - backend_fail(f"inbox update failed — {id_} was not confirmed updated") - _success(f"updated {id_}", env) - return 0 - - -def cmd_inbox_ready(backend: str, root: Path, argv: Sequence[str], runner: CommandRunner, env: Mapping[str, str]) -> int: - # The Inbox ready/drop bridge promotes a groomed capture from Refinement to delivery - # while preserving Acceptance-criteria and returned-attempt safety (ADR 0015/0016). - if not argv: - usage("clerk inbox ready: missing id — usage: clerk inbox ready <id> [--design-file <path>] [--acceptance-file <path>]") - id_ = argv[0] - title = "" - body_file = "" - design_file = "" - acceptance_file = "" - returned_disposition = "" - args = list(argv[1:]) - i = 0 - while i < len(args): - arg = args[i] - if arg == "--title": - if i + 1 >= len(args): - usage("clerk inbox ready: --title needs a value") - title = args[i + 1] - i += 2 - elif arg == "--body-file": - if i + 1 >= len(args): - usage("clerk inbox ready: --body-file needs a value") - body_file = args[i + 1] - i += 2 - elif arg == "--design-file": - if i + 1 >= len(args): - usage("clerk inbox ready: --design-file needs a path") - design_file = args[i + 1] - i += 2 - elif arg == "--acceptance-file": - if i + 1 >= len(args): - usage("clerk inbox ready: --acceptance-file needs a path") - acceptance_file = args[i + 1] - i += 2 - elif arg == "--returned": - if i + 1 >= len(args): - usage("clerk inbox ready: --returned needs keep or discard") - returned_disposition = args[i + 1] - i += 2 - else: - usage(f"clerk inbox ready: unknown argument '{arg}'") - - short = _returned_short_from_id(id_) - - if backend == "bd": - if title: - usage("clerk inbox ready: --title is only for gh-backed promotion; use --design-file/--acceptance-file for bd") - if body_file: - usage("clerk inbox ready: --body-file is only for gh-backed promotion; use --design-file/--acceptance-file for bd") - if design_file and not Path(design_file).is_file(): - usage(f"clerk inbox ready: design file not found: {design_file}") - if acceptance_file and not Path(acceptance_file).is_file(): - usage(f"clerk inbox ready: acceptance file not found: {acceptance_file}") - - obj = _bd_issue_json_or_usage(runner, id_, "clerk inbox ready") - if not _is_active_inbox(obj): - usage(f"clerk inbox ready: {id_} must be an open inbox item (not ready/promoted/closed)") - _planning_holder_refusal("inbox ready", root, obj, runner, env) - _handle_returned_disposition("inbox ready", root, short, returned_disposition, runner, env) - - if design_file or acceptance_file: - update_args = ["bd", "update", id_] - if design_file: - update_args.extend(["--design-file", design_file]) - if acceptance_file: - update_args.extend(["--acceptance", _read_file_trimmed(acceptance_file, "clerk inbox ready", body=True)]) - result = runner.run(update_args) - _emit_stderr(result) - if result.returncode != 0: - backend_fail(f"inbox ready failed — bd update did not succeed for {id_}") - refreshed = _bd_issue_json_or_backend(runner, id_, f"inbox ready failed — {id_} was not confirmed updated") - if design_file and str(refreshed.get("design") or "").rstrip("\n") != _read_file_trimmed(design_file, "clerk inbox ready"): - backend_fail(f"inbox ready failed — design was not confirmed after writing {design_file}") - if acceptance_file and str(refreshed.get("acceptance_criteria") or "").rstrip("\n") != _read_file_trimmed(acceptance_file, "clerk inbox ready"): - backend_fail(f"inbox ready failed — acceptance criteria were not confirmed after writing {acceptance_file}") - obj = refreshed - - # C-e: bd's first-class `acceptance_criteria` field IS the structural section by - # construction, so its mere non-empty presence satisfies the gate without rescanning; - # otherwise description+design prose is scanned for a heading or bare line. - desc = str(obj.get("description") or "") - design = str(obj.get("design") or "") - ac = str(obj.get("acceptance_criteria") or "") - if not ac.strip() and not has_acceptance_criteria_section(f"{desc}\n{design}"): - usage(f"clerk inbox ready: {id_} has no 'Acceptance Criteria' section — rerun with --acceptance-file <path> (and optionally --design-file <path>) before promoting it") - - result = runner.run(["bd", "update", id_, "--status", "open", "--assignee", "", "--add-label", "stage:ready"]) - _emit_stderr(result) - if result.returncode != 0: - backend_fail(f"inbox ready failed — bd update did not succeed for {id_}") - after = _bd_issue_json_or_backend(runner, id_, f"inbox ready failed — {id_} was not confirmed stage:ready after promotion") - if "stage:ready" not in (after.get("labels") or []): - backend_fail(f"inbox ready failed — {id_} was not confirmed stage:ready after promotion") - _success(f"promoted {id_} to stage:ready", env) - return 0 - - # gh-backed promotion: create a ready GitHub issue, then close the bd capture as promoted. - if design_file: - usage("clerk inbox ready: --design-file is only for bd-backed promotion; use --title/--body-file for gh") - if acceptance_file: - usage("clerk inbox ready: --acceptance-file is only for bd-backed promotion; use --title/--body-file for gh") - if not title or not body_file: - usage('clerk inbox ready: gh backend needs both --title "<title>" and --body-file <file> — rerun as \'clerk inbox ready <id> --title "<title>" --body-file <file>\'') - if not Path(body_file).is_file(): - usage(f"clerk inbox ready: body file not found: {body_file}") - - obj = _bd_issue_json_or_usage(runner, id_, "clerk inbox ready") - if not _is_active_inbox(obj): - usage(f"clerk inbox ready: {id_} must be an open inbox item (not ready/promoted/closed)") - _planning_holder_refusal("inbox ready", root, obj, runner, env) - _handle_returned_disposition("inbox ready", root, short, returned_disposition, runner, env) - - create_result = runner.run(["gh", "issue", "create", "--title", title, "--body-file", body_file, "--label", "ready-for-agent"]) - _emit_stderr(create_result) - if create_result.returncode != 0: - backend_fail("inbox ready failed — gh issue create did not succeed") - url = create_result.stdout.strip() - num = url.rsplit("/", 1)[-1] - close_result = runner.run(["bd", "close", id_, "--reason", f"promoted to GitHub #{num}"]) - _emit_stderr(close_result) - if close_result.returncode != 0: - backend_fail(f"inbox ready failed — bd close did not succeed for {id_}") - after = _bd_issue_json_or_backend(runner, id_, f"inbox ready failed — {id_} was not confirmed closed after promotion") - if str(after.get("status") or "") != "closed" or str(after.get("close_reason") or "") != f"promoted to GitHub #{num}": - backend_fail(f"inbox ready failed — {id_} was not confirmed closed after promotion") - _success(f"promoted {id_} to #{num} ({url})", env) - return 0 - - -def cmd_inbox_drop(backend: str, root: Path, argv: Sequence[str], runner: CommandRunner, env: Mapping[str, str]) -> int: - # Drop closes an Inbox capture as wontfix for both bd and gh backends. For gh the bd - # capture is still the raw Inbox store; no GitHub issue exists yet, so gh adds no action. - if not argv: - usage("clerk inbox drop: missing id — usage: clerk inbox drop <id> [--returned keep|discard]") - id_ = argv[0] - returned_disposition = "" - args = list(argv[1:]) - i = 0 - while i < len(args): - arg = args[i] - if arg == "--returned": - if i + 1 >= len(args): - usage("clerk inbox drop: --returned needs keep or discard") - returned_disposition = args[i + 1] - i += 2 - else: - usage(f"clerk inbox drop: unknown argument '{arg}'") - - if backend not in {"bd", "gh"}: - backend_fail(f"drop failed — unsupported backend {backend}") - - short = _returned_short_from_id(id_) - obj = _bd_issue_json_or_usage(runner, id_, "clerk inbox drop") - _planning_holder_refusal("inbox drop", root, obj, runner, env) - _handle_returned_disposition("inbox drop", root, short, returned_disposition, runner, env) - - result = runner.run(["bd", "close", id_, "--reason", "wontfix"]) - _emit_stderr(result) - if result.returncode != 0: - backend_fail(f"inbox drop failed — bd close did not succeed for {id_}") - after = _bd_issue_json_or_backend(runner, id_, f"inbox drop failed — {id_} was not confirmed closed") - if str(after.get("status") or "") != "closed": - backend_fail(f"inbox drop failed — {id_} was not confirmed closed") - _success(f"dropped {id_} (wontfix)", env) - return 0 - - -def _in_job_context(env: Mapping[str, str]) -> bool: - if env.get("CLERK_JOB"): - return True - return env.get("CI", "").lower() not in {"", "0", "false", "no"} - - -def _fetch_origin(runner: CommandRunner, root: Path, env: Mapping[str, str]) -> bool: - return runner.run(["git", "-C", str(root), "fetch", "origin"], env={**env, "GIT_TERMINAL_PROMPT": "0"}, timeout=10).returncode == 0 - - -def _ensure_delivery_worktree(runner: CommandRunner, root: Path, short: str) -> Path | None: - worktree = root / ".worktrees" / short - if worktree.is_dir(): - return worktree - _git(runner, root, ["worktree", "prune"]) - if _git(runner, root, ["worktree", "add", str(worktree), f"delivery/{short}"]).returncode == 0: - return worktree - if _show_ref(runner, root, f"refs/remotes/origin/delivery/{short}") and _git( - runner, root, ["worktree", "add", "-b", f"delivery/{short}", str(worktree), f"origin/delivery/{short}"] - ).returncode == 0: - return worktree - return None - - -def _provision_worktree_beads(adapter: BdWorkGraphAdapter, root: Path, worktree: Path, id_: str) -> bool: - metadata = worktree / ".beads" / "metadata.json" - if (worktree / ".beads" / "config.yaml").is_file() and not metadata.is_file(): - source = root / ".beads" / "metadata.json" - try: - shutil.copyfile(source, metadata) - except OSError: - return False - try: - return adapter.inspect_at(id_, str(worktree)).get("id") == id_ - except WorkGraphBackendError: - return False - - -def _replay_returned(runner: CommandRunner, root: Path, worktree: Path, short: str, base: str) -> None: - ref = f"returned/{short}" if _show_ref(runner, root, f"refs/heads/returned/{short}") else f"origin/returned/{short}" - commits = _git(runner, root, ["rev-list", "--reverse", f"{base}..{ref}"]) - if commits.returncode == 0 and not commits.stdout.strip(): - return - if _git(runner, worktree, ["cherry-pick", f"{base}..{ref}"]).returncode == 0: - return - conflicts = _git(runner, worktree, ["diff", "--name-only", "--diff-filter=U"]).stdout.strip().replace("\n", " ") or "unknown" - print(f"clerk: claim --from-returned hit conflicts while replaying returned/{short} onto delivery/{short}", file=sys.stderr) - print(f" resolve in {worktree}, run git cherry-pick --continue, then clerk backlog submit; conflicted paths: {conflicts}", file=sys.stderr) - raise ClerkExit(2) - - -def _gh_backlog_item_or_usage(runner: CommandRunner, id_: str, verb: str) -> dict[str, Any]: - result = runner.run(["gh", "issue", "view", id_, "--json", "number,title,body,assignees,state"]) - if result.returncode != 0: - if "not found" in result.stderr.lower(): - usage(f"{verb}: {id_} not found — check the id ('clerk backlog next' shows ready units)") - backend_fail(f"{verb.removeprefix('clerk ')} failed — gh issue view did not succeed for {id_}") - try: - value = json.loads(result.stdout) - except json.JSONDecodeError: - backend_fail(f"{verb.removeprefix('clerk ')} failed — gh issue view did not return valid JSON for {id_}") - if not isinstance(value, dict) or not value.get("number"): - backend_fail(f"{verb.removeprefix('clerk ')} failed — gh issue view did not return an issue object for {id_}") - assignees = value.get("assignees") or [] - holder = assignees[0].get("login", "") if assignees and isinstance(assignees[0], dict) else "" - return {"id": str(value["number"]), "title": value.get("title", ""), "description": value.get("body", ""), "status": value.get("state", ""), "assignee": holder} - - -def _delivery_actor(backend: str, runner: CommandRunner, root: Path, env: Mapping[str, str]) -> str: - if backend == "bd": - return _claim_current_actor(runner, root, env) - result = runner.run(["gh", "api", "user", "--jq", ".login"]) - return result.stdout.strip() if result.returncode == 0 else "" - - -def _parse_claim_args(argv: Sequence[str]) -> tuple[str, bool, bool, str]: - if not argv: - usage("clerk backlog claim: missing id — usage: clerk backlog claim <id>") - id_ = argv[0] - replay = fresh = False - disposition = "" - args = list(argv[1:]) - i = 0 - while i < len(args): - if args[i] == "--from-returned": - replay = True - elif args[i] == "--fresh": - fresh = True - elif args[i] == "--returned": - if i + 1 == len(args): - usage("clerk backlog claim: --returned needs keep or discard") - disposition = args[i + 1] - i += 1 - else: - usage(f"clerk backlog claim: unknown argument '{args[i]}' — usage: clerk backlog claim <id> [--from-returned|--fresh --returned keep|discard]") - i += 1 - if replay and fresh: - usage("clerk backlog claim: choose only one of --from-returned or --fresh") - if replay and disposition: - usage("clerk backlog claim: --returned is only valid with --fresh") - if not fresh and disposition: - usage("clerk backlog claim: --returned is only valid with --fresh") - if disposition not in {"", "keep", "discard"}: - usage("clerk backlog claim: --returned must be keep or discard") - return id_, replay, fresh, disposition - - -def cmd_backlog_claim(backend: str, root: Path, argv: Sequence[str], runner: CommandRunner, env: Mapping[str, str]) -> int: - id_arg, replay, fresh, disposition = _parse_claim_args(argv) - if backend == "bd": - item = _bd_issue_json_or_usage(runner, id_arg, "clerk backlog claim", "'clerk backlog next' shows ready units") - elif backend == "gh": - item = _gh_backlog_item_or_usage(runner, id_arg, "clerk backlog claim") - else: - backend_fail(f"backlog claim failed — unsupported backend {backend}") - id_ = str(item.get("id") or id_arg) - short = _returned_short_from_id(id_) - if not has_acceptance_criteria(item): - usage(f"clerk backlog claim: {id_} has no 'Acceptance Criteria' section — it needs a grill pass first (e.g. 'clerk inbox pregrill {id_}', then add the section) before it can be claimed") - adapter = BdWorkGraphAdapter(runner) if backend == "bd" else None - actor = _delivery_actor(backend, runner, root, env) - holder = str(item.get("assignee") or "") - mine = holder == actor and bool(actor) or _show_ref(runner, root, f"refs/heads/delivery/{short}") - if mine: - worktree = _ensure_delivery_worktree(runner, root, short) - if worktree is None: - backend_fail(f"claim failed — could not provision the worktree at {root}/.worktrees/{short} for delivery/{short}") - if adapter is not None and not _provision_worktree_beads(adapter, root, worktree, id_): - backend_fail(f"claim failed — could not provision or verify the worktree at {worktree}") - _success(f"{id_} already claimed by you — worktree ready", env) - print(worktree) - return 0 - if holder: - _claim_conflict(f"clerk: backlog claim refused — delivery/{short} is already claimed by {holder}\n wait for {holder} to release or finish it, or pick a different unit ('clerk backlog next')") - if adapter is not None: - try: - graph = adapter.load() - except WorkGraphBackendError as exc: - _emit_stderr(exc.result) - backend_fail("backlog claim failed — could not load the Work graph") - # A complete Work graph is required for blocker/child pickability. - work = graph.resolve(id_) - if work is None: - usage(f"clerk backlog claim: {id_} not found — check the id ('clerk backlog next' shows ready units)") - reasons = graph.pickability_reasons(work) - if reasons: - usage(f"clerk backlog claim: {id_} is not pickable — {', '.join(reasons)}") - offline = not _fetch_origin(runner, root, env) - has_returned = _returned_branch_exists(runner, root, short) - if replay and not has_returned: - usage(f"clerk backlog claim: --from-returned requested but returned/{short} was not found") - if has_returned and not replay and (not fresh or not disposition): - print(f"clerk backlog claim: returned/{short} exists — choose how to claim", file=sys.stderr) - print(f" reuse returned work: clerk backlog claim {id_} --from-returned", file=sys.stderr) - print(f" start fresh: clerk backlog claim {id_} --fresh --returned keep|discard", file=sys.stderr) - raise ClerkExit(2) - if offline: - if _in_job_context(env): - usage(f"clerk: OFFLINE in a job context - refusing {short}: the claim lock needs the remote and no attendant can accept the staleness hazard. Retry when origin is reachable.") - base = "main" - if not _show_ref(runner, root, "refs/heads/main"): - backend_fail(f"claim failed — no local 'main' branch to base delivery/{short} on") - if _git(runner, root, ["branch", f"delivery/{short}", base]).returncode != 0: - backend_fail(f"claim failed — could not create local branch delivery/{short} from main") - else: - if _show_ref(runner, root, f"refs/remotes/origin/delivery/{short}"): - _claim_conflict(f"clerk: backlog claim refused — delivery/{short} is already claimed by {holder or 'someone else'}\n wait for {holder or 'someone else'} to release or finish it, or pick a different unit ('clerk backlog next')") - base = "origin/main" if _show_ref(runner, root, "refs/remotes/origin/main") else "main" - base_sha = _git(runner, root, ["rev-parse", base]).stdout.strip() - if not base_sha: - backend_fail(f"claim failed — could not resolve a base commit (origin/main or main) for delivery/{short}") - if _git(runner, root, ["push", "origin", f"{base_sha}:refs/heads/delivery/{short}"]).returncode != 0: - _fetch_origin(runner, root, env) - _claim_conflict(f"clerk: backlog claim refused — delivery/{short} was just claimed by {holder or 'someone else'}\n wait for {holder or 'someone else'} to release or finish it, or pick a different unit ('clerk backlog next')") - if _git(runner, root, ["branch", f"delivery/{short}", base_sha]).returncode != 0: - backend_fail(f"claim failed — delivery/{short} is pushed but the local branch could not be created") - _git(runner, root, ["branch", "--set-upstream-to", f"origin/delivery/{short}", f"delivery/{short}"]) - if adapter is not None: - claimed = adapter.claim(id_) - _emit_stderr(claimed) - if claimed.returncode != 0 or str(_bd_issue_json_or_backend(runner, id_, f"claim failed — delivery/{short} was created but the bd claim did not confirm for {id_}").get("assignee") or "") != actor: - backend_fail(f"claim failed — delivery/{short} was created but the bd claim did not confirm for {id_}") - elif actor and runner.run(["gh", "issue", "edit", id_, "--add-assignee", actor]).returncode != 0: - backend_fail(f"claim failed — delivery/{short} was created but the GitHub claim did not succeed for {id_}") - worktree = _ensure_delivery_worktree(runner, root, short) - if worktree is None: - backend_fail(f"claim failed — could not provision the worktree at {root}/.worktrees/{short} for delivery/{short}") - if adapter is not None and not _provision_worktree_beads(adapter, root, worktree, id_): - backend_fail(f"claim failed — could not provision or verify the worktree at {worktree}") - if replay: - _replay_returned(runner, root, worktree, short, base) - elif fresh and disposition == "discard": - _dispose_returned(runner, root, short, env) - if offline: - print(f"clerk: OFFLINE - 'delivery/{short}' claimed LOCALLY ONLY (not pushed). The branch is the lock; it is compare-and-swapped at first reconnect (clerk submit/sync). If another machine claimed {short} meanwhile, that push wins and this local work is discarded. Proceeding, attended.", file=sys.stderr) - else: - _success(f"claimed {id_} — delivery/{short} pushed, worktree ready", env) - print(worktree) - return 0 - - -def _delivery_ahead_count(runner: CommandRunner, root: Path, short: str) -> int: - base = "origin/main" if _show_ref(runner, root, "refs/remotes/origin/main") else "main" - result = _git(runner, root, ["rev-list", "--count", f"{base}..delivery/{short}"]) - try: - return int(result.stdout.strip()) - except ValueError: - return 0 - - -def cmd_backlog_release(backend: str, root: Path, argv: Sequence[str], runner: CommandRunner, env: Mapping[str, str]) -> int: - if not argv: - usage("clerk backlog release: missing id — usage: clerk backlog release <id>") - if len(argv) > 1: - usage(f"clerk backlog release: unknown argument '{argv[1]}' — usage: clerk backlog release <id>") - if backend == "bd": - item = _bd_issue_json_or_usage(runner, argv[0], "clerk backlog release", "'clerk backlog next' shows ready units") - elif backend == "gh": - item = _gh_backlog_item_or_usage(runner, argv[0], "clerk backlog release") - else: - backend_fail(f"backlog release failed — unsupported backend {backend}") - id_, short = str(item.get("id") or argv[0]), _returned_short_from_id(str(item.get("id") or argv[0])) - main_root = _primary_repo_root(runner, root) - actor, holder = _delivery_actor(backend, runner, main_root, env), str(item.get("assignee") or "") - if not ((actor and holder == actor) or _show_ref(runner, main_root, f"refs/heads/delivery/{short}")): - _success(f"{id_} is not claimed here (no local delivery/{short}) — nothing to release", env) - return 0 - offline = not _fetch_origin(runner, main_root, env) - ahead = _delivery_ahead_count(runner, main_root, short) - if ahead: - print(f"clerk: backlog release refused — delivery/{short} has {ahead} commit(s) beyond main", file=sys.stderr) - print(f" run 'clerk backlog submit {id_}' to save the work, or 'clerk backlog return {id_} --reason \"<text>\"' to abandon it", file=sys.stderr) - raise ClerkExit(2) - if offline and _in_job_context(env): - usage(f"clerk: OFFLINE in a job context - refusing to release {short}: the remote teardown needs origin and no attendant can accept the staleness hazard. Retry when origin is reachable.") - # The caller may be inside this disposable linked worktree; leave it before removal. - os.chdir(main_root) - worktree = main_root / ".worktrees" / short - if worktree.is_dir() and _git(runner, main_root, ["worktree", "remove", str(worktree)]).returncode != 0: - backend_fail(f"release failed — could not remove the worktree at {worktree} (commit or stash local changes first)") - if not worktree.is_dir(): - _git(runner, main_root, ["worktree", "prune"]) - if not offline and _show_ref(runner, main_root, f"refs/remotes/origin/delivery/{short}") and _git(runner, main_root, ["push", "origin", "--delete", f"delivery/{short}"]).returncode != 0: - backend_fail(f"release failed — could not delete origin delivery/{short}") - if _show_ref(runner, main_root, f"refs/heads/delivery/{short}") and _git(runner, main_root, ["branch", "-D", f"delivery/{short}"]).returncode != 0: - backend_fail(f"release failed — could not delete local branch delivery/{short}") - if backend == "bd": - adapter = BdWorkGraphAdapter(runner) - result = adapter.release(id_) - if result.returncode != 0: - backend_fail(f"release failed — bd update did not succeed for {id_}") - after = _bd_issue_json_or_backend(runner, id_, f"release failed — {id_} was not confirmed open/unassigned after release") - if after.get("status") != "open" or after.get("assignee"): - backend_fail(f"release failed — {id_} was not confirmed open/unassigned after release") - elif actor and runner.run(["gh", "issue", "edit", id_, "--remove-assignee", actor]).returncode != 0: - backend_fail(f"release failed — could not remove the GitHub claim for {id_}") - if offline: - print(f"clerk: OFFLINE - delivery/{short} deleted locally only; the remote branch delete is deferred to sync (clerk claim/sync will finish it at the next reconnect).", file=sys.stderr) - _success(f"released {id_} — delivery/{short} torn down, unit reopened (stage:ready kept)", env) - return 0 - - -def _archive_returned(runner: CommandRunner, root: Path, short: str, offline: bool) -> None: - branch, remote = f"returned/{short}", f"refs/remotes/origin/returned/{short}" - if not _show_ref(runner, root, f"refs/heads/{branch}"): - if not _show_ref(runner, root, remote): - return - if _git(runner, root, ["branch", branch, f"origin/{branch}"]).returncode != 0: - backend_fail(f"return failed — could not materialize origin/{branch} for archiving") - suffix = _git(runner, root, ["rev-parse", "--short", branch]).stdout.strip() - archive = f"{branch}-{suffix}" - if _git(runner, root, ["branch", "-M", branch, archive]).returncode != 0: - backend_fail(f"return failed — could not archive {branch} as {archive}") - if not offline: - if _git(runner, root, ["push", "origin", archive]).returncode != 0: - backend_fail(f"return failed — could not push {archive} to origin") - if _show_ref(runner, root, remote) and _git(runner, root, ["push", "origin", "--delete", branch]).returncode != 0: - backend_fail(f"return failed — could not delete origin {branch} before replacing it") - - -def cmd_backlog_return(backend: str, root: Path, argv: Sequence[str], runner: CommandRunner, env: Mapping[str, str]) -> int: - if not argv: - usage('clerk backlog return: missing id — usage: clerk backlog return <id> --reason "<text>"') - id_arg, reason = argv[0], "" - args, i = list(argv[1:]), 0 - while i < len(args): - if args[i] != "--reason": - usage(f"clerk backlog return: unknown argument '{args[i]}' — usage: clerk backlog return <id> --reason \"<text>\"") - if i + 1 == len(args): - usage("clerk backlog return: --reason needs a value") - reason = args[i + 1] - i += 2 - if not reason: - usage(f"clerk backlog return: missing --reason — usage: clerk backlog return {id_arg} --reason \"<text>\"") - if backend == "bd": - item = _bd_issue_json_or_usage(runner, id_arg, "clerk backlog return", "'clerk backlog next' shows ready units") - elif backend == "gh": - item = _gh_backlog_item_or_usage(runner, id_arg, "clerk backlog return") - else: - backend_fail(f"backlog return failed — unsupported backend {backend}") - id_ = str(item.get("id") or id_arg) - short, main_root = _returned_short_from_id(id_), _primary_repo_root(runner, root) - if not _show_ref(runner, main_root, f"refs/heads/delivery/{short}"): - usage(f"clerk backlog return: no local delivery/{short} — claim it first ('clerk backlog claim {id_}')") - offline = not _fetch_origin(runner, main_root, env) - if offline and _in_job_context(env): - usage(f"clerk: OFFLINE in a job context - refusing to return {short}: preserving the branch needs origin and no attendant can accept the staleness hazard. Retry when origin is reachable.") - sha = _git(runner, main_root, ["rev-parse", f"delivery/{short}"]).stdout.strip() - # The caller may be inside this disposable linked worktree. Leave it before - # removal so subsequent backend commands never inherit a deleted cwd. - os.chdir(main_root) - worktree = main_root / ".worktrees" / short - if worktree.is_dir() and _git(runner, main_root, ["worktree", "remove", str(worktree)]).returncode != 0: - backend_fail(f"return failed — could not remove the worktree at {worktree} (commit or stash local changes first)") - if not worktree.is_dir(): - _git(runner, main_root, ["worktree", "prune"]) - _archive_returned(runner, main_root, short, offline) - if _git(runner, main_root, ["branch", "-m", f"delivery/{short}", f"returned/{short}"]).returncode != 0: - backend_fail(f"return failed — could not rename delivery/{short} to returned/{short}") - if not offline: - if _git(runner, main_root, ["push", "origin", f"returned/{short}"]).returncode != 0: - backend_fail(f"return failed — could not push returned/{short} to origin") - if _show_ref(runner, main_root, f"refs/remotes/origin/delivery/{short}") and _git(runner, main_root, ["push", "origin", "--delete", f"delivery/{short}"]).returncode != 0: - backend_fail(f"return failed — could not delete origin delivery/{short}") - body = f"{reason}\n\nreturned from delivery of {id_}\nevidence: returned/{short} @ {sha}" - if backend == "bd": - adapter = BdWorkGraphAdapter(runner) - result = adapter.return_to_inbox(id_) - if result.returncode != 0: - backend_fail(f"return failed — bd update did not succeed for {id_}") - after = _bd_issue_json_or_backend(runner, id_, f"return failed — {id_} was not confirmed open/not-ready after return") - if after.get("status") != "open" or "stage:ready" in (after.get("labels") or []): - backend_fail(f"return failed — {id_} was not confirmed open/not-ready after return") - _bd_ensure_impediment_type(runner) - capture = adapter.create_impediment(f"backlog return: {id_}", body) - if capture.returncode != 0 or not capture.stdout.strip(): - backend_fail(f"return failed — could not file the reason capture for {id_}") - capture_id = capture.stdout.strip() - _bd_issue_json_or_backend(runner, capture_id, f"return failed — reason capture {capture_id} was not confirmed after filing") - else: - if runner.run(["gh", "issue", "reopen", id_]).returncode != 0 or runner.run(["gh", "issue", "edit", id_, "--remove-label", "ready-for-agent"]).returncode != 0: - backend_fail(f"return failed — could not reopen {id_} as a GitHub backlog item") - actor = _delivery_actor("gh", runner, main_root, env) - if actor and runner.run(["gh", "issue", "edit", id_, "--remove-assignee", actor]).returncode != 0: - backend_fail(f"return failed — could not remove the GitHub claim for {id_}") - capture = runner.run(["gh", "issue", "create", "--title", f"backlog return: {id_}", "--body", body, "--label", "type:impediment"]) - if capture.returncode != 0 or not capture.stdout.strip(): - backend_fail(f"return failed — could not file the reason capture for {id_}") - capture_id = capture.stdout.strip() - if offline: - print(f"clerk: OFFLINE - returned/{short} created locally only; pushing it and deleting delivery/{short} on origin is deferred to sync (clerk claim/sync will finish it at the next reconnect).", file=sys.stderr) - _success(f"returned {id_} — returned/{short} preserved, reopened, reason filed as {capture_id}", env) - return 0 - - -MUTATION_HANDLERS = { - ("capture",): cmd_capture, - ("inbox", "pregrill"): cmd_inbox_pregrill, - ("inbox", "ready"): cmd_inbox_ready, - ("inbox", "drop"): cmd_inbox_drop, - ("inbox", "parent"): cmd_inbox_parent, - ("inbox", "dep"): cmd_inbox_dep, - ("inbox", "claim"): cmd_inbox_claim, - ("inbox", "release"): cmd_inbox_release, - ("inbox", "note"): cmd_inbox_note, - ("inbox", "update"): cmd_inbox_update, - ("inbox", "resolve"): cmd_inbox_resolve, - ("backlog", "resolve"): cmd_backlog_resolve, - ("backlog", "claim"): cmd_backlog_claim, - ("backlog", "release"): cmd_backlog_release, - ("backlog", "return"): cmd_backlog_return, -} - - -QUERY_HANDLERS = { - ("inbox", "list"): cmd_inbox_list, - ("inbox", "show"): cmd_inbox_show, - ("inbox", "dups"): cmd_inbox_dups, - ("inbox", "children"): cmd_inbox_children, - ("inbox", "frontier"): cmd_inbox_frontier, - ("inbox", "blockers"): cmd_inbox_blockers, - ("inbox", "blocked"): cmd_inbox_blocked, - ("backlog", "next"): cmd_backlog_next, - ("backlog", "waiting"): cmd_backlog_waiting, - ("backlog", "show"): cmd_backlog_show, -} - - -def run_query(path: tuple[str, ...], backend: str, root: Path, argv: Sequence[str], env: Mapping[str, str] = os.environ, runner: CommandRunner | None = None) -> int: - handler = QUERY_HANDLERS[path] - try: - return handler(backend, root, argv, runner or CommandRunner(), env) - except ClerkExit as exc: - return exc.code - - -def run_mutation(path: tuple[str, ...], backend: str, root: Path, argv: Sequence[str], env: Mapping[str, str] = os.environ, runner: CommandRunner | None = None) -> int: - handler = MUTATION_HANDLERS[path] - try: - return handler(backend, root, argv, runner or CommandRunner(), env) - except ClerkExit as exc: - return exc.code diff --git a/clerk/src/clerk/doctor.py b/clerk/src/clerk/doctor.py deleted file mode 100644 index 8769b03..0000000 --- a/clerk/src/clerk/doctor.py +++ /dev/null @@ -1,179 +0,0 @@ -"""Python implementation of ``clerk doctor``.""" - -from __future__ import annotations - -import os -import shutil -import subprocess -import sys -from collections.abc import Mapping, Sequence -from pathlib import Path - -from . import __version__ -from .manifest import ManifestStatus, read_manifest -from .output import Palette - - -def repo_root() -> Path | None: - try: - proc = subprocess.run( - ["git", "rev-parse", "--show-toplevel"], - stdout=subprocess.PIPE, - stderr=subprocess.DEVNULL, - text=True, - check=False, - ) - except FileNotFoundError: - return None - if proc.returncode != 0: - return None - root = proc.stdout.rstrip("\n") - return Path(root) if root else None - - -def _usage(message: str) -> int: - print(message, file=sys.stderr) - return 2 - - -def _canon(path: str | Path) -> str: - try: - return str(Path(path).resolve(strict=False)) - except OSError: - return str(path) - - -class DoctorReport: - def __init__(self, palette: Palette) -> None: - self.palette = palette - self.failures = 0 - - def ok(self, message: str) -> None: - print(f" {self.palette.green}[ ok ]{self.palette.reset} {message}") - - def warn(self, message: str) -> None: - print(f" {self.palette.yellow}[warn]{self.palette.reset} {message}") - - def fail(self, message: str) -> None: - print(f" {self.palette.red}[fail]{self.palette.reset} {message}") - self.failures += 1 - - def hint(self, message: str) -> None: - print(f" {message}") - - -def parse_args(argv: Sequence[str]) -> tuple[int, str] | int: - fix = 0 - backend = "" - args = list(argv) - i = 0 - while i < len(args): - arg = args[i] - if arg == "--fix": - fix = 1 - elif arg == "--backend": - if i + 1 >= len(args): - return _usage("clerk doctor: --backend needs a value — use --backend bd or --backend gh") - backend = args[i + 1] - i += 1 - elif arg.startswith("--backend="): - backend = arg[len("--backend=") :] - else: - return _usage(f"clerk doctor: unknown argument '{arg}' — usage: clerk doctor [--fix --backend bd|gh]") - i += 1 - - if fix: - if backend in {"bd", "gh"}: - return fix, backend - if backend == "": - return _usage("clerk doctor: --fix requires --backend bd|gh — rerun as 'clerk doctor --fix --backend bd' (or gh)") - return _usage(f"clerk doctor: unknown backend '{backend}' — use --backend bd or --backend gh") - if backend: - return _usage("clerk doctor: --backend applies only with --fix — rerun with --fix, e.g. 'clerk doctor --fix --backend bd'") - return fix, backend - - -def run_doctor(argv: Sequence[str], env: Mapping[str, str] = os.environ) -> int: - parsed = parse_args(argv) - if isinstance(parsed, int): - return parsed - fix, backend = parsed - - palette = Palette.from_env(env) - report = DoctorReport(palette) - root = repo_root() - - if root is not None: - print(f"{palette.bold}clerk doctor{palette.reset} — {root}") - else: - print(f"{palette.bold}clerk doctor{palette.reset}") - - if root is None: - report.fail(".clerk marker: not inside a git repository") - report.hint("cd into the target repo, then rerun 'clerk doctor'") - else: - manifest_path = root / ".clerk" - manifest = read_manifest(manifest_path) - if manifest.status is ManifestStatus.OK: - report.ok(f".clerk marker: backlog: {manifest.backend} ({manifest_path})") - elif fix: - try: - manifest_path.write_text(f"backlog: {backend}\n", encoding="utf-8") - manifest = read_manifest(manifest_path) - except OSError: - manifest = read_manifest(manifest_path) - if manifest.status is ManifestStatus.OK: - report.ok(f".clerk marker: provisioned backlog: {manifest.backend} ({manifest_path})") - report.hint("commit .clerk so worktrees and clones see it: git add .clerk && git commit") - else: - report.fail(f".clerk marker: could not provision ({manifest_path})") - report.hint(f"check that {root} is writable and .clerk is not a directory") - elif manifest.status is ManifestStatus.MISSING: - report.fail(f".clerk marker: missing ({manifest_path})") - report.hint("provision it: clerk doctor --fix --backend bd (or --backend gh)") - else: - report.fail(f".clerk marker: invalid ({manifest_path})") - report.hint("expected a single line 'backlog: bd' or 'backlog: gh' (comments after # are fine)") - report.hint("rewrite it: clerk doctor --fix --backend bd (or --backend gh)") - - home = env.get("HOME", "") - candidates = [Path(home) / ".config/bin/bd"] - if root is not None: - candidates.append(root / "bin/bd") - - resolved = shutil.which("bd", path=env.get("PATH")) - shim = next((candidate for candidate in candidates if candidate.is_file() and os.access(candidate, os.X_OK)), None) - if resolved is None: - report.warn("bd shim: no 'bd' on PATH — bd-backed verbs will not work until one is installed") - else: - is_shim = any(_canon(resolved) == _canon(candidate) for candidate in candidates) - if is_shim: - report.ok(f"bd shim: {resolved} (shim wins PATH resolution)") - elif shim is not None: - report.fail(f"bd shim: SHADOWED — 'bd' resolves to {resolved}, expected shim {shim}") - report.hint(f"fix: put {shim.parent} before {Path(resolved).parent} in PATH") - else: - report.warn("bd shim: 'bd' resolves to {resolved} and no clerk-managed shim exists (~/.config/bin/bd or <repo>/bin/bd)".format(resolved=resolved)) - - report.ok(f"version: clerk {__version__} (clerk --version reports the same string)") - - if shutil.which("gh", path=env.get("PATH")) is None: - report.warn("gh auth: gh not on PATH (non-fatal) — install gh before using gh-backed verbs") - else: - gh = subprocess.run( - ["gh", "auth", "status"], - stdout=subprocess.DEVNULL, - stderr=subprocess.DEVNULL, - env=dict(env), - check=False, - ) - if gh.returncode == 0: - report.ok("gh auth: authenticated") - else: - report.warn("gh auth: not authenticated (non-fatal) — run 'gh auth login' before gh-backed verbs") - - if report.failures == 0: - print(f"{palette.green}clerk doctor: all clear{palette.reset}") - return 0 - print(f"{palette.red}clerk doctor: {report.failures} problem(s) — fix the [fail] lines above{palette.reset}") - return 1 diff --git a/clerk/src/clerk/glean.py b/clerk/src/clerk/glean.py deleted file mode 100644 index 247f4cc..0000000 --- a/clerk/src/clerk/glean.py +++ /dev/null @@ -1,345 +0,0 @@ -"""Transcript harvesting for ``clerk glean``.""" - -from __future__ import annotations - -import fcntl -import hashlib -import json -import os -import shutil -import subprocess -import sys -import tempfile -from collections.abc import Mapping, Sequence -from pathlib import Path -from typing import Any - -from .commands import _bd_ensure_impediment_type -from .proc import CommandRunner -from .work_graph import BdWorkGraphAdapter, WorkGraphBackendError - -_PROMPT = """You are a retrospective friction harvester (glean). You are reading a CHUNK of a Claude Code session transcript (JSONL lines) to find IMPEDIMENTS: friction the agent routed around that would recur and cost tokens unless an instruction, skill, or tool changes. - -IMPEDIMENT DEFINITION (ADR 0012): friction the agent had to route around that *would recur and cost tokens again unless an instruction, skill, or tool changed*. A bare `is_error` from normal probing (empty grep, a guard that fails) is NOT an impediment; a denied permission, an interface retried three times, a misfiring bundled skill, or an ambiguous injected instruction IS. - -Highest-value class: friction with *our own* instructions/skills — those we can actually fix. - -For each impediment you find, output ONE JSON object on its own line with this exact shape: -{ - "type": "impediment", - "title": "<one-line summary, <=80 chars>", - "body": "<evidence-rich description: quote the failing command, the error, the retry count, roughly what it cost. Do NOT decide the fix — choosing which instruction to change is a grill decision, not a capture-time call.>", - "transcript_file": "<path>", - "chunk_lines": "<start>-<end>" -} - -If you find no impediments, output exactly one JSON object: -{"type":"none","reason":"<why no recurring workflow/tooling friction was found>"} - -Malformed output is treated as a failed harvest and the watermark will not advance. - -Categories (ADR 0016 loop map) — this run only emits `type: impediment`. Future categories: `criteria-miss`, `sort-miss`, `prep-miss`. - -""" - - -class GleanFailure(Exception): - pass - - -def _state_dir(env: Mapping[str, str]) -> Path: - configured = env.get("CLERK_GLEAN_STATE_DIR") - if configured: - return Path(configured) - return Path(env.get("HOME") or "/") / ".local" / "state" / "clerk" - - -def _transcript_dirs(root: Path, env: Mapping[str, str]) -> tuple[Path, ...]: - configured = env.get("CLERK_GLEAN_TRANSCRIPT_DIR") - if configured: - return (Path(configured),) - projects = Path(env.get("CLERK_GLEAN_PROJECTS_ROOT") or Path(env.get("HOME") or "/") / ".config" / "claude-code" / "projects") - slug = str(root.resolve()).replace("/", "-") - return (projects / slug,) - - -def _watermark_path(state_dir: Path, transcript: Path) -> Path: - digest = hashlib.sha256(str(transcript.resolve()).encode()).hexdigest() - return state_dir / f"{digest}.watermark" - - -def _read_watermark(state_dir: Path, transcript: Path) -> int: - path = _watermark_path(state_dir, transcript) - if not path.is_file(): - return 0 - try: - return int(path.read_text() or "0") - except (OSError, ValueError) as exc: - raise GleanFailure(f"invalid watermark for {transcript}") from exc - - -def _write_watermark(state_dir: Path, transcript: Path, offset: int) -> None: - path = _watermark_path(state_dir, transcript) - temporary = "" - try: - with tempfile.NamedTemporaryFile("w", dir=state_dir, prefix=f"{path.name}.tmp.", delete=False) as handle: - temporary = handle.name - handle.write(str(offset)) - os.replace(temporary, path) - except OSError as exc: - if temporary: - Path(temporary).unlink(missing_ok=True) - raise GleanFailure(f"failed to write watermark for {transcript}") from exc - - -def _judgment_prompt(chunk: str, transcript: Path, start: int, end: int) -> str: - return f"{_PROMPT}TRANSCRIPT CHUNK (lines {start}-{end} of {transcript}):\n{chunk}" - - -def _run_judgment(prompt: str, env: Mapping[str, str], runner: CommandRunner) -> str: - command = env.get("CLERK_GLEAN_JUDGMENT_CMD") - if command: - result = runner.run(["bash", "-c", command], env=env, input=prompt) - elif shutil.which("claude", path=env.get("PATH")): - result = runner.run( - [ - "claude", - "-p", - "--model", - env.get("CLERK_GLEAN_MODEL", "haiku"), - "--max-budget-usd", - env.get("CLERK_GLEAN_MAX_BUDGET_USD", "0.05"), - ], - env=env, - input=prompt, - ) - else: - print("clerk glean: no judgment runner available (expected claude on PATH)", file=sys.stderr) - raise GleanFailure("no judgment runner") - if result.stderr: - print(result.stderr, end="", file=sys.stderr) - if result.returncode != 0: - raise GleanFailure("judgment fork failed") - if not result.stdout.strip(): - print("clerk glean: judgment fork produced no JSONL; watermark not advanced", file=sys.stderr) - raise GleanFailure("empty judgment") - return result.stdout - - -def _candidates(output: str) -> list[tuple[str, dict[str, Any]]]: - candidates: list[tuple[str, dict[str, Any]]] = [] - seen_none = False - for line in output.splitlines(): - if not line.strip(): - continue - try: - candidate = json.loads(line) - except json.JSONDecodeError as exc: - print("clerk glean: malformed judgment JSONL; watermark not advanced", file=sys.stderr) - raise GleanFailure("malformed judgment") from exc - if not isinstance(candidate, dict) or candidate.get("type") not in {"none", "impediment"}: - print("clerk glean: malformed judgment JSONL; watermark not advanced", file=sys.stderr) - raise GleanFailure("malformed judgment") - if candidate["type"] == "none": - seen_none = True - continue - if not candidate.get("title") or not candidate.get("body"): - print("clerk glean: impediment candidate missing title/body; watermark not advanced", file=sys.stderr) - raise GleanFailure("incomplete impediment") - candidates.append((line, candidate)) - if seen_none and candidates: - print("clerk glean: ambiguous judgment output; watermark not advanced", file=sys.stderr) - raise GleanFailure("ambiguous judgment") - if seen_none: - return [] - if not candidates: - print("clerk glean: ambiguous judgment output; watermark not advanced", file=sys.stderr) - raise GleanFailure("ambiguous judgment") - return candidates - - -def _existing_capture(backend: str, source_key: str, runner: CommandRunner) -> str: - if backend == "bd": - try: - work = BdWorkGraphAdapter(runner).find_by_description(source_key) - except WorkGraphBackendError as exc: - print("clerk glean: capture lookup failed — rerun 'clerk glean' after the backend recovers", file=sys.stderr) - raise GleanFailure("capture lookup failed") from exc - return work.id if work is not None else "" - result = runner.run(["gh", "issue", "list", "--search", source_key, "--json", "url", "--jq", ".[0].url // empty"]) - if result.returncode != 0: - print("clerk glean: capture lookup failed — rerun 'clerk glean' after the backend recovers", file=sys.stderr) - raise GleanFailure("capture lookup failed") - return result.stdout.strip() - - -def _file_capture(backend: str, title: str, body: str, source_keys: Sequence[str], runner: CommandRunner) -> str: - for source_key in source_keys: - existing = _existing_capture(backend, source_key, runner) - if existing: - return existing - temporary = "" - try: - with tempfile.NamedTemporaryFile("w", delete=False) as handle: - temporary = handle.name - handle.write(body + "\n\n" + "\n".join(source_keys) + "\n") - if backend == "bd": - _bd_ensure_impediment_type(runner) - adapter = BdWorkGraphAdapter(runner) - result = adapter.create_impediment_from_file(title, temporary) - if result.returncode != 0: - raise GleanFailure("capture filing failed") - id_ = result.stdout.strip() - try: - seen = adapter.find(id_) - except WorkGraphBackendError as exc: - raise GleanFailure("capture confirmation failed") from exc - if seen is None or seen.id != id_: - raise GleanFailure("capture confirmation failed") - return id_ - if backend == "gh": - result = runner.run(["gh", "issue", "create", "--title", title, "--body-file", temporary, "--label", "type:impediment"]) - if result.returncode != 0: - raise GleanFailure("capture filing failed") - url = result.stdout.strip() - confirmed = runner.run(["gh", "issue", "view", url, "--json", "url", "--jq", ".url"]) - if confirmed.returncode != 0 or confirmed.stdout.strip() != url: - raise GleanFailure("capture confirmation failed") - return url - raise GleanFailure(f"unsupported backend {backend}") - finally: - if temporary: - Path(temporary).unlink(missing_ok=True) - - -def _judge_and_file( - backend: str, - transcript: Path, - chunk: str, - start: int, - end: int, - env: Mapping[str, str], - runner: CommandRunner, -) -> str: - output = _run_judgment(_judgment_prompt(chunk, transcript, start, end), env, runner) - filed: list[str] = [] - for index, (raw, candidate) in enumerate(_candidates(output), start=1): - stable_input = f"{transcript.resolve()}:{start}-{end}:{index}" - legacy_input = f"{raw}\n{transcript}:{start}-{end}" - source_keys = ( - f"glean-source-v2:{hashlib.sha256(stable_input.encode()).hexdigest()}", - f"glean-source:{hashlib.sha256(legacy_input.encode()).hexdigest()}", - ) - filed.append(_file_capture(backend, str(candidate["title"]), str(candidate["body"]), source_keys, runner)) - return "\n".join(filed) - - -def _process_transcript( - backend: str, - transcript: Path, - state_dir: Path, - minimum: int, - env: Mapping[str, str], - runner: CommandRunner, -) -> None: - if not transcript.is_file() or transcript.stat().st_size == 0: - return - lines = transcript.read_text().splitlines() - watermark = _read_watermark(state_dir, transcript) - if watermark >= len(lines): - return - start = watermark + 1 - while start + minimum - 1 <= len(lines): - end = start + minimum - 1 - chunk = "\n".join(lines[start - 1 : end]) + "\n" - try: - capture_ids = _judge_and_file(backend, transcript, chunk, start, end, env, runner) - except GleanFailure as exc: - print(f"glean: judgment fork failed for {transcript} lines {start}-{end}; watermark not advanced", file=sys.stderr) - raise exc - if capture_ids: - print(f" filed {capture_ids} (lines {start}-{end})") - else: - print(f" judgment fork returned no capture for lines {start}-{end}") - _write_watermark(state_dir, transcript, end) - start = end + 1 - remaining = len(lines) - start + 1 - if 0 < remaining < minimum: - print(f"glean: sub-threshold chunk skipped ({remaining} lines, min {minimum}) in {transcript}") - - -def _start_async(root: Path, state_dir: Path, env: Mapping[str, str]) -> int: - log_path = state_dir / "glean.log" - with log_path.open("a") as log: - subprocess.Popen( - [sys.executable, "-m", "clerk", "glean"], - cwd=root, - env=dict(env), - stdin=subprocess.DEVNULL, - stdout=log, - stderr=subprocess.STDOUT, - start_new_session=True, - ) - print(f"glean: async harvest started (log: {log_path})") - return 0 - - -def run_glean( - backend: str, - root: Path, - argv: Sequence[str], - env: Mapping[str, str] = os.environ, - runner: CommandRunner | None = None, -) -> int: - """Run the Python-owned Glean watermark sweep.""" - - async_ = False - for arg in argv: - if arg == "--async": - async_ = True - else: - print(f"clerk glean: unknown argument '{arg}' — usage: clerk glean [--async]", file=sys.stderr) - return 2 - - state_dir = _state_dir(env) - try: - state_dir.mkdir(parents=True, exist_ok=True) - if async_: - return _start_async(root, state_dir, env) - lock = (state_dir / "glean.lock").open("a+") - except OSError: - print(f"clerk glean: state path unavailable at {state_dir} — fix it, then rerun 'clerk glean'", file=sys.stderr) - return 5 - - try: - try: - fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) - except BlockingIOError: - print("glean: another instance is running — exiting", file=sys.stderr) - return 0 - - directories = _transcript_dirs(root, env) - transcripts = sorted(path for directory in directories if directory.is_dir() for path in directory.rglob("*.jsonl") if path.is_file()) - display = " ".join(str(path) for path in directories) - if not transcripts: - print(f"glean: no transcript files found in {display}") - return 0 - - print(f"glean: scanning {len(transcripts)} transcript file(s)") - command_runner = runner or CommandRunner() - minimum = int(env.get("CLERK_GLEAN_MIN_CHUNK_LINES", "50")) - failed = False - for transcript in transcripts: - print(f" harvesting {transcript}") - try: - _process_transcript(backend, transcript, state_dir, minimum, env, command_runner) - except (GleanFailure, OSError): - failed = True - print(f"glean: failed to process {transcript}", file=sys.stderr) - if failed: - print("glean: harvest completed with failures — rerun 'clerk glean'; failed watermarks were not advanced", file=sys.stderr) - return 5 - print("glean: harvest complete") - return 0 - finally: - lock.close() diff --git a/clerk/src/clerk/manifest.py b/clerk/src/clerk/manifest.py deleted file mode 100644 index 5a7390c..0000000 --- a/clerk/src/clerk/manifest.py +++ /dev/null @@ -1,56 +0,0 @@ -"""Strict parser for the Clerk repository manifest.""" - -from __future__ import annotations - -from dataclasses import dataclass -from enum import Enum -from pathlib import Path - - -class ManifestStatus(Enum): - OK = "ok" - MISSING = "missing" - INVALID = "invalid" - AMBIGUOUS = "ambiguous" - - -@dataclass(frozen=True) -class ManifestResult: - status: ManifestStatus - path: Path - backend: str | None = None - project_gate: str | None = None - - @property - def is_ok(self) -> bool: - return self.status is ManifestStatus.OK - - -def _directive(line: str) -> str: - line = line.split("#", 1)[0] - return line.strip() - - -def parse_manifest(text: str, path: Path) -> ManifestResult: - """Parse manifest content from *path* for both checkout and Git-tree reads.""" - - directives = [directive for raw in text.splitlines() if (directive := _directive(raw))] - backlog = [line[len("backlog:") :].strip() for line in directives if line.startswith("backlog:")] - gates = [line[len("project-gate:") :].strip() for line in directives if line.startswith("project-gate:")] - if len(backlog) != 1 or len(gates) > 1 or len(directives) != len(backlog) + len(gates): - return ManifestResult(ManifestStatus.INVALID if not directives else ManifestStatus.AMBIGUOUS, path) - backend = backlog[0] - if backend not in {"bd", "gh"}: - return ManifestResult(ManifestStatus.INVALID, path) - return ManifestResult(ManifestStatus.OK, path, backend, gates[0] if gates else None) - - -def read_manifest(path: Path) -> ManifestResult: - """Read and parse a v1 manifest from the working tree.""" - - if not path.is_file(): - return ManifestResult(ManifestStatus.MISSING, path) - try: - return parse_manifest(path.read_text(encoding="utf-8"), path) - except OSError: - return ManifestResult(ManifestStatus.INVALID, path) diff --git a/clerk/src/clerk/output.py b/clerk/src/clerk/output.py deleted file mode 100644 index af25267..0000000 --- a/clerk/src/clerk/output.py +++ /dev/null @@ -1,36 +0,0 @@ -"""Output helpers for Clerk's public CLI contract.""" - -from __future__ import annotations - -import os -import sys -from collections.abc import Mapping -from dataclasses import dataclass - - -@dataclass(frozen=True) -class Palette: - bold: str = "" - red: str = "" - green: str = "" - yellow: str = "" - reset: str = "" - - @classmethod - def from_env(cls, env: Mapping[str, str] = os.environ) -> "Palette": - if "NO_COLOR" in env: - enabled = False - elif env.get("CLICOLOR_FORCE") not in {None, "", "0"}: - enabled = True - else: - enabled = sys.stdout.isatty() - - if not enabled: - return cls() - return cls( - bold="\033[1m", - red="\033[31m", - green="\033[32m", - yellow="\033[33m", - reset="\033[0m", - ) diff --git a/clerk/src/clerk/ownership.py b/clerk/src/clerk/ownership.py deleted file mode 100644 index 19ec4f2..0000000 --- a/clerk/src/clerk/ownership.py +++ /dev/null @@ -1,57 +0,0 @@ -"""Static Python ownership for every public Clerk verb path.""" - -from __future__ import annotations - -from collections.abc import Sequence - -from .commands import MUTATION_HANDLERS, QUERY_HANDLERS -from .reconciliation import RECONCILIATION_VERBS -from .roster import NOUN_VERBS, TOP_LEVEL_VERBS - -PYTHON_OWNED_DIRECT_PATHS: frozenset[tuple[str, ...]] = frozenset( - { - ("doctor",), - ("glean",), - ("--version",), - ("-V",), - ("--help",), - ("-h",), - ("backlog", "proof"), - ("backlog", "submit"), - ("backlog", "gate"), - } - | set(QUERY_HANDLERS) - | set(MUTATION_HANDLERS) - | set(RECONCILIATION_VERBS) -) - - -def public_verb_path(argv: Sequence[str]) -> tuple[str, ...] | None: - """Return the public Clerk verb path in *argv*, if it is a roster path.""" - - args = list(argv) - if not args: - return None - if args[0] == "--explain": - args = args[1:] - if not args: - return None - if args[0] in {"--version", "-V", "--help", "-h"}: - return (args[0],) - if args[0] in TOP_LEVEL_VERBS: - return (args[0],) - if len(args) >= 2 and args[0] in NOUN_VERBS and args[1] in NOUN_VERBS[args[0]]: - return (args[0], args[1]) - return None - - -def is_python_owned(argv: Sequence[str]) -> bool: - """Whether the supplied public argv should be handled by Python.""" - - args = list(argv) - if not args: - return True - if "--explain" in args or "--help" in args or "-h" in args: - return True - path = public_verb_path(args) - return path in PYTHON_OWNED_DIRECT_PATHS if path is not None else True diff --git a/clerk/src/clerk/proc.py b/clerk/src/clerk/proc.py deleted file mode 100644 index 3ac1971..0000000 --- a/clerk/src/clerk/proc.py +++ /dev/null @@ -1,47 +0,0 @@ -"""Subprocess seam for Clerk backend adapters.""" - -from __future__ import annotations - -import subprocess -from collections.abc import Mapping, Sequence -from dataclasses import dataclass -from pathlib import Path - - -@dataclass(frozen=True) -class CommandResult: - args: tuple[str, ...] - returncode: int - stdout: str - stderr: str - - -class CommandRunner: - """Small wrapper around subprocess.run, injectable in tests.""" - - def run( - self, - args: Sequence[str], - *, - cwd: str | Path | None = None, - env: Mapping[str, str] | None = None, - input: str | None = None, - timeout: float | None = None, - ) -> CommandResult: - try: - proc = subprocess.run( - list(args), - cwd=str(cwd) if cwd is not None else None, - env=dict(env) if env is not None else None, - input=input, - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - text=True, - check=False, - timeout=timeout, - ) - except FileNotFoundError as exc: - return CommandResult(tuple(args), 127, "", str(exc)) - except subprocess.TimeoutExpired as exc: - return CommandResult(tuple(args), 124, exc.stdout or "", exc.stderr or "") - return CommandResult(tuple(args), proc.returncode, proc.stdout, proc.stderr) diff --git a/clerk/src/clerk/project_gate.py b/clerk/src/clerk/project_gate.py deleted file mode 100644 index b18df89..0000000 --- a/clerk/src/clerk/project_gate.py +++ /dev/null @@ -1,413 +0,0 @@ -"""Project-gate protocol and trusted-default adapter execution.""" - -from __future__ import annotations - -import json -import os -import re -import stat -import sys -import tempfile -from collections.abc import Mapping, Sequence -from dataclasses import dataclass -from pathlib import Path, PurePosixPath -from typing import Any - -from .commands import ClerkExit, _emit_stderr, _git, _success, backend_fail, usage -from .manifest import ManifestStatus, parse_manifest -from .proc import CommandResult, CommandRunner -from .work_graph import BdWorkGraphAdapter, WorkGraphBackendError, acceptance_criteria - - -_PR_URL = re.compile( - r"https://github\.com/" - r"[A-Za-z0-9](?:[A-Za-z0-9]|-(?=[A-Za-z0-9])){0,38}/" - r"(?=[A-Za-z0-9._-]{1,100}/pull/)(?=[^/]*[A-Za-z0-9])[A-Za-z0-9._-]+/" - r"pull/[1-9][0-9]*\n?" -) - - -@dataclass(frozen=True) -class GateConfig: - adapter: str - submission_owner: str - trusted_ref: str - - -@dataclass(frozen=True) -class GateResult: - status: str - summary: str - assessed_commit: str - run_id: str | None - delivery_completed: bool - - -def _safe_repo_path(value: object) -> str | None: - if not isinstance(value, str) or not value: - return None - path = PurePosixPath(value) - if path.is_absolute() or ".." in path.parts or path == PurePosixPath("."): - return None - return str(path) - - -def _trusted_ref(runner: CommandRunner, root: Path) -> str: - result = _git(runner, root, ["symbolic-ref", "--quiet", "--short", "refs/remotes/origin/HEAD"]) - candidate = result.stdout.strip() - if candidate and _git(runner, root, ["rev-parse", "--verify", "--quiet", candidate]).returncode == 0: - return candidate - for candidate in ("origin/main", "main"): - if _git(runner, root, ["rev-parse", "--verify", "--quiet", candidate]).returncode == 0: - return candidate - backend_fail("project gate failed — could not resolve the trusted default branch") - raise AssertionError("unreachable") - - -def _trusted_file(runner: CommandRunner, root: Path, ref: str, path: str, message: str) -> str: - result = _git(runner, root, ["show", f"{ref}:{path}"]) - if result.returncode != 0: - backend_fail(message) - return result.stdout - - -def _load_config(runner: CommandRunner, root: Path) -> GateConfig: - ref = _trusted_ref(runner, root) - manifest = parse_manifest( - _trusted_file(runner, root, ref, ".clerk", "project gate failed — trusted .clerk is missing or unreadable"), - root / ".clerk", - ) - if manifest.status is not ManifestStatus.OK or not manifest.project_gate: - backend_fail("project gate failed — trusted .clerk has no project-gate configuration") - config_path = _safe_repo_path(manifest.project_gate) - if config_path is None: - backend_fail("project gate failed — trusted .clerk project-gate configuration is outside the repository") - raw = _trusted_file( - runner, - root, - ref, - config_path, - "project gate failed — trusted project-gate configuration is missing or unreadable", - ) - try: - config = json.loads(raw) - except json.JSONDecodeError: - backend_fail("project gate failed — trusted project-gate configuration is malformed") - if not isinstance(config, dict): - backend_fail("project gate failed — trusted project-gate configuration is malformed") - adapter = _safe_repo_path(config.get("adapter")) - owner = config.get("submission_owner", "clerk") - if adapter is None or owner not in {"clerk", "project-gate"}: - backend_fail("project gate failed — trusted project-gate configuration is malformed") - # Read it now, while ref is fixed, so a delivery branch can never supply the executable. - _trusted_file(runner, root, ref, adapter, "project gate failed — trusted project-gate adapter is missing or unreadable") - return GateConfig(adapter=adapter, submission_owner=owner, trusted_ref=ref) - - -def _adapter_source(runner: CommandRunner, root: Path, config: GateConfig) -> str: - return _trusted_file( - runner, - root, - config.trusted_ref, - config.adapter, - "project gate failed — trusted project-gate adapter is missing or unreadable", - ) - - -def _work(backend: str, runner: CommandRunner, id_: str, verb: str) -> tuple[str, str, str]: - if backend == "bd": - try: - work = BdWorkGraphAdapter(runner).find(id_) - except WorkGraphBackendError as exc: - _emit_stderr(exc.result) - backend_fail(f"{verb.removeprefix('clerk ')} Work lookup failed — {exc}") - if work is None: - usage(f"{verb}: {id_} not found — check the id ('clerk backlog next' shows ready units)") - return work.id, work.title, work.acceptance_criteria - result = runner.run(["gh", "issue", "view", id_, "--json", "number,title,body"]) - if result.returncode != 0: - usage(f"{verb}: {id_} not found — check the id ('clerk backlog next' shows ready units)") - try: - obj = json.loads(result.stdout) - except json.JSONDecodeError: - backend_fail(f"{verb.removeprefix('clerk ')} failed — gh issue view did not return valid JSON") - if not isinstance(obj, dict): - backend_fail(f"{verb.removeprefix('clerk ')} failed — gh issue view did not return an issue object") - return f"#{obj.get('number')}", str(obj.get("title") or ""), acceptance_criteria({"description": obj.get("body")}) - - -def _proof_criteria(acceptance: str) -> list[str]: - bullets: list[str] = [] - fallback: list[str] = [] - for line in acceptance.splitlines(): - text = line.strip() - if not text or re.fullmatch(r"#{0,6}\s*acceptance criteria:?", text, re.IGNORECASE): - continue - bullet = re.fullmatch(r"(?:-|\d+[.)])\s+(.+?)\s*", text) - if bullet: - bullets.append(bullet.group(1).strip()) - else: - fallback.append(text) - return bullets if bullets or len(fallback) != 1 else fallback - - -def cmd_backlog_proof(backend: str, root: Path, argv: Sequence[str], runner: CommandRunner) -> int: - if not argv: - usage("clerk backlog proof: missing id — usage: clerk backlog proof <id>") - if len(argv) > 1: - usage(f"clerk backlog proof: unknown argument '{argv[1]}' — usage: clerk backlog proof <id>") - work_id, _, acceptance = _work(backend, runner, argv[0], "clerk backlog proof") - criteria = _proof_criteria(acceptance) - if not criteria: - usage(f"clerk backlog proof: {work_id} has no acceptance criteria — return it to discovery before submitting") - print(json.dumps({"acceptance": [{"text": text, "evidence": ""} for text in criteria]}, indent=2, ensure_ascii=False)) - return 0 - - -def _short(id_: str) -> str: - value = id_[1:] if id_.startswith("#") else id_ - return value.split("-", 1)[1] if "-" in value else value - - -def _current_branch(runner: CommandRunner, root: Path) -> str: - return _git(runner, root, ["symbolic-ref", "--quiet", "--short", "HEAD"]).stdout.strip() - - -def _request(work_id: str, title: str, acceptance: str, branch: str, root: Path, owner: str, run_id: str | None = None) -> dict[str, Any]: - request: dict[str, Any] = { - "work": {"id": work_id, "title": title, "acceptance_criteria": acceptance}, - "delivery": {"branch": branch, "starting_commit": "", "worktree": str(root)}, - "submission_owner": owner, - } - if run_id is not None: - request["run"] = {"id": run_id} - return request - - -def _with_starting_commit(runner: CommandRunner, root: Path, request: dict[str, Any]) -> dict[str, Any]: - result = _git(runner, root, ["rev-parse", "HEAD"]) - if result.returncode != 0: - backend_fail("project gate failed — could not resolve the delivery worktree head") - request["delivery"]["starting_commit"] = result.stdout.strip() - return request - - -def _parse_result(raw: str) -> GateResult: - try: - value = json.loads(raw) - except json.JSONDecodeError: - backend_fail("project gate failed — adapter did not emit exactly one valid Gate result JSON") - if not isinstance(value, dict): - backend_fail("project gate failed — adapter did not emit exactly one valid Gate result JSON") - status = value.get("status") - summary = value.get("summary") - assessed_commit = value.get("assessed_commit") - run = value.get("run") - if run is not None and not isinstance(run, dict): - backend_fail("project gate failed — adapter emitted a malformed Gate result") - run_id = run.get("id") if isinstance(run, dict) else None - if status not in {"passed", "failed", "pending"} or not isinstance(summary, str) or not isinstance(assessed_commit, str) or not assessed_commit: - backend_fail("project gate failed — adapter emitted a malformed Gate result") - if run is not None and (not isinstance(run_id, str) or not run_id): - backend_fail("project gate failed — adapter emitted a malformed Gate result") - if status == "pending" and run_id is None: - backend_fail("project gate failed — pending Gate result requires run.id") - delivery = value.get("delivery") - completed = isinstance(delivery, dict) and delivery.get("status") == "completed" - return GateResult(status, summary, assessed_commit, run_id, completed) - - -def _invoke(runner: CommandRunner, root: Path, config: GateConfig, operation: str, request: Mapping[str, Any]) -> GateResult: - source = _adapter_source(runner, root, config) - fd, executable = tempfile.mkstemp(prefix="clerk-project-gate-") - try: - with os.fdopen(fd, "w", encoding="utf-8") as adapter_file: - adapter_file.write(source) - os.chmod(executable, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR) - result = runner.run([executable, operation], cwd=root, input=json.dumps(request) + "\n") - finally: - Path(executable).unlink(missing_ok=True) - _emit_stderr(result) - if result.returncode != 0: - backend_fail("project gate failed — adapter execution failed") - gate_result = _parse_result(result.stdout) - assessed = _git(runner, root, ["rev-parse", "--verify", "--quiet", f"{gate_result.assessed_commit}^{{commit}}"]) - if assessed.returncode != 0: - backend_fail("project gate failed — adapter emitted an unknown assessed_commit") - return gate_result - - -def _state_path(runner: CommandRunner, root: Path, short: str) -> Path: - result = _git(runner, root, ["rev-parse", "--git-path", f"clerk/gates/{short}.json"]) - if result.returncode != 0 or not result.stdout.strip(): - backend_fail("project gate failed — could not locate Gate-run metadata") - path = Path(result.stdout.strip()) - return path if path.is_absolute() else root / path - - -def _save_pending(runner: CommandRunner, root: Path, short: str, request: Mapping[str, Any], run_id: str) -> None: - path = _state_path(runner, root, short) - path.parent.mkdir(parents=True, exist_ok=True) - path.write_text(json.dumps({"request": request, "run_id": run_id}) + "\n", encoding="utf-8") - - -def _load_pending(runner: CommandRunner, root: Path, short: str) -> tuple[dict[str, Any], str]: - path = _state_path(runner, root, short) - try: - value = json.loads(path.read_text(encoding="utf-8")) - request, run_id = value["request"], value["run_id"] - except (OSError, KeyError, TypeError, json.JSONDecodeError): - usage("clerk backlog gate: no pending Project-gate run for this Work") - if not isinstance(request, dict) or not isinstance(run_id, str) or not run_id: - usage("clerk backlog gate: no pending Project-gate run for this Work") - return request, run_id - - -def _clear_pending(runner: CommandRunner, root: Path, short: str) -> None: - _state_path(runner, root, short).unlink(missing_ok=True) - - -def _record_terminal(runner: CommandRunner, root: Path, short: str, request: Mapping[str, Any], result: GateResult) -> None: - path = _state_path(runner, root, short).with_suffix(".result.json") - path.parent.mkdir(parents=True, exist_ok=True) - path.write_text( - json.dumps( - { - "request": request, - "result": { - "status": result.status, - "summary": result.summary, - "assessed_commit": result.assessed_commit, - **({"run": {"id": result.run_id}} if result.run_id else {}), - }, - } - ) - + "\n", - encoding="utf-8", - ) - - -def _close_work(backend: str, runner: CommandRunner, id_: str) -> None: - if backend == "bd": - try: - BdWorkGraphAdapter(runner).complete_delivery(id_) - except WorkGraphBackendError as exc: - _emit_stderr(exc.result) - backend_fail(f"project gate failed — could not confirm project-gate delivery completion: {exc}") - return - result = runner.run(["gh", "issue", "close", id_]) - _emit_stderr(result) - if result.returncode != 0: - backend_fail("project gate failed — could not record project-gate delivery completion") - - -def _handoff(runner: CommandRunner, root: Path, branch: str, title: str, work_id: str, summary: str, acceptance: str) -> None: - result = _git(runner, root, ["push", "-u", "origin", branch]) - if result.returncode != 0: - backend_fail(f"submit failed — could not push {branch} to origin") - result = runner.run( - [ - "gh", - "pr", - "create", - "--head", - branch, - "--base", - "main", - "--title", - f"{title} ({work_id})", - "--body", - f"## Project gate\n\n{summary}\n\n## Acceptance criteria\n\n{acceptance}", - ] - ) - _emit_stderr(result) - if result.returncode != 0: - backend_fail("submit failed — gh pr create did not succeed") - if _PR_URL.fullmatch(result.stdout) is None: - backend_fail("submit failed — gh pr create did not emit exactly one well-formed GitHub pull-request URL") - - -def _finish_terminal(backend: str, runner: CommandRunner, root: Path, config: GateConfig, result: GateResult, work_id: str, title: str, acceptance: str, branch: str, short: str, env: Mapping[str, str]) -> int: - if result.status == "failed": - print(f"clerk: project gate failed for {work_id}: {result.summary}", file=sys.stderr) - return 6 - if result.status == "pending": - assert result.run_id is not None - request = _with_starting_commit(runner, root, _request(work_id, title, acceptance, branch, root, config.submission_owner)) - _save_pending(runner, root, short, request, result.run_id) - _success(f"project gate pending for {work_id}: {result.summary}", env) - return 0 - if config.submission_owner == "clerk": - head = _git(runner, root, ["rev-parse", "HEAD"]) - if head.returncode != 0 or head.stdout.strip() != result.assessed_commit: - backend_fail("project gate failed — passed assessed_commit is not the current delivery worktree head") - _handoff(runner, root, branch, title, work_id, result.summary, acceptance) - _success(f"submitted {work_id} — project gate passed; PR created", env) - return 0 - if not result.delivery_completed: - backend_fail("project gate failed — project-gate-owned passed result must report delivery.status 'completed'") - _close_work(backend, runner, work_id) - _success(f"completed {work_id} — project gate owns delivery", env) - return 0 - - -def cmd_backlog_submit(backend: str, root: Path, argv: Sequence[str], runner: CommandRunner, env: Mapping[str, str]) -> int: - if len(argv) != 1: - usage("clerk backlog submit: usage: clerk backlog submit <id>") - work_id, title, acceptance = _work(backend, runner, argv[0], "clerk backlog submit") - if not acceptance: - usage(f"clerk backlog submit: {work_id} has no acceptance criteria — return it to discovery before submitting") - short = _short(work_id) - branch = f"delivery/{short}" - if _current_branch(runner, root) != branch: - usage(f"clerk backlog submit: not inside {branch} — claim {work_id} first") - config = _load_config(runner, root) - _clear_pending(runner, root, short) - request = _with_starting_commit(runner, root, _request(work_id, title, acceptance, branch, root, config.submission_owner)) - result = _invoke(runner, root, config, "run", request) - if result.status == "pending": - assert result.run_id is not None - _save_pending(runner, root, short, request, result.run_id) - _success(f"project gate pending for {work_id}: {result.summary}", env) - return 0 - _record_terminal(runner, root, short, request, result) - return _finish_terminal(backend, runner, root, config, result, work_id, title, acceptance, branch, short, env) - - -def cmd_backlog_gate(backend: str, root: Path, argv: Sequence[str], runner: CommandRunner, env: Mapping[str, str]) -> int: - if len(argv) != 1: - usage("clerk backlog gate: usage: clerk backlog gate <id>") - requested_id = argv[0] - short = _short(requested_id) - branch = f"delivery/{short}" - if _current_branch(runner, root) != branch: - usage(f"clerk backlog gate: not inside {branch} — claim {requested_id} first") - current_work_id = "" - if backend == "bd": - current_work_id, _, current_acceptance = _work(backend, runner, requested_id, "clerk backlog gate") - if not current_acceptance: - usage(f"clerk backlog gate: {current_work_id} has no acceptance criteria — return it to discovery before submitting") - request, run_id = _load_pending(runner, root, short) - work = request.get("work") - if ( - not isinstance(work, dict) - or not isinstance(work.get("id"), str) - or not isinstance(work.get("title"), str) - or not isinstance(work.get("acceptance_criteria"), str) - or not work["acceptance_criteria"] - or (current_work_id and work["id"] != current_work_id) - ): - backend_fail("project gate failed — pending Gate-run metadata is malformed") - work_id, title, acceptance = work["id"], work["title"], work["acceptance_criteria"] - config = _load_config(runner, root) - request = dict(request) - request["run"] = {"id": run_id} - result = _invoke(runner, root, config, "status", request) - if result.status == "pending": - assert result.run_id is not None - _save_pending(runner, root, short, request, result.run_id) - _success(f"project gate pending for {work_id}: {result.summary}", env) - return 0 - _clear_pending(runner, root, short) - _record_terminal(runner, root, short, request, result) - return _finish_terminal(backend, runner, root, config, result, work_id, title, acceptance, branch, short, env) diff --git a/clerk/src/clerk/reconciliation.py b/clerk/src/clerk/reconciliation.py deleted file mode 100644 index 2fa5e95..0000000 --- a/clerk/src/clerk/reconciliation.py +++ /dev/null @@ -1,331 +0,0 @@ -"""Delivery reconciliation for ``backlog finish`` and ``sync``.""" - -from __future__ import annotations - -import json -import os -import sys -from collections.abc import Mapping, Sequence -from pathlib import Path -from typing import Any - -from .commands import ClerkExit, _emit_stderr, _git, _primary_repo_root, _returned_short_from_id, _show_ref, _success, backend_fail, usage -from .proc import CommandResult, CommandRunner -from .work_graph import BdWorkGraphAdapter, Work, WorkGraphBackendError - -RECONCILIATION_VERBS = frozenset({("sync",), ("backlog", "finish")}) - - -def _current_delivery_short(runner: CommandRunner, root: Path) -> str: - branch = _git(runner, root, ["symbolic-ref", "--quiet", "--short", "HEAD"]).stdout.strip() - return branch.removeprefix("delivery/") if branch.startswith("delivery/") else "" - - -def _gh_not_found(result: CommandResult) -> bool: - message = f"{result.stdout}\n{result.stderr}".lower() - return any(text in message for text in ("could not resolve to an issue", "no issue")) - - -def _gh_issue(runner: CommandRunner, id_: str) -> dict[str, Any] | None: - result = runner.run(["gh", "issue", "view", id_, "--json", "number,title,body,assignees,state,labels"]) - if result.returncode != 0: - if _gh_not_found(result): - return None - _emit_stderr(result) - backend_fail(f"finish failed — gh issue view did not succeed for {id_}") - try: - value = json.loads(result.stdout) - except json.JSONDecodeError: - backend_fail(f"finish failed — gh issue view did not return valid JSON for {id_}") - if not isinstance(value, dict) or not value.get("number"): - backend_fail(f"finish failed — gh issue view did not return an issue object for {id_}") - return value - - -def _resolve_work(backend: str, runner: CommandRunner, root: Path, id_arg: str) -> tuple[str, str] | None: - if backend == "bd": - try: - work = BdWorkGraphAdapter(runner).find(id_arg) - except WorkGraphBackendError as exc: - _emit_stderr(exc.result) - backend_fail(f"finish failed — could not resolve Work {id_arg}: {exc}") - return (work.id, _returned_short_from_id(work.id)) if work is not None else None - if backend == "gh": - value = _gh_issue(runner, id_arg) - if value is None: - return None - work_id = str(value["number"]) - return work_id, work_id - backend_fail(f"finish failed — unsupported backend {backend}") - raise AssertionError("unreachable") - - -def _active_pr(runner: CommandRunner, branch: str) -> dict[str, Any] | None: - result = runner.run( - [ - "gh", "pr", "list", "--head", branch, "--state", "all", "--json", - "number,url,state,mergedAt,reviewDecision,statusCheckRollup,headRefName,isDraft,updatedAt", - ] - ) - if result.returncode != 0: - backend_fail(f"finish failed — gh pr list did not succeed for {branch}") - try: - values = json.loads(result.stdout or "[]") - except json.JSONDecodeError: - backend_fail(f"finish failed — gh pr list did not return valid JSON for {branch}") - if not isinstance(values, list) or any(not isinstance(value, dict) for value in values): - backend_fail(f"finish failed — gh pr list did not return a PR list for {branch}") - open_prs = sorted((value for value in values if value.get("state") == "OPEN"), key=lambda value: str(value.get("updatedAt") or ""), reverse=True) - merged_prs = sorted( - (value for value in values if value.get("state") == "MERGED" or value.get("mergedAt")), - key=lambda value: str(value.get("updatedAt") or ""), - reverse=True, - ) - return (open_prs or merged_prs or [None])[0] - - -def _check_names(pr: Mapping[str, Any], kind: str) -> tuple[str, ...]: - names: list[str] = [] - for check in pr.get("statusCheckRollup") or []: - if not isinstance(check, dict): - continue - conclusion = str(check.get("conclusion") or "").upper() - status = str(check.get("status") or "").upper() - failed = conclusion in {"FAILURE", "TIMED_OUT", "CANCELLED", "ACTION_REQUIRED"} or ( - status == "COMPLETED" and conclusion not in {"", "SUCCESS", "SKIPPED", "NEUTRAL"} - ) - pending = not conclusion and status != "COMPLETED" - if (kind == "failed" and failed) or (kind == "pending" and pending): - names.append(str(check.get("name") or check.get("context") or check.get("workflowName") or "unnamed check")) - return tuple(names) - - -def _push_if_needed(runner: CommandRunner, root: Path, short: str) -> int: - branch = f"delivery/{short}" - if not _show_ref(runner, root, f"refs/heads/{branch}") or _show_ref(runner, root, f"refs/remotes/origin/{branch}"): - return 0 - _git(runner, root, ["fetch", "origin", "main"]) - base = _git(runner, root, ["rev-parse", "origin/main"]) - merge_base = _git(runner, root, ["merge-base", branch, "origin/main"]) - if base.returncode == 0 and merge_base.returncode == 0 and merge_base.stdout.strip() != base.stdout.strip(): - print(f"clerk: backlog finish refused — delivery/{short} is behind origin/main", file=sys.stderr) - print(" run 'git rebase origin/main', then rerun 'clerk backlog finish'", file=sys.stderr) - return 2 - if _git(runner, root, ["push", "-u", "origin", branch]).returncode != 0: - backend_fail(f"finish failed — could not push {branch} to origin") - _git(runner, root, ["fetch", "origin"]) - return 0 - - -def _remote_branch_exists(runner: CommandRunner, root: Path, branch: str) -> bool: - result = _git(runner, root, ["ls-remote", "--exit-code", "--heads", "origin", branch]) - if result.returncode == 0: - return True - if result.returncode == 2: - return False - _emit_stderr(result) - backend_fail(f"finish failed — could not query origin for {branch}") - raise AssertionError("unreachable") - - -def _finish_gh_work(runner: CommandRunner, work_id: str) -> None: - work = _gh_issue(runner, work_id) - if work is None: - backend_fail(f"finish failed — could not read {work_id} after finish") - labels = {str(label.get("name") or "") for label in work.get("labels") or [] if isinstance(label, dict)} - if work.get("state") != "CLOSED": - result = runner.run(["gh", "issue", "close", work_id]) - _emit_stderr(result) - if result.returncode != 0: - backend_fail(f"finish failed — could not close {work_id}") - if "ready-for-agent" in labels: - result = runner.run(["gh", "issue", "edit", work_id, "--remove-label", "ready-for-agent"]) - _emit_stderr(result) - if result.returncode != 0: - backend_fail(f"finish failed — could not remove ready-for-agent from {work_id}") - work = _gh_issue(runner, work_id) - if work is None or work.get("state") != "CLOSED": - backend_fail(f"finish failed — {work_id} was not confirmed closed after finish") - labels = {str(label.get("name") or "") for label in work.get("labels") or [] if isinstance(label, dict)} - if "ready-for-agent" in labels: - backend_fail(f"finish failed — {work_id} was not confirmed without ready-for-agent after finish") - - -def _cleanup_merged( - backend: str, - runner: CommandRunner, - root: Path, - full: str, - short: str, - pr_number: str, - env: Mapping[str, str], -) -> None: - main_root = _primary_repo_root(runner, root) - try: - os.chdir(main_root) - except OSError: - backend_fail(f"finish failed — could not cd to {main_root} before cleanup") - worktree = main_root / ".worktrees" / short - if worktree.is_dir(): - if _git(runner, main_root, ["worktree", "remove", str(worktree)]).returncode != 0: - backend_fail(f"finish failed — could not remove the worktree at {worktree} (commit or stash local changes first)") - else: - _git(runner, main_root, ["worktree", "prune"]) - branch = f"delivery/{short}" - if _show_ref(runner, main_root, f"refs/heads/{branch}") and _git(runner, main_root, ["branch", "-D", branch]).returncode != 0: - backend_fail(f"finish failed — could not delete local branch {branch}") - if _remote_branch_exists(runner, main_root, branch): - if _git(runner, main_root, ["push", "origin", "--delete", branch]).returncode != 0: - backend_fail(f"finish failed — could not delete origin {branch}") - if _remote_branch_exists(runner, main_root, branch): - backend_fail(f"finish failed — origin still advertises {branch} after deletion") - if backend == "bd": - try: - BdWorkGraphAdapter(runner).finish_delivery(full, f"delivered: PR #{pr_number} merged") - except WorkGraphBackendError as exc: - _emit_stderr(exc.result) - backend_fail(f"finish failed — {exc}") - else: - _finish_gh_work(runner, full) - _success(f"finished {full} — PR #{pr_number} merged, delivery/{short} cleaned up, unit closed", env) - - -def _reconcile( - backend: str, - runner: CommandRunner, - root: Path, - id_arg: str, - watch: bool, - sync: bool, - env: Mapping[str, str], -) -> int: - supplied_id = bool(id_arg) - inferred_short = "" - if not supplied_id: - inferred_short = _current_delivery_short(runner, root) - id_arg = inferred_short - resolved = _resolve_work(backend, runner, root, id_arg) if id_arg else None - if resolved is None: - if sync: - print(f"clerk: sync: skipped an unresolvable claim id {id_arg or '<current>'}") - return 0 - if inferred_short: - usage( - f"clerk backlog finish: could not resolve Work for delivery/{inferred_short} — run 'clerk doctor' to check backend state or rerun 'clerk backlog finish <full-id>'" - ) - if supplied_id: - usage(f"clerk backlog finish: {id_arg} not found — check the id ('clerk backlog show <id>' inspects Work)") - usage("clerk backlog finish: not inside delivery/<short> and no id was supplied — cd into the claimed worktree or run 'clerk backlog finish <id>'") - work_id, branch_token = resolved - branch = f"delivery/{branch_token}" - push_code = _push_if_needed(runner, root, branch_token) - if push_code: - return push_code - pr = _active_pr(runner, branch) - if pr is None: - if sync: - if not _show_ref(runner, root, f"refs/heads/{branch}") and not _show_ref(runner, root, f"refs/remotes/origin/{branch}"): - print(f"clerk: sync: {work_id} is claimed but has no delivery/{branch_token} branch/worktree — no PR created") - else: - print(f"clerk: sync: {work_id} has delivery/{branch_token} but no PR — no PR created; run 'clerk backlog submit {work_id} --body-file <path-to-pr-body.md>'") - return 0 - print(f"clerk: backlog finish refused — no PR found for delivery/{branch_token}", file=sys.stderr) - print(f" run 'clerk backlog submit {work_id} --body-file <path-to-pr-body.md>'", file=sys.stderr) - return 2 - pr_number = str(pr.get("number") or "") - if pr.get("state") == "MERGED" or pr.get("mergedAt"): - _cleanup_merged(backend, runner, root, work_id, branch_token, pr_number, env) - return 0 - if watch: - result = runner.run(["gh", "pr", "checks", pr_number, "--watch"]) - if result.returncode != 0: - backend_fail(f"finish failed — gh pr checks --watch failed for PR #{pr_number}") - pr = _active_pr(runner, branch) - if pr is None: - backend_fail(f"finish failed — PR #{pr_number} disappeared after gh pr checks --watch") - failures = _check_names(pr, "failed") - if failures: - print(f"clerk: PR #{pr_number} for {work_id} has failing checks") - for name in failures: - print(f" {name}") - return 1 - pending = _check_names(pr, "pending") - if pending: - print(f"clerk: PR #{pr_number} for {work_id} has pending checks — run 'clerk backlog finish {work_id} --watch' to wait") - for name in pending: - print(f" {name}") - return 0 - if pr.get("isDraft"): - print(f"clerk: PR #{pr_number} for {work_id} is a draft — finish will complete after it is marked ready") - return 0 - if pr.get("reviewDecision") in {"REVIEW_REQUIRED", "CHANGES_REQUESTED"}: - print(f"clerk: PR #{pr_number} for {work_id} is awaiting review — finish will complete after review") - return 0 - if runner.run(["gh", "pr", "merge", pr_number, "--squash", "--delete-branch=false"]).returncode != 0: - backend_fail(f"finish failed — gh pr merge --squash did not succeed for PR #{pr_number}") - pr = _active_pr(runner, branch) - if pr is None or (pr.get("state") != "MERGED" and not pr.get("mergedAt")): - backend_fail(f"finish failed — PR #{pr_number} was not confirmed merged after gh pr merge") - _cleanup_merged(backend, runner, root, work_id, branch_token, pr_number, env) - return 0 - - -def cmd_backlog_finish( - backend: str, - root: Path, - argv: Sequence[str], - runner: CommandRunner, - env: Mapping[str, str], -) -> int: - watch = False - id_arg = "" - for arg in argv: - if arg == "--watch": - watch = True - elif id_arg: - usage(f"clerk backlog finish: unknown argument '{arg}' — usage: clerk backlog finish [<id>] [--watch]") - else: - id_arg = arg - return _reconcile(backend, runner, root, id_arg, watch, False, env) - - -def cmd_sync( - backend: str, - root: Path, - argv: Sequence[str], - runner: CommandRunner, - env: Mapping[str, str], -) -> int: - if argv: - usage(f"clerk sync: unknown argument '{argv[0]}' — usage: clerk sync") - if backend == "gh": - print("clerk: sync: gh-backed claim sweep is not available in this generation; skipping", file=sys.stderr) - return 0 - if backend != "bd": - backend_fail(f"sync failed — unsupported backend {backend}") - try: - claims = BdWorkGraphAdapter(runner).open_claims() - except WorkGraphBackendError as exc: - _emit_stderr(exc.result) - backend_fail("sync failed — bd list did not succeed") - print(f"clerk: sync scanning {len(claims)} open claim(s)") - for work in claims: - _reconcile(backend, runner, root, work.id, False, True, env) - return 0 - - -_HANDLERS = {("sync",): cmd_sync, ("backlog", "finish"): cmd_backlog_finish} - - -def run_reconciliation( - path: tuple[str, ...], - backend: str, - root: Path, - argv: Sequence[str], - env: Mapping[str, str] = os.environ, - runner: CommandRunner | None = None, -) -> int: - try: - return _HANDLERS[path](backend, root, argv, runner or CommandRunner(), env) - except ClerkExit as exc: - return exc.code diff --git a/clerk/src/clerk/roster.py b/clerk/src/clerk/roster.py deleted file mode 100644 index f24b92b..0000000 --- a/clerk/src/clerk/roster.py +++ /dev/null @@ -1,257 +0,0 @@ -"""Public Clerk command roster and explain text.""" - -from __future__ import annotations - -from collections.abc import Iterable, Sequence - -ADR15 = "ADR 0015 — clerk/docs/adr/0015-clerk-opaque-workflow-verb-facade.md" -ADR16 = "ADR 0016 — umbel/docs/adr/0016-delivery-gate-acceptance-proof-and-judgment-loops.md" -ADR17 = "ADR 0017 — clerk/docs/adr/0017-tier-retired-backlog-location-and-merge-gate-axes.md" - -TOP_LEVEL_VERBS = ("capture", "sync", "doctor", "glean") -NOUN_VERBS: dict[str, tuple[str, ...]] = { - "inbox": ( - "list", - "show", - "dups", - "ready", - "drop", - "pregrill", - "children", - "frontier", - "blockers", - "blocked", - "parent", - "dep", - "claim", - "release", - "note", - "update", - "resolve", - ), - "backlog": ( - "next", - "show", - "waiting", - "claim", - "release", - "resolve", - "proof", - "submit", - "gate", - "finish", - "return", - ), -} - -ROSTER_LINES = ( - "Known verbs:", - ' capture "<title>" [--stdin|--type <type>|--impediment|--parent <id>|--blocked-by <id>]', - " inbox list|show|dups|ready|drop|pregrill|children|frontier|blockers|blocked|parent|dep|claim|release|note|update|resolve", - " backlog next|show|waiting|claim|release|resolve|proof|submit|gate|finish|return", - " sync", - " doctor [--fix --backend bd|gh]", - " glean", - "Next: run 'clerk --explain <verb>' to see what a verb does.", -) - -EXPLAIN_TEXT: dict[str, tuple[str, ...]] = { - "capture": ( - "clerk capture — file one raw capture into the bd inbox", - ' usage: clerk capture "<title>" [--stdin|--type <type>|--impediment|--parent <id>|--blocked-by <id>...]', - ' runs: bd create "<title>" [--stdin] [--type ...] [--parent ...] [--deps ...] (backlog: bd|gh)', - " (GitHub-backed repos use GitHub only after inbox ready promotion)", - f" see: {ADR15}", - ), - "sync": ( - "clerk sync — reconcile every open claim (authorship-free phases only)", - " runs: gh pr view --json state,mergedAt per open claim; then bd close / bd update", - " (backlog: bd) or gh issue close / gh issue edit (backlog: gh) per reconciled", - " state; reclaims stale claims; files reports for judgment-needing states", - f" see: {ADR15}", - ), - "doctor": ( - "clerk doctor — check and provision workflow plumbing", - " runs: git rev-parse --show-toplevel; reads .clerk; command -v bd vs the shim locations; gh auth status", - " --fix --backend bd|gh writes the .clerk marker", - f" see: {ADR17}", - ), - "glean": ( - "clerk glean — watermark sweep of session transcripts into captures", - " runs: flock-guarded sweep over per-transcript line offsets (state in ~/.local/state/clerk/); spawns the judgment fork per unharvested chunk", - f" see: {ADR15}", - ), - "inbox list": ( - "clerk inbox list — list the unrefined bd capture pool", - " usage: clerk inbox list [--limit <n>]", - " runs: bd list, filtered to open minus stage:ready (backlog: bd|gh)", - " --limit forwards to bd; 0 = unlimited", - f" see: {ADR15}", - ), - "inbox show": ( - "clerk inbox show — show one bd-backed inbox item", - " usage: clerk inbox show <id> [--json|--pretty]", - " runs: bd show <id> (backlog: bd|gh)", - f" see: {ADR15}", - ), - "inbox dups": ( - "clerk inbox dups — cluster duplicate bd captures for pre-sort", - " runs: bd duplicates (backlog: bd|gh)", - f" see: {ADR16}", - ), - "inbox ready": ( - "clerk inbox ready — write refinement output, then promote a groomed bd capture", - " usage: clerk inbox ready <id> [--design-file <path>] [--acceptance-file <path>] [--returned keep|discard]", - ' (gh: --title "<title>" --body-file <path>)', - " runs: for bd, optional bd update --design-file / --acceptance, then refuses", - " units still lacking acceptance criteria (ADR 0016); if returned/<id> exists,", - " requires --returned keep|discard before stage:ready; for gh, creates a", - " GitHub issue labelled ready-for-agent, then closes the bd capture as promoted", - f" see: {ADR16}", - ), - "inbox drop": ( - "clerk inbox drop — close a bd capture as not worth doing", - " usage: clerk inbox drop <id> [--returned keep|discard]", - " runs: if returned/<id> exists, requires --returned keep|discard; discard deletes", - " that evidence branch, keep preserves it; then bd close <id> --reason wontfix", - " (backlog: bd|gh)", - f" see: {ADR16}", - ), - "inbox pregrill": ( - "clerk inbox pregrill — append prep notes onto a bd capture before its grill", - ' runs: bd update <id> --notes "<dated, state-neutral prep note>" (backlog: bd|gh)', - " note carries open decisions, premises with suggested verifications, draft criteria", - f" see: {ADR16}", - ), - "backlog next": ( - "clerk backlog next — pick the next pickable ready unit", - " runs: Work graph adapter loads bd list --all --readonly --json --limit 0 once, then selects unclaimed ready leaves without open blockers (backlog: bd)", - " gh issue list --label ready-for-agent (backlog: gh)", - f" see: {ADR17}", - ), - "backlog show": ( - "clerk backlog show — show one backlog unit", - " runs: bd show <id> (backlog: bd)", - " gh issue view <id> (backlog: gh)", - f" see: {ADR15}", - ), - "backlog waiting": ( - "clerk backlog waiting — list refined-ready work that is waiting on graph state", - " runs: Work graph adapter loads the full bd graph once, then reports open blocker/child counts (backlog: bd)", - " gh issue list --label ready-for-agent (backlog: gh; no graph waiting view yet)", - f" see: {ADR17}", - ), - "backlog claim": ( - "clerk backlog claim — take the claim lock on a unit", - " usage: clerk backlog claim <id> [--from-returned|--fresh --returned keep|discard]", - " runs: refuses units with no Acceptance Criteria section (ADR 0016 C4); short-circuits", - " if you already hold it; else git push of the canonical delivery/<id> branch", - " (first push wins — the universal CAS lock, exit 5 if occupied or the race is", - " lost); on success, bd update <id> --claim as the online fast-path record", - " (backlog: bd); offline: local-only branch + claim, attended only; finally", - " git worktree add .worktrees/<id>, printing its absolute path; with returned/<id>,", - " plain claim refuses until you choose --from-returned (reuse and keep evidence)", - " or --fresh --returned keep|discard (start from main explicitly)", - f" see: {ADR17}", - ), - "backlog release": ( - "clerk backlog release — give a claim back without finishing (unit stays stage:ready)", - " runs: refuses if delivery/<id> carries commits beyond main (prescribes submit or", - " return instead); else git worktree remove + git branch -D delivery/<id>,", - " plus git push origin --delete delivery/<id> when reachable; then", - ' bd update <id> --status open --assignee "" (backlog: bd)', - " gh issue edit <id> --remove-assignee (backlog: gh)", - " offline: local teardown only, remote delete deferred to sync; job-context refuses;", - " idempotent (exit 0) on a unit not claimed here", - f" see: {ADR15}", - ), - "backlog resolve": ( - "clerk backlog resolve — close a pickable ready unit without delivery code", - " usage: clerk backlog resolve <id> [--returned keep|discard] [--file <path>|--stdin]", - ' runs: refuses non-pickable/claimed units and criteria-less units; appends a non-empty resolution note; bd close --reason "resolved without delivery" (backlog: bd)', - f" see: {ADR16}", - ), - "backlog proof": ( - "clerk backlog proof — print the JSON proof skeleton consumed by submit", - " usage: clerk backlog proof <id>", - " runs: bd show <id> --readonly --json / gh issue view <id>, then prints proof-only JSON:", - ' {"acceptance":[{"text":"<normalized criterion>","evidence":""}]}', - f" see: {ADR16}", - ), - "backlog submit": ( - "clerk backlog submit — invoke the configured Project gate for a delivery Work", - " usage: clerk backlog submit <id>", - " runs: reads project-gate config and adapter with git show from the trusted default branch, sends one structured run request, and relays its generic Gate result; a Clerk-owned pass uses git push and gh pr create for the assessed head", - " see: ADR 0019 — clerk/docs/adr/0019-project-gate-adapter-contract.md", - ), - "backlog gate": ( - "clerk backlog gate — reconcile one pending Project-gate run", - " usage: clerk backlog gate <id>", - " runs: reads the saved opaque run.id from git-managed Gate metadata and supplies it to the configured adapter status operation; refuses when no pending Gate run exists", - " see: ADR 0019 — clerk/docs/adr/0019-project-gate-adapter-contract.md", - ), - "backlog finish": ( - "clerk backlog finish — reconcile a submitted unit to done", - " runs: gh pr view --json state,mergedAt (merge detected via PR state, never ancestry); closes the unit; tears down the worktree; --watch wraps gh pr checks --watch", - f" see: {ADR15}", - ), - "backlog return": ( - "clerk backlog return — send a unit back to discovery (verdict: cannot be fulfilled as designed)", - ' runs: requires --reason "<text>"; renames delivery/<id> -> returned/<id> (local; pushes', - " the new ref and deletes delivery/<id> on origin when reachable) so the attempt", - " survives as grill evidence, then git worktree remove; bd update <id> --status open", - ' --remove-label stage:ready --assignee "" (backlog: bd)', - " gh issue reopen <id> + edit --remove-label ready-for-agent --remove-assignee (backlog: gh)", - " then files the reason verbatim as an impediment-typed capture referencing", - " returned/<id>: bd create --type impediment (backlog: bd) / gh issue create", - " --label type:impediment (backlog: gh); offline: local rename only, remote", - " deferred to sync; job-context refuses", - f" see: {ADR16}", - ), -} - -for graph_verb in ("inbox children", "inbox frontier", "inbox blockers", "inbox blocked"): - EXPLAIN_TEXT[graph_verb] = ( - f"clerk {graph_verb} — query inbox graph relationships as Clerk-owned JSON", - " usage: clerk inbox children|frontier|blockers|blocked <id> [--pretty]", - " runs: Work graph adapter uses bd list --all --readonly --json --limit 0 once and normalizes parent-child / blocks edges", - f" see: {ADR15}", - ) - -for mutation_verb in ( - "inbox parent", - "inbox dep", - "inbox claim", - "inbox release", - "inbox note", - "inbox update", - "inbox resolve", -): - EXPLAIN_TEXT[mutation_verb] = ( - f"clerk {mutation_verb} — mutate generic inbox graph/planning state", - " usage: clerk inbox parent set|clear ...; clerk inbox dep add|remove ...; clerk inbox claim|release <id>; clerk inbox note|update|resolve ...", - " runs: bd update / bd dep / bd close behind validated Clerk guards", - f" see: {ADR15}", - ) - - -def roster_text() -> str: - return "\n".join(ROSTER_LINES) + "\n" - - -def verb_label(path: Sequence[str]) -> str: - return " ".join(path) - - -def all_public_verb_paths() -> set[tuple[str, ...]]: - return {(verb,) for verb in TOP_LEVEL_VERBS} | { - (noun, verb) for noun, verbs in NOUN_VERBS.items() for verb in verbs - } - - -def iter_public_verb_labels() -> Iterable[str]: - for verb in TOP_LEVEL_VERBS: - yield verb - for noun, verbs in NOUN_VERBS.items(): - for verb in verbs: - yield f"{noun} {verb}" diff --git a/clerk/src/clerk/work_graph.py b/clerk/src/clerk/work_graph.py deleted file mode 100644 index b8f4aeb..0000000 --- a/clerk/src/clerk/work_graph.py +++ /dev/null @@ -1,434 +0,0 @@ -"""Work graph seam and bd-backed adapter. - -Clerk command handlers ask this module domain questions. Beads command shapes, -edge representations, and full-set query details stay inside the adapter. -""" - -from __future__ import annotations - -import json -import re -from dataclasses import dataclass -from typing import Any - -from .proc import CommandResult, CommandRunner - - -class WorkGraphBackendError(Exception): - """The backing store could not produce a valid Work graph snapshot.""" - - def __init__(self, message: str, result: CommandResult) -> None: - super().__init__(message) - self.result = result - - -def acceptance_criteria(value: dict[str, Any]) -> str: - direct = str(value.get("acceptance_criteria") or "") - if direct.strip(): - return direct - for source in (str(value.get("description") or ""), str(value.get("design") or "")): - lines = source.splitlines(keepends=True) - for index, line in enumerate(lines): - if line.strip().lower().strip("# ").rstrip(":") == "acceptance criteria": - return "".join(lines[index + 1 :]) - return "" - - -@dataclass(frozen=True) -class Work: - id: str - title: str - status: str - labels: tuple[str, ...] - assignee: str - parent: str - acceptance_criteria: str - raw: dict[str, Any] - - @classmethod - def from_json(cls, value: dict[str, Any]) -> Work: - return cls( - id=str(value.get("id") or ""), - title=str(value.get("title") or ""), - status=str(value.get("status") or ""), - labels=tuple(str(label) for label in value.get("labels") or []), - assignee=str(value.get("assignee") or ""), - parent=str(value.get("parent") or ""), - acceptance_criteria=acceptance_criteria(value), - raw=value, - ) - - -@dataclass(frozen=True) -class WaitingWork: - work: Work - blocker_count: int - child_count: int - - -@dataclass(frozen=True) -class Backlog: - """One consistent view of refinement-complete Work graph state.""" - - ready: tuple[Work, ...] - pickable: tuple[Work, ...] - waiting: tuple[WaitingWork, ...] - - -def edge_type(edge: dict[str, Any]) -> str: - return str(edge.get("dependency_type") or edge.get("type") or "") - - -def edge_target(edge: dict[str, Any]) -> str: - return str(edge.get("depends_on_id") or edge.get("id") or "") - - -def edge_ids(value: dict[str, Any], collection: str, kind: str) -> tuple[str, ...]: - return tuple( - edge_target(edge) - for edge in value.get(collection) or [] - if isinstance(edge, dict) and edge_type(edge) == kind and edge_target(edge) - ) - - -def has_open_edges(value: dict[str, Any], collection: str, kind: str) -> bool: - return any( - isinstance(edge, dict) - and edge_type(edge) == kind - and str(edge.get("status") or "open") != "closed" - for edge in value.get(collection) or [] - ) - - -def is_ready_promoted(value: dict[str, Any]) -> bool: - return "stage:ready" in (value.get("labels") or []) or str(value.get("close_reason") or "").startswith("promoted") - - -_ACCEPTANCE_HEADING = re.compile(r"^#{1,6}\s*acceptance criteria|^acceptance criteria:?\s*$", re.IGNORECASE | re.MULTILINE) - - -def has_acceptance_criteria(value: dict[str, Any]) -> bool: - if str(value.get("acceptance_criteria") or "").strip(): - return True - return bool(_ACCEPTANCE_HEADING.search(f"{value.get('description') or ''}\n{value.get('design') or ''}")) - - -def is_active_inbox(value: dict[str, Any]) -> bool: - return value.get("status") in {"open", "in_progress"} and "stage:ready" not in (value.get("labels") or []) - - -def is_open_inbox(value: dict[str, Any]) -> bool: - return value.get("status") == "open" and "stage:ready" not in (value.get("labels") or []) - - -def is_nonclosed_work(value: dict[str, Any]) -> bool: - return bool(value.get("status")) and value.get("status") != "closed" - - -def parent_id(value: dict[str, Any]) -> str: - return str(value.get("parent") or "") - - -def shares_parent(value: dict[str, Any], other: dict[str, Any]) -> bool: - parent = parent_id(value) - return bool(parent) and parent == parent_id(other) - - -def has_blocker(value: dict[str, Any], blocker: str) -> bool: - return blocker in edge_ids(value, "dependencies", "blocks") - - -def has_open_blockers(value: dict[str, Any]) -> bool: - return has_open_edges(value, "dependencies", "blocks") - - -def has_open_children(value: dict[str, Any]) -> bool: - return has_open_edges(value, "dependents", "parent-child") - - -class WorkGraph: - """Backend-neutral graph snapshot used to answer Clerk domain questions.""" - - def __init__(self, items: list[Work]) -> None: - self.items = tuple(items) - self._by_id = {item.id: item for item in items} - - def get(self, id_: str) -> Work | None: - return self._by_id.get(id_) - - def require(self, id_: str) -> Work: - item = self.get(id_) - if item is None: - raise KeyError(id_) - return item - - def resolve(self, id_: str) -> Work | None: - item = self.get(id_) - if item is not None: - return item - matches = [candidate for candidate in self.items if candidate.id.split("-", 1)[-1] == id_] - return matches[0] if len(matches) == 1 else None - - def pickability_reasons(self, item: Work) -> tuple[str, ...]: - reasons: list[str] = [] - if item.status != "open": - reasons.append(f"status is {item.status}") - if "stage:ready" not in item.labels: - reasons.append("not stage:ready") - if item.assignee: - reasons.append(f"claimed by {item.assignee}") - blockers = self.open_blockers(item) - children = self.open_children(item) - if blockers: - reasons.append(f"{len(blockers)} open blocker(s)") - if children: - reasons.append(f"{len(children)} open child(ren)") - return tuple(reasons) - - def children(self, item: Work) -> tuple[Work, ...]: - children: list[Work] = [] - seen: set[str] = set() - for value in item.raw.get("dependents") or []: - if not isinstance(value, dict) or edge_type(value) != "parent-child": - continue - child = self.get(edge_target(value)) - if child is not None and child.id not in seen: - children.append(child) - seen.add(child.id) - for child in self.items: - if child.parent == item.id and child.id not in seen: - children.append(child) - seen.add(child.id) - return tuple(children) - - def blockers(self, item: Work) -> tuple[Work, ...]: - result: list[Work] = [] - for value in item.raw.get("dependencies") or []: - if not isinstance(value, dict) or edge_type(value) != "blocks": - continue - target = self.get(edge_target(value)) - if target is not None: - result.append(target) - return tuple(result) - - def blocked_by(self, item: Work) -> tuple[Work, ...]: - return tuple(candidate for candidate in self.items if item.id in {blocker.id for blocker in self.blockers(candidate)}) - - def open_blockers(self, item: Work) -> tuple[Work | None, ...]: - blockers: list[Work | None] = [] - for value in item.raw.get("dependencies") or []: - if not isinstance(value, dict) or edge_type(value) != "blocks": - continue - target = self._by_id.get(edge_target(value)) - edge_status = str(value.get("status") or "") - if edge_status: - is_open = edge_status != "closed" - elif target is not None: - is_open = target.status != "closed" - else: - is_open = True - if is_open: - blockers.append(target) - return tuple(blockers) - - def open_children(self, item: Work) -> tuple[Work, ...]: - return tuple(child for child in self.children(item) if child.status != "closed") - - def frontier(self, parent: Work) -> tuple[Work, ...]: - return tuple( - child - for child in self.children(parent) - if child.status == "open" - and "stage:ready" not in child.labels - and not child.assignee - and not self.open_blockers(child) - ) - - def backlog(self) -> Backlog: - ready = tuple(item for item in self.items if item.status == "open" and "stage:ready" in item.labels) - unclaimed = tuple(item for item in ready if not item.assignee) - pickable: list[Work] = [] - waiting: list[WaitingWork] = [] - for item in unclaimed: - blockers = self.open_blockers(item) - children = self.open_children(item) - if blockers or children: - waiting.append(WaitingWork(item, len(blockers), len(children))) - elif has_acceptance_criteria(item.raw): - pickable.append(item) - return Backlog(ready, tuple(pickable), tuple(waiting)) - - -class BdWorkGraphAdapter: - """Translate beads primitives into Clerk's Work graph model.""" - - def __init__(self, runner: CommandRunner) -> None: - self._runner = runner - - def load(self) -> WorkGraph: - result = self._runner.run(["bd", "list", "--all", "--readonly", "--json", "--limit", "0"]) - if result.returncode != 0: - raise WorkGraphBackendError("bd list did not succeed", result) - try: - data = json.loads(result.stdout or "null") - except json.JSONDecodeError as exc: - raise WorkGraphBackendError("bd list did not return valid JSON", result) from exc - if not isinstance(data, list) or any(not isinstance(value, dict) for value in data): - raise WorkGraphBackendError("bd list did not return a Work list", result) - return WorkGraph([Work.from_json(value) for value in data]) - - def backlog(self) -> Backlog: - return self.load().backlog() - - def open_claims(self) -> tuple[Work, ...]: - return tuple(work for work in self.load().items if work.status == "in_progress") - - def _find(self, id_: str, *, cwd: str | None = None) -> tuple[Work | None, CommandResult]: - result = self._runner.run(["bd", "show", id_, "--readonly", "--json"], cwd=cwd) - try: - data = json.loads(result.stdout or "null") - except json.JSONDecodeError as exc: - raise WorkGraphBackendError(f"bd show did not return valid JSON for {id_}", result) from exc - if result.returncode != 0: - if isinstance(data, dict) and "no issue" in str(data.get("error") or ""): - return None, result - raise WorkGraphBackendError(f"bd show did not succeed for {id_}", result) - if not isinstance(data, list) or not data or not isinstance(data[0], dict): - raise WorkGraphBackendError(f"bd show did not return a Work item for {id_}", result) - return Work.from_json(data[0]), result - - def find(self, id_: str) -> Work | None: - return self._find(id_)[0] - - def _inspect(self, id_: str, *, cwd: str | None = None) -> dict[str, Any]: - work, result = self._find(id_, cwd=cwd) - if work is None: - raise WorkGraphBackendError(f"bd show did not return a Work item for {id_}", result) - return work.raw - - def append_notes(self, id_: str, note: str) -> CommandResult: - return self._runner.run(["bd", "update", id_, "--append-notes", note]) - - def close(self, id_: str, reason: str) -> CommandResult: - return self._runner.run(["bd", "close", id_, "--reason", reason]) - - def complete_delivery(self, id_: str) -> None: - result = self.close(id_, "project gate completed") - if result.returncode != 0: - raise WorkGraphBackendError(f"bd close did not succeed for {id_}", result) - work = self._inspect(id_) - if work.get("status") != "closed" or work.get("close_reason") != "project gate completed": - raise WorkGraphBackendError(f"delivery completion was not confirmed for {id_}", result) - - def finish_delivery(self, id_: str, reason: str) -> None: - work = self._inspect(id_) - if work.get("status") != "closed": - result = self.close(id_, reason) - if result.returncode != 0: - raise WorkGraphBackendError(f"bd close did not succeed for {id_}", result) - work = self._inspect(id_) - if work.get("status") != "closed": - raise WorkGraphBackendError(f"{id_} was not confirmed closed after finish", result) - if "stage:ready" in (work.get("labels") or []): - result = self.remove_ready_label(id_) - if result.returncode != 0: - raise WorkGraphBackendError(f"could not remove stage:ready from {id_}", result) - work = self._inspect(id_) - if "stage:ready" in (work.get("labels") or []): - raise WorkGraphBackendError(f"{id_} was not confirmed without stage:ready after finish", result) - result = self._runner.run(["bd", "dolt", "push"]) - if result.returncode != 0: - raise WorkGraphBackendError("bd dolt push did not succeed", result) - - def inspect(self, id_: str) -> dict[str, Any]: - return self._inspect(id_) - - def inspect_at(self, id_: str, cwd: str) -> dict[str, Any]: - return self._inspect(id_, cwd=cwd) - - def parent_cycle_would_form(self, child: str, parent: str) -> bool: - seen: set[str] = set() - current = parent - while current: - if current == child or current in seen: - return True - seen.add(current) - current = str(self._inspect(current).get("parent") or "") - return False - - def invalid_blockers_for_parent_move(self, child: str, parent: str, child_json: dict[str, Any]) -> tuple[tuple[str, str], ...]: - invalid: list[tuple[str, str]] = [] - for blocker in edge_ids(child_json, "dependencies", "blocks"): - other_parent = str(self._inspect(blocker).get("parent") or "") - if not parent or other_parent != parent: - invalid.append((child, blocker)) - for dependent in edge_ids(child_json, "dependents", "blocks"): - other_parent = str(self._inspect(dependent).get("parent") or "") - if not parent or other_parent != parent: - invalid.append((dependent, child)) - return tuple(invalid) - - def dependency_path_exists(self, start: str, target: str, seen: set[str] | None = None) -> bool: - visited = seen or set() - if start in visited: - return False - visited.add(start) - for blocker in edge_ids(self._inspect(start), "dependencies", "blocks"): - if blocker == target or self.dependency_path_exists(blocker, target, visited): - return True - return False - - def create(self, title: str, *, use_stdin: bool = False, issue_type: str = "", parent: str = "", blockers: tuple[str, ...] = ()) -> CommandResult: - args = ["bd", "create", title, "--silent"] - if use_stdin: - args.append("--stdin") - if issue_type: - args.extend(["--type", issue_type]) - if parent: - args.extend(["--parent", parent]) - for blocker in blockers: - args.extend(["--deps", blocker]) - return self._runner.run(args) - - def remove_ready_label(self, id_: str) -> CommandResult: - return self._runner.run(["bd", "update", id_, "--remove-label", "stage:ready"]) - - def set_parent(self, child: str, parent: str) -> CommandResult: - return self._runner.run(["bd", "update", child, "--parent", parent]) - - def add_blocker(self, child: str, blocker: str) -> CommandResult: - return self._runner.run(["bd", "dep", "add", child, blocker]) - - def remove_blocker(self, child: str, blocker: str) -> CommandResult: - return self._runner.run(["bd", "dep", "remove", child, blocker]) - - def claim(self, id_: str) -> CommandResult: - return self._runner.run(["bd", "update", id_, "--claim"]) - - def release(self, id_: str) -> CommandResult: - return self._runner.run(["bd", "update", id_, "--status", "open", "--assignee", ""]) - - def return_to_inbox(self, id_: str) -> CommandResult: - return self._runner.run(["bd", "update", id_, "--status", "open", "--remove-label", "stage:ready", "--assignee", ""]) - - def create_impediment(self, title: str, body: str) -> CommandResult: - return self._runner.run(["bd", "create", title, "--description", body, "--type", "impediment", "--silent"]) - - def find_by_description(self, text: str) -> Work | None: - result = self._runner.run(["bd", "search", "--desc-contains", text, "--readonly", "--json"]) - try: - data = json.loads(result.stdout or "null") - except json.JSONDecodeError as exc: - raise WorkGraphBackendError("bd search did not return valid JSON", result) from exc - if result.returncode != 0: - raise WorkGraphBackendError("bd search did not succeed", result) - if not isinstance(data, list): - raise WorkGraphBackendError("bd search did not return a Work list", result) - if not data: - return None - if not isinstance(data[0], dict): - raise WorkGraphBackendError("bd search did not return Work items", result) - return Work.from_json(data[0]) - - def create_impediment_from_file(self, title: str, body_file: str) -> CommandResult: - return self._runner.run(["bd", "create", title, "--body-file", body_file, "--type", "impediment", "--silent"]) diff --git a/docs/adr/0001-reusable-scripts-as-config-bin-executables.md b/docs/adr/0001-reusable-scripts-as-config-bin-executables.md index 4747f19..900ac9a 100644 --- a/docs/adr/0001-reusable-scripts-as-config-bin-executables.md +++ b/docs/adr/0001-reusable-scripts-as-config-bin-executables.md @@ -71,6 +71,6 @@ rejected up front — it would silently break every non-zsh caller (yazi, pi's b diverges from zsh. The retry snippet the inline function comment had carried was dropped — `bd list --ready --label stage:ready --sort priority` now lives verbatim in `bin/nextdelivery`. -- 2026-07-11: `nextdelivery` retired to a compatibility shim that execs `clerk backlog next`. - `md` remains the exemplar reusable helper in `bin/`; Clerk owns ready-pool dispatch and setup +- 2026-07-11: `nextdelivery` retired to a compatibility shim that execs `phyllary backlog next`. + `md` remains the exemplar reusable helper in `bin/`; Phyllary owns ready-pool dispatch and setup diagnosis now. diff --git a/docs/agents/domain.md b/docs/agents/domain.md index ee848b2..6d2a1d6 100644 --- a/docs/agents/domain.md +++ b/docs/agents/domain.md @@ -1,17 +1,17 @@ # Domain Docs How the engineering skills should consume this repo's domain documentation when exploring the -codebase. This repo is **multi-context**: Umbel and Clerk are documented contexts; more are added -only when they need their own vocabulary or decisions. +codebase. This repo's local documented context is Umbel; Phyllary is an external documented context. +More local contexts are added only when they need their own vocabulary or decisions. ## Before exploring, read these - **`CONTEXT-MAP.md`** at the repo root, if it exists — it points at one `CONTEXT.md` per context. Read the `CONTEXT.md` for the context you're working in. - **`<context>/CONTEXT.md`** — read the context that owns the area: currently - `umbel/CONTEXT.md` or `clerk/CONTEXT.md`. + `umbel/CONTEXT.md`, or the external Phyllary context linked from `CONTEXT-MAP.md`. - **`<context>/docs/adr/`** — read ADRs that touch the area: currently - `umbel/docs/adr/` or `clerk/docs/adr/`. System-wide decisions live at `docs/adr/`. + `umbel/docs/adr/`, or Phyllary's external ADRs. System-wide decisions live at `docs/adr/`. If any of these files don't exist, proceed silently. The producer skills create them lazily when a term or decision is actually resolved. @@ -25,9 +25,6 @@ term or decision is actually resolved. ├── umbel/ ← discovery/delivery workflow context │ ├── CONTEXT.md │ └── docs/adr/ -├── clerk/ ← workflow-verb facade context -│ ├── CONTEXT.md -│ └── docs/adr/ ``` Other dotfile areas (zsh, nvim, tmux, git, etc.) carry no domain language yet and need no @@ -35,7 +32,7 @@ Other dotfile areas (zsh, nvim, tmux, git, etc.) carry no domain language yet an ## Use the glossary's vocabulary -When your output names a domain concept — a Clerk capture title, refactor proposal, hypothesis, or +When your output names a domain concept — a Phyllary capture title, refactor proposal, hypothesis, or test name — use the term as defined in the relevant `CONTEXT.md`. Don't drift to synonyms the glossary explicitly avoids. diff --git a/docs/agents/issue-tracker.md b/docs/agents/issue-tracker.md index a6d3d20..f7c4267 100644 --- a/docs/agents/issue-tracker.md +++ b/docs/agents/issue-tracker.md @@ -1,37 +1,37 @@ -# Issue tracker: Clerk +# Issue tracker: Phyllary -Work for this repo uses a **Clerk-backed backlog** through **Clerk** (`clerk`), not GitHub +Work for this repo uses a **Phyllary-backed backlog** through **Phyllary** (`phyllary`), not GitHub Issues. Even though the remote is on GitHub, do **not** create GitHub issues for this repo's normal workflow. -Clerk is the workflow facade. Skills and agents should speak Clerk verbs only; lower-level storage +Phyllary is the workflow facade. Skills and agents should speak Phyllary verbs only; lower-level storage or tracker details belong in operator-maintenance docs, not runtime instructions. ## Lifecycle -- **Raw capture / inbox item** — created with `clerk capture "<title>"`. -- **Refinement** — inspect and shape inbox items with `clerk inbox list`, `clerk inbox show <id>`, - `clerk inbox dups`, `clerk inbox pregrill <id> ...`, `clerk inbox ready <id>`, and - `clerk inbox drop <id>`. -- **Ready for delivery** — an item promoted by `clerk inbox ready <id>`. Ready means - refinement-complete; it appears in `clerk backlog next` only when it is currently pickable. +- **Raw capture / inbox item** — created with `phyllary capture "<title>"`. +- **Refinement** — inspect and shape inbox items with `phyllary inbox list`, `phyllary inbox show <id>`, + `phyllary inbox dups`, `phyllary inbox pregrill <id> ...`, `phyllary inbox ready <id>`, and + `phyllary inbox drop <id>`. +- **Ready for delivery** — an item promoted by `phyllary inbox ready <id>`. Ready means + refinement-complete; it appears in `phyllary backlog next` only when it is currently pickable. - **Waiting backlog work** — ready but not pickable because of open blockers or open direct - children; inspect it with `clerk backlog waiting` / `clerk backlog show <id>`. + children; inspect it with `phyllary backlog waiting` / `phyllary backlog show <id>`. - **Delivery** — claim, resolve without code, submit, reconcile, or return work with - `clerk backlog ...` verbs. -- **Resolved or dropped** — Clerk records the outcome through the relevant inbox/backlog verb. + `phyllary backlog ...` verbs. +- **Resolved or dropped** — Phyllary records the outcome through the relevant inbox/backlog verb. -Run `clerk doctor` when setup or the next workflow step is unclear. +Run `phyllary doctor` when setup or the next workflow step is unclear. ## When a skill says "publish to the issue tracker" / "create an issue" -Use `clerk capture`, with a concise title and enough body/context for later refinement. Do not use +Use `phyllary capture`, with a concise title and enough body/context for later refinement. Do not use `gh issue create` for this repo. Examples: ```bash -clerk capture "two bundle seeds duplicate the same skill instructions" --stdin <<'EOF' +phyllary capture "two bundle seeds duplicate the same skill instructions" --stdin <<'EOF' While editing one bundle, another carried a near-identical copy of the same skill guidance and the two copies had already drifted. Options include factoring the shared text into one artifact or leaving the copies until drift causes a real bug. @@ -39,76 +39,76 @@ EOF ``` If the capture is already well-shaped and you are in a refinement pass, continue through -`clerk inbox ...` rather than bypassing Clerk. +`phyllary inbox ...` rather than bypassing Phyllary. ## When a skill says "fetch the relevant ticket" -Use Clerk: +Use Phyllary: -- Inbox/refinement item: `clerk inbox show <id>` -- Delivery-ready/backlog item: `clerk backlog show <id>` +- Inbox/refinement item: `phyllary inbox show <id>` +- Delivery-ready/backlog item: `phyllary backlog show <id>` -The user normally passes the Clerk ID directly. +The user normally passes the Phyllary ID directly. ## When a skill says "break this into issues" or "publish tickets" -Create one Clerk capture per vertical slice with `clerk capture`, then refine those captures through -`clerk inbox ...` until each keeper has explicit acceptance criteria and can be promoted with -`clerk inbox ready <id>`. Blocked children may still be promoted once refined; blockers affect +Create one Phyllary capture per vertical slice with `phyllary capture`, then refine those captures through +`phyllary inbox ...` until each keeper has explicit acceptance criteria and can be promoted with +`phyllary inbox ready <id>`. Blocked children may still be promoted once refined; blockers affect backlog pickability, not readiness. ## Wayfinding operations -Use Clerk's generic inbox graph primitives rather than raw tracker commands or a +Use Phyllary's generic inbox graph primitives rather than raw tracker commands or a workflow-specific namespace. Wayfinder map cheat sheet when the user names a map by title instead of ID: -1. Find and inspect the map with `clerk inbox list` and `clerk inbox show <map-id>`. -2. Work the Refinement map frontier with `clerk inbox frontier <map-id>` to see open, takeable - children. Do not use `clerk backlog next` here; that is only for delivery-ready work. -3. Claim a planning child with `clerk inbox claim <ticket-id>`. -4. Resolve non-delivery planning work with `clerk inbox resolve <ticket-id>`. -5. Update the map with `clerk inbox update <map-id> ...` after reading the current `body_guard`. +1. Find and inspect the map with `phyllary inbox list` and `phyllary inbox show <map-id>`. +2. Work the Refinement map frontier with `phyllary inbox frontier <map-id>` to see open, takeable + children. Do not use `phyllary backlog next` here; that is only for delivery-ready work. +3. Claim a planning child with `phyllary inbox claim <ticket-id>`. +4. Resolve non-delivery planning work with `phyllary inbox resolve <ticket-id>`. +5. Update the map with `phyllary inbox update <map-id> ...` after reading the current `body_guard`. Common operations: -- Create a map/epic: `clerk capture "<map title>" --type epic --stdin`. -- Create direct children: `clerk capture "<ticket title>" --parent <map-id> --type task --stdin`. +- Create a map/epic: `phyllary capture "<map title>" --type epic --stdin`. +- Create direct children: `phyllary capture "<ticket title>" --parent <map-id> --type task --stdin`. The parent may be any non-closed Work graph item, including an already-ready spec/epic. Use canonical core types (`task`, `bug`, `feature`, `epic`, `chore`, `decision`) or configured custom - types. Wayfinder ticket kind can live in the body or existing `wayfinder:<type>` labels; Clerk's + types. Wayfinder ticket kind can live in the body or existing `wayfinder:<type>` labels; Phyllary's graph semantics do not depend on those labels. -- Wire sibling blockers: `clerk inbox dep add <child> <blocker>`; remove with - `clerk inbox dep remove <child> <blocker>`. Dependency edges are only between siblings with the +- Wire sibling blockers: `phyllary inbox dep add <child> <blocker>`; remove with + `phyllary inbox dep remove <child> <blocker>`. Dependency edges are only between siblings with the same immediate parent. -- Query a map: `clerk inbox children <map-id>` for direct children, `clerk inbox frontier <map-id>` - for open, unassigned direct children whose blockers are all closed, `clerk inbox blockers <id>` - for what blocks an item, and `clerk inbox blocked <id>` for what it blocks. These query verbs - emit Clerk-owned JSON by default; add `--pretty` for formatted JSON. -- Claim a planning ticket before work with `clerk inbox claim <id>`; release an abandoned claim with - `clerk inbox release <id>`. A claimed ticket no longer appears in `clerk inbox frontier`. -- Correct parentage: `clerk inbox parent set <child> <parent>` or - `clerk inbox parent clear <child>`. If moving would leave invalid sibling-only dependency edges, +- Query a map: `phyllary inbox children <map-id>` for direct children, `phyllary inbox frontier <map-id>` + for open, unassigned direct children whose blockers are all closed, `phyllary inbox blockers <id>` + for what blocks an item, and `phyllary inbox blocked <id>` for what it blocks. These query verbs + emit Phyllary-owned JSON by default; add `--pretty` for formatted JSON. +- Claim a planning ticket before work with `phyllary inbox claim <id>`; release an abandoned claim with + `phyllary inbox release <id>`. A claimed ticket no longer appears in `phyllary inbox frontier`. +- Correct parentage: `phyllary inbox parent set <child> <parent>` or + `phyllary inbox parent clear <child>`. If moving would leave invalid sibling-only dependency edges, rerun with `--drop-invalid-deps` only when dropping those edges is intended. -- Promote after refinement: planning graph items remain inbox items until `clerk inbox ready <id>` +- Promote after refinement: planning graph items remain inbox items until `phyllary inbox ready <id>` records Acceptance criteria and marks them ready. It may promote blocked items and parents with - open children; those ready items then leave `clerk inbox list` / refinement frontier and appear in - `clerk backlog waiting` until blockers/children close. `clerk backlog next`, `claim`, and + open children; those ready items then leave `phyllary inbox list` / refinement frontier and appear in + `phyllary backlog waiting` until blockers/children close. `phyllary backlog next`, `claim`, and `resolve` only use pickable ready work: open, unclaimed, no open blockers, no open direct children. -- Record planning progress with `clerk inbox note <id> [--file <path>|--stdin]`. -- Resolve non-delivery planning items with `clerk inbox resolve <id> [--file <path>|--stdin]`; it +- Record planning progress with `phyllary inbox note <id> [--file <path>|--stdin]`. +- Resolve non-delivery planning items with `phyllary inbox resolve <id> [--file <path>|--stdin]`; it appends the resolution note and closes the inbox item without backlog promotion. Resolve a pickable ready backlog item that needs no code with - `clerk backlog resolve <id> [--returned keep|discard] [--file <path>|--stdin]`. -- Update a planning item with `clerk inbox update <id> --title "..." --type <type>`. To replace the - body, first read `body_guard` from `clerk inbox show <id> --json`, then pass it with + `phyllary backlog resolve <id> [--returned keep|discard] [--file <path>|--stdin]`. +- Update a planning item with `phyllary inbox update <id> --title "..." --type <type>`. To replace the + body, first read `body_guard` from `phyllary inbox show <id> --json`, then pass it with `--body-guard <guard>` alongside `--body-file <path>` or `--stdin`. Do not create GitHub Issues. Do not use lower-level tracker commands in normal agent workflow. ## Triage state -See `docs/agents/triage-labels.md` for how Matt Pocock's canonical triage roles map to Clerk +See `docs/agents/triage-labels.md` for how Matt Pocock's canonical triage roles map to Phyllary inbox/backlog dispositions. diff --git a/docs/agents/pi-setup-survey.md b/docs/agents/pi-setup-survey.md index 0fdf983..2ad3bc2 100644 --- a/docs/agents/pi-setup-survey.md +++ b/docs/agents/pi-setup-survey.md @@ -68,7 +68,7 @@ the corrections are kept inline so a future reader isn't misled. Project-level `.pi/prompts/*.md`, declarative only. Most relevant: - **`/wr` → `/deliver`** — context-aware wrap (changelog + commit + push), - `[instructions]` arg. Mirrors this repo's `clerk`/`nextdelivery`/ + `[instructions]` arg. Mirrors this repo's `phyllary`/`nextdelivery`/ `dotfiles-dft.N` gate as one command. Highest fit. - **`/pr <PR-URL>`** — review a PR by URL without checking out (files-only via `gh pr diff` + `git show <ref>:<path>`). Matches the no-`gh pr checkout` diff --git a/docs/agents/triage-labels.md b/docs/agents/triage-labels.md index 6631613..6675e78 100644 --- a/docs/agents/triage-labels.md +++ b/docs/agents/triage-labels.md @@ -1,19 +1,19 @@ # Triage Labels -This repo tracks work through **Clerk**, so Matt Pocock's five canonical triage roles map to Clerk +This repo tracks work through **Phyllary**, so Matt Pocock's five canonical triage roles map to Phyllary inbox/backlog dispositions rather than GitHub labels. -| Canonical role (mattpocock/skills) | Clerk mechanism | +| Canonical role (mattpocock/skills) | Phyllary mechanism | | ---------------------------------- | --------------- | -| `needs-triage` | An item shown by `clerk inbox list`: raw captured work that has not yet been promoted. | +| `needs-triage` | An item shown by `phyllary inbox list`: raw captured work that has not yet been promoted. | | `needs-info` | Keep it in the inbox. Record the missing external fact in the item body, a pregrill note, or the refinement output; do not promote until the fact is available. | -| `ready-for-agent` | `clerk inbox ready <id>` after refinement has named the work and explicit acceptance criteria. Pickable work appears in `clerk backlog next`; blocked ready work appears in `clerk backlog waiting`. | +| `ready-for-agent` | `phyllary inbox ready <id>` after refinement has named the work and explicit acceptance criteria. Pickable work appears in `phyllary backlog next`; blocked ready work appears in `phyllary backlog waiting`. | | `ready-for-human` | Not a separate track in this repo. Keep it in the inbox when human judgment is still needed; use pregrill/refinement notes to state the decision. | -| `wontfix` | `clerk inbox drop <id>` with the reason. | +| `wontfix` | `phyllary inbox drop <id>` with the reason. | -When a skill mentions applying a triage label, perform the corresponding Clerk disposition above. +When a skill mentions applying a triage label, perform the corresponding Phyllary disposition above. The most important boundary is **inbox vs delivery-ready**: do not call something `ready-for-agent` -until `clerk inbox ready` can record acceptance criteria. +until `phyllary inbox ready` can record acceptance criteria. -If setup or the next workflow step is unclear, run `clerk doctor` rather than dropping to lower-level +If setup or the next workflow step is unclear, run `phyllary doctor` rather than dropping to lower-level tracker commands. diff --git a/mise/config.toml b/mise/config.toml index 62c72c0..1f8fc5b 100644 --- a/mise/config.toml +++ b/mise/config.toml @@ -33,8 +33,8 @@ uv = "latest" "pipx:markitdown" = { version = "latest", extras = "pdf,docx,pptx,xlsx" } actionlint = "latest" # python — pinned because without it the mise shim shadows every `python3` with -# macOS's system 3.9.6. Clerk is what made this visible: its launcher gates on -# >=3.11 and was exiting 4 on every invocation, so `clerk` did nothing on the Mac +# macOS's system 3.9.6. Phyllary is what made this visible: its launcher gates on +# >=3.11 and was exiting 4 on every invocation, so `phyllary` did nothing on the Mac # while still *looking* healthy — an abort that returns in ~100ms reads like a # fast success, and it silently poisoned a performance comparison against devbox # for two rounds. 3.13 over 3.14: it's already installed on both boxes. diff --git a/clerk/project-gate b/phyllary/project-gate similarity index 53% rename from clerk/project-gate rename to phyllary/project-gate index 63d150b..f45bae5 100755 --- a/clerk/project-gate +++ b/phyllary/project-gate @@ -7,22 +7,9 @@ operation=${1:-} request=$(cat) worktree=$(printf '%s' "$request" | jq -er '.delivery.worktree') -cpus=$(getconf _NPROCESSORS_ONLN 2>/dev/null || printf '1') -case "$cpus" in - "" | *[!0-9]*) cpus=1 ;; -esac -jobs=$((cpus / 2)) -[ "$jobs" -ge 1 ] || jobs=1 - -if command -v parallel >/dev/null 2>&1 || command -v rush >/dev/null 2>&1; then - bats_command=(bats --jobs "$jobs" tests/clerk) -else - bats_command=(bats tests/clerk) -fi - -if (cd "$worktree" && "${bats_command[@]}" && shellcheck -S error bin/*) >&2; then +if (cd "$worktree" && bats tests/phyllary && shellcheck -S error bin/* phyllary/project-gate) >&2; then status=passed - summary='bats tests/clerk and shellcheck -S error bin/* passed' + summary='bats tests/phyllary and shellcheck passed' else status=failed summary='dotfiles validation commands failed' diff --git a/phyllary/project-gate.json b/phyllary/project-gate.json new file mode 100644 index 0000000..28ce542 --- /dev/null +++ b/phyllary/project-gate.json @@ -0,0 +1,4 @@ +{ + "adapter": "phyllary/project-gate", + "submission_owner": "phyllary" +} diff --git a/pi/agent/extensions/clerk-implement/.gitignore b/pi/agent/extensions/phyllary-implement/.gitignore similarity index 100% rename from pi/agent/extensions/clerk-implement/.gitignore rename to pi/agent/extensions/phyllary-implement/.gitignore diff --git a/pi/agent/extensions/clerk-implement/index.ts b/pi/agent/extensions/phyllary-implement/index.ts similarity index 59% rename from pi/agent/extensions/clerk-implement/index.ts rename to pi/agent/extensions/phyllary-implement/index.ts index bee8351..376413b 100644 --- a/pi/agent/extensions/clerk-implement/index.ts +++ b/pi/agent/extensions/phyllary-implement/index.ts @@ -5,25 +5,25 @@ import { dirname } from "node:path"; const NO_WORK_ID = "no Work ID supplied"; function buildWorkflowPrompt(workId: string): string { - return `Implement Clerk Backlog Work (${workId}). + return `Implement Phyllary Backlog Work (${workId}). -Follow this repo's Clerk workflow: +Follow this repo's Phyllary workflow: -1. Run \`clerk doctor\` if setup or the next workflow step is unclear. +1. Run \`phyllary doctor\` if setup or the next workflow step is unclear. 2. Resolve exactly one pickable Work item: - - If no Work ID was supplied, run \`clerk backlog next\`, choose one item, and inspect it with \`clerk backlog show <id>\`. - - Otherwise, treat the supplied argument (\`${workId}\`) as one pickable Work ID and inspect it with \`clerk backlog show <id>\`. + - If no Work ID was supplied, run \`phyllary backlog next\`, choose one item, and inspect it with \`phyllary backlog show <id>\`. + - Otherwise, treat the supplied argument (\`${workId}\`) as one pickable Work ID and inspect it with \`phyllary backlog show <id>\`. - Epic or parent IDs, multiple IDs, and free-form scope are unsupported. Stop rather than trying to resolve or guess them. - - Let Clerk determine pickability. Do not infer it independently from ready state, parent/child state, or blockers. -3. Claim the Work item with \`clerk backlog claim <id>\`. + - Let Phyllary determine pickability. Do not infer it independently from ready state, parent/child state, or blockers. +3. Claim the Work item with \`phyllary backlog claim <id>\`. 4. Change directory to the authoritative worktree path printed on the final line by Claim. Do not construct or guess the path. -5. Implement only that Work item and satisfy its Acceptance criteria; use TDD/test-first where practical. Record unrelated discoveries with \`clerk capture\` instead of expanding scope. +5. Implement only that Work item and satisfy its Acceptance criteria; use TDD/test-first where practical. Record unrelated discoveries with \`phyllary capture\` instead of expanding scope. 6. Run the relevant checks/tests and commit the work to the current delivery branch. 7. Use \`/skill:code-review\` or the code-review skill to review the completed diff against the fixed point \`origin/main\` before submit. -8. Submit with exactly \`clerk backlog submit <id>\`. -9. If the Project gate is pending, repeat \`clerk backlog gate <id>\` until it reaches a terminal result. If it fails, repair, verify, review, commit, and submit again. -10. Run \`clerk backlog finish <id>\` only when Submission ownership is \`clerk\` and Clerk owns a submitted PR. -11. If the Work item is impossible as refined, use \`clerk backlog return <id> --reason "..."\` rather than improvising scope.`; +8. Submit with exactly \`phyllary backlog submit <id>\`. +9. If the Project gate is pending, repeat \`phyllary backlog gate <id>\` until it reaches a terminal result. If it fails, repair, verify, review, commit, and submit again. +10. Run \`phyllary backlog finish <id>\` only when Submission ownership is \`phyllary\` and Phyllary owns a submitted PR. +11. If the Work item is impossible as refined, use \`phyllary backlog return <id> --reason "..."\` rather than improvising scope.`; } function expandSkill(command: SlashCommandInfo): string { @@ -39,14 +39,14 @@ ${body} } export default function (pi: ExtensionAPI) { - pi.registerCommand("clerk-implement", { - description: "Run the implement skill with this repo's Clerk backlog workflow", + pi.registerCommand("phyllary-implement", { + description: "Run the implement skill with this repo's Phyllary backlog workflow", handler: async (args, ctx) => { const implementSkill = pi .getCommands() .find((command) => command.name === "skill:implement" && command.source === "skill"); if (!implementSkill) { - ctx.ui.notify("The implement skill is not loaded; cannot run Clerk implement workflow.", "error"); + ctx.ui.notify("The implement skill is not loaded; cannot run Phyllary implement workflow.", "error"); return; } diff --git a/tests/clerk/backlog-read.bats b/tests/clerk/backlog-read.bats deleted file mode 100644 index 73ef353..0000000 --- a/tests/clerk/backlog-read.bats +++ /dev/null @@ -1,296 +0,0 @@ -#!/usr/bin/env bats -# backlog-read.bats — clerk backlog next + backlog show (unit dotfiles-dft.3, read group). -# -# Printed output is load-bearing (ADR 0015), so these tests assert verbatim lines, not just -# exit codes. bd-backed verbs run against a SCRATCH bd db created fresh per test in the bats -# tmp dir (never this repo's real .beads); gh-backed verbs run against a FAKE `gh` placed -# earlier on PATH that logs its argv and returns canned output (same double pattern -# inbox.bats uses). PATH deliberately excludes this repo's personal ~/.config/bin/bd -# auto-sync shim (ADR 0013) — see inbox.bats's header for the rationale. - -setup() { - source "$BATS_TEST_DIRNAME/helpers.bash" - git_sandbox - CLERK="$BATS_TEST_DIRNAME/../../bin/clerk" - # Excludes ~/.config/bin (the ADR 0013 auto-sync shim) on purpose — see header comment. - BD_MIN_PATH="/usr/local/bin:/usr/bin:/bin" - REAL_BD=$(PATH="$BD_MIN_PATH" command -v bd 2>/dev/null || command -v bd) - export PATH="$BD_MIN_PATH" -} - -# ---------------------------------------------------------------- fixtures -- - -# Scratch git repo + `.clerk` (backlog: bd) + a fresh scratch bd db (never this repo's real -# .beads). Echoes the physical path. -make_bd_repo() { # $1 = subdir name - local dir="$BATS_TEST_TMPDIR/$1" - mkdir -p "$dir" - dir="$(cd "$dir" && pwd -P)" - git init -q -b main "$dir" - printf 'backlog: bd\n' >"$dir/.clerk" - git -C "$dir" add -A - git -C "$dir" -c user.email=clerk@test -c user.name=clerk commit -q -m fixture - (cd "$dir" && bd init -q --non-interactive --skip-hooks --skip-agents >/dev/null 2>&1) - printf '%s\n' "$dir" -} - -add_origin() { # $1 = repo - local repo="$1" origin="$BATS_TEST_TMPDIR/origin-$(basename "$repo").git" - git init -q --bare -b main "$origin" - git -C "$repo" remote add origin "$origin" - git -C "$repo" push -q origin main -} - -mk_returned_attempt() { # $1=repo $2=short $3=subject - local repo="$1" short="$2" subject="$3" wt="$BATS_TEST_TMPDIR/backlog-returned-$short-$RANDOM" - git -C "$repo" branch "returned/$short" main - git -C "$repo" worktree add -q "$wt" "returned/$short" - printf 'returned work\n' >"$wt/returned.txt" - git -C "$wt" add returned.txt - git -C "$wt" -c user.email=clerk@test -c user.name=clerk commit -q -m "$subject" - git -C "$repo" worktree remove "$wt" >/dev/null - git -C "$repo" push -q origin "returned/$short" -} - -advance_main() { # $1=repo - local repo="$1" - printf 'new main\n' >"$repo/main.txt" - git -C "$repo" add main.txt - git -C "$repo" -c user.email=clerk@test -c user.name=clerk commit -q -m "advance main" - git -C "$repo" push -q origin main 2>/dev/null || true -} - -# Scratch git repo + `.clerk` (backlog: gh); no bd involved at all. -make_gh_repo() { # $1 = subdir name - local dir="$BATS_TEST_TMPDIR/$1" - mkdir -p "$dir" - dir="$(cd "$dir" && pwd -P)" - git init -q -b main "$dir" - printf 'backlog: gh\n' >"$dir/.clerk" - git -C "$dir" add -A - git -C "$dir" -c user.email=clerk@test -c user.name=clerk commit -q -m fixture - printf '%s\n' "$dir" -} - -# A fake `gh` that logs every invocation's argv to $FAKE_GH_LOG (\x1f-joined per call, -# ===CALL=== delimited) and returns canned output driven by $FAKE_GH_LIST_JSON. -make_fake_gh() { # $1 = dir to place the fake gh - mkdir -p "$1" - cat >"$1/gh" <<'SHIM' -#!/bin/sh -{ - printf '===CALL===\n' - for a in "$@"; do printf '%s\x1f' "$a"; done - printf '\n' -} >>"$FAKE_GH_LOG" -case "$1 $2" in - "issue list") - if [ -n "${FAKE_GH_LIST_JSON:-}" ] && [ -f "$FAKE_GH_LIST_JSON" ]; then - cat "$FAKE_GH_LIST_JSON" - else - printf '[]' - fi - ;; - "issue view") - printf 'fake gh issue view: %s\n' "$3" - ;; - *) - printf 'fake-gh: unhandled: %s\n' "$*" >&2 - exit 1 - ;; -esac -SHIM - chmod +x "$1/gh" -} - -# A `bd` fork that logs every invocation's argv verbatim to $BD_TRACE_LOG (one line per call, -# \x1f-joined) then always proxies through to the real bd — used to assert the read verbs -# invoke bd with --readonly, without changing behaviour. -make_traced_bd() { # $1 = dir to place the shim - mkdir -p "$1" - cat >"$1/bd" <<SHIM -#!/bin/sh -{ - for a in "\$@"; do printf '%s\\x1f' "\$a"; done - printf '\\n' -} >>"\$BD_TRACE_LOG" -exec "$REAL_BD" "\$@" -SHIM - chmod +x "$1/bd" -} - -# A unit with a real Acceptance Criteria section. Echoes the created id. -mk_ac_unit() { # $1 = title - bd create "$1" --description '## Acceptance Criteria -- does the thing' --silent -} - -# -------------------------------------------------------------- backlog next - - -@test "backlog next (bd): includes ready Work and excludes non-ready, closed, and missing-criteria Work; bd invoked with --readonly" { - repo=$(make_bd_repo next1) - tracedbin="$BATS_TEST_TMPDIR/next1-tracedbin" - make_traced_bd "$tracedbin" - export BD_TRACE_LOG="$BATS_TEST_TMPDIR/next1.trace" - : >"$BD_TRACE_LOG" - export PATH="$tracedbin:$PATH" - cd "$repo" - ready_id=$(mk_ac_unit "ready and unblocked") - bd update "$ready_id" --add-label stage:ready >/dev/null - missing_id=$(bd create "ready label but no criteria" --silent) - bd update "$missing_id" --add-label stage:ready >/dev/null - notready_id=$(bd create "still in the inbox" --silent) - closed_id=$(bd create "long done" --silent) - bd close "$closed_id" --reason wontfix >/dev/null - - run "$CLERK" backlog next - [ "$status" -eq 0 ] - [[ "$output" == "Backlog (ready) — 1 item(s): - $ready_id ready ready and unblocked" ]] - [[ "$output" != *"$missing_id"* ]] - [[ "$output" != *"$notready_id"* ]] - [[ "$output" != *"$closed_id"* ]] - grep -q -- '--readonly' "$BD_TRACE_LOG" -} - -@test "backlog next (bd): marks an otherwise-pickable returned attempt without changing the pool" { - repo=$(make_bd_repo next_returned) - add_origin "$repo" - cd "$repo" - normal=$(mk_ac_unit "normal Work") - returned=$(mk_ac_unit "returned Work") - bd update "$normal" --add-label stage:ready >/dev/null - bd update "$returned" --add-label stage:ready >/dev/null - short="${returned#*-}" - mk_returned_attempt "$repo" "$short" "returned backlog work" - - run "$CLERK" backlog next - [ "$status" -eq 0 ] - [[ "$output" == "Backlog (ready) — 2 item(s):"$'\n'* ]] - [[ "$output" == *" $normal ready normal Work"* ]] - [[ "$output" == *" $returned returned returned Work"* ]] -} - -@test "backlog next and waiting split pickable ready work from blocked-ready graph work" { - repo=$(make_bd_repo next_waiting) - cd "$repo" - pickable=$(mk_ac_unit "pickable") - blocked=$(mk_ac_unit "blocked ready") - claimed=$(mk_ac_unit "claimed ready") - blocker=$(bd create "blocker" --silent) - parent=$(bd create "ready parent" --acceptance "parent ac" --silent) - child=$(bd create "open child" --parent "$parent" --silent) - bd update "$pickable" --add-label stage:ready >/dev/null - bd update "$blocked" --add-label stage:ready >/dev/null - bd update "$parent" --add-label stage:ready >/dev/null - bd update "$claimed" --add-label stage:ready --claim >/dev/null - bd dep add "$blocked" "$blocker" >/dev/null - - run "$CLERK" backlog next - [ "$status" -eq 0 ] - [[ "$output" == *"$pickable ready pickable"* ]] - ! grep -F -q " $blocked " <<<"$output" - ! grep -F -q " $claimed " <<<"$output" - ! grep -F -q " $parent " <<<"$output" - - run "$CLERK" backlog waiting - [ "$status" -eq 0 ] - [[ "$output" == *"$blocked blockers:1 children:0 blocked ready"* ]] - [[ "$output" == *"$parent blockers:0 children:1 ready parent"* ]] - [[ "$output" != *"$pickable"* ]] -} - -@test "backlog next (bd): empty ready pool prints (empty)" { - repo=$(make_bd_repo next2) - cd "$repo" - bd create "still in the inbox" --silent >/dev/null - run "$CLERK" backlog next - [ "$status" -eq 0 ] - [ "$output" = "Backlog (ready) — 0 item(s): - (empty)" ] -} - -@test "backlog next (gh): lists ready-for-agent issues, invoking gh with --label ready-for-agent" { - repo=$(make_gh_repo next3) - fakebin="$BATS_TEST_TMPDIR/next3-fakebin" - make_fake_gh "$fakebin" - export FAKE_GH_LOG="$BATS_TEST_TMPDIR/next3.log" - : >"$FAKE_GH_LOG" - export FAKE_GH_LIST_JSON="$BATS_TEST_TMPDIR/next3.json" - printf '[{"number":9,"title":"do the thing"}]' >"$FAKE_GH_LIST_JSON" - export PATH="$fakebin:$PATH" - cd "$repo" - run "$CLERK" backlog next - [ "$status" -eq 0 ] - [ "$output" = "Backlog (ready) — 1 item(s): - #9 ready do the thing" ] - grep -F -q -- 'issue\x1flist\x1f--label\x1fready-for-agent' "$FAKE_GH_LOG" -} - -# -------------------------------------------------------------- backlog show - - -@test "backlog show (bd): passes the id through to bd show, invoking bd with --readonly" { - repo=$(make_bd_repo show1) - tracedbin="$BATS_TEST_TMPDIR/show1-tracedbin" - make_traced_bd "$tracedbin" - export BD_TRACE_LOG="$BATS_TEST_TMPDIR/show1.trace" - : >"$BD_TRACE_LOG" - export PATH="$tracedbin:$PATH" - cd "$repo" - id=$(bd create "look at the backlog" --silent) - run "$CLERK" backlog show "$id" - [ "$status" -eq 0 ] - [[ "$output" == *"$id"*"look at the backlog"* ]] - grep -q -- '--readonly' "$BD_TRACE_LOG" -} - -@test "backlog show (bd): returned attempt banner points to backlog delivery choices" { - repo=$(make_bd_repo show_returned_backlog) - add_origin "$repo" - cd "$repo" - id=$(bd create "returned backlog show unit" --silent) - short="${id#*-}" - mk_returned_attempt "$repo" "$short" "backlog returned subject" - advance_main "$repo" - - run "$CLERK" backlog show "$id" - [ "$status" -eq 0 ] - [[ "$output" == *"returned attempt: returned/$short"* ]] - [[ "$output" == *"1 commit(s) behind main"* ]] - [[ "$output" == *"subject: backlog returned subject"* ]] - [[ "$output" == *"reuse via: clerk backlog claim $id --from-returned"* ]] - [[ "$output" == *"fresh via: clerk backlog claim $id --fresh --returned keep|discard"* ]] - [[ "$output" != *"dispose via: clerk inbox"* ]] -} - -@test "backlog show (bd): no returned attempt is an exact passthrough" { - repo=$(make_bd_repo show_no_returned_backlog) - cd "$repo" - id=$(bd create "plain backlog show unit" --silent) - expected=$(bd show "$id" --readonly) - run "$CLERK" backlog show "$id" - [ "$status" -eq 0 ] - [ "$output" = "$expected" ] - [[ "$output" != *"returned attempt"* ]] -} - -@test "backlog show: missing id is a usage error, exit 2" { - repo=$(make_bd_repo show2) - cd "$repo" - run "$CLERK" backlog show - [ "$status" -eq 2 ] - [ "$output" = 'clerk backlog show: missing id — usage: clerk backlog show <id>' ] -} - -@test "backlog show (gh): passes the id through to gh issue view" { - repo=$(make_gh_repo show3) - fakebin="$BATS_TEST_TMPDIR/show3-fakebin" - make_fake_gh "$fakebin" - export FAKE_GH_LOG="$BATS_TEST_TMPDIR/show3.log" - : >"$FAKE_GH_LOG" - export PATH="$fakebin:$PATH" - cd "$repo" - run "$CLERK" backlog show 7 - [ "$status" -eq 0 ] - [ "$output" = "fake gh issue view: 7" ] -} diff --git a/tests/clerk/backlog-resolve.bats b/tests/clerk/backlog-resolve.bats deleted file mode 100644 index 7401e3f..0000000 --- a/tests/clerk/backlog-resolve.bats +++ /dev/null @@ -1,113 +0,0 @@ -#!/usr/bin/env bats -# backlog-resolve.bats — no-code completion for pickable ready work. - -setup() { - source "$BATS_TEST_DIRNAME/helpers.bash" - git_sandbox - CLERK="$BATS_TEST_DIRNAME/../../bin/clerk" - BD_MIN_PATH="/usr/local/bin:/usr/bin:/bin" - export PATH="$BD_MIN_PATH" -} - -make_bd_repo() { # $1 = subdir name - local base="$BATS_TEST_TMPDIR/$1" origin clone - mkdir -p "$base" - origin="$base/origin.git" - clone="$base/clone" - git init -q --bare -b main "$origin" - git init -q -b main "$clone" - clone="$(cd "$clone" && pwd -P)" - git -C "$clone" config user.email clerk@test - git -C "$clone" config user.name clerk - git -C "$clone" remote add origin "$origin" - printf 'backlog: bd\n' >"$clone/.clerk" - git -C "$clone" add -A - git -C "$clone" commit -q -m fixture - git -C "$clone" push -q origin main - (cd "$clone" && bd init -q --non-interactive --skip-hooks --skip-agents >/dev/null 2>&1) - printf '%s\n' "$clone" -} - -mk_ready_unit() { # $1=title - local id - id=$(bd create "$1" --acceptance "- satisfied" --silent) - bd update "$id" --add-label stage:ready >/dev/null - printf '%s\n' "$id" -} - -seed_returned_attempt() { # $1=repo $2=short - local repo="$1" short="$2" wt="$BATS_TEST_TMPDIR/returned-$short" - git -C "$repo" branch "returned/$short" main - git -C "$repo" worktree add -q "$wt" "returned/$short" - printf 'returned\n' >"$wt/returned.txt" - git -C "$wt" add returned.txt - git -C "$wt" commit -q -m returned-attempt - git -C "$repo" worktree remove "$wt" >/dev/null - git -C "$repo" push -q origin "returned/$short" -} - -@test "backlog resolve closes a pickable ready unit with a distinct no-code reason and note" { - repo=$(make_bd_repo resolve_ok) - cd "$repo" - id=$(mk_ready_unit "no code needed") - printf 'verified externally' >resolution.txt - - run "$CLERK" backlog resolve "$id" --file resolution.txt - [ "$status" -eq 0 ] - [ "$output" = "clerk: resolved $id without delivery" ] - json=$(bd show "$id" --readonly --json) - [ "$(jq -r '.[0].status' <<<"$json")" = closed ] - [ "$(jq -r '.[0].close_reason' <<<"$json")" = "resolved without delivery" ] - [[ "$(jq -r '.[0].notes' <<<"$json")" == *"clerk-backlog-resolution:"* ]] - [[ "$(jq -r '.[0].notes' <<<"$json")" == *"verified externally"* ]] -} - -@test "backlog resolve refuses non-pickable and claimed ready units consistently with backlog next" { - repo=$(make_bd_repo resolve_not_pickable) - cd "$repo" - blocked=$(mk_ready_unit "blocked resolve") - blocker=$(bd create "open blocker" --silent) - claimed=$(mk_ready_unit "claimed resolve") - bd dep add "$blocked" "$blocker" >/dev/null - bd update "$claimed" --claim --actor other-agent >/dev/null - - run "$CLERK" backlog next - [ "$status" -eq 0 ] - [[ "$output" != *"$blocked"* ]] - [[ "$output" != *"$claimed"* ]] - - run bash -c 'printf "note" | "$1" backlog resolve "$2"' _ "$CLERK" "$blocked" - [ "$status" -eq 2 ] - [[ "$output" == *"not pickable"* ]] - [[ "$output" == *"open blocker"* ]] - - run bash -c 'printf "note" | "$1" backlog resolve "$2"' _ "$CLERK" "$claimed" - [ "$status" -eq 2 ] - [[ "$output" == *"not pickable"* ]] - [[ "$output" == *"claimed by other-agent"* ]] -} - -@test "backlog resolve requires criteria, non-empty note, and returned branch disposition" { - repo=$(make_bd_repo resolve_guards) - cd "$repo" - no_ac=$(bd create "no ac" --labels stage:ready --silent) - id=$(mk_ready_unit "returned resolve") - short="${id#*-}" - seed_returned_attempt "$repo" "$short" - - run bash -c 'printf "note" | "$1" backlog resolve "$2"' _ "$CLERK" "$no_ac" - [ "$status" -eq 2 ] - [[ "$output" == *"no 'Acceptance Criteria'"* ]] - - run "$CLERK" backlog resolve "$id" --file missing.txt - [ "$status" -eq 2 ] - [[ "$output" == *"returned/$short exists"* ]] - - run bash -c 'printf " " | "$1" backlog resolve "$2" --returned keep' _ "$CLERK" "$id" - [ "$status" -eq 2 ] - [[ "$output" == *"note text must be non-empty"* ]] - - run bash -c 'printf "kept evidence" | "$1" backlog resolve "$2" --returned keep' _ "$CLERK" "$id" - [ "$status" -eq 0 ] - git -C "$repo" show-ref --verify --quiet "refs/heads/returned/$short" -} diff --git a/tests/clerk/claim.bats b/tests/clerk/claim.bats deleted file mode 100644 index 325effd..0000000 --- a/tests/clerk/claim.bats +++ /dev/null @@ -1,442 +0,0 @@ -#!/usr/bin/env bats -# claim.bats — clerk backlog claim (unit dotfiles-dft.3). -# -# Printed output is load-bearing (ADR 0015), so these tests assert verbatim lines (the two -# OFFLINE strings are asserted byte-for-byte per the ratified contract), not just exit codes. -# The claim lock is a real git push-CAS, so every fixture is a SCRATCH BARE git repo used as -# 'origin' plus a clone (never this repo's real origin), with its own scratch bd db (never -# this repo's real .beads). PATH deliberately excludes this repo's personal ~/.config/bin/bd -# auto-sync shim (ADR 0013) — same rationale as inbox.bats. - -setup() { - source "$BATS_TEST_DIRNAME/helpers.bash" - git_sandbox - CLERK="$BATS_TEST_DIRNAME/../../bin/clerk" - BD_MIN_PATH="/usr/local/bin:/usr/bin:/bin" - export PATH="$BD_MIN_PATH" -} - -# ---------------------------------------------------------------- fixtures -- - -# A scratch bare git repo as 'origin' plus a working repo with a committed `.clerk` -# (backlog: bd) marker and a fresh scratch bd db. Git identity is pinned to a fixed, -# known actor ("clerk") so bd's default --claim assignee is predictable across tests. -# Echoes the working repo's physical path. -make_claim_repo() { # $1 = subdir name - local base="$BATS_TEST_TMPDIR/$1" origin="" clone="" - mkdir -p "$base" - origin="$base/origin.git" - clone="$base/clone" - git init -q --bare -b main "$origin" - git init -q -b main "$clone" - clone="$(cd "$clone" && pwd -P)" - git -C "$clone" config user.email clerk@test - git -C "$clone" config user.name clerk - git -C "$clone" remote add origin "$origin" - printf 'backlog: bd\n' >"$clone/.clerk" - git -C "$clone" add -A - git -C "$clone" commit -q -m fixture - git -C "$clone" push -q origin main - (cd "$clone" && bd init -q --non-interactive --skip-hooks --skip-agents >/dev/null 2>&1) - printf '%s\n' "$clone" -} - -# A unit with a real Acceptance Criteria section (C4 must pass). Echoes the created id. -mk_ac_unit() { # $1 = title - local id - id=$(bd create "$1" --description '## Acceptance Criteria -- does the thing' --silent) - bd update "$id" --add-label stage:ready >/dev/null - printf '%s\n' "$id" -} - -track_beads_config() { # $1 = repo - local repo="$1" - git -C "$repo" rm --cached -q --ignore-unmatch .beads/metadata.json - git -C "$repo" commit -q -m 'track beads config' - git -C "$repo" push -q origin main -} - -# Points `origin` at a path that will never resolve, so `git fetch origin` fails immediately -# (no network hang) — the OFFLINE signal. -break_origin() { # $1 = repo - git -C "$1" remote set-url origin "$1-gone-nonexistent" -} - -seed_returned_attempt() { # $1=repo $2=short $3=file $4=content $5=subject - local repo="$1" short="$2" file="$3" content="$4" subject="$5" wt - git -C "$repo" branch "returned/$short" origin/main - wt="$BATS_TEST_TMPDIR/returned-$short-$RANDOM" - git -C "$repo" worktree add -q "$wt" "returned/$short" - printf '%s\n' "$content" >"$wt/$file" - git -C "$wt" add "$file" - git -C "$wt" commit -q -m "$subject" - git -C "$repo" worktree remove "$wt" >/dev/null - git -C "$repo" push -q origin "returned/$short" -} - -advance_main() { # $1=repo $2=file $3=content $4=subject - local repo="$1" file="$2" content="$3" subject="$4" - printf '%s\n' "$content" >"$repo/$file" - git -C "$repo" add "$file" - git -C "$repo" commit -q -m "$subject" - git -C "$repo" push -q origin main -} - -# ------------------------------------------------------------------- claim -- - -@test "claim (bd): success prints the ABSOLUTE worktree path as the LAST line; worktree and pushed branch exist; bd claim recorded" { - repo=$(make_claim_repo claim_a) - cd "$repo" - id=$(mk_ac_unit "unit A") - short="${id#*-}" - run "$CLERK" backlog claim "$id" - [ "$status" -eq 0 ] - [ "${lines[-1]}" = "$repo/.worktrees/$short" ] - [ -d "$repo/.worktrees/$short" ] - git -C "$repo" fetch -q origin - git -C "$repo" show-ref --verify --quiet "refs/remotes/origin/delivery/$short" - [ "$(bd show "$id" --readonly --json | jq -r '.[0].assignee')" = clerk ] - [ "$(bd show "$id" --readonly --json | jq -r '.[0].status')" = in_progress ] -} - -@test "claim (bd): bootstraps worktree-local Beads metadata before reporting ready" { - repo=$(make_claim_repo claim_bootstrap) - track_beads_config "$repo" - cd "$repo" - id=$(mk_ac_unit "bootstrapped unit") - short="${id#*-}" - - run "$CLERK" backlog claim "$id" - [ "$status" -eq 0 ] - wt="${lines[-1]}" - [ "$wt" = "$repo/.worktrees/$short" ] - [ -f "$wt/.beads/metadata.json" ] - cmp "$repo/.beads/metadata.json" "$wt/.beads/metadata.json" - run git -C "$wt" ls-files --error-unmatch .beads/metadata.json - [ "$status" -ne 0 ] - run bash -c 'cd "$1" && "$2" backlog show "$3"' -- "$wt" "$CLERK" "$id" - [ "$status" -eq 0 ] -} - -@test "claim (bd): a failed worktree Beads bootstrap fails without reporting ready" { - repo=$(make_claim_repo claim_bootstrap_failure) - track_beads_config "$repo" - cd "$repo" - id=$(mk_ac_unit "bootstrap failure unit") - short="${id#*-}" - fake="$BATS_TEST_TMPDIR/fake-bin" - real_python=$(command -v python3) - mkdir -p "$fake" - cat >"$fake/python" <<EOF -#!/usr/bin/env bash -if [ "\$1" = - ]; then - exec "$real_python" "\$@" -fi -shift 2 -exec "$real_python" -c 'import shutil, sys; shutil.copyfile = lambda *_: (_ for _ in ()).throw(OSError()); from clerk.cli import main; raise SystemExit(main(sys.argv[1:]))' "\$@" -EOF - chmod +x "$fake/python" - - run env CLERK_PYTHON="$fake/python" "$CLERK" backlog claim "$id" - [ "$status" -eq 5 ] - [[ "$output" == *"could not provision or verify the worktree"* ]] - [[ "$output" != *"worktree ready"* ]] - [ ! -f "$repo/.worktrees/$short/.beads/metadata.json" ] -} - -@test "claim (bd): OCCUPIED — exit 5, names the holder, no orphan worktree, no bd mutation on our side" { - repo=$(make_claim_repo claim_b) - cd "$repo" - id=$(mk_ac_unit "unit B") - short="${id#*-}" - # Deterministic pre-occupied fixture: push delivery/<short> to origin AND set the scratch - # bead's assignee to a different holder, both BEFORE our claim call. - base=$(git -C "$repo" rev-parse origin/main) - git -C "$repo" push -q origin "$base:refs/heads/delivery/$short" - bd update "$id" --claim --actor other-agent >/dev/null - run "$CLERK" backlog claim "$id" - [ "$status" -eq 5 ] - [[ "$output" == *"other-agent"* ]] - [ ! -d "$repo/.worktrees/$short" ] - ! git -C "$repo" show-ref --verify --quiet "refs/heads/delivery/$short" - [ "$(bd show "$id" --readonly --json | jq -r '.[0].assignee')" = other-agent ] - [ "$(bd show "$id" --readonly --json | jq -r '.[0].status')" = in_progress ] -} - -@test "claim (bd): OFFLINE attended — exact LOCAL-ONLY warning, path last line, no push" { - repo=$(make_claim_repo claim_c) - cd "$repo" - id=$(mk_ac_unit "unit C") - short="${id#*-}" - break_origin "$repo" - run env CI= "$CLERK" backlog claim "$id" - [ "$status" -eq 0 ] - [ "${lines[-1]}" = "$repo/.worktrees/$short" ] - [ -d "$repo/.worktrees/$short" ] - [[ "$output" == *"clerk: OFFLINE - 'delivery/$short' claimed LOCALLY ONLY (not pushed). The branch is the lock; it is compare-and-swapped at first reconnect (clerk submit/sync). If another machine claimed $short meanwhile, that push wins and this local work is discarded. Proceeding, attended."* ]] - git -C "$repo" show-ref --verify --quiet "refs/heads/delivery/$short" - [ "$(bd show "$id" --readonly --json | jq -r '.[0].assignee')" = clerk ] -} - -@test "claim (bd): OFFLINE in a job context — exact refusal, exit 2, no side effects" { - repo=$(make_claim_repo claim_d) - cd "$repo" - id=$(mk_ac_unit "unit D") - short="${id#*-}" - break_origin "$repo" - run env CLERK_JOB=1 "$CLERK" backlog claim "$id" - [ "$status" -eq 2 ] - [ "$output" = "clerk: OFFLINE in a job context - refusing $short: the claim lock needs the remote and no attendant can accept the staleness hazard. Retry when origin is reachable." ] - [ ! -d "$repo/.worktrees/$short" ] - ! git -C "$repo" show-ref --verify --quiet "refs/heads/delivery/$short" - [ "$(bd show "$id" --readonly --json | jq -r '.[0].status')" = open ] -} - -@test "claim (bd): ready item with open blockers is not pickable and refuses before branch side effects" { - repo=$(make_claim_repo claim_not_pickable_blocked) - cd "$repo" - id=$(mk_ac_unit "blocked claim unit") - blocker=$(bd create "open blocker" --silent) - short="${id#*-}" - bd dep add "$id" "$blocker" >/dev/null - - run "$CLERK" backlog claim "$id" - [ "$status" -eq 2 ] - [[ "$output" == *"not pickable"* ]] - [[ "$output" == *"open blocker"* ]] - [ ! -d "$repo/.worktrees/$short" ] - ! git -C "$repo" show-ref --verify --quiet "refs/heads/delivery/$short" - ! git -C "$repo" show-ref --verify --quiet "refs/remotes/origin/delivery/$short" -} - -@test "claim (bd): criteria-less unit refuses, prescribes the grill, exit 2, no side effects" { - repo=$(make_claim_repo claim_e) - cd "$repo" - id=$(bd create "unit E" --description "just prose, no heading" --silent) - short="${id#*-}" - run "$CLERK" backlog claim "$id" - [ "$status" -eq 2 ] - [[ "$output" == *"$id has no 'Acceptance Criteria' section"* ]] - [[ "$output" == *"pregrill"* ]] - [ ! -d "$repo/.worktrees/$short" ] - ! git -C "$repo" show-ref --verify --quiet "refs/heads/delivery/$short" - [ "$(bd show "$id" --readonly --json | jq -r '.[0].status')" = open ] -} - -@test "claim (bd): re-claim of a unit you already hold is idempotent — already-yours + path, exit 0, no second push" { - repo=$(make_claim_repo claim_f1) - cd "$repo" - id=$(mk_ac_unit "unit F1") - run "$CLERK" backlog claim "$id" - [ "$status" -eq 0 ] - first_wt="${lines[-1]}" - # Break the remote AFTER the first claim: if re-claim ever fell through to SYNC-CHECK - # instead of short-circuiting, this would surface as the OFFLINE path (different output) - # or a failed branch-create (already exists) instead of a clean idempotent re-claim. - break_origin "$repo" - run "$CLERK" backlog claim "$id" - [ "$status" -eq 0 ] - [ "${lines[-1]}" = "$first_wt" ] - [ -d "$first_wt" ] -} - -@test "claim (bd): re-claim after the worktree directory was removed recreates it" { - repo=$(make_claim_repo claim_f2) - cd "$repo" - id=$(mk_ac_unit "unit F2") - run "$CLERK" backlog claim "$id" - [ "$status" -eq 0 ] - wt="${lines[-1]}" - rm -rf "$wt" - [ ! -d "$wt" ] - run "$CLERK" backlog claim "$id" - [ "$status" -eq 0 ] - [ "${lines[-1]}" = "$wt" ] - [ -d "$wt" ] -} - -@test "claim (bd): --from-returned replays the returned attempt onto current main and keeps evidence" { - repo=$(make_claim_repo claim_from_returned) - cd "$repo" - id=$(mk_ac_unit "reuse returned unit") - short="${id#*-}" - seed_returned_attempt "$repo" "$short" attempt.txt returned-work "returned attempt subject" - returned_tip=$(git -C "$repo" rev-parse "returned/$short") - git -C "$repo" branch -D "returned/$short" >/dev/null - advance_main "$repo" base.txt current-main "advance main after return" - git -C "$repo" fetch -q origin - main_tip=$(git -C "$repo" rev-parse origin/main) - - run "$CLERK" backlog claim "$id" --from-returned - [ "$status" -eq 0 ] - [ "${lines[-1]}" = "$repo/.worktrees/$short" ] - git -C "$repo" show-ref --verify --quiet "refs/heads/delivery/$short" - [ "$(git -C "$repo" merge-base "delivery/$short" origin/main)" = "$main_tip" ] - [ "$(cat "$repo/.worktrees/$short/base.txt")" = current-main ] - [ "$(cat "$repo/.worktrees/$short/attempt.txt")" = returned-work ] - [ "$(git -C "$repo" log -1 --format=%s "delivery/$short")" = "returned attempt subject" ] - [ "$(git -C "$repo" rev-parse "origin/returned/$short")" = "$returned_tip" ] - ! git -C "$repo" show-ref --verify --quiet "refs/heads/returned/$short" - [ "$(bd show "$id" --readonly --json | jq -r '.[0].status')" = in_progress ] -} - -@test "claim (bd): --from-returned refuses without a returned branch and has no side effects" { - repo=$(make_claim_repo claim_from_returned_absent) - cd "$repo" - id=$(mk_ac_unit "no returned reuse unit") - short="${id#*-}" - run "$CLERK" backlog claim "$id" --from-returned - [ "$status" -eq 2 ] - [[ "$output" == *"returned/$short was not found"* ]] - ! git -C "$repo" show-ref --verify --quiet "refs/heads/delivery/$short" - ! git -C "$repo" show-ref --verify --quiet "refs/remotes/origin/delivery/$short" - [ "$(bd show "$id" --readonly --json | jq -r '.[0].status')" = open ] -} - -@test "claim (bd): plain claim with returned attempt refuses before side effects" { - repo=$(make_claim_repo claim_plain_with_returned) - cd "$repo" - id=$(mk_ac_unit "plain claim with returned unit") - short="${id#*-}" - seed_returned_attempt "$repo" "$short" attempt.txt returned-work "returned attempt subject" - advance_main "$repo" base.txt current-main "advance main for plain claim" - git -C "$repo" fetch -q origin - - run "$CLERK" backlog claim "$id" - [ "$status" -eq 2 ] - [ "$output" = "clerk backlog claim: returned/$short exists — choose how to claim - reuse returned work: clerk backlog claim $id --from-returned - start fresh: clerk backlog claim $id --fresh --returned keep|discard" ] - ! git -C "$repo" show-ref --verify --quiet "refs/heads/delivery/$short" - ! git -C "$repo" show-ref --verify --quiet "refs/remotes/origin/delivery/$short" - [ ! -d "$repo/.worktrees/$short" ] - git -C "$repo" show-ref --verify --quiet "refs/heads/returned/$short" - [ "$(bd show "$id" --readonly --json | jq -r '.[0].status')" = open ] -} - -@test "claim (bd): --fresh --returned keep claims from main and preserves returned refs" { - repo=$(make_claim_repo claim_fresh_keep_returned) - cd "$repo" - id=$(mk_ac_unit "fresh keep returned unit") - short="${id#*-}" - seed_returned_attempt "$repo" "$short" attempt.txt returned-work "returned attempt subject" - advance_main "$repo" base.txt current-main "advance main for fresh claim" - git -C "$repo" fetch -q origin - main_tip=$(git -C "$repo" rev-parse origin/main) - - run "$CLERK" backlog claim "$id" --fresh --returned keep - [ "$status" -eq 0 ] - [ "${lines[-1]}" = "$repo/.worktrees/$short" ] - [ "$(git -C "$repo" rev-parse "delivery/$short")" = "$main_tip" ] - [ "$(cat "$repo/.worktrees/$short/base.txt")" = current-main ] - [ ! -e "$repo/.worktrees/$short/attempt.txt" ] - git -C "$repo" show-ref --verify --quiet "refs/heads/returned/$short" - git -C "$repo" show-ref --verify --quiet "refs/remotes/origin/returned/$short" - [ "$(bd show "$id" --readonly --json | jq -r '.[0].status')" = in_progress ] -} - -@test "claim (bd): --fresh --returned discard claims from main and removes canonical and archived returned refs" { - repo=$(make_claim_repo claim_fresh_discard_returned) - cd "$repo" - id=$(mk_ac_unit "fresh discard returned unit") - short="${id#*-}" - seed_returned_attempt "$repo" "$short" attempt.txt returned-work "returned attempt subject" - git -C "$repo" branch "returned/$short-archive" "returned/$short" - git -C "$repo" push -q origin "returned/$short-archive" - advance_main "$repo" base.txt current-main "advance main for fresh discard claim" - git -C "$repo" fetch -q origin - main_tip=$(git -C "$repo" rev-parse origin/main) - - run "$CLERK" backlog claim "$id" --fresh --returned discard - [ "$status" -eq 0 ] - [ "${lines[-1]}" = "$repo/.worktrees/$short" ] - [ "$(git -C "$repo" rev-parse "delivery/$short")" = "$main_tip" ] - [ "$(cat "$repo/.worktrees/$short/base.txt")" = current-main ] - [ ! -e "$repo/.worktrees/$short/attempt.txt" ] - ! git -C "$repo" show-ref --verify --quiet "refs/heads/returned/$short" - ! git -C "$repo" show-ref --verify --quiet "refs/heads/returned/$short-archive" - ! git -C "$repo" show-ref --verify --quiet "refs/remotes/origin/returned/$short" - ! git -C "$repo" show-ref --verify --quiet "refs/remotes/origin/returned/$short-archive" - [ "$(bd show "$id" --readonly --json | jq -r '.[0].status')" = in_progress ] -} - -@test "claim (bd): --fresh with returned attempt requires returned disposition" { - repo=$(make_claim_repo claim_fresh_missing_disposition) - cd "$repo" - id=$(mk_ac_unit "fresh missing disposition unit") - short="${id#*-}" - seed_returned_attempt "$repo" "$short" attempt.txt returned-work "returned attempt subject" - - run "$CLERK" backlog claim "$id" --fresh - [ "$status" -eq 2 ] - [[ "$output" == *"returned/$short exists — choose how to claim"* ]] - ! git -C "$repo" show-ref --verify --quiet "refs/heads/delivery/$short" - [ "$(bd show "$id" --readonly --json | jq -r '.[0].status')" = open ] -} - -@test "claim (bd): invalid returned claim flag combinations fail before side effects" { - repo=$(make_claim_repo claim_invalid_returned_flags) - cd "$repo" - id=$(mk_ac_unit "invalid returned flags unit") - short="${id#*-}" - seed_returned_attempt "$repo" "$short" attempt.txt returned-work "returned attempt subject" - - run "$CLERK" backlog claim "$id" --from-returned --fresh - [ "$status" -eq 2 ] - [[ "$output" == *"choose only one of --from-returned or --fresh"* ]] - run "$CLERK" backlog claim "$id" --from-returned --returned keep - [ "$status" -eq 2 ] - [[ "$output" == *"--returned is only valid with --fresh"* ]] - ! git -C "$repo" show-ref --verify --quiet "refs/heads/delivery/$short" - ! git -C "$repo" show-ref --verify --quiet "refs/remotes/origin/delivery/$short" - [ ! -d "$repo/.worktrees/$short" ] - [ "$(bd show "$id" --readonly --json | jq -r '.[0].status')" = open ] -} - -@test "claim (bd): --from-returned conflict leaves the claim lock and worktree for manual resolution" { - repo=$(make_claim_repo claim_from_returned_conflict) - cd "$repo" - printf 'base\n' >conflict.txt - git add conflict.txt - git commit -q -m "add conflict base" - git push -q origin main - id=$(mk_ac_unit "conflicting returned unit") - short="${id#*-}" - seed_returned_attempt "$repo" "$short" conflict.txt returned-change "returned conflicting attempt" - advance_main "$repo" conflict.txt main-change "main conflicting change" - git -C "$repo" fetch -q origin - - run "$CLERK" backlog claim "$id" --from-returned - [ "$status" -eq 2 ] - [[ "$output" == *"claim --from-returned hit conflicts"* ]] - [[ "$output" == *"conflict.txt"* ]] - git -C "$repo" show-ref --verify --quiet "refs/heads/delivery/$short" - git -C "$repo" show-ref --verify --quiet "refs/remotes/origin/delivery/$short" - [ -d "$repo/.worktrees/$short" ] - [ "$(git -C "$repo/.worktrees/$short" diff --name-only --diff-filter=U)" = conflict.txt ] - [ "$(bd show "$id" --readonly --json | jq -r '.[0].status')" = in_progress ] -} - -@test "claim --explain documents returned-attempt choices" { - run "$CLERK" backlog claim --explain - [ "$status" -eq 0 ] - [[ "$output" == *"--from-returned"* ]] - [[ "$output" == *"--fresh --returned keep|discard"* ]] -} - -@test "claim: missing id is a usage error, exit 2" { - repo=$(make_claim_repo claim_missing) - cd "$repo" - run "$CLERK" backlog claim - [ "$status" -eq 2 ] - [[ "$output" == *"missing id"* ]] -} - -@test "claim: an id that does not resolve is a usage error, exit 2" { - repo=$(make_claim_repo claim_nx) - cd "$repo" - run "$CLERK" backlog claim nonexistent-zzz - [ "$status" -eq 2 ] - [[ "$output" == *"not found"* ]] -} diff --git a/tests/clerk/clerk-bundles.bats b/tests/clerk/clerk-bundles.bats deleted file mode 100644 index 1a5e485..0000000 --- a/tests/clerk/clerk-bundles.bats +++ /dev/null @@ -1,136 +0,0 @@ -#!/usr/bin/env bats -# clerk-bundles.bats — clerk-native bundle generation (dotfiles-dft.7) - -setup() { - REPO_ROOT="$(cd "$BATS_TEST_DIRNAME/../.." && pwd)" - NEW_ARTIFACTS=( - "umbel/bundles/clerk-discovery.md" - "umbel/bundles/clerk-delivery-base.md" - "umbel/bundles/clerk-delivery-superpowers.md" - "umbel/hooks/local/clerk-session-start" - "umbel/skills/local/clerk-presort" - ) - FROZEN_PATHS=( - "umbel/bundles/discovery.md" - "umbel/bundles/delivery-base.md" - "umbel/bundles/delivery-superpowers.md" - "umbel/hooks/local/discovery-ruleset" - "umbel/hooks/local/delivery-base-ruleset" - "umbel/hooks/local/delivery-superpowers-locations" - "umbel/skills/local/presort" - ) - OPACITY_TOKEN_RE='(^|[^[:alnum:]_])(bd|beads?|tier|repo-visibility)([^[:alnum:]_]|$)' -} - -@test "clerk-native artifacts keep Clerk opaque" { - cd "$REPO_ROOT" - # Literal acceptance probe: the refined source artifacts carry none of the retired/backend words. - run grep -RinE 'bd|beads|tier|repo-visibility' "${NEW_ARTIFACTS[@]}" - [ "$status" -eq 1 ] - [ "$output" = "" ] - - # Token probe with controls: do not make ordinary substrings like TBD or subdirectories red. - printf 'TBD subdirectories data-path 4Bny\n' >"$BATS_TEST_TMPDIR/opacity-negative.txt" - printf 'use bd-create here\n' >"$BATS_TEST_TMPDIR/opacity-positive.txt" - run grep -inE "$OPACITY_TOKEN_RE" "$BATS_TEST_TMPDIR/opacity-negative.txt" - [ "$status" -eq 1 ] - run grep -inE "$OPACITY_TOKEN_RE" "$BATS_TEST_TMPDIR/opacity-positive.txt" - [ "$status" -eq 0 ] - - run grep -RinE "$OPACITY_TOKEN_RE" "${NEW_ARTIFACTS[@]}" - [ "$status" -eq 1 ] - [ "$output" = "" ] -} - -@test "old generation paths are untouched in the worktree" { - cd "$REPO_ROOT" - run git diff --name-only -- "${FROZEN_PATHS[@]}" - [ "$status" -eq 0 ] - [ "$output" = "" ] -} - -@test "clerk SessionStart hook injects the seed and kicks async glean" { - cd "$REPO_ROOT" - local stub_bin clerk_args - stub_bin="$BATS_TEST_TMPDIR/bin" - clerk_args="$BATS_TEST_TMPDIR/clerk-args.txt" - mkdir -p "$stub_bin" - cat >"$stub_bin/clerk" <<'SH' -#!/usr/bin/env bash -printf '%s\n' "$*" >"$CLERK_STUB_ARGS" -SH - chmod +x "$stub_bin/clerk" - export PATH="$stub_bin:$PATH" - export CLERK_STUB_ARGS="$clerk_args" - - grep -q 'clerk glean --async' umbel/hooks/local/clerk-session-start/session-start - run umbel/hooks/local/clerk-session-start/session-start - [ "$status" -eq 0 ] - [[ "$output" == *'"hookEventName": "SessionStart"'* ]] - [[ "$output" == *'clerk-operating-rules'* ]] - [[ "$output" == *'clerk backlog next|show|claim|release|return|submit|finish'* ]] - [ "$(cat "$clerk_args")" = "glean --async" ] -} - -@test "presort successor speaks Clerk grammar and demotes criteria-less candidates" { - cd "$REPO_ROOT" - presort=umbel/skills/local/clerk-presort/SKILL.md - grep -q 'clerk inbox list' "$presort" - grep -q 'clerk inbox pregrill <id>' "$presort" - grep -q 'A criteria-less ready-looking candidate is \*\*not ready\*\*' "$presort" - run grep -nE 'bd|beads|tier|repo-visibility' "$presort" - [ "$status" -eq 1 ] -} - -@test "presort successor encodes pregrill delta idempotence" { - cd "$REPO_ROOT" - presort=umbel/skills/local/clerk-presort/SKILL.md - grep -q '\[pregrill:absent\]' "$presort" - grep -q '\[pregrill:stale\]' "$presort" - grep -q '\[pregrill:present\]' "$presort" - grep -q 'A second pass over an unchanged inbox files nothing' "$presort" -} - -@test "returned attempts are called out in operating and grill guidance" { - cd "$REPO_ROOT" - grep -q 'clerk inbox show.*prior returned attempts' umbel/hooks/local/clerk-session-start/seed.md - grep -q 'prior returned attempt' umbel/skills/local/clerk-presort/SKILL.md - grep -q 'returned subject/reason' umbel/skills/local/clerk-presort/SKILL.md -} - -@test "grill-with-docs loads acceptance playbook guidance" { - cd "$REPO_ROOT" - grill=umbel/skills/pocock/grill-with-docs/SKILL.md - grep -q 'umbel/docs/acceptance-playbook.md' "$grill" - grep -q 'verbatim strings, exit codes, environment/context signals' "$grill" - grep -q 'Delivery may add evidence later, but must not invent or narrow the exam' "$grill" -} - -@test "umbel sees the clerk generation and can pin clerk-delivery-base" { - command -v umbel >/dev/null 2>&1 || skip "umbel not installed" - cd "$REPO_ROOT" - run env UMBEL_ARTIFACTS_DIR="$REPO_ROOT/umbel" umbel list - [ "$status" -eq 0 ] - [[ "$output" == *'clerk-discovery'* ]] - [[ "$output" == *'clerk-delivery-base'* ]] - [[ "$output" == *'clerk-delivery-superpowers'* ]] - - project="$BATS_TEST_TMPDIR/apply-project" - mkdir -p "$project" - cd "$project" - run env UMBEL_ARTIFACTS_DIR="$REPO_ROOT/umbel" umbel apply clerk-delivery-base - [ "$status" -eq 0 ] - [ "$(cat .umbel-bundle)" = "clerk-delivery-base" ] - - cd "$REPO_ROOT" - run env UMBEL_ARTIFACTS_DIR="$REPO_ROOT/umbel" umbel build clerk-delivery-superpowers --no-cache - [ "$status" -eq 0 ] - built="$(printf '%s\n' "$output" | tail -1)" - [ "$(find "$built/hooks" -mindepth 1 -maxdepth 1 -type d | wc -l | tr -d ' ')" = "1" ] - [ -d "$built/hooks/clerk-session-start" ] - grep -q 'clerk-session-start' "$built/hooks/hooks.json" - [ "$(grep -c '"command"[[:space:]]*:' "$built/hooks/hooks.json")" = "1" ] - run grep -RinE "$OPACITY_TOKEN_RE" "$built/bundle.md" "$built/hooks/clerk-session-start" - [ "$status" -eq 1 ] - [ "$output" = "" ] -} diff --git a/tests/clerk/core.bats b/tests/clerk/core.bats deleted file mode 100644 index 8ef909e..0000000 --- a/tests/clerk/core.bats +++ /dev/null @@ -1,587 +0,0 @@ -#!/usr/bin/env bats -# core.bats — clerk core dispatcher (unit dotfiles-dft.1). -# -# Printed output is load-bearing (ADR 0015: "error text is prompt engineering"), so these -# tests assert verbatim lines, not just exit codes. All fixtures are scratch git repos in -# bats temp dirs — the real repo's .clerk cutover belongs to unit dotfiles-dft.8, so no -# test reads or writes this repo's own state. - -setup() { - source "$BATS_TEST_DIRNAME/helpers.bash" - git_sandbox - REPO_ROOT="$(cd "$BATS_TEST_DIRNAME/../.." && pwd)" - CLERK="$REPO_ROOT/bin/clerk" - ESC=$'\033' - OK_TAG=" ${ESC}[32m[ ok ]${ESC}[0m" - # shellcheck disable=SC2034 # symmetry with OK/FAIL tags; warn lines not asserted yet - WARN_TAG=" ${ESC}[33m[warn]${ESC}[0m" - FAIL_TAG=" ${ESC}[31m[fail]${ESC}[0m" - ALL_VERBS=( - "capture" "sync" "glean" - "inbox list" "inbox show" "inbox dups" "inbox ready" "inbox drop" "inbox pregrill" - "inbox children" "inbox frontier" "inbox blockers" "inbox blocked" "inbox parent" "inbox dep" - "inbox claim" "inbox release" "inbox note" "inbox update" "inbox resolve" - "backlog next" "backlog show" "backlog waiting" "backlog claim" "backlog release" "backlog resolve" - "backlog proof" "backlog submit" "backlog gate" "backlog finish" "backlog return" - ) - mkdir -p "$BATS_TEST_TMPDIR/empty-transcripts" "$BATS_TEST_TMPDIR/glean-state" - export CLERK_GLEAN_TRANSCRIPT_DIR="$BATS_TEST_TMPDIR/empty-transcripts" - export CLERK_GLEAN_STATE_DIR="$BATS_TEST_TMPDIR/glean-state" - export CLERK_GLEAN_JUDGMENT_CMD='cat >/dev/null; echo "{\"type\":\"none\",\"reason\":\"test\"}"' -} - -# Scratch git repo with an optional .clerk marker, committed so worktrees see it -# (worktrees check out the committed tree). Echoes the PHYSICAL path — clerk resolves the -# root via `git rev-parse --show-toplevel`, which prints symlink-free paths. -make_repo() { # $1 = subdir name, $2 = marker content ('-' = none) - local dir="$BATS_TEST_TMPDIR/$1" - mkdir -p "$dir" - dir="$(cd "$dir" && pwd -P)" - git init -q -b main "$dir" - if [ "$2" != "-" ]; then printf '%s\n' "$2" >"$dir/.clerk"; fi - git -C "$dir" add -A - git -C "$dir" -c user.email=clerk@test -c user.name=clerk commit -q --allow-empty -m fixture - printf '%s\n' "$dir" -} - -make_worktree() { # $1 = repo, $2 = id; echoes the worktree path - git -C "$1" worktree add -q "$1/.worktrees/$2" -b "wt-$2" - printf '%s/.worktrees/%s\n' "$1" "$2" -} - -make_fake_bin() { # $1 = dir; drops an executable stub named bd there - mkdir -p "$1" - printf '#!/bin/sh\nexit 0\n' >"$1/bd" - chmod +x "$1/bd" -} - -phys() { # echoes the physical path of an existing dir - (cd "$1" && pwd -P) -} - -assert_roster() { # $1 = index of the 'Known verbs:' line in ${lines[@]} - local i="$1" - [ "${lines[i]}" = "Known verbs:" ] - [ "${lines[i + 1]}" = ' capture "<title>" [--stdin|--type <type>|--impediment|--parent <id>|--blocked-by <id>]' ] - [ "${lines[i + 2]}" = ' inbox list|show|dups|ready|drop|pregrill|children|frontier|blockers|blocked|parent|dep|claim|release|note|update|resolve' ] - [ "${lines[i + 3]}" = ' backlog next|show|waiting|claim|release|resolve|proof|submit|gate|finish|return' ] - [ "${lines[i + 4]}" = ' sync' ] - [ "${lines[i + 5]}" = ' doctor [--fix --backend bd|gh]' ] - [ "${lines[i + 6]}" = ' glean' ] - [ "${lines[i + 7]}" = "Next: run 'clerk --explain <verb>' to see what a verb does." ] -} - -assert_no_python_bytecode() { # $1 = package root to inspect - local found - found=$(find "$1" \( -type d -name __pycache__ -o -type f \( -name '*.py[co]' -o -name '*.pyd' \) \) -print) - if [ -n "$found" ]; then - printf 'Python bytecode/cache artifacts found:\n%s\n' "$found" >&2 - return 1 - fi -} - -# ------------------------------------------------------------- version ------ - -@test "launcher invokes the Python Clerk project" { - real_python=$(python3 -c 'import sys; print(sys.executable)') - fake_python="$BATS_TEST_TMPDIR/python3" - log="$BATS_TEST_TMPDIR/python-argv.log" - cat >"$fake_python" <<EOF -#!/bin/sh -if [ "\$1" = - ]; then - exec "$real_python" "\$@" -fi -printf '%s\n' "\$*" >>"$log" -exec "$real_python" "\$@" -EOF - chmod +x "$fake_python" - - run env -i CLERK_PYTHON="$fake_python" PATH="/usr/bin:/bin" "$CLERK" --version - [ "$status" -eq 0 ] - [ "$output" = "clerk 0.1.0" ] - [ "$(cat "$log")" = "-m clerk --version" ] -} - -@test "launcher does not write Python bytecode into its checkout" { - real_python=$(python3 -c 'import sys; print(sys.executable)') - fresh="$BATS_TEST_TMPDIR/fresh-checkout" - mkdir -p "$fresh/bin" "$fresh/clerk/src" - cp "$REPO_ROOT/bin/clerk" "$fresh/bin/clerk" - cp -R "$REPO_ROOT/clerk/src/clerk" "$fresh/clerk/src/" - rm -rf "$fresh/clerk/src/clerk/__pycache__" - find "$fresh/clerk/src/clerk" -type f \( -name '*.py[co]' -o -name '*.pyd' \) -delete - - run env -i CLERK_PYTHON="$real_python" PATH="/usr/bin:/bin" "$fresh/bin/clerk" --version - [ "$status" -eq 0 ] - [ "$output" = "clerk 0.1.0" ] - assert_no_python_bytecode "$fresh/clerk/src/clerk" -} - -@test "launcher resolves a Stow-style symlink to the checkout" { - link="$BATS_TEST_TMPDIR/stowed-clerk" - ln -s "$CLERK" "$link" - - run "$link" --version - [ "$status" -eq 0 ] - [ "$output" = "clerk 0.1.0" ] -} - -@test "launcher reports a prescriptive Clerk-shaped error when Python 3.11+ is unavailable" { - fake_bin="$BATS_TEST_TMPDIR/no-python-bin" - mkdir -p "$fake_bin" - ln -s "$(command -v bash)" "$fake_bin/bash" - - run env -i PATH="$fake_bin" "$CLERK" --version - [ "$status" -eq 4 ] - [ "${lines[0]}" = "clerk: Python 3.11 or newer is required to run Clerk" ] - [ "${lines[1]}" = " install Python 3.11+ or set CLERK_PYTHON to its path" ] - [ "${lines[2]}" = " then run 'clerk doctor' if setup is still unclear" ] -} - -@test "--version prints the single-sourced version string" { - run "$CLERK" --version - [ "$status" -eq 0 ] - [ "$output" = "clerk 0.1.0" ] -} - -# -------------------------------------------- dispatch: root vs worktree ---- - -@test "dispatch resolves the repo from a nested subdirectory of a worktree" { - repo=$(make_repo nested "backlog: bd") - wt=$(make_worktree "$repo" wt1) - mkdir -p "$wt/sub/deep" - cd "$wt/sub/deep" - # git rev-parse --show-toplevel must still find the worktree root from a nested cwd, - # so the marker gate passes and the implemented top-level verb runs normally. - run "$CLERK" glean - [ "$status" -eq 0 ] - [ "$output" = "glean: no transcript files found in $BATS_TEST_TMPDIR/empty-transcripts" ] -} - -@test "matrix: doctor resolves the marker from root and from inside the worktree" { - repo=$(make_repo docmatrix "backlog: bd") - wt=$(make_worktree "$repo" wt1) - home="$BATS_TEST_TMPDIR/docmatrix-home" - mkdir -p "$home" - home=$(phys "$home") - cd "$repo" - run env -i CLICOLOR_FORCE=1 HOME="$home" PATH="/usr/bin:/bin" "$CLERK" doctor - [ "$status" -eq 0 ] - [[ "$output" == *"$OK_TAG .clerk marker: backlog: bd ($repo/.clerk)"* ]] - cd "$wt" - run env -i CLICOLOR_FORCE=1 HOME="$home" PATH="/usr/bin:/bin" "$CLERK" doctor - [ "$status" -eq 0 ] - [[ "$output" == *"$OK_TAG .clerk marker: backlog: bd ($wt/.clerk)"* ]] -} - -# --------------------------------------------------- marker gate refusals --- - -@test "missing .clerk: dispatching verb refuses with exit 4 and prescribes doctor" { - repo=$(make_repo nomarker -) - cd "$repo" - run "$CLERK" sync - [ "$status" -eq 4 ] - [ "$output" = "clerk: missing .clerk marker at $repo/.clerk — run 'clerk doctor' to provision it" ] -} - -@test "invalid .clerk: dispatching verb refuses with exit 4 and prescribes doctor" { - repo=$(make_repo badmarker "backlog: jira") - cd "$repo" - run "$CLERK" backlog next - [ "$status" -eq 4 ] - [ "$output" = "clerk: invalid .clerk marker at $repo/.clerk — run 'clerk doctor' to diagnose it" ] -} - -@test "two directive lines make the marker invalid" { - repo=$(make_repo twomarker -) - printf 'backlog: bd\nbacklog: gh\n' >"$repo/.clerk" - cd "$repo" - run "$CLERK" glean - [ "$status" -eq 4 ] - [ "$output" = "clerk: invalid .clerk marker at $repo/.clerk — run 'clerk doctor' to diagnose it" ] -} - -@test "marker tolerates surrounding whitespace and # comments" { - repo=$(make_repo losemarker -) - printf '%s\n' \ - '# which backend holds the ready pool (ADR 0017)' \ - '' \ - ' backlog: bd # bd for now' >"$repo/.clerk" - cd "$repo" - # Probe with glean: if marker parsing accepts the valid marker, the implemented verb runs. - run "$CLERK" glean - [ "$status" -eq 0 ] - [ "$output" = "glean: no transcript files found in $BATS_TEST_TMPDIR/empty-transcripts" ] -} - -@test "outside any git repo: dispatching verb refuses with exit 4" { - cd / - run "$CLERK" sync - [ "$status" -eq 4 ] - [ "$output" = "clerk: not inside a git repository — cd into the target repo, then run 'clerk doctor'" ] -} - -# ------------------------------------------------------------ unknown verbs - - -@test "unknown verb: exit 2 and the verbatim roster" { - run "$CLERK" frobnicate - [ "$status" -eq 2 ] - [ "${lines[0]}" = "clerk: unknown verb 'frobnicate'" ] - assert_roster 1 -} - -@test "unknown subverb: exit 2 and the roster" { - run "$CLERK" inbox nuke - [ "$status" -eq 2 ] - [ "${lines[0]}" = "clerk: unknown verb 'inbox nuke'" ] - assert_roster 1 -} - -@test "unknown subverb spanning two adjacent roster words: exit 2 and the roster" { - # regression: a glob over the roster string misread one argument equal to two - # adjacent roster words as a known verb (exit 3 instead of 2, no roster) - repo=$(make_repo adjacent "backlog: bd") - cd "$repo" - run "$CLERK" inbox "list show" - [ "$status" -eq 2 ] - [ "${lines[0]}" = "clerk: unknown verb 'inbox list show'" ] - assert_roster 1 - run "$CLERK" backlog "claim release" - [ "$status" -eq 2 ] - [ "${lines[0]}" = "clerk: unknown verb 'backlog claim release'" ] - assert_roster 1 -} - -@test "bare noun: exit 2, names the noun, prints the roster" { - run "$CLERK" backlog - [ "$status" -eq 2 ] - [ "${lines[0]}" = "clerk: 'backlog' needs a verb" ] - assert_roster 1 -} - -@test "no arguments: exit 2 and the roster" { - run "$CLERK" - [ "$status" -eq 2 ] - [ "${lines[0]}" = "clerk: missing verb" ] - assert_roster 1 -} - -@test "unknown verb wins over marker state (checked before the gate)" { - repo=$(make_repo unkfirst -) - cd "$repo" - run "$CLERK" frobnicate - [ "$status" -eq 2 ] - [ "${lines[0]}" = "clerk: unknown verb 'frobnicate'" ] -} - -# --------------------------------------------------------------- --explain -- - -@test "--explain capture: underlying commands + ADR pointer, verbatim" { - run "$CLERK" --explain capture - [ "$status" -eq 0 ] - [ "${lines[0]}" = 'clerk capture — file one raw capture into the bd inbox' ] - [ "${lines[1]}" = ' usage: clerk capture "<title>" [--stdin|--type <type>|--impediment|--parent <id>|--blocked-by <id>...]' ] - [ "${lines[2]}" = ' runs: bd create "<title>" [--stdin] [--type ...] [--parent ...] [--deps ...] (backlog: bd|gh)' ] - [ "${lines[3]}" = ' (GitHub-backed repos use GitHub only after inbox ready promotion)' ] - [ "${lines[4]}" = ' see: ADR 0015 — clerk/docs/adr/0015-clerk-opaque-workflow-verb-facade.md' ] -} - -@test "--explain backlog submit describes the Project-gate boundary (ADR 0019)" { - run "$CLERK" --explain backlog submit - [ "$status" -eq 0 ] - [[ "$output" == *"trusted default branch"* ]] - [[ "$output" == *"ADR 0019 — clerk/docs/adr/0019-project-gate-adapter-contract.md"* ]] -} - -@test "--explain doctor points at the marker manifest (ADR 0017)" { - run "$CLERK" --explain doctor - [ "$status" -eq 0 ] - [[ "$output" == *"reads .clerk"* ]] - [[ "$output" == *"ADR 0017 — clerk/docs/adr/0017-tier-retired-backlog-location-and-merge-gate-axes.md"* ]] -} - -@test "trailing --explain (clerk <noun> <verb> --explain) equals the leading form" { - lead=$("$CLERK" --explain backlog claim) - trail=$("$CLERK" backlog claim --explain) - [ "$lead" = "$trail" ] - [[ "$lead" == *"delivery/<id>"* ]] - [[ "$lead" == *"ADR 0017"* ]] -} - -@test "inbox ready/drop explain returned-branch disposition" { - run "$CLERK" inbox ready --explain - [ "$status" -eq 0 ] - [[ "$output" == *"--returned keep|discard"* ]] - run "$CLERK" inbox drop --explain - [ "$status" -eq 0 ] - [[ "$output" == *"--returned keep|discard"* ]] -} - -@test "verb --help is help-only: no marker or backend needed" { - repo=$(make_repo helpnomarker -) - cd "$repo" - run "$CLERK" capture --help - [ "$status" -eq 0 ] - [ "${lines[0]}" = 'clerk capture — file one raw capture into the bd inbox' ] - [[ "$output" == *'bd create "<title>"'* ]] - [[ "$output" != *'jq:'* ]] - [[ "$output" != *'capture failed'* ]] - - run "$CLERK" inbox ready -h - [ "$status" -eq 0 ] - [ "${lines[0]}" = 'clerk inbox ready — write refinement output, then promote a groomed bd capture' ] - [[ "$output" == *'--acceptance-file <path>'* ]] -} - -@test "capture still rejects unknown non-help options after the title" { - repo=$(make_repo capturebadarg "backlog: bd") - cd "$repo" - run "$CLERK" capture "real title" --bogus - [ "$status" -eq 2 ] - [ "$output" = 'clerk capture: unknown argument '\''--bogus'\'' — usage: clerk capture "<title>" [--stdin|--type <type>|--impediment|--parent <id>|--blocked-by <id>]' ] -} - -@test "--explain covers every roster verb, with or without a marker" { - repo=$(make_repo explnomarker -) # deliberately marker-less - cd "$repo" - for v in "${ALL_VERBS[@]}" doctor; do - # shellcheck disable=SC2086 # word-split $v into noun + verb on purpose - run "$CLERK" --explain $v - [ "$status" -eq 0 ] - [ "${lines[0]}" = "clerk $v — ${lines[0]#clerk "$v" — }" ] # header names the verb - [[ "$output" == *" runs: "* ]] - [[ "$output" == *" see: ADR "* ]] - # 'runs:' must name at least one concrete underlying command (on the runs: line - # or an 8-space continuation line), never pure prose - if ! printf '%s\n' "$output" | grep -qE '^( runs: | ).*\<(bd|gh|git|flock)\>'; then - printf "no concrete command in --explain %s output:\n%s\n" "$v" "$output" >&2 - return 1 - fi - done -} - -@test "--explain of an unknown verb: exit 2 and the roster" { - run "$CLERK" --explain frobnicate - [ "$status" -eq 2 ] - [ "${lines[0]}" = "clerk: unknown verb 'frobnicate'" ] -} - -# ------------------------------------------------------------------ doctor -- - -@test "doctor: all clear on a healthy repo (verbatim 16-color status lines)" { - repo=$(make_repo dochealthy "backlog: bd") - home="$BATS_TEST_TMPDIR/dochealthy-home" - make_fake_bin "$home/.config/bin" - home=$(phys "$home") - cd "$repo" - run env -i CLICOLOR_FORCE=1 HOME="$home" PATH="$home/.config/bin:/usr/bin:/bin" "$CLERK" doctor - [ "$status" -eq 0 ] - [ "${lines[0]}" = "${ESC}[1mclerk doctor${ESC}[0m — $repo" ] - [[ "$output" == *"$OK_TAG .clerk marker: backlog: bd ($repo/.clerk)"* ]] - [[ "$output" == *"$OK_TAG bd shim: $home/.config/bin/bd (shim wins PATH resolution)"* ]] - [[ "$output" == *"$OK_TAG version: clerk 0.1.0 (clerk --version reports the same string)"* ]] - [ "${lines[${#lines[@]} - 1]}" = "${ESC}[32mclerk doctor: all clear${ESC}[0m" ] -} - -@test "doctor: missing marker fails and prints the exact provisioning command" { - repo=$(make_repo docmissing -) - home="$BATS_TEST_TMPDIR/docmissing-home" - mkdir -p "$home" - home=$(phys "$home") - cd "$repo" - run env -i CLICOLOR_FORCE=1 HOME="$home" PATH="/usr/bin:/bin" "$CLERK" doctor - [ "$status" -eq 1 ] - [[ "$output" == *"$FAIL_TAG .clerk marker: missing ($repo/.clerk)"* ]] - [[ "$output" == *" provision it: clerk doctor --fix --backend bd (or --backend gh)"* ]] - [ "${lines[${#lines[@]} - 1]}" = "${ESC}[31mclerk doctor: 1 problem(s) — fix the [fail] lines above${ESC}[0m" ] -} - -@test "doctor --fix --backend gh provisions the marker non-interactively" { - repo=$(make_repo docfix -) - home="$BATS_TEST_TMPDIR/docfix-home" - mkdir -p "$home" - home=$(phys "$home") - cd "$repo" - run env -i CLICOLOR_FORCE=1 HOME="$home" PATH="/usr/bin:/bin" "$CLERK" doctor --fix --backend gh - [ "$status" -eq 0 ] - [[ "$output" == *"$OK_TAG .clerk marker: provisioned backlog: gh ($repo/.clerk)"* ]] - [[ "$output" == *" commit .clerk so worktrees and clones see it: git add .clerk && git commit"* ]] - [ "$(cat "$repo/.clerk")" = "backlog: gh" ] - # the marker gate now passes: the same verb that would exit 4 runs normally - run "$CLERK" glean - [ "$status" -eq 0 ] - [ "$output" = "glean: no transcript files found in $BATS_TEST_TMPDIR/empty-transcripts" ] -} - -@test "doctor --fix that cannot write the marker fails loudly, never 'all clear'" { - repo=$(make_repo docfixdir -) - mkdir "$repo/.clerk" # a directory at the marker path blocks the provisioning write - home="$BATS_TEST_TMPDIR/docfixdir-home" - mkdir -p "$home" - home=$(phys "$home") - cd "$repo" - run env -i CLICOLOR_FORCE=1 HOME="$home" PATH="/usr/bin:/bin" "$CLERK" doctor --fix --backend bd - [ "$status" -eq 1 ] - [[ "$output" == *"$FAIL_TAG .clerk marker: could not provision ($repo/.clerk)"* ]] - [[ "$output" == *" check that $repo is writable and .clerk is not a directory"* ]] - [[ "$output" != *"all clear"* ]] - # the marker never validated, so dispatch still refuses at the gate - run "$CLERK" capture "a title" - [ "$status" -eq 4 ] - [ "$output" = "clerk: missing .clerk marker at $repo/.clerk — run 'clerk doctor' to provision it" ] -} - -@test "doctor --fix without --backend refuses with the exact rerun command" { - run "$CLERK" doctor --fix - [ "$status" -eq 2 ] - [ "$output" = "clerk doctor: --fix requires --backend bd|gh — rerun as 'clerk doctor --fix --backend bd' (or gh)" ] -} - -@test "doctor --fix --backend jira refuses: unknown backend" { - run "$CLERK" doctor --fix --backend jira - [ "$status" -eq 2 ] - [ "$output" = "clerk doctor: unknown backend 'jira' — use --backend bd or --backend gh" ] -} - -@test "doctor --backend without --fix is a usage error, not silently ignored" { - run "$CLERK" doctor --backend gh - [ "$status" -eq 2 ] - [ "$output" = "clerk doctor: --backend applies only with --fix — rerun with --fix, e.g. 'clerk doctor --fix --backend bd'" ] -} - -@test "doctor survives an unset HOME without crashing (set -u safe)" { - repo=$(make_repo dochome "backlog: bd") - cd "$repo" - # No HOME in the environment — the shim-candidate construction must not trip `set -u`. - # Reaching the version line proves execution passed the HOME-derived shim candidate. - run env -i PATH="/usr/bin:/bin" "$CLERK" doctor - [ "$status" -eq 0 ] - [[ "$output" == *".clerk marker: backlog: bd ($repo/.clerk)"* ]] - [[ "$output" == *"version: clerk 0.1.0 (clerk --version reports the same string)"* ]] - [[ "$output" != *"unbound variable"* ]] -} - -@test "doctor: invalid marker fails with format guidance; --fix rewrites it" { - repo=$(make_repo docinvalid "backlog: jira") - home="$BATS_TEST_TMPDIR/docinvalid-home" - mkdir -p "$home" - home=$(phys "$home") - cd "$repo" - run env -i CLICOLOR_FORCE=1 HOME="$home" PATH="/usr/bin:/bin" "$CLERK" doctor - [ "$status" -eq 1 ] - [[ "$output" == *"$FAIL_TAG .clerk marker: invalid ($repo/.clerk)"* ]] - [[ "$output" == *" expected a single line 'backlog: bd' or 'backlog: gh' (comments after # are fine)"* ]] - [[ "$output" == *" rewrite it: clerk doctor --fix --backend bd (or --backend gh)"* ]] - run env -i CLICOLOR_FORCE=1 HOME="$home" PATH="/usr/bin:/bin" "$CLERK" doctor --fix --backend bd - [ "$status" -eq 0 ] - [ "$(cat "$repo/.clerk")" = "backlog: bd" ] -} - -@test "doctor detects a bd shim shadowed by PATH ordering" { - repo=$(make_repo docshadow "backlog: bd") - home="$BATS_TEST_TMPDIR/docshadow-home" - sysbin="$BATS_TEST_TMPDIR/docshadow-sysbin" - make_fake_bin "$home/.config/bin" # the shim the user stowed - make_fake_bin "$sysbin" # a system bd that wins PATH resolution - home=$(phys "$home") - sysbin=$(phys "$sysbin") - cd "$repo" - run env -i CLICOLOR_FORCE=1 HOME="$home" PATH="$sysbin:$home/.config/bin:/usr/bin:/bin" "$CLERK" doctor - [ "$status" -eq 1 ] - [[ "$output" == *"$FAIL_TAG bd shim: SHADOWED — 'bd' resolves to $sysbin/bd, expected shim $home/.config/bin/bd"* ]] - [[ "$output" == *" fix: put $home/.config/bin before $sysbin in PATH"* ]] -} - -@test "doctor accepts the repo-local bin/bd as the expected shim" { - repo=$(make_repo doclocal "backlog: bd") - home="$BATS_TEST_TMPDIR/doclocal-home" - mkdir -p "$home" - home=$(phys "$home") - make_fake_bin "$repo/bin" - cd "$repo" - run env -i CLICOLOR_FORCE=1 HOME="$home" PATH="$repo/bin:/usr/bin:/bin" "$CLERK" doctor - [ "$status" -eq 0 ] - [[ "$output" == *"$OK_TAG bd shim: $repo/bin/bd (shim wins PATH resolution)"* ]] -} - -# -------------------------------------------------------- output discipline - - -@test "output discipline: every escape emitted is 16-color ANSI, never 256/truecolor" { - repo=$(make_repo ansi "backlog: bd") - norepo=$(make_repo ansi2 -) - home="$BATS_TEST_TMPDIR/ansi-home" - sysbin="$BATS_TEST_TMPDIR/ansi-sysbin" - make_fake_bin "$home/.config/bin" - make_fake_bin "$sysbin" - home=$(phys "$home") - sysbin=$(phys "$sysbin") - - all="" - run "$CLERK" --version - all+="$output"$'\n' - run "$CLERK" --help - all+="$output"$'\n' - run "$CLERK" frobnicate - all+="$output"$'\n' - run "$CLERK" backlog - all+="$output"$'\n' - for v in "${ALL_VERBS[@]}" doctor; do - # shellcheck disable=SC2086 # word-split $v into noun + verb on purpose - run "$CLERK" --explain $v - all+="$output"$'\n' - done - cd "$repo" - run "$CLERK" capture "a title" - all+="$output"$'\n' - run env -i CLICOLOR_FORCE=1 HOME="$home" PATH="$home/.config/bin:/usr/bin:/bin" "$CLERK" doctor - all+="$output"$'\n' - run env -i CLICOLOR_FORCE=1 HOME="$home" PATH="$sysbin:$home/.config/bin:/usr/bin:/bin" "$CLERK" doctor - all+="$output"$'\n' - cd "$norepo" - run "$CLERK" sync - all+="$output"$'\n' - run env -i CLICOLOR_FORCE=1 HOME="$home" PATH="/usr/bin:/bin" "$CLERK" doctor - all+="$output"$'\n' - run env -i CLICOLOR_FORCE=1 HOME="$home" PATH="/usr/bin:/bin" "$CLERK" doctor --fix --backend bd - all+="$output"$'\n' - - # no 256-color / truecolor SGR anywhere (38;5 / 38;2 / 48;5 / 48;2) - if printf '%s' "$all" | grep -qE '\[[0-9;]*[34]8;[25];'; then - echo "forbidden 256/truecolor escape found" >&2 - return 1 - fi - # colored output was actually captured, and every CSI sequence emitted is from the - # 16-color set: bold(1), reset(0), fg 30-37 / bright fg 90-97 - seqs=$(printf '%s' "$all" | grep -oE "${ESC}\[[0-9;]*[a-zA-Z]" | sort -u) - [ -n "$seqs" ] - while IFS= read -r s; do - if ! printf '%s' "$s" | grep -qE "^${ESC}\[(0|1|3[0-7]|9[0-7])(;(0|1|3[0-7]|9[0-7]))*m$"; then - printf 'non-16-color escape emitted: %q\n' "$s" >&2 - return 1 - fi - done <<<"$seqs" -} - -@test "output discipline: colour is suppressed off a TTY and by NO_COLOR" { - repo=$(make_repo ansisuppress "backlog: bd") - home="$BATS_TEST_TMPDIR/ansisuppress-home" - make_fake_bin "$home/.config/bin" - home=$(phys "$home") - cd "$repo" - - # bats captures through a pipe, so stdout is not a TTY. With no CLICOLOR_FORCE the - # doctor report must be escape-free — downstream parsers/logs must never see escapes - # (ADR 0015 output discipline) — while the plain-text status lines keep their meaning. - run env -i HOME="$home" PATH="$home/.config/bin:/usr/bin:/bin" "$CLERK" doctor - [ "$status" -eq 0 ] - [[ "$output" != *"$ESC["* ]] - [[ "$output" == *"[ ok ] .clerk marker: backlog: bd ($repo/.clerk)"* ]] - [ "${lines[0]}" = "clerk doctor — $repo" ] - [ "${lines[${#lines[@]} - 1]}" = "clerk doctor: all clear" ] - - # NO_COLOR wins even when colour is force-enabled: a consumer that sets NO_COLOR must - # never receive escapes, whatever CLICOLOR_FORCE says. - run env -i HOME="$home" PATH="$home/.config/bin:/usr/bin:/bin" NO_COLOR=1 CLICOLOR_FORCE=1 "$CLERK" doctor - [ "$status" -eq 0 ] - [[ "$output" != *"$ESC["* ]] -} diff --git a/tests/clerk/cutover.bats b/tests/clerk/cutover.bats deleted file mode 100644 index a7137ff..0000000 --- a/tests/clerk/cutover.bats +++ /dev/null @@ -1,75 +0,0 @@ -#!/usr/bin/env bats -# cutover.bats — clerk cutover + local docs (dotfiles-dft.8) - -setup() { - REPO_ROOT="$(cd "$BATS_TEST_DIRNAME/../.." && pwd)" -} - -@test "repo commits the Clerk marker and Project-gate configuration" { - cd "$REPO_ROOT" - [ "$(cat .clerk)" = $'backlog: bd\nproject-gate: clerk/project-gate.json' ] -} - -@test "GitHub validation invokes the project-owned adapter, not Clerk reconciliation" { - cd "$REPO_ROOT" - grep -q 'clerk/project-gate run' .github/workflows/delivery-gate.yml - ! grep -q 'bin/clerk backlog gate' .github/workflows/delivery-gate.yml -} - -@test "CLAUDE layer names Clerk, not storage backends" { - cd "$REPO_ROOT" - [ "$(readlink CLAUDE.md)" = "AGENTS.md" ] - grep -q 'clerk' AGENTS.md - run grep -nEi '(^|[^[:alnum:]_])(bd|beads?|github|gh)([^[:alnum:]_]|$)' AGENTS.md - [ "$status" -eq 1 ] - [ "$output" = "" ] -} - -@test "zshenv no longer advertises nextdelivery" { - cd "$REPO_ROOT" - run grep -n 'nextdelivery' zsh/.zshenv - [ "$status" -eq 1 ] - [ "$output" = "" ] -} - -@test "clerk repo-meta stays out of git and stow" { - cd "$REPO_ROOT" - git check-ignore -q .worktrees/example - grep -qxF '^\.clerk$' .stow-local-ignore -} - -@test "Python bytecode and cache artifacts stay out of git" { - cd "$REPO_ROOT" - git check-ignore -q clerk/src/clerk/__pycache__/cli.cpython-311.pyc - git check-ignore -q clerk/src/clerk/cli.pyc - git check-ignore -q clerk/src/clerk/cli.pyo - git check-ignore -q clerk/src/clerk/_native.pyd -} - -@test "operator issue-tracker doc no longer calls this repo private-tier" { - cd "$REPO_ROOT" - run grep -n 'private tier' docs/agents/issue-tracker.md - [ "$status" -eq 1 ] - [ "$output" = "" ] - grep -q 'Clerk-backed backlog' docs/agents/issue-tracker.md -} - -@test "nextdelivery is only a Clerk compatibility shim" { - cd "$REPO_ROOT" - grep -q "clerk backlog next" bin/nextdelivery - grep -q "clerk doctor" bin/nextdelivery - run grep -n 'umbel adopt\|repo-visibility\|bd list\|gh issue' bin/nextdelivery - [ "$status" -eq 1 ] - [ "$output" = "" ] -} - -@test "old-generation umbel bundles still resolve" { - command -v umbel >/dev/null 2>&1 || skip "umbel not installed" - cd "$REPO_ROOT" - run env UMBEL_ARTIFACTS_DIR="$REPO_ROOT/umbel" umbel show discovery - [ "$status" -eq 0 ] - [[ "$output" == *'name: discovery'* ]] - run env UMBEL_ARTIFACTS_DIR="$REPO_ROOT/umbel" umbel show delivery-superpowers - [ "$status" -eq 0 ] - [[ "$output" == *'name: delivery-superpowers'* ]] -} diff --git a/tests/clerk/finish-sync.bats b/tests/clerk/finish-sync.bats deleted file mode 100644 index 134eca3..0000000 --- a/tests/clerk/finish-sync.bats +++ /dev/null @@ -1,365 +0,0 @@ -#!/usr/bin/env bats -# finish-sync.bats — clerk backlog finish + sync reconciler (unit dotfiles-dft.5). - -setup() { - source "$BATS_TEST_DIRNAME/helpers.bash" - git_sandbox - CLERK="$BATS_TEST_DIRNAME/../../bin/clerk" - BD_MIN_PATH="/usr/local/bin:/usr/bin:/bin" - STUB_BIN="$BATS_TEST_TMPDIR/stub-bin" - mkdir -p "$STUB_BIN" - export PATH="$STUB_BIN:$BD_MIN_PATH" - install_check_stubs -} - -install_check_stubs() { - cat >"$STUB_BIN/bats" <<'SH' -#!/usr/bin/env bash -exit 0 -SH - cat >"$STUB_BIN/shellcheck" <<'SH' -#!/usr/bin/env bash -exit 0 -SH - chmod +x "$STUB_BIN/bats" "$STUB_BIN/shellcheck" -} - -make_finish_repo() { # $1=subdir - local base="$BATS_TEST_TMPDIR/$1" origin seed clone - mkdir -p "$base" - origin="$base/origin.git" - seed="$base/seed" - clone="$base/clone" - git init -q --bare -b main "$origin" - git init -q -b main "$seed" - git -C "$seed" -c user.email=clerk@test -c user.name=clerk commit -q --allow-empty -m seed - git -C "$seed" remote add origin "$origin" - git -C "$seed" push -q origin main - git clone -q "$origin" "$clone" - clone="$(cd "$clone" && pwd -P)" - git -C "$clone" config user.email clerk@test - git -C "$clone" config user.name clerk - printf 'backlog: bd\n' >"$clone/.clerk" - git -C "$clone" add -A - git -C "$clone" commit -q -m marker - git -C "$clone" push -q origin main - (cd "$clone" && bd init -q --non-interactive --skip-hooks --skip-agents >/dev/null 2>&1) - git -C "$clone" add .beads >/dev/null 2>&1 || true - git -C "$clone" commit -q -m beads-metadata >/dev/null 2>&1 || true - git -C "$clone" push -q origin main >/dev/null 2>&1 || true - printf '%s\n' "$clone" -} - -mk_claimed_unit() { # echoes id; caller cwd is repo - local id short - id=$(bd create 'finish unit' --description '## Acceptance Criteria -- does the thing' --silent) - bd update "$id" --add-label stage:ready --claim >/dev/null - short="${id#*-}" - git branch -q "delivery/$short" origin/main - git push -q origin "delivery/$short" - printf '%s\n' "$id" -} - -install_gh_pr_stub() { # $1=mode: none|review|fail|merged|multi - local mode="$1" - cat >"$STUB_BIN/gh" <<'SH' -#!/usr/bin/env bash -printf '%s\n' "$*" >>"$BATS_TEST_TMPDIR/gh.calls" -mode="__MODE__" -if [ "$1 $2" = "pr list" ]; then - case "$mode" in - none) json='[]' ;; - review) json='[{"number":7,"url":"https://example/pr/7","state":"OPEN","mergedAt":"","reviewDecision":"REVIEW_REQUIRED","statusCheckRollup":[{"name":"delivery-gate","status":"COMPLETED","conclusion":"SUCCESS"}],"headRefName":"delivery/x","isDraft":false,"updatedAt":"2026-07-10T00:00:00Z"}]' ;; - pending) json='[{"number":6,"url":"https://example/pr/6","state":"OPEN","mergedAt":"","reviewDecision":"APPROVED","statusCheckRollup":[{"name":"delivery-gate","status":"IN_PROGRESS","conclusion":""}],"headRefName":"delivery/x","isDraft":false,"updatedAt":"2026-07-10T00:00:00Z"}]' ;; - fail) json='[{"number":8,"url":"https://example/pr/8","state":"OPEN","mergedAt":"","reviewDecision":"APPROVED","statusCheckRollup":[{"name":"delivery-gate","status":"COMPLETED","conclusion":"FAILURE"},{"name":"unit-tests","status":"COMPLETED","conclusion":"SUCCESS"}],"headRefName":"delivery/x","isDraft":false,"updatedAt":"2026-07-10T00:00:00Z"}]' ;; - merged) json='[{"number":9,"url":"https://example/pr/9","state":"MERGED","mergedAt":"2026-07-10T00:00:00Z","reviewDecision":"APPROVED","statusCheckRollup":[{"name":"delivery-gate","status":"COMPLETED","conclusion":"SUCCESS"}],"headRefName":"delivery/x","isDraft":false,"updatedAt":"2026-07-10T00:00:00Z"}]' ;; - draft) json='[{"number":10,"url":"https://example/pr/10","state":"OPEN","mergedAt":"","reviewDecision":"APPROVED","statusCheckRollup":[{"name":"delivery-gate","status":"COMPLETED","conclusion":"SUCCESS"}],"headRefName":"delivery/x","isDraft":true,"updatedAt":"2026-07-10T00:00:00Z"}]' ;; - multi) json='[{"number":5,"url":"https://example/pr/5","state":"CLOSED","mergedAt":"","reviewDecision":"","statusCheckRollup":[],"headRefName":"delivery/x","isDraft":false,"updatedAt":"2026-07-09T00:00:00Z"},{"number":12,"url":"https://example/pr/12","state":"OPEN","mergedAt":"","reviewDecision":"REVIEW_REQUIRED","statusCheckRollup":[{"name":"delivery-gate","status":"COMPLETED","conclusion":"SUCCESS"}],"headRefName":"delivery/x","isDraft":false,"updatedAt":"2026-07-10T00:00:00Z"}]' ;; - esac - jq_expr="" - prev="" - for arg in "$@"; do - if [ "$prev" = "--jq" ]; then jq_expr="$arg"; fi - prev="$arg" - done - if [ -n "$jq_expr" ]; then - printf '%s\n' "$json" | jq -r "$jq_expr" - else - printf '%s\n' "$json" - fi - exit 0 -fi -if [ "$1 $2" = "issue view" ]; then - state=OPEN - labels='[{"name":"ready-for-agent"}]' - [ ! -e "$BATS_TEST_TMPDIR/gh.closed" ] || state=CLOSED - [ ! -e "$BATS_TEST_TMPDIR/gh.label-removed" ] || labels='[]' - printf '{"number":42,"title":"finish unit","body":"","assignees":[],"state":"%s","labels":%s}\n' "$state" "$labels" - exit 0 -fi -if [ "$1 $2" = "issue close" ]; then - touch "$BATS_TEST_TMPDIR/gh.closed" - exit 0 -fi -if [ "$1 $2" = "issue edit" ]; then - touch "$BATS_TEST_TMPDIR/gh.label-removed" - exit 0 -fi -if [ "$1 $2" = "pr merge" ]; then - echo merge-attempt >>"$BATS_TEST_TMPDIR/gh.calls" - exit 0 -fi -if [ "$1 $2" = "pr checks" ]; then exit 0; fi -exit 0 -SH - sed -i "s/__MODE__/$mode/" "$STUB_BIN/gh" - chmod +x "$STUB_BIN/gh" -} - -@test "finish: no-PR state refuses and prescribes the exact submit invocation" { - repo=$(make_finish_repo finish_no_pr) - cd "$repo" - id=$(mk_claimed_unit) - short="${id#*-}" - git checkout -q "delivery/$short" - install_gh_pr_stub none - run "$CLERK" backlog finish - [ "$status" -eq 2 ] - [ "${lines[0]}" = "clerk: backlog finish refused — no PR found for delivery/$short" ] - [ "${lines[1]}" = " run 'clerk backlog submit $id --body-file <path-to-pr-body.md>'" ] -} - -@test "finish: explicit missing Work id is a prescriptive usage error" { - repo=$(make_finish_repo finish_missing_work) - cd "$repo" - install_gh_pr_stub none - run "$CLERK" backlog finish dotfiles-missing - [ "$status" -eq 2 ] - [ "$output" = "clerk backlog finish: dotfiles-missing not found — check the id ('clerk backlog show <id>' inspects Work)" ] -} - -@test "finish: unresolved current branch stays behind the Clerk boundary" { - repo=$(make_finish_repo finish_unresolved_branch) - cd "$repo" - git checkout -q -b delivery/missing origin/main - run "$CLERK" backlog finish - [ "$status" -eq 2 ] - [ "$output" = "clerk backlog finish: could not resolve Work for delivery/missing — run 'clerk doctor' to check backend state or rerun 'clerk backlog finish <full-id>'" ] - [[ "$output" != *"bd "* ]] - [[ "$output" != *"bead"* ]] -} - -@test "finish: awaiting-review reports and exits 0 with no merge attempt" { - repo=$(make_finish_repo finish_review) - cd "$repo" - id=$(mk_claimed_unit) - short="${id#*-}" - git checkout -q "delivery/$short" - install_gh_pr_stub review - run "$CLERK" backlog finish - [ "$status" -eq 0 ] - [ "$output" = "clerk: PR #7 for $id is awaiting review — finish will complete after review" ] - ! grep -q 'pr merge' "$BATS_TEST_TMPDIR/gh.calls" -} - -@test "finish: pending checks prescribe --watch and exit successfully" { - repo=$(make_finish_repo finish_pending) - cd "$repo" - id=$(mk_claimed_unit) - short="${id#*-}" - git checkout -q "delivery/$short" - install_gh_pr_stub pending - run "$CLERK" backlog finish - [ "$status" -eq 0 ] - [ "${lines[0]}" = "clerk: PR #6 for $id has pending checks — run 'clerk backlog finish $id --watch' to wait" ] - [ "${lines[1]}" = " delivery-gate" ] -} - -@test "finish: failing checks output each named failure" { - repo=$(make_finish_repo finish_fail) - cd "$repo" - id=$(mk_claimed_unit) - short="${id#*-}" - git checkout -q "delivery/$short" - install_gh_pr_stub fail - run "$CLERK" backlog finish - [ "$status" -eq 1 ] - [[ "$output" == *"clerk: PR #8 for $id has failing checks"* ]] - [[ "$output" == *"delivery-gate"* ]] - [[ "$output" != *"unit-tests"* ]] -} - -@test "finish: draft PR is reported without a merge attempt" { - repo=$(make_finish_repo finish_draft) - cd "$repo" - id=$(mk_claimed_unit) - short="${id#*-}" - git checkout -q "delivery/$short" - install_gh_pr_stub draft - run "$CLERK" backlog finish - [ "$status" -eq 0 ] - [ "$output" = "clerk: PR #10 for $id is a draft — finish will complete after it is marked ready" ] - ! grep -q 'pr merge' "$BATS_TEST_TMPDIR/gh.calls" -} - -@test "finish: ignores stale closed PRs and reconciles the active PR for the branch" { - repo=$(make_finish_repo finish_multi) - cd "$repo" - id=$(mk_claimed_unit) - short="${id#*-}" - git checkout -q "delivery/$short" - install_gh_pr_stub multi - run "$CLERK" backlog finish - [ "$status" -eq 0 ] - [ "$output" = "clerk: PR #12 for $id is awaiting review — finish will complete after review" ] -} - -@test "finish: refuses to push an unpublished branch that is behind origin/main" { - repo=$(make_finish_repo finish_behind) - cd "$repo" - id=$(bd create 'behind unit' --description '## Acceptance Criteria -- does the thing' --silent) - bd update "$id" --claim >/dev/null - short="${id#*-}" - git branch -q "delivery/$short" origin/main - printf 'new base\n' >base.txt - git add base.txt - git commit -q -m 'advance main' - git push -q origin main - git checkout -q "delivery/$short" - run "$CLERK" backlog finish - [ "$status" -eq 2 ] - [ "${lines[0]}" = "clerk: backlog finish refused — delivery/$short is behind origin/main" ] - [ "${lines[1]}" = " run 'git rebase origin/main', then rerun 'clerk backlog finish'" ] - ! git -C "$repo" ls-remote --exit-code --heads origin "delivery/$short" >/dev/null 2>&1 -} - -@test "finish: post-merge cleanup closes the unit, strips stage:ready, and immediate second run is a clean no-op" { - repo=$(make_finish_repo finish_merged) - cd "$repo" - id=$(mk_claimed_unit) - short="${id#*-}" - git worktree add -q "$repo/.worktrees/$short" "delivery/$short" - install_gh_pr_stub merged - cd "$repo/.worktrees/$short" - run "$CLERK" backlog finish - [ "$status" -eq 0 ] - [[ "$output" == *"finished $id — PR #9 merged, delivery/$short cleaned up, unit closed"* ]] - [ ! -d "$repo/.worktrees/$short" ] - ! git -C "$repo" show-ref --verify --quiet "refs/heads/delivery/$short" - ! git -C "$repo" ls-remote --exit-code --heads origin "delivery/$short" >/dev/null 2>&1 - json=$(bd -C "$repo" show "$id" --readonly --json) - [ "$(jq -r '.[0].status' <<<"$json")" = closed ] - [ "$(jq -r '(.[0].labels // []) | index("stage:ready")' <<<"$json")" = null ] - cd "$repo" - run "$CLERK" backlog finish "$id" - [ "$status" -eq 0 ] - [[ "$output" == *"finished $id — PR #9 merged, delivery/$short cleaned up, unit closed"* ]] - json=$(bd -C "$repo" show "$id" --readonly --json) - [ "$(jq -r '.[0].status' <<<"$json")" = closed ] - [ "$(jq -r '(.[0].labels // []) | index("stage:ready")' <<<"$json")" = null ] -} - -@test "finish: remote branch lookup failure stops before Work closure" { - repo=$(make_finish_repo finish_remote_failure) - cd "$repo" - id=$(mk_claimed_unit) - short="${id#*-}" - git worktree add -q "$repo/.worktrees/$short" "delivery/$short" - install_gh_pr_stub merged - git remote set-url origin "$repo/missing-origin.git" - cd "$repo/.worktrees/$short" - run "$CLERK" backlog finish - [ "$status" -eq 5 ] - [[ "$output" == *"could not query origin for delivery/$short"* ]] - json=$(bd -C "$repo" show "$id" --readonly --json) - [ "$(jq -r '.[0].status' <<<"$json")" = in_progress ] -} - -@test "finish: gh-backed cleanup closes and verifies the Work exactly once" { - repo=$(make_finish_repo finish_gh_merged) - cd "$repo" - printf 'backlog: gh\n' >.clerk - git branch -q delivery/42 origin/main - git push -q origin delivery/42 - git worktree add -q "$repo/.worktrees/42" delivery/42 - printf 'backlog: gh\n' >"$repo/.worktrees/42/.clerk" - git -C "$repo/.worktrees/42" add .clerk - git -C "$repo/.worktrees/42" commit -q -m 'gh marker' - install_gh_pr_stub merged - cd "$repo/.worktrees/42" - run "$CLERK" backlog finish 42 - [ "$status" -eq 0 ] - [[ "$output" == *"finished 42 — PR #9 merged, delivery/42 cleaned up, unit closed"* ]] - cd "$repo" - run "$CLERK" backlog finish 42 - [ "$status" -eq 0 ] - [ "$(grep -c '^issue close ' "$BATS_TEST_TMPDIR/gh.calls")" -eq 1 ] - [ "$(grep -c '^issue edit ' "$BATS_TEST_TMPDIR/gh.calls")" -eq 1 ] -} - -@test "finish: gh lookup backend failure is not misreported as a bad Work id" { - repo=$(make_finish_repo finish_gh_lookup_failure) - cd "$repo" - printf 'backlog: gh\n' >.clerk - cat >"$STUB_BIN/gh" <<'SH' -#!/usr/bin/env bash -printf 'repository not found\n' >&2 -exit 1 -SH - chmod +x "$STUB_BIN/gh" - run "$CLERK" backlog finish 42 - [ "$status" -eq 5 ] - [[ "$output" == *"finish failed — gh issue view did not succeed for 42"* ]] -} - -@test "finish: stage:ready strip is self-verified before success" { - repo=$(make_finish_repo finish_strip_verify) - cd "$repo" - id=$(mk_claimed_unit) - short="${id#*-}" - git worktree add -q "$repo/.worktrees/$short" "delivery/$short" - install_gh_pr_stub merged - real_bd=$(command -v bd) - cat >"$STUB_BIN/bd" <<SH -#!/usr/bin/env bash -for arg in "\$@"; do - if [ "\$arg" = --remove-label ]; then - exit 0 - fi -done -exec "$real_bd" "\$@" -SH - chmod +x "$STUB_BIN/bd" - cd "$repo/.worktrees/$short" - run "$CLERK" backlog finish - [ "$status" -eq 5 ] - [[ "$output" == *"was not confirmed without stage:ready after finish"* ]] - json=$("$real_bd" -C "$repo" show "$id" --readonly --json) - [ "$(jq -r '.[0].status' <<<"$json")" = closed ] - [ "$(jq -r '(.[0].labels // []) | index("stage:ready")' <<<"$json")" != null ] -} - -@test "sync: gh-backed repositories warn and skip instead of failing the sweep" { - repo=$(make_finish_repo sync_gh) - cd "$repo" - printf 'backlog: gh\n' >.clerk - run "$CLERK" sync - [ "$status" -eq 0 ] - [ "$output" = "clerk: sync: gh-backed claim sweep is not available in this generation; skipping" ] -} - -@test "sync: dangling claim is reported and no PR is created" { - repo=$(make_finish_repo sync_dangling) - cd "$repo" - id=$(bd create 'dangling unit' --description '## Acceptance Criteria -- does the thing' --silent) - bd update "$id" --claim >/dev/null - install_gh_pr_stub none - run "$CLERK" sync - [ "$status" -eq 0 ] - [[ "$output" == *"clerk: sync scanning 1 open claim(s)"* ]] - [[ "$output" == *"$id is claimed but has no delivery/${id#*-} branch/worktree — no PR created"* ]] - ! grep -q 'pr create' "$BATS_TEST_TMPDIR/gh.calls" -} diff --git a/tests/clerk/gate-submit.bats b/tests/clerk/gate-submit.bats deleted file mode 100644 index de68122..0000000 --- a/tests/clerk/gate-submit.bats +++ /dev/null @@ -1,271 +0,0 @@ -#!/usr/bin/env bats -# Project-gate protocol coverage for Clerk delivery submission. - -setup() { - source "$BATS_TEST_DIRNAME/helpers.bash" - git_sandbox - CLERK="$BATS_TEST_DIRNAME/../../bin/clerk" - BD_MIN_PATH="/usr/local/bin:/usr/bin:/bin" - STUB_BIN="$BATS_TEST_TMPDIR/stub-bin" - mkdir -p "$STUB_BIN" - export PATH="$STUB_BIN:$BD_MIN_PATH" -} - -install_gh_stub() { - cat >"$STUB_BIN/gh" <<'SH' -#!/usr/bin/env bash -printf '%s\n' "$*" >>"$BATS_TEST_TMPDIR/gh.calls" -previous= -for arg; do - case "$previous" in - --title) printf '%s' "$arg" >"$BATS_TEST_TMPDIR/gh.title" ;; - --body) printf '%s' "$arg" >"$BATS_TEST_TMPDIR/gh.body" ;; - esac - previous="$arg" -done -printf '%s' "${GH_PR_CREATE_OUTPUT-https://github.com/example/repo/pull/1}" -SH - chmod +x "$STUB_BIN/gh" -} - -make_repo() { # $1=name $2=adapter body $3=owner - local base origin repo adapter="$2" owner="${3:-clerk}" - base="$BATS_TEST_TMPDIR/$1" - origin="$base/origin.git" - repo="$base/repo" - mkdir -p "$base" - git init -q --bare -b main "$origin" - git init -q -b main "$repo" - git -C "$repo" config user.email clerk@test - git -C "$repo" config user.name clerk - git -C "$repo" remote add origin "$origin" - (cd "$repo" && bd init -q --non-interactive --skip-hooks --skip-agents >/dev/null 2>&1) - printf 'backlog: bd\nproject-gate: gate.json\n' >"$repo/.clerk" - printf '{"adapter":"gate","submission_owner":"%s"}\n' "$owner" >"$repo/gate.json" - printf '%s\n' "$adapter" >"$repo/gate" - chmod +x "$repo/gate" - git -C "$repo" add . - git -C "$repo" commit -q -m gate - git -C "$repo" push -q origin main - printf '%s\n' "$repo" -} - -claimable_work() { # $1=repo $2=acceptance - local repo="$1" acceptance="${2:-gate acceptance}" id short - id=$(cd "$repo" && bd create 'gate work' --acceptance "$acceptance" --silent) - short="${id#*-}" - git -C "$repo" checkout -q -b "delivery/$short" - printf '%s\n' "$id" -} - -@test "submit fails closed without a project-gate configuration" { - repo=$(make_repo no_config $'#!/usr/bin/env bash\nexit 0') - printf 'backlog: bd\n' >"$repo/.clerk" - git -C "$repo" add .clerk && git -C "$repo" commit -q -m remove-gate - git -C "$repo" push -q origin main - id=$(claimable_work "$repo") - cd "$repo" - run "$CLERK" backlog submit "$id" - [ "$status" -eq 5 ] - [[ "$output" == *"no project-gate configuration"* ]] -} - -@test "submit runs the trusted-default adapter, not delivery-branch replacement content" { - adapter=$'#!/usr/bin/env bash\nset -euo pipefail\nop=$1; request=$(cat); printf "trusted:%s\\n" "$op" >> "$BATS_TEST_TMPDIR/adapter.calls"; head=$(printf "%s" "$request" | jq -r .delivery.starting_commit); jq -cn --arg h "$head" \'{status:"failed",summary:"expected failure",assessed_commit:$h}\'' - repo=$(make_repo trusted "$adapter") - id=$(claimable_work "$repo") - printf 'backlog: bd\nproject-gate: evil.json\n' >"$repo/.clerk" - printf '{"adapter":"gate"}\n' >"$repo/evil.json" - printf '#!/usr/bin/env bash\nprintf evil >&2\nexit 99\n' >"$repo/gate" - chmod +x "$repo/gate" - cd "$repo" - run "$CLERK" backlog submit "$id" - [ "$status" -eq 6 ] - [ "$(cat "$BATS_TEST_TMPDIR/adapter.calls")" = "trusted:run" ] -} - -@test "a valid failed verdict differs from operational and malformed adapter failures" { - failed=$'#!/usr/bin/env bash\nrequest=$(cat); head=$(printf "%s" "$request" | jq -r .delivery.starting_commit); jq -cn --arg h "$head" \'{status:"failed",summary:"check failed",assessed_commit:$h}\'' - repo=$(make_repo failed "$failed") - id=$(claimable_work "$repo") - cd "$repo" - run "$CLERK" backlog submit "$id" - [ "$status" -eq 6 ] - [[ "$output" == *"check failed"* ]] - [ -z "$(git ls-remote --heads origin "delivery/${id#*-}")" ] - [ ! -e "$BATS_TEST_TMPDIR/gh.calls" ] - - broken=$'#!/usr/bin/env bash\nexit 9' - repo=$(make_repo broken "$broken") - id=$(claimable_work "$repo") - cd "$repo" - run "$CLERK" backlog submit "$id" - [ "$status" -eq 5 ] - [[ "$output" == *"adapter execution failed"* ]] - - malformed=$'#!/usr/bin/env bash\nprintf not-json' - repo=$(make_repo malformed "$malformed") - id=$(claimable_work "$repo") - cd "$repo" - run "$CLERK" backlog submit "$id" - [ "$status" -eq 5 ] - [[ "$output" == *"valid Gate result JSON"* ]] - - missing_run=$'#!/usr/bin/env bash\nrequest=$(cat); head=$(printf "%s" "$request" | jq -r .delivery.starting_commit); jq -cn --arg h "$head" \'{status:"pending",summary:"queued",assessed_commit:$h}\'' - repo=$(make_repo missing_run "$missing_run") - id=$(claimable_work "$repo") - cd "$repo" - run "$CLERK" backlog submit "$id" - [ "$status" -eq 5 ] - [[ "$output" == *"pending Gate result requires run.id"* ]] -} - -@test "a Clerk-owned passing result hands off the assessed delivery head" { - adapter=$'#!/usr/bin/env bash\nrequest=$(cat); head=$(printf "%s" "$request" | jq -r .delivery.starting_commit); jq -cn --arg h "$head" \'{status:"passed",summary:"green",assessed_commit:$h}\'' - repo=$(make_repo clerk_pass "$adapter") - acceptance=$' indented criterion\n- gate acceptance' - id=$(claimable_work "$repo" "$acceptance") - install_gh_stub - cd "$repo" - run "$CLERK" backlog submit "$id" - [ "$status" -eq 0 ] - [ "$(grep -c '^pr create' "$BATS_TEST_TMPDIR/gh.calls")" -eq 1 ] - [ "$(cat "$BATS_TEST_TMPDIR/gh.title")" = "gate work ($id)" ] - [ "$(cat "$BATS_TEST_TMPDIR/gh.body")" = "$(printf '## Project gate\n\ngreen\n\n## Acceptance criteria\n\n%s' "$acceptance")" ] - ! grep -q -- '--auto-merge' "$BATS_TEST_TMPDIR/gh.calls" -} - -@test "submit refuses Work without Acceptance criteria before the Project gate" { - adapter=$'#!/usr/bin/env bash\ntouch "$BATS_TEST_TMPDIR/adapter-called"' - repo=$(make_repo missing_acceptance "$adapter") - id=$(cd "$repo" && bd create 'missing acceptance' --silent) - git -C "$repo" checkout -q -b "delivery/${id#*-}" - install_gh_stub - cd "$repo" - run "$CLERK" backlog submit "$id" - [ "$status" -eq 2 ] - [[ "$output" == *"has no acceptance criteria"* ]] - [ ! -e "$BATS_TEST_TMPDIR/adapter-called" ] - [ ! -e "$BATS_TEST_TMPDIR/gh.calls" ] -} - -@test "submit rejects missing malformed and additional PR creation output" { - adapter=$'#!/usr/bin/env bash\nrequest=$(cat); head=$(printf "%s" "$request" | jq -r .delivery.starting_commit); jq -cn --arg h "$head" \'{status:"passed",summary:"green",assessed_commit:$h}\'' - for fixture in missing malformed invalid_owner invalid_repo additional; do - repo=$(make_repo "create_$fixture" "$adapter") - id=$(claimable_work "$repo") - install_gh_stub - case "$fixture" in - missing) export GH_PR_CREATE_OUTPUT='' ;; - malformed) export GH_PR_CREATE_OUTPUT='not-a-url' ;; - invalid_owner) export GH_PR_CREATE_OUTPUT='https://github.com/-owner/repo/pull/1' ;; - invalid_repo) export GH_PR_CREATE_OUTPUT='https://github.com/owner/./pull/1' ;; - additional) export GH_PR_CREATE_OUTPUT=$'https://github.com/example/repo/pull/1\nextra' ;; - esac - cd "$repo" - run "$CLERK" backlog submit "$id" - [ "$status" -eq 5 ] - [[ "$output" == *"exactly one well-formed GitHub pull-request URL"* ]] - [[ "$output" != *"submitted $id"* ]] - unset GH_PR_CREATE_OUTPUT - done -} - -@test "submit reports a Work backend failure without running the Project gate" { - adapter=$'#!/usr/bin/env bash\ntouch "$BATS_TEST_TMPDIR/adapter-called"' - repo=$(make_repo backend_failure "$adapter") - id=$(claimable_work "$repo") - cat >"$STUB_BIN/bd" <<'SH' -#!/usr/bin/env bash -printf 'not-json' -SH - chmod +x "$STUB_BIN/bd" - cd "$repo" - run "$CLERK" backlog submit "$id" - [ "$status" -eq 5 ] - [[ "$output" == *"Work lookup failed"* ]] - [ ! -e "$BATS_TEST_TMPDIR/adapter-called" ] -} - -@test "pending runs require an id and only reconciliation invokes status" { - adapter=$'#!/usr/bin/env bash\nset -euo pipefail\nop=$1; request=$(cat); printf "%s\\n" "$op" >> "$BATS_TEST_TMPDIR/adapter.calls"; head=$(printf "%s" "$request" | jq -r .delivery.starting_commit); if [ "$op" = run ]; then jq -cn --arg h "$head" \'{status:"pending",summary:"queued",assessed_commit:$h,run:{id:"run-1"}}\'; else jq -cn --arg h "$head" \'{status:"failed",summary:"reconciled",assessed_commit:$h}\'; fi' - repo=$(make_repo pending "$adapter") - id=$(claimable_work "$repo") - cd "$repo" - run "$CLERK" backlog submit "$id" - [ "$status" -eq 0 ] - [ "$(cat "$BATS_TEST_TMPDIR/adapter.calls")" = run ] - run "$CLERK" backlog gate "$id" - [ "$status" -eq 6 ] - [ "$(tr '\n' ' ' <"$BATS_TEST_TMPDIR/adapter.calls")" = "run status " ] -} - -@test "Clerk-owned passes require the assessed commit to remain checked out" { - adapter=$'#!/usr/bin/env bash\nrequest=$(cat); worktree=$(printf "%s" "$request" | jq -r .delivery.worktree); head=$(printf "%s" "$request" | jq -r .delivery.starting_commit); git -C "$worktree" commit --allow-empty -qm "gate advanced head"; jq -cn --arg h "$head" \'{status:"passed",summary:"wrong head",assessed_commit:$h}\'' - repo=$(make_repo mismatch "$adapter") - id=$(claimable_work "$repo") - cd "$repo" - run "$CLERK" backlog submit "$id" - [ "$status" -eq 5 ] - [[ "$output" == *"not the current delivery worktree head"* ]] -} - -@test "project-gate ownership closes Work only when completion is reported" { - adapter=$'#!/usr/bin/env bash\nrequest=$(cat); head=$(printf "%s" "$request" | jq -r .delivery.starting_commit); jq -cn --arg h "$head" \'{status:"passed",summary:"delivered",assessed_commit:$h,delivery:{status:"completed"}}\'' - repo=$(make_repo owner "$adapter" project-gate) - id=$(claimable_work "$repo") - cd "$repo" - run "$CLERK" backlog submit "$id" - [ "$status" -eq 0 ] - run bd show "$id" --json - printf '%s' "$output" | jq -e '.[0].status == "closed"' >/dev/null -} - -@test "the dotfiles synchronous adapter runs Bats on half the available CPUs" { - worktree="$BATS_TEST_TMPDIR/worktree" - mkdir -p "$worktree/bin" "$worktree/tests/clerk" - export BATS_ARGS="$BATS_TEST_TMPDIR/bats.args" - cat >"$STUB_BIN/bats" <<'SH' -#!/usr/bin/env bash -printf '%s\n' "$*" >"$BATS_ARGS" -SH - cat >"$STUB_BIN/shellcheck" <<'SH' -#!/usr/bin/env bash -exit 0 -SH - chmod +x "$STUB_BIN/bats" "$STUB_BIN/shellcheck" - git init -q -b main "$worktree" - git -C "$worktree" config user.email clerk@test - git -C "$worktree" config user.name clerk - : >"$worktree/bin/tool" - git -C "$worktree" add . && git -C "$worktree" commit -q -m fixture - - run bash -c 'printf "%s" "{\"delivery\":{\"worktree\":\"$1\"}}" | "$2" run' _ "$worktree" "$BATS_TEST_DIRNAME/../../clerk/project-gate" - [ "$status" -eq 0 ] - cpus=$(getconf _NPROCESSORS_ONLN) - jobs=$((cpus / 2)) - [ "$jobs" -ge 1 ] || jobs=1 - [ "$(cat "$BATS_ARGS")" = "--jobs $jobs tests/clerk" ] -} - -@test "the dotfiles synchronous adapter translates selected command failure to a terminal verdict" { - worktree="$BATS_TEST_TMPDIR/worktree" - mkdir -p "$worktree/bin" "$worktree/tests/clerk" - cat >"$STUB_BIN/bats" <<'SH' -#!/usr/bin/env bash -exit 1 -SH - cat >"$STUB_BIN/shellcheck" <<'SH' -#!/usr/bin/env bash -exit 0 -SH - chmod +x "$STUB_BIN/bats" "$STUB_BIN/shellcheck" - git init -q -b main "$worktree" - git -C "$worktree" config user.email clerk@test - git -C "$worktree" config user.name clerk - : >"$worktree/bin/tool" - git -C "$worktree" add . && git -C "$worktree" commit -q -m fixture - run bash -c 'printf "%s" "{\"delivery\":{\"worktree\":\"$1\"}}" | "$2" run' _ "$worktree" "$BATS_TEST_DIRNAME/../../clerk/project-gate" - [ "$status" -eq 0 ] - printf '%s' "$output" | jq -e '.status == "failed" and .summary != "" and .assessed_commit != ""' >/dev/null -} diff --git a/tests/clerk/glean.bats b/tests/clerk/glean.bats deleted file mode 100644 index db8e441..0000000 --- a/tests/clerk/glean.bats +++ /dev/null @@ -1,544 +0,0 @@ -#!/usr/bin/env bats -# tests/clerk/glean.bats — acceptance tests for clerk glean (dotfiles-dft.6) - -load 'helpers.bash' - -setup() { - git_sandbox - CLERK="$BATS_TEST_DIRNAME/../../bin/clerk" - export CLERK_TEST_TRANSCRIPT_DIR="${BATS_TEST_TMPDIR}/transcripts" - mkdir -p "${CLERK_TEST_TRANSCRIPT_DIR}" - export CLERK_GLEAN_STATE_DIR="${BATS_TEST_TMPDIR}/clerk-glean-state" - mkdir -p "${CLERK_GLEAN_STATE_DIR}" - # Avoid launching a real model in tests; the mocked judgment fork reads stdin and - # emits no candidates (successful no-finding fork). - export CLERK_GLEAN_JUDGMENT_CMD='cat >/dev/null; echo "{\"type\":\"none\",\"reason\":\"test\"}"' -} - -# Helper: write a transcript file with N JSONL lines -write_transcript() { # $1=file $2=lines... - local file="$1" - shift - for line in "$@"; do - printf '%s\n' "$line" >>"$file" - done -} - -# Helper: write a transcript line with is_error=true -write_error_line() { # $1=file $2=command $3=error_msg - local file="$1" cmd="$2" err="$3" - local uuid - uuid=$(uuidgen 2>/dev/null || cat /proc/sys/kernel/random/uuid 2>/dev/null || date +%s%N) - printf '{"type":"user","message":{"role":"user","content":"run %s"},"timestamp":"2026-07-10T12:00:00.000Z","sessionId":"test"}\n' "$cmd" >>"$file" - printf '{"type":"assistant","message":{"role":"assistant","content":[{"type":"tool_use","id":"%s","name":"Bash","input":{"command":"%s"}}]},"timestamp":"2026-07-10T12:00:01.000Z","sessionId":"test"}\n' "$uuid" "$cmd" >>"$file" - printf '{"type":"user","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"%s","content":"%s","is_error":true}],"timestamp":"2026-07-10T12:00:02.000Z","sessionId":"test"}\n' "$uuid" "$err" >>"$file" -} - -# Helper: create a minimal valid transcript with some errors -create_test_transcripts() { - local base_dir="$1" - mkdir -p "${base_dir}/session-main" - write_transcript "${base_dir}/session-main/transcript.jsonl" \ - '{"type":"mode","mode":"normal","sessionId":"main","timestamp":"2026-07-10T10:00:00.000Z"}' \ - '{"type":"user","message":{"role":"user","content":"hello"},"timestamp":"2026-07-10T10:00:01.000Z","sessionId":"main"}' \ - '{"type":"assistant","message":{"role":"assistant","content":"hi"},"timestamp":"2026-07-10T10:00:02.000Z","sessionId":"main"}' - write_error_line "${base_dir}/session-main/transcript.jsonl" "grep -r foo" "grep: foo: No such file or directory" - write_transcript "${base_dir}/session-main/transcript.jsonl" \ - '{"type":"user","message":{"role":"user","content":"done"},"timestamp":"2026-07-10T10:00:05.000Z","sessionId":"main"}' -} - -@test "glean: refuses when not in a git repo" { - cd /tmp - run "$CLERK" glean - [ "$status" -eq 4 ] - [[ "$output" == *"not inside a git repository"* ]] -} - -@test "glean: refuses when .clerk marker missing" { - local tmpdir - tmpdir=$(mktemp -d) - cd "$tmpdir" - git init -q - git config user.email "test@test" - git config user.name "Test" - run "$CLERK" glean - [ "$status" -eq 4 ] - [[ "$output" == *"missing .clerk marker"* ]] -} - -@test "glean: runs without error on empty transcript dir (no captures filed)" { - local tmpdir - tmpdir=$(mktemp -d) - cd "$tmpdir" - git init -q - git config user.email "test@test" - git config user.name "Test" - printf 'backlog: bd\n' >.clerk - - export CLERK_GLEAN_TRANSCRIPT_DIR="${CLERK_TEST_TRANSCRIPT_DIR}" - export CLERK_GLEAN_STATE_DIR="${CLERK_GLEAN_STATE_DIR}" - - run "$CLERK" glean - [ "$status" -eq 0 ] - [[ "$output" == *"clerk: glean"* ]] || [[ "$output" == *"glean"* ]] -} - -@test "glean: default Claude judgment fork uses cheap bounded model" { - local tmpdir stub_bin args_file - tmpdir=$(mktemp -d) - cd "$tmpdir" - git init -q - git config user.email "test@test" - git config user.name "Test" - printf 'backlog: bd\n' >.clerk - - stub_bin="${BATS_TEST_TMPDIR}/bin" - args_file="${BATS_TEST_TMPDIR}/claude-args.txt" - mkdir -p "$stub_bin" - cat >"$stub_bin/claude" <<'SH' -#!/usr/bin/env bash -printf '%s\n' "$@" >"$CLERK_STUB_CLAUDE_ARGS" -cat >/dev/null -printf '{"type":"none","reason":"stub"}\n' -SH - chmod +x "$stub_bin/claude" - export PATH="$stub_bin:$PATH" - export CLERK_STUB_CLAUDE_ARGS="$args_file" - unset CLERK_GLEAN_JUDGMENT_CMD - export CLERK_GLEAN_TRANSCRIPT_DIR="${CLERK_TEST_TRANSCRIPT_DIR}" - export CLERK_GLEAN_STATE_DIR="${CLERK_GLEAN_STATE_DIR}" - export CLERK_GLEAN_MIN_CHUNK_LINES=1 - create_test_transcripts "${CLERK_TEST_TRANSCRIPT_DIR}" - - run "$CLERK" glean - [ "$status" -eq 0 ] - grep -qx -- '--model' "$args_file" - grep -qx -- 'haiku' "$args_file" - grep -qx -- '--max-budget-usd' "$args_file" - grep -qx -- '0.05' "$args_file" -} - -@test "glean: flock - two simultaneous invocations, only one harvests" { - local tmpdir - tmpdir=$(mktemp -d) - cd "$tmpdir" - git init -q - git config user.email "test@test" - git config user.name "Test" - printf 'backlog: bd\n' >.clerk - - export CLERK_GLEAN_TRANSCRIPT_DIR="${CLERK_TEST_TRANSCRIPT_DIR}" - export CLERK_GLEAN_STATE_DIR="${CLERK_GLEAN_STATE_DIR}" - create_test_transcripts "${CLERK_TEST_TRANSCRIPT_DIR}" - - # Hold the lock long enough that the second invocation collides with it. - export CLERK_GLEAN_MIN_CHUNK_LINES=1 - export CLERK_GLEAN_JUDGMENT_CMD='sleep 1; cat >/dev/null; echo "{\"type\":\"none\",\"reason\":\"test\"}"' - local out1="${BATS_TEST_TMPDIR}/glean-1.out" out2="${BATS_TEST_TMPDIR}/glean-2.out" - "$CLERK" glean >"$out1" 2>&1 & - local pid1=$! - sleep 0.1 - "$CLERK" glean >"$out2" 2>&1 & - local pid2=$! - wait "$pid1" - wait "$pid2" - - local locked_count scanning_count - locked_count=$(grep -h -c 'another instance is running' "$out1" "$out2" | paste -sd+ - | bc) - scanning_count=$(grep -h -c '^glean: scanning ' "$out1" "$out2" | paste -sd+ - | bc) - [ "$locked_count" -eq 1 ] - [ "$scanning_count" -eq 1 ] - - local watermarks - watermarks=$(find "${CLERK_GLEAN_STATE_DIR}" -name '*.watermark' 2>/dev/null) - [ -n "$watermarks" ] -} - -@test "glean: kill mid-harvest leaves watermark unmoved; next run re-harvests" { - local tmpdir - tmpdir=$(mktemp -d) - cd "$tmpdir" - git init -q - git config user.email "test@test" - git config user.name "Test" - printf 'backlog: bd\n' >.clerk - - export CLERK_GLEAN_TRANSCRIPT_DIR="${CLERK_TEST_TRANSCRIPT_DIR}" - export CLERK_GLEAN_STATE_DIR="${CLERK_GLEAN_STATE_DIR}" - create_test_transcripts "${CLERK_TEST_TRANSCRIPT_DIR}" - - # Start a harvest whose judgment fork blocks, then kill it before the fork can finish. - export CLERK_GLEAN_MIN_CHUNK_LINES=1 - export CLERK_GLEAN_JUDGMENT_CMD='sleep 5; cat >/dev/null; echo "{\"type\":\"none\",\"reason\":\"test\"}"' - "$CLERK" glean >"${BATS_TEST_TMPDIR}/killed.out" 2>&1 & - local pid=$! - sleep 0.2 - kill "$pid" 2>/dev/null || true - wait "$pid" 2>/dev/null || true - - # Watermark is still absent because the fork never completed. - [ -z "$(find "${CLERK_GLEAN_STATE_DIR}" -name '*.watermark' -print -quit 2>/dev/null)" ] - - # A later successful run sees the same chunk and advances the watermark. - export CLERK_GLEAN_JUDGMENT_CMD='cat >/dev/null; echo "{\"type\":\"none\",\"reason\":\"test\"}"' - run "$CLERK" glean - [ "$status" -eq 0 ] - [ -n "$(find "${CLERK_GLEAN_STATE_DIR}" -name '*.watermark' -print -quit 2>/dev/null)" ] -} - -@test "glean: /clear-orphaned transcript segment is harvested" { - local tmpdir - tmpdir=$(mktemp -d) - cd "$tmpdir" - git init -q - git config user.email "test@test" - git config user.name "Test" - printf 'backlog: bd\n' >.clerk - - local clear_dir="${CLERK_TEST_TRANSCRIPT_DIR}/session-clear" - mkdir -p "$clear_dir" - write_transcript "${clear_dir}/transcript.jsonl" \ - '{"type":"mode","mode":"normal","sessionId":"clear","timestamp":"2026-07-10T10:00:00.000Z"}' \ - '{"type":"user","message":{"role":"user","content":"/clear"},"timestamp":"2026-07-10T10:00:01.000Z","sessionId":"clear"}' \ - '{"type":"system","subtype":"clear_orphaned","timestamp":"2026-07-10T10:00:02.000Z","sessionId":"clear"}' - write_error_line "${clear_dir}/transcript.jsonl" "cat /nonexistent" "cat: /nonexistent: No such file or directory" - - export CLERK_GLEAN_TRANSCRIPT_DIR="${CLERK_TEST_TRANSCRIPT_DIR}" - export CLERK_GLEAN_STATE_DIR="${CLERK_GLEAN_STATE_DIR}" - export CLERK_GLEAN_MIN_CHUNK_LINES=1 - - run "$CLERK" glean - [ "$status" -eq 0 ] - [ -n "$(find "${CLERK_GLEAN_STATE_DIR}" -name '*.watermark' -print -quit 2>/dev/null)" ] -} - -@test "glean: sub-threshold chunk skipped and logged (no silent caps)" { - local tmpdir - tmpdir=$(mktemp -d) - cd "$tmpdir" - git init -q - git config user.email "test@test" - git config user.name "Test" - printf 'backlog: bd\n' >.clerk - - local small_dir="${CLERK_TEST_TRANSCRIPT_DIR}/session-tiny" - mkdir -p "$small_dir" - # Very small transcript - below minimum chunk size - write_transcript "${small_dir}/transcript.jsonl" \ - '{"type":"mode","mode":"normal","sessionId":"tiny","timestamp":"2026-07-10T10:00:00.000Z"}' - - export CLERK_GLEAN_TRANSCRIPT_DIR="${CLERK_TEST_TRANSCRIPT_DIR}" - export CLERK_GLEAN_STATE_DIR="${CLERK_GLEAN_STATE_DIR}" - - run "$CLERK" glean - [ "$status" -eq 0 ] - [[ "$output" == *"sub-threshold chunk skipped"* ]] -} - -@test "glean: exactly-once - no transcript line harvested twice across runs" { - local tmpdir - tmpdir=$(mktemp -d) - cd "$tmpdir" - git init -q - git config user.email "test@test" - git config user.name "Test" - printf 'backlog: bd\n' >.clerk - - export CLERK_GLEAN_TRANSCRIPT_DIR="${CLERK_TEST_TRANSCRIPT_DIR}" - export CLERK_GLEAN_STATE_DIR="${CLERK_GLEAN_STATE_DIR}" - create_test_transcripts "${CLERK_TEST_TRANSCRIPT_DIR}" - - # Run glean twice; the second run sees the watermark and cannot advance or reprocess. - export CLERK_GLEAN_MIN_CHUNK_LINES=1 - run "$CLERK" glean - [ "$status" -eq 0 ] - local first_watermark - first_watermark=$(cat "${CLERK_GLEAN_STATE_DIR}"/*.watermark 2>/dev/null | sort) - - run "$CLERK" glean - [ "$status" -eq 0 ] - local second_watermark - second_watermark=$(cat "${CLERK_GLEAN_STATE_DIR}"/*.watermark 2>/dev/null | sort) - [ "$first_watermark" = "$second_watermark" ] - [[ "$output" != *"sub-threshold chunk skipped"* ]] -} - -@test "glean: appended transcript lines are harvested from the saved offset" { - local tmpdir transcript - tmpdir=$(mktemp -d) - cd "$tmpdir" - git init -q - git config user.email "test@test" - git config user.name "Test" - printf 'backlog: bd\n' >.clerk - - transcript="${CLERK_TEST_TRANSCRIPT_DIR}/session.jsonl" - write_transcript "$transcript" '{"type":"mode","sessionId":"first"}' - export CLERK_GLEAN_TRANSCRIPT_DIR="${CLERK_TEST_TRANSCRIPT_DIR}" - export CLERK_GLEAN_STATE_DIR="${CLERK_GLEAN_STATE_DIR}" - export CLERK_GLEAN_MIN_CHUNK_LINES=1 - - run "$CLERK" glean - [ "$status" -eq 0 ] - [ "$(cat "${CLERK_GLEAN_STATE_DIR}"/*.watermark)" -eq 1 ] - - printf '%s\n' '{"type":"mode","sessionId":"second"}' >>"$transcript" - run "$CLERK" glean - [ "$status" -eq 0 ] - [[ "$output" == *"lines 2-2"* ]] - [ "$(cat "${CLERK_GLEAN_STATE_DIR}"/*.watermark)" -eq 2 ] -} - -@test "glean: malformed judgment output does not advance the watermark" { - local tmpdir - tmpdir=$(mktemp -d) - cd "$tmpdir" - git init -q - git config user.email "test@test" - git config user.name "Test" - printf 'backlog: bd\n' >.clerk - - export CLERK_GLEAN_TRANSCRIPT_DIR="${CLERK_TEST_TRANSCRIPT_DIR}" - export CLERK_GLEAN_STATE_DIR="${CLERK_GLEAN_STATE_DIR}" - export CLERK_GLEAN_MIN_CHUNK_LINES=1 - export CLERK_GLEAN_JUDGMENT_CMD='cat >/dev/null; echo not-json' - create_test_transcripts "${CLERK_TEST_TRANSCRIPT_DIR}" - - run "$CLERK" glean - [ "$status" -eq 5 ] - [[ "$output" == *"failed to process"* ]] - [[ "$output" == *"rerun 'clerk glean'"* ]] - [ -z "$(find "${CLERK_GLEAN_STATE_DIR}" -name '*.watermark' -print -quit 2>/dev/null)" ] -} - -@test "glean: failed judgment command does not advance the watermark" { - local tmpdir - tmpdir=$(mktemp -d) - cd "$tmpdir" - git init -q - git config user.email "test@test" - git config user.name "Test" - printf 'backlog: bd\n' >.clerk - - export CLERK_GLEAN_TRANSCRIPT_DIR="${CLERK_TEST_TRANSCRIPT_DIR}" - export CLERK_GLEAN_STATE_DIR="${CLERK_GLEAN_STATE_DIR}" - export CLERK_GLEAN_MIN_CHUNK_LINES=1 - export CLERK_GLEAN_JUDGMENT_CMD='cat >/dev/null; exit 9' - create_test_transcripts "${CLERK_TEST_TRANSCRIPT_DIR}" - - run "$CLERK" glean - [ "$status" -eq 5 ] - [[ "$output" == *"failed to process"* ]] - [[ "$output" == *"rerun 'clerk glean'"* ]] - [ -z "$(find "${CLERK_GLEAN_STATE_DIR}" -name '*.watermark' -print -quit 2>/dev/null)" ] -} - -@test "glean: whitespace-only judgment separator lines are ignored" { - local tmpdir - tmpdir=$(mktemp -d) - cd "$tmpdir" - git init -q - git config user.email "test@test" - git config user.name "Test" - printf 'backlog: bd\n' >.clerk - - export CLERK_GLEAN_TRANSCRIPT_DIR="${CLERK_TEST_TRANSCRIPT_DIR}" - export CLERK_GLEAN_STATE_DIR="${CLERK_GLEAN_STATE_DIR}" - export CLERK_GLEAN_MIN_CHUNK_LINES=1 - export CLERK_GLEAN_JUDGMENT_CMD='cat >/dev/null; printf " \n{\"type\":\"none\",\"reason\":\"test\"}\n\t\n"' - create_test_transcripts "${CLERK_TEST_TRANSCRIPT_DIR}" - - run "$CLERK" glean - [ "$status" -eq 0 ] - [ -n "$(find "${CLERK_GLEAN_STATE_DIR}" -name '*.watermark' -print -quit 2>/dev/null)" ] -} - -@test "glean: default transcript scope is the current project slug, not the whole archive" { - local tmpdir projects slug wanted other - tmpdir=$(mktemp -d) - projects="${BATS_TEST_TMPDIR}/projects-root" - mkdir -p "$projects" - cd "$tmpdir" - git init -q - git config user.email "test@test" - git config user.name "Test" - printf 'backlog: bd\n' >.clerk - slug=$(printf '%s' "$(pwd -P)" | tr '/' '-') - wanted="$projects/$slug" - other="$projects/-other-project" - mkdir -p "$wanted" "$other" - write_transcript "$wanted/session.jsonl" '{"type":"mode","sessionId":"wanted"}' - write_transcript "$other/session.jsonl" '{"type":"mode","sessionId":"other"}' - - unset CLERK_GLEAN_TRANSCRIPT_DIR - export CLERK_GLEAN_PROJECTS_ROOT="$projects" - export CLERK_GLEAN_STATE_DIR="${CLERK_GLEAN_STATE_DIR}" - - run "$CLERK" glean - [ "$status" -eq 0 ] - [[ "$output" == *"glean: scanning 1 transcript file(s)"* ]] - [[ "$output" == *"harvesting $wanted/session.jsonl"* ]] - [[ "$output" != *"$other/session.jsonl"* ]] -} - -@test "glean: partial candidate filing is idempotent across retry" { - local tmpdir fakebin logdir transcript_dir - tmpdir=$(mktemp -d) - fakebin="${BATS_TEST_TMPDIR}/fakebin" - logdir="${BATS_TEST_TMPDIR}/fake-bd" - mkdir -p "$fakebin" "$logdir" - cat >"$fakebin/bd" <<'FAKEBD' -#!/usr/bin/env bash -set -euo pipefail -state="${FAKE_BD_STATE:?}" -mkdir -p "$state/captures" -case "$1" in - config) exit 0 ;; - search) - [ "${FAIL_BD_SEARCH:-0}" = 1 ] && exit 9 - if [ "$2" != "--desc-contains" ]; then - # Real bd searches titles by default; the idempotency key lives in the body. - printf '[]\n' - exit 0 - fi - key="$3" - for f in "$state"/captures/*; do - [ -f "$f" ] || continue - if grep -qF "$key" "$f"; then - id=$(basename "$f") - printf '[{"id":"%s"}]\n' "$id" - exit 0 - fi - done - printf '[]\n' - ;; - create) - title="$2" body_file="" - shift 2 - while [ $# -gt 0 ]; do - case "$1" in - --body-file) body_file="$2"; shift ;; - esac - shift || true - done - if [ "$title" = "candidate two" ]; then - echo fail-second >>"$state/create.log" - exit 1 - fi - id="fake-$(wc -l <"$state/create.log" 2>/dev/null || printf 0)" - echo "$title" >>"$state/create.log" - cat "$body_file" >"$state/captures/$id" - printf '%s\n' "$id" - ;; - show) - printf '[{"id":"%s"}]\n' "$2" - ;; - *) exit 0 ;; -esac -FAKEBD - chmod +x "$fakebin/bd" - - cd "$tmpdir" - git init -q - git config user.email "test@test" - git config user.name "Test" - printf 'backlog: bd\n' >.clerk - transcript_dir="${CLERK_TEST_TRANSCRIPT_DIR}" - export CLERK_GLEAN_TRANSCRIPT_DIR="$transcript_dir" - export CLERK_GLEAN_STATE_DIR="${CLERK_GLEAN_STATE_DIR}" - export CLERK_GLEAN_MIN_CHUNK_LINES=1 - export FAKE_BD_STATE="$logdir" - export PATH="$fakebin:$PATH" - export CLERK_GLEAN_JUDGMENT_CMD='cat >/dev/null; echo "{\"type\":\"impediment\",\"title\":\"candidate one\",\"body\":\"body one\"}"; echo "{\"type\":\"impediment\",\"title\":\"candidate two\",\"body\":\"body two\"}"' - create_test_transcripts "$transcript_dir" - - run "$CLERK" glean - [ "$status" -eq 5 ] - [ -z "$(find "${CLERK_GLEAN_STATE_DIR}" -name '*.watermark' -print -quit 2>/dev/null)" ] - [ "$(grep -c '^candidate one$' "$logdir/create.log")" -eq 1 ] - - # Retry output may differ; chunk position, not model wording, is the idempotency key. - export CLERK_GLEAN_JUDGMENT_CMD='cat >/dev/null; echo "{\"type\":\"impediment\",\"title\":\"candidate one\",\"body\":\"reworded body\"}"; echo "{\"type\":\"impediment\",\"title\":\"candidate two\",\"body\":\"body two\"}"' - run "$CLERK" glean - [ "$status" -eq 5 ] - [ "$(grep -c '^candidate one$' "$logdir/create.log")" -eq 1 ] - - # A failed idempotency lookup is operational failure, never permission to duplicate. - export FAIL_BD_SEARCH=1 - run "$CLERK" glean - [ "$status" -eq 5 ] - [[ "$output" == *"capture lookup failed"* ]] - [ "$(grep -c '^candidate one$' "$logdir/create.log")" -eq 1 ] -} - -@test "glean: state directory created at ~/.local/state/clerk/ by default" { - local tmpdir - tmpdir=$(mktemp -d) - cd "$tmpdir" - git init -q - git config user.email "test@test" - git config user.name "Test" - printf 'backlog: bd\n' >.clerk - - # Don't override state dir - use default - unset CLERK_GLEAN_STATE_DIR - export CLERK_GLEAN_TRANSCRIPT_DIR="${CLERK_TEST_TRANSCRIPT_DIR}" - - run "$CLERK" glean - [ "$status" -eq 0 ] -} - -@test "glean: unavailable state directory is a prescriptive operational failure" { - local tmpdir - tmpdir=$(mktemp -d) - cd "$tmpdir" - git init -q - git config user.email "test@test" - git config user.name "Test" - printf 'backlog: bd\n' >.clerk - - export CLERK_GLEAN_STATE_DIR=/dev/null/clerk-glean - export CLERK_GLEAN_TRANSCRIPT_DIR="${CLERK_TEST_TRANSCRIPT_DIR}" - run "$CLERK" glean - [ "$status" -eq 5 ] - [[ "$output" == *"state path unavailable"* ]] - [[ "$output" == *"rerun 'clerk glean'"* ]] - [[ "$output" != *"Traceback"* ]] -} - -@test "glean: --async starts a background harvest and returns immediately" { - local tmpdir - tmpdir=$(mktemp -d) - cd "$tmpdir" - git init -q - git config user.email "test@test" - git config user.name "Test" - printf 'backlog: bd\n' >.clerk - - export CLERK_GLEAN_TRANSCRIPT_DIR="${CLERK_TEST_TRANSCRIPT_DIR}" - export CLERK_GLEAN_STATE_DIR="${CLERK_GLEAN_STATE_DIR}" - run "$CLERK" glean --async - [ "$status" -eq 0 ] - [ "$output" = "glean: async harvest started (log: ${CLERK_GLEAN_STATE_DIR}/glean.log)" ] -} - -@test "glean: --explain prints verb documentation" { - run "$CLERK" --explain glean - [ "$status" -eq 0 ] - [[ "$output" == *"watermark sweep"* ]] - [[ "$output" == *"clerk glean"* ]] -} - -@test "glean: unknown sub-verb under glean fails" { - local tmpdir - tmpdir=$(mktemp -d) - cd "$tmpdir" - git init -q - git config user.email "test@test" - git config user.name "Test" - printf 'backlog: bd\n' >.clerk - - run "$CLERK" glean unknown - [ "$status" -eq 2 ] - [[ "$output" == *"unknown argument 'unknown'"* ]] -} \ No newline at end of file diff --git a/tests/clerk/helpers.bash b/tests/clerk/helpers.bash deleted file mode 100644 index afc5138..0000000 --- a/tests/clerk/helpers.bash +++ /dev/null @@ -1,13 +0,0 @@ -# tests/clerk/helpers.bash — shared setup helpers for the clerk bats suite. -# shellcheck shell=bash - -# git_sandbox: redirect git's global + system config to throwaway locations so the -# scratch fixtures (git init / config / worktree) can never read or write the -# developer's real git config. A dft.3-era delivery leaked `init.defaultBranch` -# into the symlinked ~/.config/git/config because scratch git ran against the real -# global config; GIT_CONFIG_GLOBAL overrides the $HOME/$XDG lookup, so these two -# exports make the whole suite hermetic. Call first in every setup(). -git_sandbox() { - export GIT_CONFIG_SYSTEM=/dev/null - export GIT_CONFIG_GLOBAL="${BATS_TEST_TMPDIR:?git_sandbox needs BATS_TEST_TMPDIR}/gitconfig" -} diff --git a/tests/clerk/hermetic.bats b/tests/clerk/hermetic.bats deleted file mode 100644 index 0a34d1f..0000000 --- a/tests/clerk/hermetic.bats +++ /dev/null @@ -1,28 +0,0 @@ -#!/usr/bin/env bats -# hermetic.bats — proves the suite's git sandbox: scratch git config writes land in -# a throwaway location, never the developer's real global/system config. Guards the -# dft.3-era leak fix (an init.defaultBranch write bled into ~/.config/git/config). - -setup() { - source "$BATS_TEST_DIRNAME/helpers.bash" - git_sandbox - export PATH="/usr/local/bin:/usr/bin:/bin" -} - -@test "git sandbox: system config is neutralised" { - [ "$GIT_CONFIG_SYSTEM" = /dev/null ] -} - -@test "git sandbox: global config points inside the per-test tmpdir" { - case "$GIT_CONFIG_GLOBAL" in - "$BATS_TEST_TMPDIR"/*) : ;; - *) printf 'GIT_CONFIG_GLOBAL not sandboxed: %s\n' "$GIT_CONFIG_GLOBAL"; return 1 ;; - esac -} - -@test "git sandbox: a --global write lands in the sandbox, not the real config" { - git config --global clerk.leak.canary tripped - [ "$(git config --global --get clerk.leak.canary)" = tripped ] - run grep -q canary "$GIT_CONFIG_GLOBAL" - [ "$status" -eq 0 ] -} diff --git a/tests/clerk/inbox-graph.bats b/tests/clerk/inbox-graph.bats deleted file mode 100644 index fd94a96..0000000 --- a/tests/clerk/inbox-graph.bats +++ /dev/null @@ -1,326 +0,0 @@ -#!/usr/bin/env bats -# inbox-graph.bats — Clerk-native inbox graph primitives (unit dotfiles-2d8o). - -setup() { - source "$BATS_TEST_DIRNAME/helpers.bash" - git_sandbox - CLERK="$BATS_TEST_DIRNAME/../../bin/clerk" - BD_MIN_PATH="/usr/local/bin:/usr/bin:/bin" - export PATH="$BD_MIN_PATH" -} - -make_bd_repo() { - local dir="$BATS_TEST_TMPDIR/$1" - mkdir -p "$dir" - dir="$(cd "$dir" && pwd -P)" - git init -q -b main "$dir" - printf 'backlog: bd\n' >"$dir/.clerk" - git -C "$dir" add -A - git -C "$dir" -c user.email=clerk@test -c user.name=clerk commit -q -m fixture - (cd "$dir" && bd init -q --non-interactive --skip-hooks --skip-agents >/dev/null 2>&1) - printf '%s\n' "$dir" -} - -@test "capture supports canonical type, parent, repeatable blocked-by, and --impediment conflict" { - repo=$(make_bd_repo capture_graph) - cd "$repo" - parent=$("$CLERK" capture "map" --type epic | awk '{print $3}') - blocker=$("$CLERK" capture "first child" --parent "$parent" --type task | awk '{print $3}') - run "$CLERK" capture "blocked child" --parent "$parent" --blocked-by "$blocker" --type decision - [ "$status" -eq 0 ] - child="${output#clerk: filed }" - json=$(bd show "$child" --readonly --json) - [ "$(jq -r '.[0].issue_type' <<<"$json")" = decision ] - [ "$(jq -r '.[0].parent' <<<"$json")" = "$parent" ] - jq -e --arg blocker "$blocker" '.[0].dependencies | any(.dependency_type == "blocks" and .id == $blocker)' <<<"$json" >/dev/null - [ "$(jq -r '.[0].labels | index("stage:ready")' <<<"$json")" = null ] - - run "$CLERK" capture "bad" --impediment --type task - [ "$status" -eq 2 ] - [[ "$output" == *"do not combine"* ]] - - run "$CLERK" capture "missing parent" --blocked-by "$blocker" - [ "$status" -eq 2 ] - [[ "$output" == *"--blocked-by requires --parent"* ]] - - run "$CLERK" capture "bad type" --type enhancement - [ "$status" -eq 2 ] - [[ "$output" == *"invalid --type"* ]] - - bd config set types.custom research >/dev/null - run "$CLERK" capture "custom type" --type research - [ "$status" -eq 0 ] - custom="${output#clerk: filed }" - [ "$(bd show "$custom" --readonly --json | jq -r '.[0].issue_type')" = research ] -} - -@test "capture keeps a child of ready Work in the Inbox" { - repo=$(make_bd_repo capture_ready_parent) - cd "$repo" - parent=$(bd create "ready parent" --acceptance "parent ac" --silent) - "$CLERK" inbox ready "$parent" >/dev/null - - run "$CLERK" capture "new child" --parent "$parent" - [ "$status" -eq 0 ] - child="${output#clerk: filed }" - json=$(bd show "$child" --readonly --json) - [ "$(jq -r '.[0].parent' <<<"$json")" = "$parent" ] - [ "$(jq -r '.[0].labels | index("stage:ready")' <<<"$json")" = null ] - - run "$CLERK" backlog next - [ "$status" -eq 0 ] - [[ "$output" != *"$child"* ]] - - printf 'child design\n' >"$repo/design" - printf '%s\n' '- child acceptance' >"$repo/acceptance" - run "$CLERK" inbox ready "$child" --design-file "$repo/design" --acceptance-file "$repo/acceptance" - [ "$status" -eq 0 ] - json=$(bd show "$child" --readonly --json) - [ "$(jq -r '.[0].labels | index("stage:ready")' <<<"$json")" != null ] -} - -@test "capture preserves ready-parent sibling blockers" { - repo=$(make_bd_repo capture_ready_parent_blocked) - cd "$repo" - parent=$(bd create "ready parent" --acceptance "parent ac" --silent) - ready_sibling=$(bd create "ready sibling" --parent "$parent" --acceptance "sibling ac" --silent) - "$CLERK" inbox ready "$parent" >/dev/null - "$CLERK" inbox ready "$ready_sibling" >/dev/null - - run "$CLERK" capture "new blocked child" --parent "$parent" --blocked-by "$ready_sibling" - [ "$status" -eq 0 ] - child="${output#clerk: filed }" - json=$(bd show "$child" --readonly --json) - [ "$(jq -r '.[0].parent' <<<"$json")" = "$parent" ] - jq -e --arg blocker "$ready_sibling" '.[0].dependencies | any(.dependency_type == "blocks" and .id == $blocker)' <<<"$json" >/dev/null - [ "$(jq -r '.[0].labels | index("stage:ready")' <<<"$json")" = null ] -} - -@test "children/frontier/blockers/blocked return normalized JSON and frontier only open unblocked unclaimed direct children" { - repo=$(make_bd_repo queries) - cd "$repo" - parent=$(bd create "map" --type epic --silent) - a=$(bd create "a" --parent "$parent" --silent) - b=$(bd create "b" --parent "$parent" --silent) - assigned=$(bd create "assigned" --parent "$parent" --silent) - closed=$(bd create "closed" --parent "$parent" --silent) - ready=$(bd create "ready" --parent "$parent" --labels stage:ready --silent) - bd dep add "$b" "$a" >/dev/null - bd update "$assigned" --assignee other >/dev/null - bd close "$closed" --reason done >/dev/null - - run "$CLERK" inbox children "$parent" - [ "$status" -eq 0 ] - [ "$(jq -r '.parent.id' <<<"$output")" = "$parent" ] - [ "$(jq '.items | length' <<<"$output")" -eq 5 ] - - run "$CLERK" inbox frontier "$parent" - [ "$status" -eq 0 ] - [ "$(jq -r '.items[].id' <<<"$output")" = "$a" ] - - bd close "$a" --reason done >/dev/null - run "$CLERK" inbox frontier "$parent" --pretty - [ "$status" -eq 0 ] - [ "$(jq -r '.items[].id' <<<"$output")" = "$b" ] - [[ "$output" == *$'\n "items"'* ]] - - run "$CLERK" inbox blockers "$b" - [ "$status" -eq 0 ] - [ "$(jq -r '.items[0].id' <<<"$output")" = "$a" ] - run "$CLERK" inbox blocked "$a" - [ "$status" -eq 0 ] - [ "$(jq -r '.items[0].id' <<<"$output")" = "$b" ] - - bd close "$parent" --reason done --force >/dev/null - run "$CLERK" inbox frontier "$parent" - [ "$status" -eq 2 ] - [[ "$output" == *"non-closed Work graph parent"* ]] -} - -@test "parent mutation refuses cycles and dependency-invalidating moves unless dropped" { - repo=$(make_bd_repo parent_mutation) - cd "$repo" - p1=$(bd create "p1" --type epic --silent) - p2=$(bd create "p2" --type epic --silent) - a=$(bd create "a" --parent "$p1" --silent) - b=$(bd create "b" --parent "$p1" --silent) - bd dep add "$b" "$a" >/dev/null - - run "$CLERK" inbox parent set "$p1" "$a" - [ "$status" -eq 2 ] - [[ "$output" == *"parent cycle"* ]] - - run "$CLERK" inbox parent set "$b" "$p2" - [ "$status" -eq 2 ] - [[ "$output" == *"--drop-invalid-deps"* ]] - [ "$(bd show "$b" --readonly --json | jq -r '.[0].parent')" = "$p1" ] - - run "$CLERK" inbox parent set "$b" "$p2" --drop-invalid-deps - [ "$status" -eq 0 ] - [ "$(bd show "$b" --readonly --json | jq -r '.[0].parent')" = "$p2" ] - ! bd show "$b" --readonly --json | jq -e --arg a "$a" '.[0].dependencies | any(.dependency_type == "blocks" and .id == $a)' >/dev/null - - run "$CLERK" inbox parent clear "$b" - [ "$status" -eq 0 ] - [ "$(bd show "$b" --readonly --json | jq -r '.[0].parent // ""')" = "" ] -} - -@test "dependency mutation is sibling-only and refuses cycles" { - repo=$(make_bd_repo dep_mutation) - cd "$repo" - p=$(bd create "p" --type epic --silent) - other=$(bd create "other" --type epic --silent) - a=$(bd create "a" --parent "$p" --silent) - b=$(bd create "b" --parent "$p" --silent) - c=$(bd create "c" --parent "$other" --silent) - - run "$CLERK" inbox dep add "$b" "$a" - [ "$status" -eq 0 ] - jq -e --arg a "$a" '.[0].dependencies | any(.dependency_type == "blocks" and .id == $a)' < <(bd show "$b" --readonly --json) >/dev/null - - run "$CLERK" inbox dep add "$a" "$b" - [ "$status" -eq 2 ] - [[ "$output" == *"dependency cycle"* ]] - - run "$CLERK" inbox dep add "$a" "$c" - [ "$status" -eq 2 ] - [[ "$output" == *"sibling-only"* ]] - - run "$CLERK" inbox dep remove "$b" "$a" - [ "$status" -eq 0 ] - ! bd show "$b" --readonly --json | jq -e --arg a "$a" '.[0].dependencies | any(.dependency_type == "blocks" and .id == $a)' >/dev/null - - bd close "$a" --reason done >/dev/null - run "$CLERK" inbox dep add "$b" "$a" - [ "$status" -eq 0 ] - jq -e --arg a "$a" '.[0].dependencies | any(.dependency_type == "blocks" and .id == $a and .status == "closed")' < <(bd show "$b" --readonly --json) >/dev/null -} - -@test "claim and release manage planning-item assignment and frontier visibility" { - repo=$(make_bd_repo planning_claim) - cd "$repo" - parent=$(bd create "map" --type epic --silent) - a=$(bd create "a" --parent "$parent" --silent) - b=$(bd create "b" --parent "$parent" --silent) - blocked=$(bd create "blocked" --parent "$parent" --silent) - bd dep add "$blocked" "$a" >/dev/null - bd update "$b" --assignee other >/dev/null - - run "$CLERK" inbox claim "$blocked" - [ "$status" -eq 2 ] - [[ "$output" == *"open blockers"* ]] - - run "$CLERK" inbox claim "$b" - [ "$status" -eq 5 ] - [[ "$output" == *"already claimed by other"* ]] - - run "$CLERK" inbox claim "$a" - [ "$status" -eq 0 ] - [ "$output" = "clerk: claimed $a" ] - [ -n "$(bd show "$a" --readonly --json | jq -r '.[0].assignee // ""')" ] - - run "$CLERK" inbox frontier "$parent" - [ "$status" -eq 0 ] - [ "$(jq '.items | length' <<<"$output")" -eq 0 ] - - run "$CLERK" inbox claim "$a" - [ "$status" -eq 0 ] - [ "$output" = "clerk: $a already claimed by you" ] - - run "$CLERK" inbox release "$a" - [ "$status" -eq 0 ] - [ "$output" = "clerk: released $a" ] - [ -z "$(bd show "$a" --readonly --json | jq -r '.[0].assignee // ""')" ] - - run "$CLERK" inbox frontier "$parent" - [ "$status" -eq 0 ] - [ "$(jq -r '.items[].id' <<<"$output")" = "$a" ] -} - -@test "current planning claim may ready resolve or drop; another actor's claim refuses" { - repo=$(make_bd_repo planning_claim_disposition) - cd "$repo" - mine_ready=$(bd create "mine ready" --acceptance "ready ac" --silent) - mine_resolve=$(bd create "mine resolve" --silent) - mine_drop=$(bd create "mine drop" --silent) - other=$(bd create "other" --acceptance "other ac" --silent) - bd update "$mine_ready" --claim >/dev/null - bd update "$mine_resolve" --claim >/dev/null - bd update "$mine_drop" --claim >/dev/null - bd update "$other" --claim --actor other-agent >/dev/null - - run "$CLERK" inbox ready "$mine_ready" - [ "$status" -eq 0 ] - json=$(bd show "$mine_ready" --readonly --json) - [ "$(jq -r '.[0].status' <<<"$json")" = open ] - [ -z "$(jq -r '.[0].assignee // ""' <<<"$json")" ] - [ "$(jq -r '.[0].labels | index("stage:ready")' <<<"$json")" != null ] - - run bash -c 'printf "done" | "$1" inbox resolve "$2"' _ "$CLERK" "$mine_resolve" - [ "$status" -eq 0 ] - [ "$(bd show "$mine_resolve" --readonly --json | jq -r '.[0].status')" = closed ] - - run "$CLERK" inbox drop "$mine_drop" - [ "$status" -eq 0 ] - [ "$(bd show "$mine_drop" --readonly --json | jq -r '.[0].status')" = closed ] - - run "$CLERK" inbox ready "$other" - [ "$status" -eq 5 ] - [[ "$output" == *"claimed by other-agent"* ]] -} - -@test "note, guarded update, and resolve mutate planning items without promotion" { - repo=$(make_bd_repo planning_mutations) - cd "$repo" - id=$(bd create "old title" --description "old body" --silent) - printf 'plain note' >note.txt - run "$CLERK" inbox note "$id" --file note.txt - [ "$status" -eq 0 ] - [[ "$(bd show "$id" --readonly --json | jq -r '.[0].notes')" == *"plain note"* ]] - [ "$(bd show "$id" --readonly --json | jq -r '.[0].status')" = open ] - - guard=$("$CLERK" inbox show "$id" --json | jq -r .body_guard) - run bash -c 'printf "new body" | "$1" inbox update "$2" --title "new title" --type bug --stdin --body-guard "$3"' _ "$CLERK" "$id" "$guard" - [ "$status" -eq 0 ] - json=$(bd show "$id" --readonly --json) - [ "$(jq -r '.[0].title' <<<"$json")" = "new title" ] - [ "$(jq -r '.[0].issue_type' <<<"$json")" = bug ] - [ "$(jq -r '.[0].description' <<<"$json")" = "new body" ] - - run bash -c 'printf "stale body" | "$1" inbox update "$2" --stdin --body-guard "$3"' _ "$CLERK" "$id" "$guard" - [ "$status" -eq 2 ] - [[ "$output" == *"stale body guard"* ]] - - run bash -c 'printf "resolution" | "$1" inbox resolve "$2"' _ "$CLERK" "$id" - [ "$status" -eq 0 ] - json=$(bd show "$id" --readonly --json) - [ "$(jq -r '.[0].status' <<<"$json")" = closed ] - [ "$(jq -r '.[0].close_reason' <<<"$json")" = resolved ] - [[ "$(jq -r '.[0].notes' <<<"$json")" == *"clerk-resolution:"* ]] -} - -@test "inbox ready promotes refined items despite blockers or children; ready items leave refinement views" { - repo=$(make_bd_repo ready_graph) - cd "$repo" - parent=$(bd create "parent" --acceptance "parent ac" --silent) - blocker=$(bd create "blocker" --parent "$parent" --acceptance "blocker ac" --silent) - leaf=$(bd create "leaf" --parent "$parent" --acceptance "leaf ac" --silent) - bd dep add "$leaf" "$blocker" >/dev/null - - run "$CLERK" inbox ready "$leaf" - [ "$status" -eq 0 ] - [ "$(bd show "$leaf" --readonly --json | jq -r '.[0].labels | index("stage:ready")')" != null ] - - run "$CLERK" inbox ready "$parent" - [ "$status" -eq 0 ] - [ "$(bd show "$parent" --readonly --json | jq -r '.[0].labels | index("stage:ready")')" != null ] - - run "$CLERK" inbox list - [ "$status" -eq 0 ] - ! grep -F -q " $parent " <<<"$output" - ! grep -F -q " $leaf " <<<"$output" - - run "$CLERK" inbox frontier "$parent" - [ "$status" -eq 0 ] - [ "$(jq -r '.items[].id' <<<"$output")" = "$blocker" ] -} diff --git a/tests/clerk/inbox.bats b/tests/clerk/inbox.bats deleted file mode 100644 index f2c95b3..0000000 --- a/tests/clerk/inbox.bats +++ /dev/null @@ -1,1021 +0,0 @@ -#!/usr/bin/env bats -# inbox.bats — clerk capture + the six inbox verbs (unit dotfiles-dft.2). -# -# Printed output is load-bearing (ADR 0015), so these tests assert verbatim lines, not just -# exit codes. bd-backed verbs run against a SCRATCH bd db created fresh per test in the bats -# tmp dir (never this repo's real .beads); gh-backed verbs run against a FAKE `gh` placed -# earlier on PATH that logs its argv and returns canned output (same double pattern -# core.bats uses for the shadowed-shim test). PATH deliberately excludes this repo's -# personal ~/.config/bin/bd auto-sync shim (ADR 0013) — that shim triggers a background -# dolt push after every mutating call, which is unwanted noise (and a real-remote risk) for -# a scratch db; resolving straight to the underlying bd binary keeps these tests hermetic. -# In `backlog: gh` fixtures, bd is still initialized because GitHub is only the ready -# delivery backlog; raw capture/inbox storage remains bd. - -setup() { - source "$BATS_TEST_DIRNAME/helpers.bash" - git_sandbox - CLERK="$BATS_TEST_DIRNAME/../../bin/clerk" - # Excludes ~/.config/bin (the ADR 0013 auto-sync shim) on purpose — see header comment. - BD_MIN_PATH="/usr/local/bin:/usr/bin:/bin" - REAL_BD=$(PATH="$BD_MIN_PATH" command -v bd 2>/dev/null || command -v bd) - export PATH="$BD_MIN_PATH" -} - -# ---------------------------------------------------------------- fixtures -- - -# Scratch git repo + `.clerk` (backlog: bd) + a fresh scratch bd db (never this repo's real -# .beads). --skip-hooks/--skip-agents/--non-interactive keep the fixture from writing -# Claude/AGENTS.md scaffolding into the scratch dir. Echoes the physical path. -make_bd_repo() { # $1 = subdir name - local dir="$BATS_TEST_TMPDIR/$1" - mkdir -p "$dir" - dir="$(cd "$dir" && pwd -P)" - git init -q -b main "$dir" - printf 'backlog: bd\n' >"$dir/.clerk" - git -C "$dir" add -A - git -C "$dir" -c user.email=clerk@test -c user.name=clerk commit -q -m fixture - (cd "$dir" && bd init -q --non-interactive --skip-hooks --skip-agents >/dev/null 2>&1) - printf '%s\n' "$dir" -} - -add_origin() { # $1 = repo - local repo="$1" origin="$BATS_TEST_TMPDIR/origin-$(basename "$repo").git" - git init -q --bare -b main "$origin" - git -C "$repo" remote add origin "$origin" - git -C "$repo" push -q origin main -} - -mk_returned_branch() { # $1=repo $2=short - local repo="$1" short="$2" - git -C "$repo" branch "returned/$short" main - git -C "$repo" push -q origin "returned/$short" -} - -mk_returned_attempt() { # $1=repo $2=short $3=subject - local repo="$1" short="$2" subject="$3" wt="$BATS_TEST_TMPDIR/returned-$short-$RANDOM" - git -C "$repo" branch "returned/$short" main - git -C "$repo" worktree add -q "$wt" "returned/$short" - printf 'returned work\n' >"$wt/returned.txt" - git -C "$wt" add returned.txt - git -C "$wt" -c user.email=clerk@test -c user.name=clerk commit -q -m "$subject" - git -C "$repo" worktree remove "$wt" >/dev/null - git -C "$repo" push -q origin "returned/$short" -} - -advance_main() { # $1=repo - local repo="$1" - printf 'new main\n' >"$repo/main.txt" - git -C "$repo" add main.txt - git -C "$repo" -c user.email=clerk@test -c user.name=clerk commit -q -m "advance main" - git -C "$repo" push -q origin main 2>/dev/null || true -} - -# Scratch public-style repo + `.clerk` (backlog: gh) + a fresh scratch bd db. -# GitHub is the delivery backlog; bd remains the raw capture/inbox store. -make_gh_repo() { # $1 = subdir name - local dir="$BATS_TEST_TMPDIR/$1" - mkdir -p "$dir" - dir="$(cd "$dir" && pwd -P)" - git init -q -b main "$dir" - printf 'public\n' >"$dir/.repo-visibility" - printf 'backlog: gh\n' >"$dir/.clerk" - git -C "$dir" add -A - git -C "$dir" -c user.email=clerk@test -c user.name=clerk commit -q -m fixture - (cd "$dir" && bd init -q --non-interactive --skip-hooks --skip-agents >/dev/null 2>&1) - printf '%s\n' "$dir" -} - -# A fake `gh` that logs every invocation's argv to $FAKE_GH_LOG (\x1f-joined per call, -# ===CALL=== delimited — readable, grep-able, never parsed field-by-field) and returns -# canned output driven by $FAKE_GH_CREATE_URL / $FAKE_GH_LIST_JSON. -make_traced_bd() { # $1 = dir to place traced bd shim - mkdir -p "$1" - cat >"$1/bd" <<SHIM -#!/bin/sh -{ - for a in "\$@"; do printf '%s\\x1f' "\$a"; done - printf '\\n' -} >>"\$BD_TRACE_LOG" -exec "$REAL_BD" "\$@" -SHIM - chmod +x "$1/bd" -} - -make_fake_gh() { # $1 = dir to place the fake gh - mkdir -p "$1" - cat >"$1/gh" <<'SHIM' -#!/bin/sh -{ - printf '===CALL===\n' - for a in "$@"; do printf '%s\x1f' "$a"; done - printf '\n' -} >>"$FAKE_GH_LOG" -case "$1 $2" in - "issue create") - printf '%s\n' "${FAKE_GH_CREATE_URL:-https://github.com/acme/repo/issues/42}" - ;; - "issue list") - if [ -n "${FAKE_GH_LIST_JSON:-}" ] && [ -f "$FAKE_GH_LIST_JSON" ]; then - cat "$FAKE_GH_LIST_JSON" - else - printf '[]' - fi - ;; - "issue view") - printf 'fake gh issue view: %s\n' "$3" - ;; - "issue close") - printf 'closed\n' - ;; - "issue comment") - printf 'commented\n' - ;; - *) - printf 'fake-gh: unhandled: %s\n' "$*" >&2 - exit 1 - ;; -esac -SHIM - chmod +x "$1/gh" -} - -# A `bd` fork simulating a harness allowlisted to reads + pregrill's single write: any -# invocation carrying --readonly, or the exact `update <id> --append-notes ...` shape, -# proxies through to the real bd; every other shape is refused outright. Logs ALLOWED / -# REFUSED lines to $GUARD_LOG so a test can assert both "it succeeded" and "here is -# everything it actually tried to run". Caller exports REAL_BD and GUARD_LOG. -make_guarded_bd() { # $1 = dir to place the shim - mkdir -p "$1" - cat >"$1/bd" <<'SHIM' -#!/bin/sh -log() { [ -n "${GUARD_LOG:-}" ] && printf '%s\n' "ALLOWED: $*" >>"$GUARD_LOG"; } -refuse() { - [ -n "${GUARD_LOG:-}" ] && printf '%s\n' "REFUSED: $*" >>"$GUARD_LOG" - echo "guarded-bd: refused: $*" >&2 - exit 13 -} -case " $* " in - *' --readonly '*) log "$@"; exec "$REAL_BD" "$@" ;; - *' list '*|*' show '*|*' find-duplicates '*) refuse "$@" ;; - *' update '*' --append-notes '*) - case " $* " in - *' --add-label '*|*' --remove-label '*|*' --set-labels '*|*' --status '*|*' --claim '*) - refuse "$@" - ;; - *) log "$@"; exec "$REAL_BD" "$@" ;; - esac - ;; - *) refuse "$@" ;; -esac -SHIM - chmod +x "$1/bd" -} - -# ---------------------------------------------------------------- capture --- - -@test "capture (bd): files a bead and self-verifies before reporting success" { - repo=$(make_bd_repo cap1) - cd "$repo" - run "$CLERK" capture "fix the flaky test" - [ "$status" -eq 0 ] - [[ "$output" == "clerk: filed "* ]] - id="${output#clerk: filed }" - [ "$(bd show "$id" --readonly --json | jq -r '.[0].title')" = "fix the flaky test" ] - [ "$(bd show "$id" --readonly --json | jq -r '.[0].issue_type')" = task ] -} - -@test "capture (bd) --impediment: applies type:impediment, even against a brand-new db with no prior config" { - repo=$(make_bd_repo cap2) - cd "$repo" - # no `bd config set types.custom …` here — capture must self-provision it - run "$CLERK" capture "the harness denied a benign permission" --impediment - [ "$status" -eq 0 ] - [[ "$output" == "clerk: filed "*" (type: impediment)" ]] - id="${output#clerk: filed }" - id="${id% (type: impediment)}" - [ "$(bd show "$id" --readonly --json | jq -r '.[0].issue_type')" = impediment ] -} - -@test "capture (bd) --impediment is idempotent across repeated captures in the same db" { - repo=$(make_bd_repo cap3) - cd "$repo" - run "$CLERK" capture "first impediment" --impediment - [ "$status" -eq 0 ] - run "$CLERK" capture "second impediment" --impediment - [ "$status" -eq 0 ] - id="${output#clerk: filed }" - id="${id% (type: impediment)}" - [ "$(bd show "$id" --readonly --json | jq -r '.[0].issue_type')" = impediment ] -} - -@test "capture (bd) --stdin reads the description from stdin" { - repo=$(make_bd_repo cap4) - cd "$repo" - run bash -c "printf 'the reasoning at hand' | \"$CLERK\" capture \"a captured thought\" --stdin" - [ "$status" -eq 0 ] - id="${output#clerk: filed }" - [ "$(bd show "$id" --readonly --json | jq -r '.[0].description')" = "the reasoning at hand" ] -} - -@test "capture: missing title is a usage error, exit 2" { - repo=$(make_bd_repo cap5) - cd "$repo" - run "$CLERK" capture - [ "$status" -eq 2 ] - [ "$output" = 'clerk capture: missing title — usage: clerk capture "<title>" [--stdin|--type <type>|--impediment|--parent <id>|--blocked-by <id>]' ] -} - -@test "capture (gh backlog): files raw captures in bd, not GitHub" { - repo=$(make_gh_repo cap6) - fakebin="$BATS_TEST_TMPDIR/cap6-fakebin" - make_fake_gh "$fakebin" - export FAKE_GH_LOG="$BATS_TEST_TMPDIR/cap6.log" - : >"$FAKE_GH_LOG" - export PATH="$fakebin:$PATH" - cd "$repo" - run "$CLERK" capture "a gh-backed raw capture" - [ "$status" -eq 0 ] - [[ "$output" == "clerk: filed "* ]] - id="${output#clerk: filed }" - [ "$(bd show "$id" --readonly --json | jq -r '.[0].title')" = "a gh-backed raw capture" ] - [ ! -s "$FAKE_GH_LOG" ] -} - -@test "capture (gh backlog) --stdin passes body to bd" { - repo=$(make_gh_repo cap7) - cd "$repo" - run bash -c 'printf "%s\n" "details from stdin" | "$1" capture "a gh-backed stdin capture" --stdin' _ "$CLERK" - [ "$status" -eq 0 ] - id="${output#clerk: filed }" - [ "$(bd show "$id" --readonly --json | jq -r '.[0].description')" = "details from stdin" ] -} - -# ---------------------------------------------------------------- inbox list - - -@test "inbox list (bd) excludes stage:ready beads (the pool is OPEN minus stage:ready)" { - repo=$(make_bd_repo list1) - cd "$repo" - bd create "still in the inbox" --silent >/dev/null - bd create "already promoted" --labels stage:ready --silent >/dev/null - run "$CLERK" inbox list - [ "$status" -eq 0 ] - [ "${lines[0]}" = "Inbox (open, not ready) — 1 item(s):" ] - [[ "$output" == *"still in the inbox"* ]] - [[ "$output" != *"already promoted"* ]] -} - -@test "inbox list (bd): pregrill marker is absent before any pregrill" { - repo=$(make_bd_repo list2) - cd "$repo" - id=$(bd create "untouched" --silent) - run "$CLERK" inbox list - [ "$status" -eq 0 ] - [ "$output" = "Inbox (open, not ready) — 1 item(s): - $id [pregrill:absent] untouched" ] -} - -@test "inbox list (bd): pregrill marker is present immediately after pregrilling" { - repo=$(make_bd_repo list3) - cd "$repo" - id=$(bd create "about to be pregrilled" --silent) - run "$CLERK" inbox pregrill "$id" --decision "d" --premise "p|v" --criterion "c" - [ "$status" -eq 0 ] - run "$CLERK" inbox list - [ "$status" -eq 0 ] - [[ "$output" == *"$id [pregrill:present] about to be pregrilled"* ]] -} - -@test "inbox list (bd): pregrill marker flips present->stale after the bead body is edited" { - repo=$(make_bd_repo list4) - cd "$repo" - id=$(bd create "will be edited" --silent) - run "$CLERK" inbox pregrill "$id" - [ "$status" -eq 0 ] - run "$CLERK" inbox list - [[ "$output" == *"$id [pregrill:present]"* ]] - bd update "$id" --description "edited after the pregrill" >/dev/null - # Test the stale branch deterministically instead of waiting past the production tolerance. - # A negative test tolerance makes any post-pregrill metadata update stale, even when bd's - # timestamps are still within the same wall-clock second on fast machines. - run env CLERK_PREGRILL_STALE_TOLERANCE_S=-1 "$CLERK" inbox list - [ "$status" -eq 0 ] - [[ "$output" == *"$id [pregrill:stale]"* ]] -} - -@test "inbox list (bd): --limit 0 forwards unlimited limit and prints rows past the default cap" { - repo=$(make_bd_repo list_limit0) - tracedbin="$BATS_TEST_TMPDIR/list-limit0-tracedbin" - make_traced_bd "$tracedbin" - export BD_TRACE_LOG="$BATS_TEST_TMPDIR/list-limit0.trace" - : >"$BD_TRACE_LOG" - export PATH="$tracedbin:$PATH" - cd "$repo" - for n in $(seq 1 55); do - bd create "visible $n" --silent >/dev/null - done - - run "$CLERK" inbox list --limit 0 - [ "$status" -eq 0 ] - [[ "$output" == "Inbox (open, not ready) — 55 item(s):"* ]] - [[ "$output" == *"visible 55"* ]] - grep -F -q -- 'list\x1f--status\x1fopen\x1f--exclude-label\x1fstage:ready\x1f--readonly\x1f--json\x1f--limit\x1f0' "$BD_TRACE_LOG" -} - -@test "inbox list (bd): --limit forwards a positive numeric limit" { - repo=$(make_bd_repo list_limit3) - tracedbin="$BATS_TEST_TMPDIR/list-limit3-tracedbin" - make_traced_bd "$tracedbin" - export BD_TRACE_LOG="$BATS_TEST_TMPDIR/list-limit3.trace" - : >"$BD_TRACE_LOG" - export PATH="$tracedbin:$PATH" - cd "$repo" - for n in $(seq 1 5); do - bd create "limited $n" --silent >/dev/null - done - - run "$CLERK" inbox list --limit 3 - [ "$status" -eq 0 ] - [[ "$output" == *"Inbox (open, not ready) — 3 item(s):"* ]] - grep -F -q -- '--limit\x1f3' "$BD_TRACE_LOG" -} - -@test "inbox list: invalid limits are usage errors before backend calls" { - repo=$(make_bd_repo list_bad_limit) - tracedbin="$BATS_TEST_TMPDIR/list-bad-limit-tracedbin" - make_traced_bd "$tracedbin" - export BD_TRACE_LOG="$BATS_TEST_TMPDIR/list-bad-limit.trace" - : >"$BD_TRACE_LOG" - export PATH="$tracedbin:$PATH" - cd "$repo" - - run "$CLERK" inbox list --limit nope - [ "$status" -eq 2 ] - [ "$output" = 'clerk inbox list: --limit must be a non-negative integer' ] - [ ! -s "$BD_TRACE_LOG" ] - run "$CLERK" inbox list --limit - [ "$status" -eq 2 ] - [ "$output" = 'clerk inbox list: --limit needs a value — usage: clerk inbox list [--limit <n>]' ] - [ ! -s "$BD_TRACE_LOG" ] -} - -@test "inbox list (bd): empty inbox prints (empty), exit 0" { - repo=$(make_bd_repo list5) - cd "$repo" - run "$CLERK" inbox list - [ "$status" -eq 0 ] - [ "$output" = "Inbox (open, not ready) — 0 item(s): - (empty)" ] -} - -@test "inbox list (gh backlog): --limit forwards to bd and never lists GitHub issues" { - repo=$(make_gh_repo list_gh_limit) - tracedbin="$BATS_TEST_TMPDIR/list-gh-limit-tracedbin" - make_traced_bd "$tracedbin" - fakebin="$BATS_TEST_TMPDIR/list-gh-limit-fakebin" - make_fake_gh "$fakebin" - export BD_TRACE_LOG="$BATS_TEST_TMPDIR/list-gh-limit.trace" - export FAKE_GH_LOG="$BATS_TEST_TMPDIR/list-gh-limit.log" - : >"$BD_TRACE_LOG" - : >"$FAKE_GH_LOG" - export PATH="$tracedbin:$fakebin:$PATH" - cd "$repo" - bd create "bd capture 1" --silent >/dev/null - bd create "bd capture 2" --silent >/dev/null - run "$CLERK" inbox list --limit 1 - [ "$status" -eq 0 ] - [[ "$output" == *"Inbox (open, not ready) — 1 item(s):"* ]] - grep -F -q -- 'list\x1f--status\x1fopen\x1f--exclude-label\x1fstage:ready\x1f--readonly\x1f--json\x1f--limit\x1f1' "$BD_TRACE_LOG" - [ ! -s "$FAKE_GH_LOG" ] -} - -@test "inbox list (gh backlog): --limit 0 remains bd unlimited" { - repo=$(make_gh_repo list_gh_limit0) - cd "$repo" - bd create "visible after migration" --silent >/dev/null - run "$CLERK" inbox list --limit 0 - [ "$status" -eq 0 ] - [[ "$output" == *"visible after migration"* ]] -} - -@test "public gh backlog keeps bd raw captures separate from GitHub ready issues" { - repo=$(make_gh_repo list6) - fakebin="$BATS_TEST_TMPDIR/list6-fakebin" - make_fake_gh "$fakebin" - cat >"$BATS_TEST_TMPDIR/list6.json" <<'JSON' -[ - {"number": 57, "title": "ready GitHub delivery"}, - {"number": 47, "title": "another ready GitHub delivery"} -] -JSON - export FAKE_GH_LIST_JSON="$BATS_TEST_TMPDIR/list6.json" - export FAKE_GH_LOG="$BATS_TEST_TMPDIR/list6.log" - : >"$FAKE_GH_LOG" - export PATH="$fakebin:$PATH" - cd "$repo" - id=$(bd create "bd-only raw capture" --silent) - bd create "ready bead is not the gh backlog" --labels stage:ready --silent >/dev/null - - run "$CLERK" inbox list - [ "$status" -eq 0 ] - [ "$output" = "Inbox (open, not ready) — 1 item(s): - $id [pregrill:absent] bd-only raw capture" ] - [ ! -s "$FAKE_GH_LOG" ] - - run "$CLERK" backlog next - [ "$status" -eq 0 ] - [ "$output" = "Backlog (ready) — 2 item(s): - #57 ready ready GitHub delivery - #47 ready another ready GitHub delivery" ] - [[ "$output" != *"bd-only raw capture"* ]] - grep -F -q -- 'issue\x1flist\x1f--label\x1fready-for-agent' "$FAKE_GH_LOG" -} - -# ---------------------------------------------------------------- inbox show - - -@test "inbox show (bd) shows the bead" { - repo=$(make_bd_repo show1) - cd "$repo" - id=$(bd create "look at me" --silent) - run "$CLERK" inbox show "$id" - [ "$status" -eq 0 ] - [[ "$output" == *"$id"*"look at me"* ]] -} - -@test "inbox show (bd): returned attempt banner names branch, staleness, subject, and disposition" { - repo=$(make_bd_repo show_returned) - add_origin "$repo" - cd "$repo" - id=$(bd create "returned show unit" --silent) - short="${id#*-}" - mk_returned_attempt "$repo" "$short" "returned delivery subject" - advance_main "$repo" - - run "$CLERK" inbox show "$id" - [ "$status" -eq 0 ] - [[ "$output" == *"$id"*"returned show unit"* ]] - [[ "$output" == *"returned attempt: returned/$short"* ]] - [[ "$output" == *"1 commit(s) behind main"* ]] - [[ "$output" == *"subject: returned delivery subject"* ]] - [[ "$output" == *"--returned keep|discard"* ]] -} - -@test "inbox show (bd): no returned attempt is an exact passthrough" { - repo=$(make_bd_repo show_no_returned) - cd "$repo" - id=$(bd create "plain show unit" --silent) - expected=$(bd show "$id" --readonly) - run "$CLERK" inbox show "$id" - [ "$status" -eq 0 ] - [ "$output" = "$expected" ] - [[ "$output" != *"returned attempt"* ]] -} - -@test "inbox show (bd): origin-only returned attempt is detected" { - repo=$(make_bd_repo show_returned_origin_only) - add_origin "$repo" - cd "$repo" - id=$(bd create "origin returned show unit" --silent) - short="${id#*-}" - mk_returned_attempt "$repo" "$short" "origin-only returned subject" - git -C "$repo" branch -D "returned/$short" >/dev/null - - run "$CLERK" inbox show "$id" - [ "$status" -eq 0 ] - [[ "$output" == *"returned attempt: returned/$short (origin;"* ]] - [[ "$output" == *"subject: origin-only returned subject"* ]] -} - -@test "inbox show: missing id is a usage error, exit 2" { - repo=$(make_bd_repo show2) - cd "$repo" - run "$CLERK" inbox show - [ "$status" -eq 2 ] - [ "$output" = 'clerk inbox show: missing id — usage: clerk inbox show <id> [--json|--pretty]' ] -} - -@test "inbox show (gh backlog) shows the bd capture" { - repo=$(make_gh_repo show3) - fakebin="$BATS_TEST_TMPDIR/show3-fakebin" - make_fake_gh "$fakebin" - export FAKE_GH_LOG="$BATS_TEST_TMPDIR/show3.log" - : >"$FAKE_GH_LOG" - export PATH="$fakebin:$PATH" - cd "$repo" - id=$(bd create "look at my bd capture" --silent) - run "$CLERK" inbox show "$id" - [ "$status" -eq 0 ] - [[ "$output" == *"$id"*"look at my bd capture"* ]] - [ ! -s "$FAKE_GH_LOG" ] -} - -# ---------------------------------------------------------------- inbox dups - - -@test "inbox dups (bd) is cross-pool: a ready bead still shows up as a duplicate of an inbox capture" { - repo=$(make_bd_repo dups1) - cd "$repo" - bd create "fix the login timeout bug" --labels stage:ready --description '## Acceptance Criteria -- x' --silent >/dev/null - bd create "fix the login timeout bug again" --silent >/dev/null - run "$CLERK" inbox dups - [ "$status" -eq 0 ] - [[ "$output" == "Duplicate candidates — "*" pair(s):"* ]] - [[ "$output" == *"fix the login timeout bug"* ]] -} - -@test "inbox dups (bd): no candidates prints (none), exit 0" { - repo=$(make_bd_repo dups2) - cd "$repo" - bd create "a wholly unique title about zoology" --silent >/dev/null - run "$CLERK" inbox dups - [ "$status" -eq 0 ] - [ "$output" = "Duplicate candidates — 0 pair(s): - (none)" ] -} - -@test "inbox dups (gh backlog) uses the bd capture pool" { - repo=$(make_gh_repo dups3) - cd "$repo" - bd create "fix the auth bug" --silent >/dev/null - bd create "fix the auth bug again" --silent >/dev/null - run "$CLERK" inbox dups - [ "$status" -eq 0 ] - [[ "$output" == "Duplicate candidates — "* ]] - [[ "$output" == *"fix the auth bug"* ]] -} - -# --------------------------------------------------------------- inbox ready - - -@test "inbox ready (bd) on a criteria-less unit: refusal names the missing section, exit 2" { - repo=$(make_bd_repo ready1) - cd "$repo" - id=$(bd create "no criteria here" --description "just prose, no heading" --silent) - run "$CLERK" inbox ready "$id" - [ "$status" -eq 2 ] - [[ "$output" == *"$id has no 'Acceptance Criteria' section"* ]] -} - -@test "inbox ready (bd) on a unit with an Acceptance Criteria heading promotes it, self-verified" { - repo=$(make_bd_repo ready2) - cd "$repo" - id=$(bd create "has criteria" --description '## Acceptance Criteria -- does the thing' --silent) - run "$CLERK" inbox ready "$id" - [ "$status" -eq 0 ] - [ "$output" = "clerk: promoted $id to stage:ready" ] - [ "$(bd show "$id" --readonly --json | jq -r '.[0].labels | index("stage:ready")')" != null ] -} - -@test "inbox ready (bd): a bare 'Acceptance Criteria' line (no markdown heading) also counts" { - repo=$(make_bd_repo ready3) - cd "$repo" - id=$(bd create "has criteria too" --design 'Acceptance Criteria -- does the thing' --silent) - run "$CLERK" inbox ready "$id" - [ "$status" -eq 0 ] -} - -@test "inbox ready (bd): prose merely mentioning the phrase is not a section, still refused" { - repo=$(make_bd_repo ready4) - cd "$repo" - id=$(bd create "fake-out" --description "no acceptance criteria yet, sorry" --silent) - run "$CLERK" inbox ready "$id" - [ "$status" -eq 2 ] - [[ "$output" == *"has no 'Acceptance Criteria' section"* ]] -} - -@test "inbox ready (bd) on an id with a dedicated acceptance_criteria field (bd create --acceptance) promotes it" { - repo=$(make_bd_repo ready8) - cd "$repo" - id=$(bd create "has acceptance field" --acceptance $'## Acceptance Criteria\n- does the thing' --silent) - run "$CLERK" inbox ready "$id" - [ "$status" -eq 0 ] - [ "$output" = "clerk: promoted $id to stage:ready" ] -} - -@test "inbox ready (bd) on an id whose only criteria live in the dedicated acceptance_criteria field, with no description/design, still promotes" { - repo=$(make_bd_repo ready9) - cd "$repo" - id=$(bd create "bare criteria field" --acceptance "does the thing" --silent) - run "$CLERK" inbox ready "$id" - [ "$status" -eq 0 ] -} - -@test "inbox ready (bd) authors design and first-class criteria from files, then promotes" { - repo=$(make_bd_repo ready11) - cd "$repo" - id=$(bd create "needs refinement output" --description "raw capture" --silent) - printf 'Implementation notes from grill\n' >"$BATS_TEST_TMPDIR/design.md" - printf -- '- delivered behavior is observable\n' >"$BATS_TEST_TMPDIR/acceptance.md" - - run "$CLERK" inbox ready "$id" --design-file "$BATS_TEST_TMPDIR/design.md" --acceptance-file "$BATS_TEST_TMPDIR/acceptance.md" - [ "$status" -eq 0 ] - [ "$output" = "clerk: promoted $id to stage:ready" ] - json=$(bd show "$id" --readonly --json) - [ "$(jq -r '.[0].design' <<<"$json")" = "Implementation notes from grill" ] - [ "$(jq -r '.[0].acceptance_criteria' <<<"$json")" = "- delivered behavior is observable" ] - [ "$(jq -r '(.[0].labels // []) | index("stage:ready")' <<<"$json")" != null ] -} - -@test "inbox ready (bd) writes design but still refuses if criteria remain absent" { - repo=$(make_bd_repo ready12) - cd "$repo" - id=$(bd create "design only" --description "raw capture" --silent) - printf 'Design without an exam\n' >"$BATS_TEST_TMPDIR/design-only.md" - - run "$CLERK" inbox ready "$id" --design-file "$BATS_TEST_TMPDIR/design-only.md" - [ "$status" -eq 2 ] - [[ "$output" == *"--acceptance-file"* ]] - json=$(bd show "$id" --readonly --json) - [ "$(jq -r '.[0].design' <<<"$json")" = "Design without an exam" ] - [ "$(jq -r '(.[0].labels // []) | index("stage:ready")' <<<"$json")" = null ] -} - -@test "inbox ready (bd) preserves pure-gate behavior for existing first-class criteria" { - repo=$(make_bd_repo ready13) - cd "$repo" - id=$(bd create "already refined" --acceptance "does the thing" --silent) - run "$CLERK" inbox ready "$id" - [ "$status" -eq 0 ] - [ "$(bd show "$id" --readonly --json | jq -r '(.[0].labels // []) | index("stage:ready")')" != null ] -} - -@test "inbox ready (bd): returned branch requires explicit keep or discard" { - repo=$(make_bd_repo ready_returned_fail) - add_origin "$repo" - cd "$repo" - id=$(bd create "returned ready fail" --acceptance "does the thing" --silent) - short="${id#*-}" - mk_returned_branch "$repo" "$short" - - run "$CLERK" inbox ready "$id" - [ "$status" -eq 2 ] - [[ "$output" == *"--returned keep"* ]] - [[ "$output" == *"--returned discard"* ]] - [ "$(bd show "$id" --readonly --json | jq -r '(.[0].labels // []) | index("stage:ready")')" = null ] -} - -@test "inbox ready (bd): returned discard removes local and origin refs before promoting" { - repo=$(make_bd_repo ready_returned_discard) - add_origin "$repo" - cd "$repo" - id=$(bd create "returned ready discard" --acceptance "does the thing" --silent) - short="${id#*-}" - mk_returned_branch "$repo" "$short" - - run "$CLERK" inbox ready "$id" --returned discard - [ "$status" -eq 0 ] - [ "$output" = "clerk: promoted $id to stage:ready" ] - ! git -C "$repo" show-ref --verify --quiet "refs/heads/returned/$short" - ! git -C "$repo" show-ref --verify --quiet "refs/remotes/origin/returned/$short" - [ "$(bd show "$id" --readonly --json | jq -r '(.[0].labels // []) | index("stage:ready")')" != null ] -} - -@test "inbox ready (bd): returned discard removes canonical and archived returned refs" { - repo=$(make_bd_repo ready_returned_discard_archives) - add_origin "$repo" - cd "$repo" - id=$(bd create "returned ready discard archives" --acceptance "does the thing" --silent) - short="${id#*-}" - mk_returned_branch "$repo" "$short" - git -C "$repo" branch "returned/$short-abc1234" main - git -C "$repo" push -q origin "returned/$short-abc1234" - - run "$CLERK" inbox ready "$id" --returned discard - [ "$status" -eq 0 ] - ! git -C "$repo" show-ref --verify --quiet "refs/heads/returned/$short" - ! git -C "$repo" show-ref --verify --quiet "refs/heads/returned/$short-abc1234" - ! git -C "$repo" show-ref --verify --quiet "refs/remotes/origin/returned/$short" - ! git -C "$repo" show-ref --verify --quiet "refs/remotes/origin/returned/$short-abc1234" - [ "$(bd show "$id" --readonly --json | jq -r '(.[0].labels // []) | index("stage:ready")')" != null ] -} - -@test "inbox ready (bd): returned keep preserves refs and promotes" { - repo=$(make_bd_repo ready_returned_keep) - add_origin "$repo" - cd "$repo" - id=$(bd create "returned ready keep" --acceptance "does the thing" --silent) - short="${id#*-}" - mk_returned_branch "$repo" "$short" - - run "$CLERK" inbox ready "$id" --returned keep - [ "$status" -eq 0 ] - git -C "$repo" show-ref --verify --quiet "refs/heads/returned/$short" - git -C "$repo" show-ref --verify --quiet "refs/remotes/origin/returned/$short" - [ "$(bd show "$id" --readonly --json | jq -r '(.[0].labels // []) | index("stage:ready")')" != null ] -} - -@test "inbox ready (bd): returned discard is a no-op when no returned branch exists" { - repo=$(make_bd_repo ready_returned_absent) - cd "$repo" - id=$(bd create "no returned branch" --acceptance "does the thing" --silent) - run "$CLERK" inbox ready "$id" --returned discard - [ "$status" -eq 0 ] - [ "$(bd show "$id" --readonly --json | jq -r '(.[0].labels // []) | index("stage:ready")')" != null ] -} - -@test "inbox ready (bd): returned discard offline deletes local ref, warns, and still promotes" { - repo=$(make_bd_repo ready_returned_offline) - add_origin "$repo" - cd "$repo" - id=$(bd create "returned ready offline" --acceptance "does the thing" --silent) - short="${id#*-}" - mk_returned_branch "$repo" "$short" - git -C "$repo" remote set-url origin "$repo-gone-nonexistent" - - run "$CLERK" inbox ready "$id" --returned discard - [ "$status" -eq 0 ] - [[ "$output" == *"OFFLINE"* ]] - [[ "$output" == *"deferred to sync"* ]] - ! git -C "$repo" show-ref --verify --quiet "refs/heads/returned/$short" - [ "$(bd show "$id" --readonly --json | jq -r '(.[0].labels // []) | index("stage:ready")')" != null ] -} - -@test "inbox ready (bd): returned disposition has no collateral branches" { - repo=$(make_bd_repo ready_returned_collateral) - add_origin "$repo" - cd "$repo" - id=$(bd create "returned ready collateral" --acceptance "does the thing" --silent) - short="${id#*-}" - mk_returned_branch "$repo" "$short" - git -C "$repo" branch "delivery/$short" main - git -C "$repo" branch "returned/other" main - - run "$CLERK" inbox ready "$id" --returned discard - [ "$status" -eq 0 ] - git -C "$repo" show-ref --verify --quiet "refs/heads/delivery/$short" - git -C "$repo" show-ref --verify --quiet "refs/heads/returned/other" -} - -@test "inbox ready (bd) on an id that does not resolve: bad-id usage error, exit 2 (not the acceptance-criteria refusal)" { - repo=$(make_bd_repo ready10) - cd "$repo" - run "$CLERK" inbox ready does-not-exist-42 - [ "$status" -eq 2 ] - [ "$output" = "clerk inbox ready: does-not-exist-42 not found — check the id ('clerk inbox list' shows open units)" ] -} - -@test "backend command failure surfaces as exit 5 with a prescriptive next action" { - repo=$(make_bd_repo backendfail1) - # a bd that fails outright, simulating a broken/unreachable backend - fake="$BATS_TEST_TMPDIR/failbd" - mkdir -p "$fake" - printf '#!/bin/sh\nexit 1\n' >"$fake/bd" - chmod +x "$fake/bd" - cd "$repo" - PATH="$fake:$PATH" - run "$CLERK" inbox list - [ "$status" -eq 5 ] - [[ "$output" == *"clerk: inbox list failed — bd list did not succeed"* ]] - [[ "$output" == *"run 'clerk doctor' to check the backend"* ]] -} - -@test "inbox ready (gh backlog) without --title/--body-file: refusal text prescribes both flags, exit 2" { - repo=$(make_gh_repo ready5) - cd "$repo" - id=$(bd create "ready gh needs args" --silent) - run "$CLERK" inbox ready "$id" - [ "$status" -eq 2 ] - [[ "$output" == *"--title"* ]] - [[ "$output" == *"--body-file"* ]] -} - -@test "inbox ready (gh backlog) creates a ready GitHub issue, then closes the bd capture" { - repo=$(make_gh_repo ready6) - fakebin="$BATS_TEST_TMPDIR/ready6-fakebin" - make_fake_gh "$fakebin" - export FAKE_GH_LOG="$BATS_TEST_TMPDIR/ready6.log" - : >"$FAKE_GH_LOG" - export PATH="$fakebin:$PATH" - cd "$repo" - id=$(bd create "raw capture to promote" --silent) - printf 'the groomed body\n' >body.md - run "$CLERK" inbox ready "$id" --title "promoted title" --body-file body.md - [ "$status" -eq 0 ] - [ "$output" = "clerk: promoted $id to #42 (https://github.com/acme/repo/issues/42)" ] - grep -qF 'issue\x1fcreate\x1f--title\x1fpromoted title\x1f--body-file\x1fbody.md\x1f--label\x1fready-for-agent' "$FAKE_GH_LOG" - ! grep -qF 'issue\x1fclose' "$FAKE_GH_LOG" - [ "$(bd show "$id" --readonly --json | jq -r '.[0].status')" = closed ] - [ "$(bd show "$id" --readonly --json | jq -r '.[0].close_reason')" = "promoted to GitHub #42" ] -} - -@test "inbox ready: missing id is a usage error, exit 2" { - repo=$(make_bd_repo ready7) - cd "$repo" - run "$CLERK" inbox ready - [ "$status" -eq 2 ] - [[ "$output" == "clerk inbox ready: missing id"* ]] -} - -# ---------------------------------------------------------------- inbox drop - - -@test "inbox drop (bd) closes with reason wontfix, self-verified" { - repo=$(make_bd_repo drop1) - cd "$repo" - id=$(bd create "not worth doing" --silent) - run "$CLERK" inbox drop "$id" - [ "$status" -eq 0 ] - [ "$output" = "clerk: dropped $id (wontfix)" ] - [ "$(bd show "$id" --readonly --json | jq -r '.[0].status')" = closed ] - [ "$(bd show "$id" --readonly --json | jq -r '.[0].close_reason')" = wontfix ] -} - -@test "inbox drop (bd): returned branch requires explicit keep or discard" { - repo=$(make_bd_repo drop_returned_fail) - add_origin "$repo" - cd "$repo" - id=$(bd create "returned drop fail" --silent) - short="${id#*-}" - mk_returned_branch "$repo" "$short" - - run "$CLERK" inbox drop "$id" - [ "$status" -eq 2 ] - [[ "$output" == *"--returned keep"* ]] - [[ "$output" == *"--returned discard"* ]] - [ "$(bd show "$id" --readonly --json | jq -r '.[0].status')" = open ] -} - -@test "inbox drop (bd): returned discard removes branch and closes" { - repo=$(make_bd_repo drop_returned_discard) - add_origin "$repo" - cd "$repo" - id=$(bd create "returned drop discard" --silent) - short="${id#*-}" - mk_returned_branch "$repo" "$short" - - run "$CLERK" inbox drop "$id" --returned discard - [ "$status" -eq 0 ] - [ "$(bd show "$id" --readonly --json | jq -r '.[0].status')" = closed ] - ! git -C "$repo" show-ref --verify --quiet "refs/heads/returned/$short" - ! git -C "$repo" show-ref --verify --quiet "refs/remotes/origin/returned/$short" -} - -@test "inbox drop (bd): returned discard removes canonical and archived returned refs" { - repo=$(make_bd_repo drop_returned_discard_archives) - add_origin "$repo" - cd "$repo" - id=$(bd create "returned drop discard archives" --silent) - short="${id#*-}" - mk_returned_branch "$repo" "$short" - git -C "$repo" branch "returned/$short-abc1234" main - git -C "$repo" push -q origin "returned/$short-abc1234" - - run "$CLERK" inbox drop "$id" --returned discard - [ "$status" -eq 0 ] - [ "$(bd show "$id" --readonly --json | jq -r '.[0].status')" = closed ] - ! git -C "$repo" show-ref --verify --quiet "refs/heads/returned/$short" - ! git -C "$repo" show-ref --verify --quiet "refs/heads/returned/$short-abc1234" - ! git -C "$repo" show-ref --verify --quiet "refs/remotes/origin/returned/$short" - ! git -C "$repo" show-ref --verify --quiet "refs/remotes/origin/returned/$short-abc1234" -} - -@test "inbox drop (bd): returned keep preserves branch and closes" { - repo=$(make_bd_repo drop_returned_keep) - add_origin "$repo" - cd "$repo" - id=$(bd create "returned drop keep" --silent) - short="${id#*-}" - mk_returned_branch "$repo" "$short" - - run "$CLERK" inbox drop "$id" --returned keep - [ "$status" -eq 0 ] - [ "$(bd show "$id" --readonly --json | jq -r '.[0].status')" = closed ] - git -C "$repo" show-ref --verify --quiet "refs/heads/returned/$short" -} - -@test "inbox drop (bd): returned discard is a no-op when no returned branch exists" { - repo=$(make_bd_repo drop_returned_absent) - cd "$repo" - id=$(bd create "drop no returned" --silent) - run "$CLERK" inbox drop "$id" --returned discard - [ "$status" -eq 0 ] - [ "$(bd show "$id" --readonly --json | jq -r '.[0].status')" = closed ] -} - -@test "inbox drop (gh backlog) closes the bd capture" { - repo=$(make_gh_repo drop2) - fakebin="$BATS_TEST_TMPDIR/drop2-fakebin" - make_fake_gh "$fakebin" - export FAKE_GH_LOG="$BATS_TEST_TMPDIR/drop2.log" - : >"$FAKE_GH_LOG" - export PATH="$fakebin:$PATH" - cd "$repo" - id=$(bd create "drop gh-backed capture" --silent) - run "$CLERK" inbox drop "$id" - [ "$status" -eq 0 ] - [ "$output" = "clerk: dropped $id (wontfix)" ] - [ "$(bd show "$id" --readonly --json | jq -r '.[0].status')" = closed ] - [ ! -s "$FAKE_GH_LOG" ] -} - -@test "inbox drop: missing id is a usage error, exit 2" { - repo=$(make_bd_repo drop3) - cd "$repo" - run "$CLERK" inbox drop - [ "$status" -eq 2 ] - [ "$output" = 'clerk inbox drop: missing id — usage: clerk inbox drop <id> [--returned keep|discard]' ] -} - -# ------------------------------------------------------------- inbox pregrill - - -@test "inbox pregrill (bd) is state-neutral: status and labels are byte-identical before/after" { - repo=$(make_bd_repo preg1) - cd "$repo" - id=$(bd create "pregrill target" --labels some-label --silent) - before=$(bd show "$id" --readonly --json | jq -c '.[0] | {status, labels}') - run "$CLERK" inbox pregrill "$id" --decision "which backend" --premise "the api is stable|check changelog" --criterion "returns 200" - [ "$status" -eq 0 ] - after=$(bd show "$id" --readonly --json | jq -c '.[0] | {status, labels}') - [ "$before" = "$after" ] -} - -@test "inbox pregrill (bd) appends a dated, structured note: open decisions, premises with verification, draft criteria" { - repo=$(make_bd_repo preg2) - cd "$repo" - id=$(bd create "pregrill target" --silent) - run "$CLERK" inbox pregrill "$id" --decision "which backend" --premise "the api is stable|check changelog" --criterion "returns 200" - [ "$status" -eq 0 ] - notes=$(bd show "$id" --readonly --json | jq -r '.[0].notes') - [[ "$notes" == "clerk-pregrill: "* ]] - [[ "$notes" == *"Open decisions:"* ]] - [[ "$notes" == *"- which backend"* ]] - [[ "$notes" == *"Premises:"* ]] - [[ "$notes" == *"- the api is stable (verify: check changelog)"* ]] - [[ "$notes" == *"Draft acceptance criteria:"* ]] - [[ "$notes" == *"- returns 200"* ]] -} - -@test "inbox pregrill (bd) with no decisions/premises/criteria still files a structured note ((none) sections)" { - repo=$(make_bd_repo preg3) - cd "$repo" - id=$(bd create "bare pregrill" --silent) - run "$CLERK" inbox pregrill "$id" - [ "$status" -eq 0 ] - notes=$(bd show "$id" --readonly --json | jq -r '.[0].notes') - [[ "$notes" == *"Open decisions:"$'\n'"- (none)"* ]] - [[ "$notes" == *"Premises:"$'\n'"- (none)"* ]] - [[ "$notes" == *"Draft acceptance criteria:"$'\n'"- (none)"* ]] -} - -@test "inbox pregrill (gh backlog) appends notes to the bd capture" { - repo=$(make_gh_repo preg4) - fakebin="$BATS_TEST_TMPDIR/preg4-fakebin" - make_fake_gh "$fakebin" - export FAKE_GH_LOG="$BATS_TEST_TMPDIR/preg4.log" - : >"$FAKE_GH_LOG" - export PATH="$fakebin:$PATH" - cd "$repo" - id=$(bd create "pregrill gh-backed capture" --silent) - run "$CLERK" inbox pregrill "$id" --decision "d" - [ "$status" -eq 0 ] - notes=$(bd show "$id" --readonly --json | jq -r '.[0].notes') - [[ "$notes" == "clerk-pregrill: "* ]] - [[ "$notes" == *"- d"* ]] - [ ! -s "$FAKE_GH_LOG" ] -} - -@test "inbox pregrill: missing id is a usage error, exit 2" { - repo=$(make_bd_repo preg5) - cd "$repo" - run "$CLERK" inbox pregrill - [ "$status" -eq 2 ] - [[ "$output" == "clerk inbox pregrill: missing id"* ]] -} - -# ---------------------------------------------------- readonly / write allowlist --- - -@test "backend reads run under --readonly; a fork allowlisted to reads+pregrill cannot execute any other write" { - repo=$(make_bd_repo guard1) - cd "$repo" - id=$(bd create "guarded target" --description '## Acceptance Criteria -- x' --silent) - - guarddir="$BATS_TEST_TMPDIR/guard1-bin" - make_guarded_bd "$guarddir" - export REAL_BD - export GUARD_LOG="$BATS_TEST_TMPDIR/guard1.log" - : >"$GUARD_LOG" - export PATH="$guarddir:$PATH" - - run "$CLERK" inbox list - [ "$status" -eq 0 ] - run "$CLERK" inbox show "$id" - [ "$status" -eq 0 ] - run "$CLERK" inbox dups - [ "$status" -eq 0 ] - run "$CLERK" inbox pregrill "$id" --decision d --premise "p|v" --criterion c - [ "$status" -eq 0 ] - - # nothing was refused — every bd call these four verbs made fit the allowlist - ! grep -q '^REFUSED:' "$GUARD_LOG" - # the reads all carried --readonly - grep -qE '^ALLOWED: list .*--readonly' "$GUARD_LOG" - grep -qE '^ALLOWED: show .*--readonly' "$GUARD_LOG" - grep -qE '^ALLOWED: find-duplicates .*--readonly' "$GUARD_LOG" - # pregrill's write is --append-notes alone, and it does NOT carry --readonly - write_line=$(grep '^ALLOWED: update ' "$GUARD_LOG") - [[ "$write_line" == *"--append-notes"* ]] - [[ "$write_line" != *"--readonly"* ]] - [[ "$write_line" != *"--add-label"* ]] - [[ "$write_line" != *"--status"* ]] -} diff --git a/tests/clerk/release-return.bats b/tests/clerk/release-return.bats deleted file mode 100644 index 53124ca..0000000 --- a/tests/clerk/release-return.bats +++ /dev/null @@ -1,508 +0,0 @@ -#!/usr/bin/env bats -# release-return.bats — clerk backlog release / backlog return (unit dotfiles-dft.3, this -# group). Same substrate discipline as claim.bats: a SCRATCH BARE git repo as 'origin' plus a -# clone (never this repo's real origin), its own scratch bd db (never this repo's real -# .beads). PATH deliberately excludes this repo's personal ~/.config/bin/bd auto-sync shim -# (ADR 0013), same rationale as claim.bats/inbox.bats. Printed output is load-bearing (ADR -# 0015): success/refusal text is asserted, not just exit codes. - -setup() { - source "$BATS_TEST_DIRNAME/helpers.bash" - git_sandbox - CLERK="$BATS_TEST_DIRNAME/../../bin/clerk" - BD_MIN_PATH="/usr/local/bin:/usr/bin:/bin" - export PATH="$BD_MIN_PATH" -} - -# ---------------------------------------------------------------- fixtures -- - -# A scratch bare git repo as 'origin' plus a working repo with a committed `.clerk` -# (backlog: bd) marker and a fresh scratch bd db. Git identity pinned to a fixed actor -# ("clerk") so bd's --claim assignee is predictable. Echoes the working repo's physical -# path. (Mirrors claim.bats' make_claim_repo exactly — duplicated rather than shared -# across files, same as claim.bats duplicates nothing from inbox.bats.) -make_claim_repo() { # $1 = subdir name - local base="$BATS_TEST_TMPDIR/$1" origin="" clone="" - mkdir -p "$base" - origin="$base/origin.git" - clone="$base/clone" - git init -q --bare -b main "$origin" - git init -q -b main "$clone" - clone="$(cd "$clone" && pwd -P)" - git -C "$clone" config user.email clerk@test - git -C "$clone" config user.name clerk - git -C "$clone" remote add origin "$origin" - printf 'backlog: bd\n' >"$clone/.clerk" - git -C "$clone" add -A - git -C "$clone" commit -q -m fixture - git -C "$clone" push -q origin main - (cd "$clone" && bd init -q --non-interactive --skip-hooks --skip-agents >/dev/null 2>&1) - printf '%s\n' "$clone" -} - -# A unit with a real Acceptance Criteria section AND stage:ready (so release/return's "strip -# stage:ready"/"keeps stage:ready" assertions have something to observe), claimable by C4. -# Echoes the created id. -mk_ready_unit() { # $1 = title - local id - id=$(bd create "$1" --description '## Acceptance Criteria -- does the thing' --silent) - bd update "$id" --add-label stage:ready >/dev/null - printf '%s\n' "$id" -} - -# Points `origin` at a path that will never resolve, so `git fetch origin` fails immediately -# (no network hang) — the OFFLINE signal. Mirrors claim.bats' break_origin. -break_origin() { # $1 = repo - git -C "$1" remote set-url origin "$1-gone-nonexistent" -} - -# ---------------------------------------------------------------- release -- - -@test "release (bd): clean release keeps stage:ready, tears down branch+worktree, reopens unassigned" { - repo=$(make_claim_repo rel_clean) - cd "$repo" - id=$(mk_ready_unit "clean release unit") - short="${id#*-}" - "$CLERK" backlog claim "$id" >/dev/null - [ -d "$repo/.worktrees/$short" ] - - run "$CLERK" backlog release "$id" - [ "$status" -eq 0 ] - [[ "$output" == *"released $id"* ]] - [[ "$output" == *"stage:ready kept"* ]] - - [ ! -d "$repo/.worktrees/$short" ] - ! git -C "$repo" show-ref --verify --quiet "refs/heads/delivery/$short" - git -C "$repo" fetch -q origin - ! git -C "$repo" show-ref --verify --quiet "refs/remotes/origin/delivery/$short" - - json=$(bd show "$id" --readonly --json) - [ "$(jq -r '.[0].status' <<<"$json")" = open ] - [ "$(jq -r '.[0].assignee // ""' <<<"$json")" = "" ] - [ "$(jq -r '(.[0].labels // []) | index("stage:ready")' <<<"$json")" != null ] -} - -@test "release (bd): running from inside the delivery worktree tears down the primary checkout claim" { - repo=$(make_claim_repo rel_from_worktree) - cd "$repo" - id=$(mk_ready_unit "release from worktree unit") - short="${id#*-}" - "$CLERK" backlog claim "$id" >/dev/null - wt="$repo/.worktrees/$short" - - cd "$wt" - run "$CLERK" backlog release "$id" - [ "$status" -eq 0 ] - [ ! -d "$wt" ] - ! git -C "$repo" show-ref --verify --quiet "refs/heads/delivery/$short" - git -C "$repo" fetch -q origin - ! git -C "$repo" show-ref --verify --quiet "refs/remotes/origin/delivery/$short" - [ "$(bd -C "$repo" show "$id" --readonly --json | jq -r '.[0].status')" = open ] -} - -@test "release (bd): a branch with commits beyond main is refused, exit 2, branch and worktree left intact" { - repo=$(make_claim_repo rel_work) - cd "$repo" - id=$(mk_ready_unit "release with work unit") - short="${id#*-}" - "$CLERK" backlog claim "$id" >/dev/null - wt="$repo/.worktrees/$short" - git -C "$wt" -c user.email=clerk@test -c user.name=clerk commit -q --allow-empty -m "did some work" - - run "$CLERK" backlog release "$id" - [ "$status" -eq 2 ] - [[ "$output" == *"delivery/$short has 1 commit(s) beyond main"* ]] - [[ "$output" == *"submit"* ]] - [[ "$output" == *"return"* ]] - - [ -d "$wt" ] - git -C "$repo" show-ref --verify --quiet "refs/heads/delivery/$short" - [ "$(bd show "$id" --readonly --json | jq -r '.[0].status')" = in_progress ] -} - -@test "release (bd): a clean claim releases fine even when local main lags origin/main (dotfiles-dft.3 review)" { - repo=$(make_claim_repo rel_stale_main) - cd "$repo" - id=$(mk_ready_unit "stale main unit") - short="${id#*-}" - - # Someone else advances origin/main after our clone, without our local main moving. - other="$BATS_TEST_TMPDIR/rel_stale_main_other" - git clone -q "$(git -C "$repo" remote get-url origin)" "$other" - git -C "$other" -c user.email=o@test -c user.name=o commit -q --allow-empty -m "upstream advance" - git -C "$other" push -q origin main - - local_main_before=$(git -C "$repo" rev-parse main) - "$CLERK" backlog claim "$id" >/dev/null - # claim never advances local main — only its own fetch updates origin/main's tracking ref. - [ "$(git -C "$repo" rev-parse main)" = "$local_main_before" ] - [ "$(git -C "$repo" rev-list --count main..delivery/"$short")" -gt 0 ] - - run "$CLERK" backlog release "$id" - [ "$status" -eq 0 ] - [[ "$output" == *"released $id"* ]] - [[ "$output" == *"stage:ready kept"* ]] - [ ! -d "$repo/.worktrees/$short" ] - ! git -C "$repo" show-ref --verify --quiet "refs/heads/delivery/$short" - [ "$(bd show "$id" --readonly --json | jq -r '.[0].status')" = open ] -} - -@test "release (bd): releasing a unit not claimed here is idempotent, exit 0, no error" { - repo=$(make_claim_repo rel_unheld) - cd "$repo" - id=$(mk_ready_unit "never claimed unit") - - run "$CLERK" backlog release "$id" - [ "$status" -eq 0 ] - [[ "$output" == *"nothing to release"* ]] - [ "$(bd show "$id" --readonly --json | jq -r '.[0].status')" = open ] -} - -@test "release (bd): releasing after already releasing is idempotent, exit 0" { - repo=$(make_claim_repo rel_twice) - cd "$repo" - id=$(mk_ready_unit "release twice unit") - "$CLERK" backlog claim "$id" >/dev/null - run "$CLERK" backlog release "$id" - [ "$status" -eq 0 ] - run "$CLERK" backlog release "$id" - [ "$status" -eq 0 ] - [[ "$output" == *"nothing to release"* ]] -} - -@test "release (bd): OFFLINE attended — local teardown proceeds, remote delete deferred with a warning" { - repo=$(make_claim_repo rel_offline) - cd "$repo" - id=$(mk_ready_unit "offline release unit") - short="${id#*-}" - "$CLERK" backlog claim "$id" >/dev/null - break_origin "$repo" - - run env CI= "$CLERK" backlog release "$id" - [ "$status" -eq 0 ] - [[ "$output" == *"OFFLINE"* ]] - [[ "$output" == *"deferred to sync"* ]] - [ ! -d "$repo/.worktrees/$short" ] - ! git -C "$repo" show-ref --verify --quiet "refs/heads/delivery/$short" - [ "$(bd show "$id" --readonly --json | jq -r '.[0].status')" = open ] -} - -@test "release (bd): OFFLINE in a job context — refuses, exit 2, no teardown" { - repo=$(make_claim_repo rel_offline_job) - cd "$repo" - id=$(mk_ready_unit "offline job release unit") - short="${id#*-}" - "$CLERK" backlog claim "$id" >/dev/null - break_origin "$repo" - - run env CLERK_JOB=1 "$CLERK" backlog release "$id" - [ "$status" -eq 2 ] - [[ "$output" == *"OFFLINE in a job context"* ]] - [ -d "$repo/.worktrees/$short" ] - git -C "$repo" show-ref --verify --quiet "refs/heads/delivery/$short" - [ "$(bd show "$id" --readonly --json | jq -r '.[0].status')" = in_progress ] -} - -@test "release (bd): a dirty worktree fails release WITHOUT releasing the remote CAS lock first (dotfiles-dft.3 review)" { - repo=$(make_claim_repo rel_dirty_wt) - cd "$repo" - id=$(mk_ready_unit "dirty worktree release unit") - short="${id#*-}" - "$CLERK" backlog claim "$id" >/dev/null - wt="$repo/.worktrees/$short" - echo x >"$wt/untracked.log" - - run "$CLERK" backlog release "$id" - [ "$status" -eq 5 ] - [[ "$output" == *"could not remove the worktree"* ]] - - # The remote lock must still be held — worktree removal must fail BEFORE the origin branch - # is deleted, or another machine could push delivery/<short> and win a double-claim. - git -C "$repo" fetch -q origin - git -C "$repo" show-ref --verify --quiet "refs/remotes/origin/delivery/$short" - git -C "$repo" show-ref --verify --quiet "refs/heads/delivery/$short" - [ -d "$wt" ] - [ "$(bd show "$id" --readonly --json | jq -r '.[0].status')" = in_progress ] - - # Recovery: clean the worktree, rerun — release now succeeds normally. - rm -f "$wt/untracked.log" - run "$CLERK" backlog release "$id" - [ "$status" -eq 0 ] - [[ "$output" == *"released $id"* ]] -} - -@test "release: missing id is a usage error, exit 2" { - repo=$(make_claim_repo rel_missing) - cd "$repo" - run "$CLERK" backlog release - [ "$status" -eq 2 ] - [[ "$output" == *"missing id"* ]] -} - -@test "release: an id that does not resolve is a usage error, exit 2" { - repo=$(make_claim_repo rel_nx) - cd "$repo" - run "$CLERK" backlog release nonexistent-zzz - [ "$status" -eq 2 ] - [[ "$output" == *"not found"* ]] -} - -# ----------------------------------------------------------------- return -- - -@test "return: missing --reason is refused, exit 2, prescribes the flag, no side effects" { - repo=$(make_claim_repo ret_noreason) - cd "$repo" - id=$(mk_ready_unit "return no reason unit") - short="${id#*-}" - "$CLERK" backlog claim "$id" >/dev/null - - run "$CLERK" backlog return "$id" - [ "$status" -eq 2 ] - [[ "$output" == *"--reason"* ]] - git -C "$repo" show-ref --verify --quiet "refs/heads/delivery/$short" - [ -d "$repo/.worktrees/$short" ] - [ "$(bd show "$id" --readonly --json | jq -r '.[0].status')" = in_progress ] -} - -@test "return (bd): preserves returned/<short> (local+origin), deletes delivery/<short>, removes worktree, reopens + strips stage:ready, files a VERBATIM-reason impediment capture" { - repo=$(make_claim_repo ret_full) - cd "$repo" - id=$(mk_ready_unit "return full unit") - short="${id#*-}" - "$CLERK" backlog claim "$id" >/dev/null - wt="$repo/.worktrees/$short" - - reason="the upstream API this depends on was deprecated mid-flight" - run "$CLERK" backlog return "$id" --reason "$reason" - [ "$status" -eq 0 ] - [[ "$output" == *"returned $id"* ]] - [[ "$output" == *"returned/$short"* ]] - - # delivery/<short> gone (local + remote); returned/<short> present (local + remote) - ! git -C "$repo" show-ref --verify --quiet "refs/heads/delivery/$short" - git -C "$repo" show-ref --verify --quiet "refs/heads/returned/$short" - git -C "$repo" fetch -q origin - ! git -C "$repo" show-ref --verify --quiet "refs/remotes/origin/delivery/$short" - git -C "$repo" show-ref --verify --quiet "refs/remotes/origin/returned/$short" - - # worktree removed - [ ! -d "$wt" ] - - # unit reopened, unassigned, stage:ready stripped — absent from the ready population, - # present in the plain inbox pool ('backlog next' is out of this unit's scope and still a - # stub, so the ready-population check is the underlying label condition it would filter - # on; 'inbox list' is real and is exercised directly). - json=$(bd show "$id" --readonly --json) - [ "$(jq -r '.[0].status' <<<"$json")" = open ] - [ "$(jq -r '.[0].assignee // ""' <<<"$json")" = "" ] - [ "$(jq -r '(.[0].labels // []) | index("stage:ready")' <<<"$json")" = null ] - run "$CLERK" inbox list - [[ "$output" == *"$id"* ]] - - # impediment-typed capture: verbatim reason + a returned/<short> reference - cap_id=$(bd list --status open --json | jq -r --arg t impediment '.[] | select(.issue_type==$t) | .id') - [ -n "$cap_id" ] - cap_json=$(bd show "$cap_id" --readonly --json) - [ "$(jq -r '.[0].issue_type' <<<"$cap_json")" = impediment ] - body=$(jq -r '.[0].description' <<<"$cap_json") - [[ "$body" == *"$reason"* ]] - [[ "$body" == *"returned/$short"* ]] - [[ "$body" == *"returned from delivery of $id"* ]] -} - -@test "return (bd): first return creates canonical returned branch without an archive" { - repo=$(make_claim_repo ret_first_no_archive) - cd "$repo" - id=$(mk_ready_unit "first return no archive unit") - short="${id#*-}" - "$CLERK" backlog claim "$id" >/dev/null - run "$CLERK" backlog return "$id" --reason "first return" - [ "$status" -eq 0 ] - git -C "$repo" show-ref --verify --quiet "refs/heads/returned/$short" - [ -z "$(git -C "$repo" for-each-ref --format='%(refname:short)' "refs/heads/returned/$short-*")" ] -} - -@test "return (bd): second return archives the prior returned attempt and makes the new attempt canonical" { - repo=$(make_claim_repo ret_second_archive) - cd "$repo" - id=$(mk_ready_unit "second return archive unit") - short="${id#*-}" - "$CLERK" backlog claim "$id" >/dev/null - wt="$repo/.worktrees/$short" - printf 'first\n' >"$wt/attempt.txt" - git -C "$wt" add attempt.txt - git -C "$wt" commit -q -m "first attempt" - "$CLERK" backlog return "$id" --reason "first miss" >/dev/null - old_tip=$(git -C "$repo" rev-parse "returned/$short") - old_suffix=$(git -C "$repo" rev-parse --short "returned/$short") - - bd update "$id" --add-label stage:ready >/dev/null - "$CLERK" backlog claim "$id" --fresh --returned keep >/dev/null - wt="$repo/.worktrees/$short" - printf 'second\n' >"$wt/attempt.txt" - git -C "$wt" add attempt.txt - git -C "$wt" commit -q -m "second attempt" - new_tip=$(git -C "$repo" rev-parse "delivery/$short") - - run "$CLERK" backlog return "$id" --reason "second miss" - [ "$status" -eq 0 ] - git -C "$repo" show-ref --verify --quiet "refs/heads/returned/$short-$old_suffix" - [ "$(git -C "$repo" rev-parse "returned/$short-$old_suffix")" = "$old_tip" ] - git -C "$repo" show-ref --verify --quiet "refs/heads/returned/$short" - [ "$(git -C "$repo" rev-parse "returned/$short")" = "$new_tip" ] - ! git -C "$repo" show-ref --verify --quiet "refs/heads/delivery/$short" - git -C "$repo" fetch -q origin - git -C "$repo" show-ref --verify --quiet "refs/remotes/origin/returned/$short-$old_suffix" - git -C "$repo" show-ref --verify --quiet "refs/remotes/origin/returned/$short" - ! git -C "$repo" show-ref --verify --quiet "refs/remotes/origin/delivery/$short" - [ "$(bd show "$id" --readonly --json | jq -r '.[0].status')" = open ] -} - -@test "return (bd): offline second return archives locally and defers origin updates" { - repo=$(make_claim_repo ret_second_offline_archive) - cd "$repo" - id=$(mk_ready_unit "offline second return archive unit") - short="${id#*-}" - "$CLERK" backlog claim "$id" >/dev/null - wt="$repo/.worktrees/$short" - git -C "$wt" commit -q --allow-empty -m "first offline archive attempt" - "$CLERK" backlog return "$id" --reason "first miss" >/dev/null - old_tip=$(git -C "$repo" rev-parse "returned/$short") - old_suffix=$(git -C "$repo" rev-parse --short "returned/$short") - - bd update "$id" --add-label stage:ready >/dev/null - "$CLERK" backlog claim "$id" --fresh --returned keep >/dev/null - wt="$repo/.worktrees/$short" - git -C "$wt" commit -q --allow-empty -m "second offline archive attempt" - new_tip=$(git -C "$repo" rev-parse "delivery/$short") - break_origin "$repo" - - run env CI= "$CLERK" backlog return "$id" --reason "offline second miss" - [ "$status" -eq 0 ] - [[ "$output" == *"OFFLINE"* ]] - [[ "$output" == *"deferred to sync"* ]] - [ "$(git -C "$repo" rev-parse "returned/$short-$old_suffix")" = "$old_tip" ] - [ "$(git -C "$repo" rev-parse "returned/$short")" = "$new_tip" ] - ! git -C "$repo" show-ref --verify --quiet "refs/heads/delivery/$short" - [ "$(bd show "$id" --readonly --json | jq -r '.[0].status')" = open ] -} - -@test "return (bd): running from inside the delivery worktree removes the primary checkout worktree" { - repo=$(make_claim_repo ret_from_worktree) - cd "$repo" - id=$(mk_ready_unit "return from worktree unit") - short="${id#*-}" - "$CLERK" backlog claim "$id" >/dev/null - wt="$repo/.worktrees/$short" - git -C "$wt" -c user.email=clerk@test -c user.name=clerk commit -q --allow-empty -m "preserved evidence" - - cd "$wt" - run "$CLERK" backlog return "$id" --reason "return from inside worktree" - [ "$status" -eq 0 ] - [[ "$output" == *"returned $id"* ]] - - [ ! -d "$wt" ] - git -C "$repo" show-ref --verify --quiet "refs/heads/returned/$short" - ! git -C "$repo" show-ref --verify --quiet "refs/heads/delivery/$short" - git -C "$repo" fetch -q origin - git -C "$repo" show-ref --verify --quiet "refs/remotes/origin/returned/$short" - ! git -C "$repo" show-ref --verify --quiet "refs/remotes/origin/delivery/$short" - json=$(bd -C "$repo" show "$id" --readonly --json) - [ "$(jq -r '.[0].status' <<<"$json")" = open ] - [ "$(jq -r '(.[0].labels // []) | index("stage:ready")' <<<"$json")" = null ] -} - -@test "return (bd): OFFLINE attended — local rename proceeds, remote push/delete deferred with a warning" { - repo=$(make_claim_repo ret_offline) - cd "$repo" - id=$(mk_ready_unit "offline return unit") - short="${id#*-}" - "$CLERK" backlog claim "$id" >/dev/null - break_origin "$repo" - - run env CI= "$CLERK" backlog return "$id" --reason "offline test reason" - [ "$status" -eq 0 ] - [[ "$output" == *"OFFLINE"* ]] - [[ "$output" == *"deferred to sync"* ]] - git -C "$repo" show-ref --verify --quiet "refs/heads/returned/$short" - ! git -C "$repo" show-ref --verify --quiet "refs/heads/delivery/$short" - [ "$(bd show "$id" --readonly --json | jq -r '.[0].status')" = open ] -} - -@test "return (bd): OFFLINE in a job context — refuses, exit 2, no rename, no teardown" { - repo=$(make_claim_repo ret_offline_job) - cd "$repo" - id=$(mk_ready_unit "offline job return unit") - short="${id#*-}" - "$CLERK" backlog claim "$id" >/dev/null - break_origin "$repo" - - run env CLERK_JOB=1 "$CLERK" backlog return "$id" --reason "should not matter" - [ "$status" -eq 2 ] - [[ "$output" == *"OFFLINE in a job context"* ]] - [ -d "$repo/.worktrees/$short" ] - git -C "$repo" show-ref --verify --quiet "refs/heads/delivery/$short" - ! git -C "$repo" show-ref --verify --quiet "refs/heads/returned/$short" - [ "$(bd show "$id" --readonly --json | jq -r '.[0].status')" = in_progress ] -} - -@test "return (bd): a dirty worktree fails return WITHOUT renaming the branch or touching origin first (dotfiles-dft.3 review)" { - repo=$(make_claim_repo ret_dirty_wt) - cd "$repo" - id=$(mk_ready_unit "dirty worktree return unit") - short="${id#*-}" - "$CLERK" backlog claim "$id" >/dev/null - wt="$repo/.worktrees/$short" - git -C "$wt" -c user.email=clerk@test -c user.name=clerk commit -q --allow-empty -m "some evidence" - echo x >"$wt/untracked.log" - - run "$CLERK" backlog return "$id" --reason "dirty worktree repro" - [ "$status" -eq 5 ] - [[ "$output" == *"could not remove the worktree"* ]] - - # Half-return must not happen: delivery/<short> still present (local+origin), - # returned/<short> must NOT exist yet, unit still claimed, no impediment filed. - ! git -C "$repo" show-ref --verify --quiet "refs/heads/returned/$short" - git -C "$repo" show-ref --verify --quiet "refs/heads/delivery/$short" - git -C "$repo" fetch -q origin - git -C "$repo" show-ref --verify --quiet "refs/remotes/origin/delivery/$short" - [ -d "$wt" ] - json=$(bd show "$id" --readonly --json) - [ "$(jq -r '.[0].status' <<<"$json")" = in_progress ] - [ "$(jq -r '(.[0].labels // []) | index("stage:ready")' <<<"$json")" != null ] - cap_count=$(bd list --status open --json | jq -r --arg t impediment '[.[] | select(.issue_type==$t)] | length') - [ "$cap_count" -eq 0 ] - - # Recovery: clean the worktree, rerun — return now completes normally. - rm -f "$wt/untracked.log" - run "$CLERK" backlog return "$id" --reason "dirty worktree repro" - [ "$status" -eq 0 ] - [[ "$output" == *"returned $id"* ]] - git -C "$repo" show-ref --verify --quiet "refs/heads/returned/$short" -} - -@test "return: missing id is a usage error, exit 2" { - repo=$(make_claim_repo ret_missing) - cd "$repo" - run "$CLERK" backlog return - [ "$status" -eq 2 ] - [[ "$output" == *"missing id"* ]] -} - -@test "return: an id that does not resolve is a usage error, exit 2" { - repo=$(make_claim_repo ret_nx) - cd "$repo" - run "$CLERK" backlog return nonexistent-zzz --reason "whatever" - [ "$status" -eq 2 ] - [[ "$output" == *"not found"* ]] -} - -@test "return: an id not claimed here (no local delivery/<short>) is refused, exit 2" { - repo=$(make_claim_repo ret_unclaimed) - cd "$repo" - id=$(mk_ready_unit "never claimed return unit") - run "$CLERK" backlog return "$id" --reason "whatever" - [ "$status" -eq 2 ] - [[ "$output" == *"no local delivery/"* ]] -} diff --git a/tests/clerk_python/test_core_contracts.py b/tests/clerk_python/test_core_contracts.py deleted file mode 100644 index 63e5489..0000000 --- a/tests/clerk_python/test_core_contracts.py +++ /dev/null @@ -1,202 +0,0 @@ -import contextlib -import io -import os -import subprocess -import tempfile -import unittest -from pathlib import Path -from unittest import mock - -from clerk.cli import main -from clerk.manifest import ManifestStatus, read_manifest - - -class CliBoundaryTests(unittest.TestCase): - def invoke(self, argv, *, env=None): - out = io.StringIO() - err = io.StringIO() - with mock.patch.dict(os.environ, env or {}, clear=True), \ - contextlib.redirect_stdout(out), \ - contextlib.redirect_stderr(err): - code = main(argv) - return code, out.getvalue(), err.getvalue(), [] - - def test_no_arguments_prints_public_roster_without_legacy(self): - code, out, err, calls = self.invoke([]) - self.assertEqual(code, 2) - self.assertEqual(out, "") - self.assertIn("clerk: missing verb\nKnown verbs:\n", err) - self.assertIn(" doctor [--fix --backend bd|gh]\n", err) - self.assertEqual(calls, []) - - def test_unknown_and_bare_noun_are_usage_errors_not_legacy(self): - code, _, err, calls = self.invoke(["frobnicate"]) - self.assertEqual(code, 2) - self.assertIn("clerk: unknown verb 'frobnicate'", err) - self.assertEqual(calls, []) - - code, _, err, calls = self.invoke(["backlog"]) - self.assertEqual(code, 2) - self.assertIn("clerk: 'backlog' needs a verb", err) - self.assertEqual(calls, []) - - def test_version_and_explain_are_python_owned(self): - code, out, err, calls = self.invoke(["--version"]) - self.assertEqual((code, out, err, calls), (0, "clerk 0.1.0\n", "", [])) - - code, out, err, calls = self.invoke(["--explain", "doctor"]) - self.assertEqual(code, 0) - self.assertIn("clerk doctor — check and provision workflow plumbing", out) - self.assertIn("reads .clerk", out) - self.assertEqual(err, "") - self.assertEqual(calls, []) - - def test_glean_is_python_owned(self): - seen = [] - - def fake_glean(backend, root, remaining): - seen.append((backend, root.name, remaining)) - return 0 - - with tempfile.TemporaryDirectory() as td: - subprocess.run(["git", "init", "-q", "-b", "main", td], check=True) - Path(td, ".clerk").write_text("backlog: bd\n") - cwd = os.getcwd() - try: - os.chdir(td) - with mock.patch("clerk.cli.run_glean", side_effect=fake_glean): - result = self.invoke(["glean", "--async"]) - finally: - os.chdir(cwd) - self.assertEqual(result, (0, "", "", [])) - self.assertEqual(seen, [("bd", Path(td).name, ["--async"])]) - - def test_reconciliation_verbs_are_python_owned(self): - seen = [] - - def fake_reconciliation(path, backend, root, remaining): - seen.append((path, backend, root.name, remaining)) - return 0 - - with tempfile.TemporaryDirectory() as td: - subprocess.run(["git", "init", "-q", "-b", "main", td], check=True) - Path(td, ".clerk").write_text("backlog: bd\n") - cwd = os.getcwd() - try: - os.chdir(td) - with mock.patch("clerk.cli.run_reconciliation", side_effect=fake_reconciliation): - sync = self.invoke(["sync"]) - finish = self.invoke(["backlog", "finish", "dotfiles-123", "--watch"]) - finally: - os.chdir(cwd) - self.assertEqual(sync, (0, "", "", [])) - self.assertEqual(finish, (0, "", "", [])) - self.assertEqual( - seen, - [ - (("sync",), "bd", Path(td).name, []), - (("backlog", "finish"), "bd", Path(td).name, ["dotfiles-123", "--watch"]), - ], - ) - - def test_python_mutation_verb_uses_manifest_context_without_legacy(self): - seen = [] - - def fake_mutation(path, backend, root, remaining): - seen.append((path, backend, root.name, remaining)) - return 0 - - with tempfile.TemporaryDirectory() as td: - subprocess.run(["git", "init", "-q", "-b", "main", td], check=True) - Path(td, ".clerk").write_text("backlog: bd\n") - cwd = os.getcwd() - try: - os.chdir(td) - with mock.patch("clerk.cli.run_mutation", side_effect=fake_mutation): - code, out, err, calls = self.invoke(["capture", "title"]) - finally: - os.chdir(cwd) - self.assertEqual((code, out, err, calls), (0, "", "", [])) - self.assertEqual(seen, [(("capture",), "bd", Path(td).name, ["title"])]) - - def test_python_query_verb_uses_manifest_context_without_legacy(self): - seen = [] - - def fake_query(path, backend, root, remaining): - seen.append((path, backend, root.name, remaining)) - return 0 - - with tempfile.TemporaryDirectory() as td: - subprocess.run(["git", "init", "-q", "-b", "main", td], check=True) - Path(td, ".clerk").write_text("backlog: bd\n") - cwd = os.getcwd() - try: - os.chdir(td) - with mock.patch("clerk.cli.run_query", side_effect=fake_query): - code, out, err, calls = self.invoke(["backlog", "show", "dotfiles-123"]) - finally: - os.chdir(cwd) - self.assertEqual((code, out, err, calls), (0, "", "", [])) - self.assertEqual(seen, [(("backlog", "show"), "bd", Path(td).name, ["dotfiles-123"])]) - - def test_known_workflow_verb_with_bad_manifest_refuses_before_a_handler(self): - with tempfile.TemporaryDirectory() as td: - subprocess.run(["git", "init", "-q", "-b", "main", td], check=True) - cwd = os.getcwd() - try: - os.chdir(td) - code, out, err, calls = self.invoke(["sync"]) - finally: - os.chdir(cwd) - self.assertEqual(code, 4) - self.assertEqual(out, "") - self.assertIn("missing .clerk marker", err) - self.assertEqual(calls, []) - - def test_proof_is_python_owned(self): - seen = [] - - def fake_proof(backend, root, remaining, runner): - seen.append((backend, root.name, remaining)) - return 0 - - with tempfile.TemporaryDirectory() as td: - subprocess.run(["git", "init", "-q", "-b", "main", td], check=True) - Path(td, ".clerk").write_text("backlog: bd\n") - cwd = os.getcwd() - try: - os.chdir(td) - with mock.patch("clerk.cli.cmd_backlog_proof", side_effect=fake_proof): - result = self.invoke(["backlog", "proof", "dotfiles-123"]) - finally: - os.chdir(cwd) - self.assertEqual(result, (0, "", "", [])) - self.assertEqual(seen, [("bd", Path(td).name, ["dotfiles-123"])]) - - -class ManifestParsingTests(unittest.TestCase): - def test_manifest_accepts_single_commented_directive(self): - with tempfile.TemporaryDirectory() as td: - path = Path(td, ".clerk") - path.write_text("# comment\n\n backlog: gh # ok\n") - result = read_manifest(path) - self.assertEqual(result.status, ManifestStatus.OK) - self.assertEqual(result.backend, "gh") - - def test_manifest_rejects_missing_invalid_and_ambiguous(self): - with tempfile.TemporaryDirectory() as td: - missing = read_manifest(Path(td, ".clerk")) - self.assertEqual(missing.status, ManifestStatus.MISSING) - - path = Path(td, ".clerk") - path.write_text("backlog: jira\n") - invalid = read_manifest(path) - self.assertEqual(invalid.status, ManifestStatus.INVALID) - - path.write_text("backlog: bd\nbacklog: gh\n") - ambiguous = read_manifest(path) - self.assertEqual(ambiguous.status, ManifestStatus.AMBIGUOUS) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/clerk_python/test_graph_mutations.py b/tests/clerk_python/test_graph_mutations.py deleted file mode 100644 index bb9d368..0000000 --- a/tests/clerk_python/test_graph_mutations.py +++ /dev/null @@ -1,261 +0,0 @@ -import contextlib -import io -import json -import sys -import tempfile -import unittest -from pathlib import Path -from unittest import mock - -from clerk.commands import run_mutation -from clerk.proc import CommandResult - - -class FakeRunner: - def __init__(self, responses=None): - self.responses = list(responses or []) - self.calls = [] - - def run(self, args, *, cwd=None, env=None): - self.calls.append(list(args)) - if not self.responses: - return CommandResult(tuple(args), 0, "", "") - value = self.responses.pop(0) - if callable(value): - return value(args) - return value - - -def ok(args, stdout="", stderr=""): - return CommandResult(tuple(args), 0, stdout, stderr) - - -def issue(**overrides): - obj = { - "id": "item", - "title": "Item", - "status": "open", - "labels": [], - "assignee": "", - "parent": None, - "dependencies": [], - "dependents": [], - } - obj.update(overrides) - return json.dumps([obj]) - - -class GraphMutationTests(unittest.TestCase): - def invoke(self, path, argv, responses, *, stdin="", env=None): - runner = FakeRunner(responses) - out = io.StringIO() - err = io.StringIO() - with tempfile.TemporaryDirectory() as td, \ - contextlib.redirect_stdout(out), \ - contextlib.redirect_stderr(err), \ - mock.patch.object(sys, "stdin", io.StringIO(stdin)): - code = run_mutation(path, "bd", Path(td), argv, env or {}, runner) - return code, out.getvalue(), err.getvalue(), runner.calls - - def test_parent_set_self_verifies_before_success(self): - code, out, err, calls = self.invoke( - ("inbox", "parent"), - ["set", "child", "parent"], - [ - lambda args: ok(args, issue(id="child")), - lambda args: ok(args, issue(id="parent")), - lambda args: ok(args, issue(id="parent")), - lambda args: ok(args), - lambda args: ok(args, issue(id="child", parent="parent")), - ], - ) - self.assertEqual(code, 0) - self.assertEqual(out, "clerk: parent set child -> parent\n") - self.assertEqual(err, "") - self.assertEqual(calls[-2:], [ - ["bd", "update", "child", "--parent", "parent"], - ["bd", "show", "child", "--readonly", "--json"], - ]) - - def test_parent_move_refuses_invalid_dependency_edges_without_drop_flag(self): - child = issue(id="child", parent="p1", dependencies=[{"dependency_type": "blocks", "id": "blocker"}]) - code, out, err, calls = self.invoke( - ("inbox", "parent"), - ["set", "child", "p2"], - [ - lambda args: ok(args, child), - lambda args: ok(args, issue(id="p2")), - lambda args: ok(args, issue(id="p2")), - lambda args: ok(args, issue(id="blocker", parent="p1")), - ], - ) - self.assertEqual(code, 2) - self.assertEqual(out, "") - self.assertIn("--drop-invalid-deps", err) - self.assertNotIn(["bd", "update", "child", "--parent", "p2"], calls) - - def test_parent_set_with_drop_self_verifies_removed_invalid_edges(self): - child_before = issue( - id="child", - parent="p1", - dependencies=[{"dependency_type": "blocks", "id": "blocker"}], - dependents=[{"dependency_type": "blocks", "id": "blocked"}], - ) - code, out, err, calls = self.invoke( - ("inbox", "parent"), - ["set", "child", "p2", "--drop-invalid-deps"], - [ - lambda args: ok(args, child_before), - lambda args: ok(args, issue(id="p2")), - lambda args: ok(args, issue(id="p2")), - lambda args: ok(args, issue(id="blocker", parent="p1")), - lambda args: ok(args, issue(id="blocked", parent="p1")), - lambda args: ok(args), - lambda args: ok(args), - lambda args: ok(args), - lambda args: ok(args, issue(id="child", parent="p2", dependencies=[])), - lambda args: ok(args, issue(id="blocked", dependencies=[])), - ], - ) - self.assertEqual(code, 0) - self.assertEqual(out, "clerk: parent set child -> p2\n") - self.assertEqual(err, "") - self.assertIn(["bd", "dep", "remove", "child", "blocker"], calls) - self.assertIn(["bd", "dep", "remove", "blocked", "child"], calls) - self.assertEqual(calls[-2:], [ - ["bd", "show", "child", "--readonly", "--json"], - ["bd", "show", "blocked", "--readonly", "--json"], - ]) - - def test_dependency_add_is_sibling_only_cycle_checked_and_self_verified(self): - code, out, err, calls = self.invoke( - ("inbox", "dep"), - ["add", "child", "blocker"], - [ - lambda args: ok(args, issue(id="child", parent="parent")), - lambda args: ok(args, issue(id="blocker", parent="parent")), - lambda args: ok(args, issue(id="blocker")), - lambda args: ok(args), - lambda args: ok(args, issue(id="child", parent="parent", dependencies=[{"dependency_type": "blocks", "id": "blocker"}])), - ], - ) - self.assertEqual(code, 0) - self.assertEqual(out, "clerk: dependency added child blocked-by blocker\n") - self.assertEqual(err, "") - self.assertEqual(calls[-2:], [ - ["bd", "dep", "add", "child", "blocker"], - ["bd", "show", "child", "--readonly", "--json"], - ]) - - code, out, err, _ = self.invoke( - ("inbox", "dep"), - ["add", "child", "outsider"], - [ - lambda args: ok(args, issue(id="child", parent="parent")), - lambda args: ok(args, issue(id="outsider", parent="other")), - ], - ) - self.assertEqual(code, 2) - self.assertIn("sibling-only", err) - - code, out, err, _ = self.invoke( - ("inbox", "dep"), - ["add", "child", "blocker"], - [ - lambda args: ok(args, issue(id="child", parent="parent")), - lambda args: ok(args, issue(id="blocker", parent="parent")), - lambda args: ok(args, issue(id="blocker", dependencies=[{"dependency_type": "blocks", "id": "child"}])), - ], - ) - self.assertEqual(code, 2) - self.assertIn("dependency cycle", err) - - def test_claim_refuses_blocked_item_and_claims_unblocked_item_with_actor_verification(self): - blocked = issue(id="blocked", dependencies=[{"dependency_type": "blocks", "id": "blocker", "status": "open"}]) - code, out, err, calls = self.invoke(("inbox", "claim"), ["blocked"], [lambda args: ok(args, blocked)]) - self.assertEqual(code, 2) - self.assertEqual(out, "") - self.assertIn("open blockers", err) - self.assertEqual(calls, [["bd", "show", "blocked", "--readonly", "--json"]]) - - code, out, err, calls = self.invoke( - ("inbox", "claim"), - ["leaf"], - [ - lambda args: ok(args, issue(id="leaf")), - lambda args: ok(args, "Planner\n"), - lambda args: ok(args), - lambda args: ok(args, issue(id="leaf", assignee="Planner")), - ], - ) - self.assertEqual(code, 0) - self.assertEqual(out, "clerk: claimed leaf\n") - self.assertEqual(err, "") - self.assertEqual(calls[1], ["git", "-C", calls[1][2], "config", "user.name"]) - self.assertEqual(calls[-2:], [ - ["bd", "update", "leaf", "--claim"], - ["bd", "show", "leaf", "--readonly", "--json"], - ]) - - def test_release_refuses_other_holder_and_self_verifies_unclaim(self): - code, out, err, _ = self.invoke( - ("inbox", "release"), - ["leaf"], - [lambda args: ok(args, issue(id="leaf", assignee="Other")), lambda args: ok(args, "Me\n")], - ) - self.assertEqual(code, 5) - self.assertIn("claimed by Other", err) - self.assertNotIn("run 'clerk doctor'", err) - - code, out, err, calls = self.invoke( - ("inbox", "release"), - ["leaf"], - [ - lambda args: ok(args, issue(id="leaf", assignee="Me")), - lambda args: ok(args, "Me\n"), - lambda args: ok(args), - lambda args: ok(args, issue(id="leaf", assignee="")), - ], - ) - self.assertEqual(code, 0) - self.assertEqual(out, "clerk: released leaf\n") - self.assertEqual(calls[-2:], [ - ["bd", "update", "leaf", "--status", "open", "--assignee", ""], - ["bd", "show", "leaf", "--readonly", "--json"], - ]) - - def test_resolve_appends_resolution_note_closes_and_verifies_closed(self): - captured = {} - code, out, err, calls = self.invoke( - ("inbox", "resolve"), - ["leaf", "--stdin"], - [ - lambda args: ok(args, issue(id="leaf")), - lambda args: captured.__setitem__("note", args[4]) or ok(args), - lambda args: ok(args), - lambda args: ok(args, issue(id="leaf", status="closed", notes=captured["note"])), - ], - stdin="done\n", - ) - self.assertEqual(code, 0) - self.assertEqual(out, "clerk: resolved leaf\n") - self.assertEqual(err, "") - self.assertEqual(calls[1][:4], ["bd", "update", "leaf", "--append-notes"]) - self.assertIn("clerk-resolution:", calls[1][4]) - self.assertIn("\ndone", calls[1][4]) - self.assertEqual(calls[2], ["bd", "close", "leaf", "--reason", "resolved"]) - - def test_resolve_refuses_open_blockers(self): - code, out, err, calls = self.invoke( - ("inbox", "resolve"), - ["leaf"], - [lambda args: ok(args, issue(id="leaf", dependencies=[{"dependency_type": "blocks", "id": "blocker", "status": "open"}]))], - stdin="done", - ) - self.assertEqual(code, 2) - self.assertIn("open blockers", err) - self.assertEqual(calls, [["bd", "show", "leaf", "--readonly", "--json"]]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/clerk_python/test_ownership.py b/tests/clerk_python/test_ownership.py deleted file mode 100644 index 1c8982f..0000000 --- a/tests/clerk_python/test_ownership.py +++ /dev/null @@ -1,81 +0,0 @@ -import unittest -from clerk.ownership import is_python_owned, public_verb_path -from clerk.roster import all_public_verb_paths - - -class OwnershipTests(unittest.TestCase): - def test_python_owns_core_command_boundary_surfaces(self): - for argv in ( - [], - ["doctor"], - ["--version"], - ["--help"], - ["--explain", "backlog", "claim"], - ["--explain", "frobnicate"], - ["capture", "--help"], - ["frobnicate"], - ): - with self.subTest(argv=argv): - self.assertTrue(is_python_owned(argv)) - - def test_read_only_item_queries_are_python_owned(self): - for argv in ( - ["inbox", "list"], - ["inbox", "show", "dotfiles-123"], - ["inbox", "dups"], - ["inbox", "children", "dotfiles-parent"], - ["inbox", "frontier", "dotfiles-parent"], - ["inbox", "blockers", "dotfiles-child"], - ["inbox", "blocked", "dotfiles-blocker"], - ["backlog", "next"], - ["backlog", "show", "dotfiles-123"], - ): - with self.subTest(argv=argv): - self.assertTrue(is_python_owned(argv)) - - def test_text_and_graph_mutation_verbs_are_python_owned(self): - for argv in ( - ["capture", "title"], - ["inbox", "pregrill", "dotfiles-123"], - ["inbox", "parent", "set", "dotfiles-child", "dotfiles-parent"], - ["inbox", "dep", "add", "dotfiles-child", "dotfiles-blocker"], - ["inbox", "claim", "dotfiles-123"], - ["inbox", "release", "dotfiles-123"], - ["inbox", "note", "dotfiles-123"], - ["inbox", "update", "dotfiles-123"], - ["inbox", "resolve", "dotfiles-123"], - ["inbox", "ready", "dotfiles-123"], - ["inbox", "drop", "dotfiles-123"], - ): - with self.subTest(argv=argv): - self.assertTrue(is_python_owned(argv)) - - def test_delivery_claim_lifecycle_is_python_owned(self): - for argv in ( - ["backlog", "claim", "dotfiles-123"], - ["backlog", "release", "dotfiles-123"], - ["backlog", "return", "dotfiles-123", "--reason", "blocked"], - ): - with self.subTest(argv=argv): - self.assertTrue(is_python_owned(argv)) - - def test_delivery_reconciliation_is_python_owned(self): - self.assertTrue(is_python_owned(["backlog", "finish", "dotfiles-123"])) - self.assertTrue(is_python_owned(["sync"])) - - def test_glean_is_python_owned(self): - self.assertTrue(is_python_owned(["glean"])) - - def test_all_public_verb_paths_are_python_owned(self): - for path in all_public_verb_paths(): - with self.subTest(path=path): - self.assertTrue(is_python_owned(path)) - - def test_public_verb_path_identifies_roster_paths_without_validating_args(self): - self.assertEqual(public_verb_path(["backlog", "claim", "dotfiles-123"]), ("backlog", "claim")) - self.assertEqual(public_verb_path(["--explain", "inbox", "ready"]), ("inbox", "ready")) - self.assertEqual(public_verb_path(["frobnicate"]), None) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/clerk_python/test_proof.py b/tests/clerk_python/test_proof.py deleted file mode 100644 index 5aecf9a..0000000 --- a/tests/clerk_python/test_proof.py +++ /dev/null @@ -1,36 +0,0 @@ -import contextlib -import io -import unittest -from unittest import mock - -from clerk.project_gate import cmd_backlog_proof - - -class BacklogProofTests(unittest.TestCase): - def test_proof_normalizes_numbered_and_bulleted_criteria(self): - out = io.StringIO() - with mock.patch( - "clerk.project_gate._work", - return_value=("dotfiles-123", "title", "1. First criterion\n- Second criterion\n"), - ), contextlib.redirect_stdout(out): - self.assertEqual(cmd_backlog_proof("bd", None, ["dotfiles-123"], None), 0) - self.assertEqual( - out.getvalue(), - """{ - \"acceptance\": [ - { - \"text\": \"First criterion\", - \"evidence\": \"\" - }, - { - \"text\": \"Second criterion\", - \"evidence\": \"\" - } - ] -} -""", - ) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/clerk_python/test_read_queries.py b/tests/clerk_python/test_read_queries.py deleted file mode 100644 index 17efcab..0000000 --- a/tests/clerk_python/test_read_queries.py +++ /dev/null @@ -1,280 +0,0 @@ -import contextlib -import io -import json -import tempfile -import unittest -from pathlib import Path - -from clerk.commands import run_query -from clerk.proc import CommandResult - - -class FakeRunner: - def __init__(self, responses=None): - self.responses = list(responses or []) - self.calls = [] - - def run(self, args, *, cwd=None, env=None): - self.calls.append(list(args)) - if not self.responses: - return CommandResult(tuple(args), 0, "[]", "") - value = self.responses.pop(0) - if callable(value): - return value(args) - return value - - -def ok(args, stdout, stderr=""): - return CommandResult(tuple(args), 0, stdout, stderr) - - -def fail(args, stderr="boom"): - return CommandResult(tuple(args), 1, "", stderr) - - -class QueryCommandTests(unittest.TestCase): - def invoke(self, path, backend, argv, responses, *, env=None): - runner = FakeRunner(responses) - out = io.StringIO() - err = io.StringIO() - with tempfile.TemporaryDirectory() as td, contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): - code = run_query(path, backend, Path(td), argv, env or {}, runner) - return code, out.getvalue(), err.getvalue(), runner.calls - - def test_inbox_list_renders_pregrill_marker_and_uses_readonly_without_mutation(self): - data = [{ - "id": "dotfiles-abc", - "title": "raw capture", - "notes": "clerk-pregrill: 2026-07-23T01:02:03Z", - "updated_at": "2026-07-23T01:02:04Z", - }] - code, out, err, calls = self.invoke( - ("inbox", "list"), "bd", ["--limit", "0"], [lambda args: ok(args, json.dumps(data))] - ) - self.assertEqual(code, 0) - self.assertEqual(out, "Inbox (open, not ready) — 1 item(s):\n dotfiles-abc [pregrill:present] raw capture\n") - self.assertEqual(err, "") - self.assertEqual(calls, [["bd", "list", "--status", "open", "--exclude-label", "stage:ready", "--readonly", "--json", "--limit", "0"]]) - self.assertNotIn("update", " ".join(calls[0])) - - def test_inbox_show_json_normalizes_fields_and_body_guard(self): - issue = [{ - "id": "dotfiles-a1", - "title": "Show me", - "status": "open", - "issue_type": "task", - "description": "body", - "created_at": "now", - "updated_at": "later", - }] - code, out, err, calls = self.invoke( - ("inbox", "show"), "bd", ["dotfiles-a1", "--json"], [lambda args: ok(args, json.dumps(issue))] - ) - self.assertEqual(code, 0) - rendered = json.loads(out) - self.assertEqual(rendered["id"], "dotfiles-a1") - self.assertEqual(rendered["type"], "task") - self.assertEqual(rendered["assignee"], "") - self.assertEqual(rendered["labels"], []) - self.assertEqual(rendered["body"], "body") - self.assertEqual(err, "") - self.assertEqual(calls, [["bd", "show", "dotfiles-a1", "--readonly", "--json"]]) - - def test_inbox_dups_renders_duplicate_pairs(self): - payload = {"count": 1, "pairs": [{"issue_a_id": "a", "issue_a_title": "one", "issue_b_id": "b", "issue_b_title": "two", "similarity": 0.75}]} - code, out, _, calls = self.invoke( - ("inbox", "dups"), "bd", [], [lambda args: ok(args, json.dumps(payload))] - ) - self.assertEqual(code, 0) - self.assertEqual(out, 'Duplicate candidates — 1 pair(s):\n a "one" ~ b "two" (score: 0.75)\n') - self.assertEqual(calls, [["bd", "find-duplicates", "--readonly", "--json"]]) - - def test_inbox_graph_children_blockers_and_blocked_normalize_json(self): - parent = [{ - "id": "p", - "title": "Parent", - "status": "open", - "issue_type": "epic", - "dependents": [ - {"dependency_type": "parent-child", "id": "a"}, - {"dependency_type": "blocks", "id": "unrelated"}, - ], - }] - child = [{ - "id": "a", - "title": "A", - "status": "open", - "issue_type": "task", - "labels": ["x"], - "parent": "p", - "created_at": "c", - "updated_at": "u", - }] - code, out, err, calls = self.invoke( - ("inbox", "children"), "bd", ["p"], [lambda args: ok(args, json.dumps(parent + child))] - ) - self.assertEqual(code, 0) - self.assertEqual(err, "") - self.assertEqual(json.loads(out), { - "parent": {"id": "p", "title": "Parent", "status": "open", "type": "epic", "assignee": "", "labels": [], "parent": None, "created_at": None, "updated_at": None}, - "items": [{"id": "a", "title": "A", "status": "open", "type": "task", "assignee": "", "labels": ["x"], "parent": "p", "created_at": "c", "updated_at": "u"}], - }) - self.assertEqual(calls, [["bd", "list", "--all", "--readonly", "--json", "--limit", "0"]]) - - blocker = [{"id": "blocker", "title": "Blocker", "status": "open", "issue_type": "task"}] - blocked = [{"id": "blocked", "title": "Blocked", "status": "open", "issue_type": "task", "dependencies": [{"dependency_type": "blocks", "id": "blocker"}]}] - code, out, _, calls = self.invoke( - ("inbox", "blockers"), "bd", ["blocked", "--pretty"], [lambda args: ok(args, json.dumps(blocked + blocker))] - ) - self.assertEqual(code, 0) - self.assertIn('\n "items"', out) - self.assertEqual(json.loads(out)["items"][0]["id"], "blocker") - self.assertEqual(calls, [["bd", "list", "--all", "--readonly", "--json", "--limit", "0"]]) - - reverse = [{"id": "blocker", "title": "Blocker", "status": "open", "issue_type": "task"}] - code, out, _, calls = self.invoke( - ("inbox", "blocked"), "bd", ["blocker"], [lambda args: ok(args, json.dumps(reverse + blocked))] - ) - self.assertEqual(code, 0) - self.assertEqual(json.loads(out)["items"][0]["id"], "blocked") - self.assertEqual(calls, [["bd", "list", "--all", "--readonly", "--json", "--limit", "0"]]) - - def test_inbox_frontier_filters_empty_blocked_claimed_ready_and_closed_graphs(self): - parent = [{"id": "p", "title": "Parent", "status": "open", "issue_type": "epic", "dependents": [ - {"dependency_type": "parent-child", "id": "free"}, - {"dependency_type": "parent-child", "id": "blocked"}, - {"dependency_type": "parent-child", "id": "claimed"}, - {"dependency_type": "parent-child", "id": "closed"}, - {"dependency_type": "parent-child", "id": "ready"}, - {"dependency_type": "parent-child", "id": "closed_blocker"}, - ]}] - details = { - "free": [{"id": "free", "title": "Free", "status": "open", "issue_type": "task", "parent": "p"}], - "blocked": [{"id": "blocked", "title": "Blocked", "status": "open", "issue_type": "task", "dependencies": [{"dependency_type": "blocks", "id": "free", "status": "open"}]}], - "claimed": [{"id": "claimed", "title": "Claimed", "status": "open", "issue_type": "task", "assignee": "other"}], - "closed": [{"id": "closed", "title": "Closed", "status": "closed", "issue_type": "task"}], - "ready": [{"id": "ready", "title": "Ready", "status": "open", "issue_type": "task", "labels": ["stage:ready"]}], - "closed_blocker": [{"id": "closed_blocker", "title": "Closed blocker", "status": "open", "issue_type": "task", "dependencies": [{"dependency_type": "blocks", "id": "free", "status": "closed"}]}], - } - - snapshot = parent + [items[0] for items in details.values()] - code, out, _, calls = self.invoke( - ("inbox", "frontier"), "bd", ["p"], [lambda args: ok(args, json.dumps(snapshot))] - ) - self.assertEqual(code, 0) - self.assertEqual([item["id"] for item in json.loads(out)["items"]], ["free", "closed_blocker"]) - self.assertEqual(calls, [["bd", "list", "--all", "--readonly", "--json", "--limit", "0"]]) - - empty_parent = [{"id": "empty", "title": "Empty", "status": "open", "issue_type": "epic", "dependents": []}] - code, out, _, calls = self.invoke(("inbox", "frontier"), "bd", ["empty"], [lambda args: ok(args, json.dumps(empty_parent))]) - self.assertEqual(code, 0) - self.assertEqual(json.loads(out)["items"], []) - self.assertEqual(calls, [["bd", "list", "--all", "--readonly", "--json", "--limit", "0"]]) - - closed_parent = [{"id": "p", "title": "Parent", "status": "closed", "issue_type": "epic"}] - code, _, err, _ = self.invoke(("inbox", "frontier"), "bd", ["p"], [lambda args: ok(args, json.dumps(closed_parent))]) - self.assertEqual(code, 2) - self.assertIn("must be a non-closed Work graph parent", err) - - def test_inbox_graph_usage_not_found_and_backend_failures(self): - code, _, err, calls = self.invoke(("inbox", "children"), "bd", [], []) - self.assertEqual(code, 2) - self.assertIn("missing parent id", err) - self.assertEqual(calls, []) - - code, _, err, calls = self.invoke(("inbox", "frontier"), "bd", ["p", "--wat"], []) - self.assertEqual(code, 2) - self.assertIn("unknown argument '--wat'", err) - self.assertEqual(calls, []) - - code, _, err, calls = self.invoke(("inbox", "blockers"), "bd", ["missing"], [lambda args: ok(args, "[]")]) - self.assertEqual(code, 2) - self.assertIn("clerk inbox blockers: missing not found", err) - self.assertEqual(calls, [["bd", "list", "--all", "--readonly", "--json", "--limit", "0"]]) - - code, _, err, calls = self.invoke(("inbox", "blocked"), "bd", ["item"], [lambda args: ok(args, "not-json")]) - self.assertEqual(code, 5) - self.assertIn("inbox blocked failed", err) - self.assertIn("run 'clerk doctor'", err) - self.assertEqual(calls, [["bd", "list", "--all", "--readonly", "--json", "--limit", "0"]]) - - def test_backlog_next_filters_ready_items_without_serial_show_fanout(self): - rows = [ - {"id": "pick", "title": "Pick", "status": "open", "labels": ["stage:ready"], "acceptance_criteria": "- pick"}, - { - "id": "blocked", - "title": "Blocked", - "status": "open", - "labels": ["stage:ready"], - "acceptance_criteria": "- blocked", - "dependencies": [{"type": "blocks", "depends_on_id": "blocker"}], - }, - {"id": "blocker", "title": "Blocker", "status": "open"}, - {"id": "parent", "title": "Parent", "status": "open", "labels": ["stage:ready"], "acceptance_criteria": "- parent"}, - {"id": "child", "title": "Child", "status": "open", "parent": "parent"}, - {"id": "claimed", "title": "Claimed", "status": "open", "labels": ["stage:ready"], "acceptance_criteria": "- claimed", "assignee": "me"}, - {"id": "missing", "title": "Missing", "status": "open", "labels": ["stage:ready"]}, - ] - - code, out, _, calls = self.invoke( - ("backlog", "next"), "bd", [], [lambda args: ok(args, json.dumps(rows))] - ) - self.assertEqual(code, 0) - self.assertEqual(out, "Backlog (ready) — 1 item(s):\n pick ready Pick\n") - self.assertEqual(calls, [["bd", "list", "--all", "--readonly", "--json", "--limit", "0"]]) - - def test_backlog_waiting_lists_only_ready_work_held_by_blockers_or_children(self): - rows = [ - {"id": "pick", "title": "Pick", "status": "open", "labels": ["stage:ready"], "acceptance_criteria": "- pick"}, - {"id": "blocked", "title": "Blocked", "status": "open", "labels": ["stage:ready"], "acceptance_criteria": "- blocked", "dependencies": [{"type": "blocks", "depends_on_id": "blocker"}]}, - {"id": "blocker", "title": "Blocker", "status": "open"}, - {"id": "parent", "title": "Parent", "status": "open", "labels": ["stage:ready"], "acceptance_criteria": "- parent"}, - {"id": "child", "title": "Child", "status": "open", "parent": "parent"}, - {"id": "claimed", "title": "Claimed", "status": "open", "labels": ["stage:ready"], "acceptance_criteria": "- claimed", "assignee": "me"}, - ] - - code, out, err, calls = self.invoke( - ("backlog", "waiting"), "bd", [], [lambda args: ok(args, json.dumps(rows))] - ) - - self.assertEqual(code, 0) - self.assertEqual(out, "Backlog waiting — 2 item(s):\n blocked blockers:1 children:0 Blocked\n parent blockers:0 children:1 Parent\n") - self.assertEqual(err, "") - self.assertEqual(calls, [["bd", "list", "--all", "--readonly", "--json", "--limit", "0"]]) - - code, out, err, calls = self.invoke( - ("backlog", "waiting"), "bd", [], [lambda args: ok(args, "[]")] - ) - self.assertEqual((code, out, err), (0, "Backlog waiting — 0 item(s):\n (empty)\n", "")) - self.assertEqual(calls, [["bd", "list", "--all", "--readonly", "--json", "--limit", "0"]]) - - def test_backlog_next_gh_lists_ready_for_agent_issues(self): - payload = [{"number": 9, "title": "do the thing"}] - code, out, _, calls = self.invoke( - ("backlog", "next"), "gh", [], [lambda args: ok(args, json.dumps(payload))] - ) - self.assertEqual(code, 0) - self.assertEqual(out, "Backlog (ready) — 1 item(s):\n #9 ready do the thing\n") - self.assertEqual(calls, [["gh", "issue", "list", "--label", "ready-for-agent", "--json", "number,title"]]) - - def test_show_not_found_is_usage_error(self): - code, _, err, calls = self.invoke(("inbox", "show"), "bd", ["missing"], [lambda args: fail(args, "not found")]) - self.assertEqual(code, 2) - self.assertIn("clerk inbox show: missing not found", err) - self.assertEqual(calls, [["bd", "show", "missing", "--readonly", "--json"]]) - - def test_usage_and_backend_failures_have_distinct_exit_codes(self): - code, _, err, calls = self.invoke(("inbox", "list"), "bd", ["--limit", "nope"], []) - self.assertEqual(code, 2) - self.assertIn("--limit must be a non-negative integer", err) - self.assertEqual(calls, []) - - code, _, err, calls = self.invoke(("inbox", "list"), "bd", [], [lambda args: fail(args)]) - self.assertEqual(code, 5) - self.assertIn("clerk: inbox list failed", err) - self.assertIn("run 'clerk doctor'", err) - self.assertEqual(len(calls), 1) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/clerk_python/test_ready_drop.py b/tests/clerk_python/test_ready_drop.py deleted file mode 100644 index f00fa92..0000000 --- a/tests/clerk_python/test_ready_drop.py +++ /dev/null @@ -1,717 +0,0 @@ -import contextlib -import io -import json -import re -import subprocess -import sys -import tempfile -import unittest -from pathlib import Path -from unittest import mock - -from clerk.commands import has_acceptance_criteria_section, run_mutation -from clerk.proc import CommandResult - - -class FakeRunner: - def __init__(self, responses=None, *, git_responses=None): - self.responses = list(responses or []) - self.git_responses = list(git_responses or []) - self.calls = [] - self.envs = [] - - def run(self, args, *, cwd=None, env=None): - self.calls.append(list(args)) - self.envs.append(dict(env) if env is not None else None) - if args and args[0] == "git": - # Worktree-root discovery is not behavior under test here; use the supplied root. - if "rev-parse" in args: - return fail(args) - # Default git answer mirrors a plain temp sandbox: refs absent, config unset. - # Tests that need a present ref or a known actor supply explicit git_responses. - if not self.git_responses: - return fail(args) - value = self.git_responses.pop(0) - if callable(value): - return value(args) - return value - if not self.responses: - return CommandResult(tuple(args), 0, "", "") - value = self.responses.pop(0) - if callable(value): - return value(args) - return value - - -def ok(args, stdout="", stderr=""): - return CommandResult(tuple(args), 0, stdout, stderr) - - -def fail(args, stdout="", stderr=""): - return CommandResult(tuple(args), 1, stdout, stderr) - - -def issue(**overrides): - obj = { - "id": "item", - "title": "Item", - "status": "open", - "labels": [], - "assignee": "", - "parent": None, - "dependencies": [], - "dependents": [], - "description": "", - "design": "", - "acceptance_criteria": "", - } - obj.update(overrides) - return json.dumps([obj]) - - -class AcceptanceSectionTests(unittest.TestCase): - def test_markdown_heading_at_any_depth_counts(self): - for depth in range(1, 7): - with self.subTest(depth=depth): - self.assertTrue(has_acceptance_criteria_section(f"{'#' * depth} Acceptance Criteria\n- x")) - - def test_bare_line_counts_with_or_without_colon(self): - self.assertTrue(has_acceptance_criteria_section("Acceptance Criteria\n- x")) - self.assertTrue(has_acceptance_criteria_section("Acceptance Criteria:\n- x")) - - def test_prose_merely_mentioning_the_phrase_does_not_count(self): - self.assertFalse(has_acceptance_criteria_section("no acceptance criteria yet, sorry")) - self.assertFalse(has_acceptance_criteria_section("we should talk about Acceptance Criteria somewhere")) - - def test_case_insensitive_heading_and_bare_line(self): - self.assertTrue(has_acceptance_criteria_section("## ACCEPTANCE CRITERIA\n- x")) - self.assertTrue(has_acceptance_criteria_section("## Acceptance Criteria\n- x")) - # Heading must start at column 0, per legacy grep '^#{1,6}...': leading spaces do not count. - self.assertFalse(has_acceptance_criteria_section(" ## acceptance criteria\n- x")) - - -class ReadyDropTests(unittest.TestCase): - def invoke(self, path, argv, responses, *, stdin="", env=None, git_responses=None, files=None, root_is_temp=True): - runner = FakeRunner(responses, git_responses=git_responses) - out = io.StringIO() - err = io.StringIO() - with tempfile.TemporaryDirectory() as td, \ - contextlib.redirect_stdout(out), \ - contextlib.redirect_stderr(err), \ - mock.patch.object(sys, "stdin", io.StringIO(stdin)): - paths = {name: Path(td) / name for name in files or {}} - for name, text in (files or {}).items(): - paths[name].write_text(text) - root = Path(td) if root_is_temp else Path("/repo") - code = run_mutation(path, "bd", root, [str(paths.get(arg, arg)) for arg in argv], env or {}, runner) - return code, out.getvalue(), err.getvalue(), runner.calls - - # --- ready: bd promotion --- - - def test_ready_bd_promotes_with_first_class_criteria_and_self_verifies(self): - code, out, err, calls = self.invoke( - ("inbox", "ready"), - ["cap1"], - [ - lambda args: ok(args, issue(id="cap1", acceptance_criteria="does the thing")), - lambda args: ok(args), - lambda args: ok(args, issue(id="cap1", acceptance_criteria="does the thing", labels=["stage:ready"])), - ], - ) - self.assertEqual(code, 0) - self.assertEqual(out, "clerk: promoted cap1 to stage:ready\n") - self.assertEqual(err, "") - self.assertEqual(calls[-2:], [ - ["bd", "update", "cap1", "--status", "open", "--assignee", "", "--add-label", "stage:ready"], - ["bd", "show", "cap1", "--readonly", "--json"], - ]) - - def test_ready_bd_promotes_with_criteria_heading_in_design(self): - code, out, err, calls = self.invoke( - ("inbox", "ready"), - ["cap1"], - [ - lambda args: ok(args, issue(id="cap1", design="Acceptance Criteria\n- does it")), - lambda args: ok(args), - lambda args: ok(args, issue(id="cap1", design="Acceptance Criteria\n- does it", labels=["stage:ready"])), - ], - ) - self.assertEqual(code, 0) - self.assertEqual(out, "clerk: promoted cap1 to stage:ready\n") - - def test_ready_bd_refuses_missing_acceptance_criteria(self): - code, out, err, calls = self.invoke( - ("inbox", "ready"), - ["cap1"], - [lambda args: ok(args, issue(id="cap1", description="just prose, no heading"))], - ) - self.assertEqual(code, 2) - self.assertEqual(out, "") - self.assertIn("no 'Acceptance Criteria' section", err) - self.assertIn("--acceptance-file", err) - self.assertEqual(calls, [["bd", "show", "cap1", "--readonly", "--json"]]) - # No mutation attempted. - self.assertNotIn(["bd", "update", "cap1", "--status", "open", "--assignee", "", "--add-label", "stage:ready"], calls) - - def test_ready_bd_refuses_prose_only_criteria(self): - code, out, err, _ = self.invoke( - ("inbox", "ready"), - ["cap1"], - [lambda args: ok(args, issue(id="cap1", description="no acceptance criteria yet, sorry"))], - ) - self.assertEqual(code, 2) - self.assertIn("no 'Acceptance Criteria' section", err) - - def test_ready_bd_refuses_blank_first_class_criteria(self): - code, out, err, _ = self.invoke( - ("inbox", "ready"), - ["cap1"], - [lambda args: ok(args, issue(id="cap1", acceptance_criteria=" \n"))], - ) - self.assertEqual(code, 2) - self.assertIn("no 'Acceptance Criteria' section", err) - - def test_ready_bd_promotes_despite_open_blockers(self): - blocked = issue(id="cap1", acceptance_criteria="x", dependencies=[{"dependency_type": "blocks", "id": "blk1", "status": "open"}]) - code, out, err, calls = self.invoke( - ("inbox", "ready"), - ["cap1"], - [lambda args: ok(args, blocked), - lambda args: ok(args), - lambda args: ok(args, issue(id="cap1", acceptance_criteria="x", dependencies=[{"dependency_type": "blocks", "id": "blk1", "status": "open"}], labels=["stage:ready"]))], - ) - self.assertEqual(code, 0) - self.assertEqual(out, "clerk: promoted cap1 to stage:ready\n") - self.assertEqual(err, "") - self.assertIn(["bd", "update", "cap1", "--status", "open", "--assignee", "", "--add-label", "stage:ready"], calls) - - def test_ready_bd_promotes_parent_with_open_children(self): - parentish = issue(id="cap1", acceptance_criteria="x", dependents=[{"dependency_type": "parent-child", "id": "kid1", "status": "open"}]) - code, out, err, calls = self.invoke( - ("inbox", "ready"), - ["cap1"], - [lambda args: ok(args, parentish), - lambda args: ok(args), - lambda args: ok(args, issue(id="cap1", acceptance_criteria="x", dependents=[{"dependency_type": "parent-child", "id": "kid1", "status": "open"}], labels=["stage:ready"]))], - ) - self.assertEqual(code, 0) - self.assertEqual(out, "clerk: promoted cap1 to stage:ready\n") - self.assertEqual(err, "") - self.assertIn(["bd", "update", "cap1", "--status", "open", "--assignee", "", "--add-label", "stage:ready"], calls) - - def test_ready_bd_refuses_already_ready_promoted_item(self): - code, out, err, _ = self.invoke( - ("inbox", "ready"), - ["cap1"], - [lambda args: ok(args, issue(id="cap1", labels=["stage:ready"], acceptance_criteria="x"))], - ) - self.assertEqual(code, 2) - self.assertIn("must be an open inbox item", err) - - def test_ready_bd_refuses_closed_item(self): - code, out, err, _ = self.invoke( - ("inbox", "ready"), - ["cap1"], - [lambda args: ok(args, issue(id="cap1", status="closed", acceptance_criteria="x"))], - ) - self.assertEqual(code, 2) - self.assertIn("must be an open inbox item", err) - - def test_ready_bd_bad_id_is_usage_error_not_acceptance_refusal(self): - code, out, err, _ = self.invoke( - ("inbox", "ready"), - ["does-not-exist-42"], - [lambda args: CommandResult(tuple(args), 1, "", "")], - ) - self.assertEqual(code, 2) - self.assertEqual(err[: len("clerk inbox ready")], "clerk inbox ready") - self.assertIn("not found", err) - - def test_ready_bd_missing_id_is_usage_error(self): - code, out, err, _ = self.invoke(("inbox", "ready"), [], []) - self.assertEqual(code, 2) - self.assertIn("missing id", err) - - def test_ready_bd_unknown_argument(self): - code, out, err, _ = self.invoke(("inbox", "ready"), ["cap1", "--bogus"], [lambda args: ok(args, issue(id="cap1"))]) - self.assertEqual(code, 2) - self.assertIn("unknown argument", err) - - def test_ready_bd_rejects_gh_only_flags(self): - code, out, err, _ = self.invoke(("inbox", "ready"), ["cap1", "--title", "x"], [lambda args: ok(args, issue(id="cap1"))]) - self.assertEqual(code, 2) - self.assertIn("--title is only for gh-backed", err) - code, out, err, _ = self.invoke(("inbox", "ready"), ["cap1", "--body-file", "x"], [lambda args: ok(args, issue(id="cap1"))]) - self.assertEqual(code, 2) - self.assertIn("--body-file is only for gh-backed", err) - - def test_ready_bd_authors_design_and_acceptance_files_then_promotes(self): - design_text = "Implementation notes from grill\n" - acceptance_text = "- delivered behavior is observable\n" - updated_after_write = issue( - id="cap1", - design="Implementation notes from grill", # rstrip'd file content - acceptance_criteria="- delivered behavior is observable", - ) - code, out, err, calls = self.invoke( - ("inbox", "ready"), - ["cap1", "--design-file", "DESIGN", "--acceptance-file", "ACCEPT"], - [lambda args: ok(args, issue(id="cap1", description="raw capture")), - lambda args: ok(args), # bd update --design-file --acceptance - lambda args: ok(args, updated_after_write), # re-show to verify write - lambda args: ok(args), # bd update --status open --assignee "" --add-label - lambda args: ok(args, issue(id="cap1", labels=["stage:ready"]))], # verify promotion - files={"DESIGN": design_text, "ACCEPT": acceptance_text}, - ) - self.assertEqual(code, 0) - self.assertEqual(out, "clerk: promoted cap1 to stage:ready\n") - self.assertEqual(err, "") - # The write update carries both --design-file and --acceptance <text> with file content rstrip'd. - write_call = calls[1] - self.assertEqual(write_call[:3], ["bd", "update", "cap1"]) - self.assertIn("--design-file", write_call) - self.assertIn("--acceptance", write_call) - acc_idx = write_call.index("--acceptance") - self.assertEqual(write_call[acc_idx + 1], "- delivered behavior is observable") - self.assertEqual(calls[-2:][0], ["bd", "update", "cap1", "--status", "open", "--assignee", "", "--add-label", "stage:ready"]) - - def test_ready_bd_writes_design_but_still_refuses_missing_criteria(self): - # bd update succeeds, re-show returns design but no acceptance_criteria or section. - code, out, err, calls = self.invoke( - ("inbox", "ready"), - ["cap1", "--design-file", "DESIGN"], - [lambda args: ok(args, issue(id="cap1", description="raw capture")), - lambda args: ok(args), # bd update --design-file - lambda args: ok(args, issue(id="cap1", design="Design without an exam")), # re-show - ], - files={"DESIGN": "Design without an exam\n"}, - ) - self.assertEqual(code, 2) - self.assertIn("--acceptance-file", err) - # No stage:ready mutation. - self.assertNotIn(["bd", "update", "cap1", "--status", "open", "--assignee", "", "--add-label", "stage:ready"], calls) - - def test_ready_bd_promotion_not_self_verified_fails_closed(self): - # bd update --add-label succeeds but the re-show lacks the label. - code, out, err, _ = self.invoke( - ("inbox", "ready"), - ["cap1"], - [lambda args: ok(args, issue(id="cap1", acceptance_criteria="x")), - lambda args: ok(args), # bd update --add-label - lambda args: ok(args, issue(id="cap1", labels=[]))], # verify shows no label - ) - self.assertEqual(code, 5) - self.assertIn("was not confirmed stage:ready", err) - self.assertIn("run 'clerk doctor'", err) - - def test_ready_bd_bd_update_write_failure_is_backend_fail(self): - code, out, err, _ = self.invoke( - ("inbox", "ready"), - ["cap1", "--design-file", "DESIGN", "--acceptance-file", "ACCEPT"], - [lambda args: ok(args, issue(id="cap1")), - lambda args: fail(args)], # bd update write fails - files={"DESIGN": "design", "ACCEPT": "acceptance"}, - ) - self.assertEqual(code, 5) - self.assertIn("bd update did not succeed", err) - - def test_ready_bd_design_write_not_confirmed_is_backend_fail(self): - code, out, err, _ = self.invoke( - ("inbox", "ready"), - ["cap1", "--design-file", "DESIGN"], - [lambda args: ok(args, issue(id="cap1")), - lambda args: ok(args), # bd update --design-file - lambda args: ok(args, issue(id="cap1", design="WRONG"))], # design mismatch on re-show - files={"DESIGN": "design"}, - ) - self.assertEqual(code, 5) - self.assertIn("design was not confirmed", err) - - def test_ready_bd_acceptance_write_not_confirmed_is_backend_fail(self): - code, out, err, _ = self.invoke( - ("inbox", "ready"), - ["cap1", "--design-file", "DESIGN", "--acceptance-file", "ACCEPT"], - [lambda args: ok(args, issue(id="cap1")), - lambda args: ok(args), - lambda args: ok(args, issue(id="cap1", design="design", acceptance_criteria="WRONG"))], - files={"DESIGN": "design", "ACCEPT": "acceptance"}, - ) - self.assertEqual(code, 5) - self.assertIn("acceptance criteria were not confirmed", err) - - def test_ready_bd_refuses_other_holder_exit_5(self): - captured = {} - promoted = issue(id="cap1", assignee="Other", acceptance_criteria="x") - code, out, err, _ = self.invoke( - ("inbox", "ready"), - ["cap1"], - [lambda args: ok(args, promoted), - lambda args: captured.__setitem__("any", args) or ok(args, "Planner\n")], - ) - self.assertEqual(code, 5) - self.assertIn("claimed by Other", err) - self.assertNotIn("run 'clerk doctor'", err) - - def test_ready_bd_allows_current_actor_holder(self): - code, out, err, _ = self.invoke( - ("inbox", "ready"), - ["cap1"], - [lambda args: ok(args, issue(id="cap1", assignee="Planner", acceptance_criteria="x")), - lambda args: ok(args), # bd update add-label - lambda args: ok(args, issue(id="cap1", labels=["stage:ready"]))], - git_responses=[lambda args: ok(args, "Planner\n")], - ) - self.assertEqual(code, 0) - self.assertEqual(out, "clerk: promoted cap1 to stage:ready\n") - - # --- ready: gh backend --- - - def test_ready_gh_needs_title_and_body_file(self): - runner = FakeRunner(responses=[lambda args: ok(args, issue(id="cap1", description="raw capture"))]) - err = io.StringIO() - with tempfile.TemporaryDirectory() as td, contextlib.redirect_stderr(err): - code = run_mutation(("inbox", "ready"), "gh", Path(td), ["cap1"], {}, runner) - self.assertEqual(code, 2) - self.assertIn("--title", err.getvalue()) - self.assertIn("--body-file", err.getvalue()) - - def test_ready_gh_creates_issue_and_closes_capture(self): - runner = FakeRunner( - responses=[ - lambda args: ok(args, issue(id="cap1", description="raw capture")), # bd show - lambda args: ok(args, "https://github.com/acme/repo/issues/42\n"), # gh issue create - lambda args: ok(args), # bd close --reason "promoted to GitHub #42" - lambda args: ok(args, issue(id="cap1", status="closed", close_reason="promoted to GitHub #42", description="raw capture")), # verify - ], - ) - out = io.StringIO() - err = io.StringIO() - with tempfile.TemporaryDirectory() as td, \ - contextlib.redirect_stdout(out), \ - contextlib.redirect_stderr(err): - body = Path(td) / "BODY" - body.write_text("groomed body") - code = run_mutation(("inbox", "ready"), "gh", Path(td), ["cap1", "--title", "promoted title", "--body-file", str(body)], - {}, runner) - self.assertEqual(code, 0) - self.assertEqual(out.getvalue(), "clerk: promoted cap1 to #42 (https://github.com/acme/repo/issues/42)\n") - self.assertIn(["gh", "issue", "create", "--title", "promoted title", "--body-file", str(body), "--label", "ready-for-agent"], runner.calls) - self.assertIn(["bd", "close", "cap1", "--reason", "promoted to GitHub #42"], runner.calls) - - def test_ready_gh_rejects_bd_only_flags(self): - runner = FakeRunner(responses=[lambda args: ok(args, issue(id="cap1"))]) - err = io.StringIO() - with tempfile.TemporaryDirectory() as td, contextlib.redirect_stderr(err): - code = run_mutation(("inbox", "ready"), "gh", Path(td), ["cap1", "--design-file", "x", "--title", "t", "--body-file", "b"], {}, runner) - self.assertEqual(code, 2) - self.assertIn("is only for bd-backed", err.getvalue()) - - # --- returned disposition --- - - def _git_show_ref_absent(self, args): - return ok(args, "", "") - - def _git_show_ref_present(self, args): - return ok(args, "present\n", "") - - def test_ready_returned_required_when_branch_exists(self): - captured = {} - runner = FakeRunner( - responses=[ - lambda args: ok(args, issue(id="cap1-wxyz", acceptance_criteria="x")), - ], - git_responses=[ - self._git_show_ref_present, # returned_branch_exists: local present - ], - ) - out = io.StringIO() - err = io.StringIO() - with tempfile.TemporaryDirectory() as td, \ - contextlib.redirect_stdout(out), \ - contextlib.redirect_stderr(err): - (Path(td) / ".git").mkdir() - code = run_mutation(("inbox", "ready"), "bd", Path(td), ["cap1-wxyz"], {}, runner) - self.assertEqual(code, 2) - self.assertIn("--returned keep", err.getvalue()) - self.assertIn("--returned discard", err.getvalue()) - # No bd mutation attempted. - self.assertNotIn(["bd", "update", "cap1-wxyz", "--status", "open", "--assignee", "", "--add-label", "stage:ready"], runner.calls) - - def test_ready_returned_discard_disposes_and_promotes(self): - runner = FakeRunner( - responses=[ - lambda args: ok(args, issue(id="cap1-wxyz", acceptance_criteria="x")), - lambda args: ok(args), # bd update add-label - lambda args: ok(args, issue(id="cap1-wxyz", labels=["stage:ready"])), - ], - # git calls: show-ref(local, present), show-ref(remote, present), - # for-each-ref(local, list), branch -D pure exit, fetch(no-op success-ish handled below), - # for-each-ref(remote). - git_responses=[ - lambda args: ok(args, "present\n"), # returned_branch_exists local - lambda args: ok(args, "present\n"), # returned_branch_exists remote - lambda args: ok(args, "refs/heads/returned/wxyz\n"), # for-each-ref local canonical - lambda args: ok(args, "", ""), # branch -D - lambda args: fail(args), # fetch origin -> offline path? No: we want online. Use success. - ], - ) - # Replace fetch with success to take online path. - runner.git_responses[4] = lambda args: ok(args) - runner.git_responses.append(lambda args: ok(args, "refs/remotes/origin/returned/wxyz\n")) # for-each-ref remote - runner.git_responses.append(lambda args: ok(args, "", "")) # push origin --delete - runner.git_responses.append(lambda args: ok(args, "", "")) # update-ref -d - out = io.StringIO() - err = io.StringIO() - with tempfile.TemporaryDirectory() as td, \ - contextlib.redirect_stdout(out), \ - contextlib.redirect_stderr(err): - code = run_mutation(("inbox", "ready"), "bd", Path(td), ["cap1-wxyz", "--returned", "discard"], {}, runner) - self.assertEqual(code, 0) - self.assertEqual(out.getvalue(), "clerk: promoted cap1-wxyz to stage:ready\n") - self.assertEqual(err.getvalue(), "") - - def test_ready_returned_keep_preserves_and_promotes(self): - runner = FakeRunner( - responses=[ - lambda args: ok(args, issue(id="cap1-wxyz", acceptance_criteria="x")), - lambda args: ok(args), - lambda args: ok(args, issue(id="cap1-wxyz", labels=["stage:ready"])), - ], - ) - out = io.StringIO() - err = io.StringIO() - with tempfile.TemporaryDirectory() as td, \ - contextlib.redirect_stdout(out), \ - contextlib.redirect_stderr(err): - code = run_mutation(("inbox", "ready"), "bd", Path(td), ["cap1-wxyz", "--returned", "keep"], {}, runner) - self.assertEqual(code, 0) - # No git ref operations because keep short-circuits disposition before any git work. - git_calls = [c for c in runner.calls if c and c[0] == "git"] - self.assertEqual(git_calls, []) - - def test_ready_returned_bad_value_is_usage_error(self): - runner = FakeRunner(responses=[lambda args: ok(args, issue(id="cap1", acceptance_criteria="x"))]) - err = io.StringIO() - with tempfile.TemporaryDirectory() as td, contextlib.redirect_stderr(err): - code = run_mutation(("inbox", "ready"), "bd", Path(td), ["cap1", "--returned", "preserve"], {}, runner) - self.assertEqual(code, 2) - self.assertIn("keep or discard", err.getvalue()) - - def test_ready_returned_discard_noop_when_no_branch(self): - runner = FakeRunner( - responses=[ - lambda args: ok(args, issue(id="cap1", acceptance_criteria="x")), - lambda args: ok(args), - lambda args: ok(args, issue(id="cap1", labels=["stage:ready"])), - ], - git_responses=[ - lambda args: fail(args), # show-ref local absent - lambda args: fail(args), # show-ref remote absent - # then dispose_returned enumerates and finds nothing -> no branch -D, but still attempts fetch+nothing. - ], - ) - out = io.StringIO() - err = io.StringIO() - with tempfile.TemporaryDirectory() as td, \ - contextlib.redirect_stdout(out), \ - contextlib.redirect_stderr(err): - code = run_mutation(("inbox", "ready"), "bd", Path(td), ["cap1", "--returned", "discard"], {}, runner) - self.assertEqual(code, 0) - self.assertEqual(out.getvalue(), "clerk: promoted cap1 to stage:ready\n") - - def test_ready_returned_discard_offline_deletes_local_warns_promotes(self): - runner = FakeRunner( - responses=[ - lambda args: ok(args, issue(id="cap1-wxyz", acceptance_criteria="x")), - lambda args: ok(args), - lambda args: ok(args, issue(id="cap1-wxyz", labels=["stage:ready"])), - ], - git_responses=[ - lambda args: ok(args, "refs/heads/returned/wxyz\n"), # for-each-ref local - lambda args: ok(args, ""), # for-each-ref remote - lambda args: ok(args, "", ""), # branch -D - lambda args: fail(args), # fetch origin -> offline - ], - ) - out = io.StringIO() - err = io.StringIO() - with tempfile.TemporaryDirectory() as td, \ - contextlib.redirect_stdout(out), \ - contextlib.redirect_stderr(err): - code = run_mutation(("inbox", "ready"), "bd", Path(td), ["cap1-wxyz", "--returned", "discard"], {}, runner) - self.assertEqual(code, 0) - self.assertIn("OFFLINE", err.getvalue()) - self.assertIn("deferred to sync", err.getvalue()) - fetch = next(i for i, call in enumerate(runner.calls) if call[-2:] == ["fetch", "origin"]) - self.assertEqual(runner.envs[fetch]["GIT_TERMINAL_PROMPT"], "0") - - def test_ready_returned_discard_removes_archived_refs(self): - runner = FakeRunner( - responses=[ - lambda args: ok(args, issue(id="cap1-wxyz", acceptance_criteria="x")), - lambda args: ok(args), - lambda args: ok(args, issue(id="cap1-wxyz", labels=["stage:ready"])), - ], - git_responses=[ - lambda args: ok(args, "present\n"), - lambda args: ok(args, "present\n"), - lambda args: ok(args, "refs/heads/returned/wxyz\nrefs/heads/returned/wxyz-abc1234\n"), # local incl archive - lambda args: ok(args, "", ""), # branch -D canonical - lambda args: ok(args, "", ""), # branch -D archive - lambda args: fail(args), # fetch origin -> offline (no remote deletes) - ], - ) - with tempfile.TemporaryDirectory() as td: - code = run_mutation(("inbox", "ready"), "bd", Path(td), ["cap1-wxyz", "--returned", "discard"], {}, runner) - self.assertEqual(code, 0) - - # --- drop --- - - def test_drop_bd_closes_wontfix_self_verified(self): - runner = FakeRunner( - responses=[ - lambda args: ok(args, issue(id="cap1")), - lambda args: ok(args), # bd close --reason wontfix - lambda args: ok(args, issue(id="cap1", status="closed", close_reason="wontfix")), - ], - ) - with tempfile.TemporaryDirectory() as td: - code = run_mutation(("inbox", "drop"), "bd", Path(td), ["cap1"], {}, runner) - self.assertEqual(code, 0) - self.assertEqual(runner.calls[-2], ["bd", "close", "cap1", "--reason", "wontfix"]) - self.assertEqual(runner.calls[-1], ["bd", "show", "cap1", "--readonly", "--json"]) - - def test_drop_not_verified_closed_is_backend_fail(self): - runner = FakeRunner( - responses=[ - lambda args: ok(args, issue(id="cap1")), - lambda args: ok(args), - lambda args: ok(args, issue(id="cap1", status="open")), - ], - ) - err = io.StringIO() - with tempfile.TemporaryDirectory() as td, contextlib.redirect_stderr(err): - code = run_mutation(("inbox", "drop"), "bd", Path(td), ["cap1"], {}, runner) - self.assertEqual(code, 5) - self.assertIn("was not confirmed closed", err.getvalue()) - - def test_drop_close_failure_is_backend_fail(self): - runner = FakeRunner( - responses=[ - lambda args: ok(args, issue(id="cap1")), - lambda args: fail(args), # bd close fails - ], - ) - err = io.StringIO() - with tempfile.TemporaryDirectory() as td, contextlib.redirect_stderr(err): - code = run_mutation(("inbox", "drop"), "bd", Path(td), ["cap1"], {}, runner) - self.assertEqual(code, 5) - self.assertIn("bd close did not succeed", err.getvalue()) - - def test_drop_missing_id_is_usage_error(self): - runner = FakeRunner() - with tempfile.TemporaryDirectory() as td: - code = run_mutation(("inbox", "drop"), "bd", Path(td), [], {}, runner) - self.assertEqual(code, 2) - - def test_drop_bad_id_is_usage_error(self): - runner = FakeRunner(responses=[lambda args: CommandResult(tuple(args), 1, "", "")]) - err = io.StringIO() - with tempfile.TemporaryDirectory() as td, contextlib.redirect_stderr(err): - code = run_mutation(("inbox", "drop"), "bd", Path(td), ["nope-1"], {}, runner) - self.assertEqual(code, 2) - self.assertIn("not found", err.getvalue()) - - def test_drop_unknown_argument(self): - runner = FakeRunner(responses=[lambda args: ok(args, issue(id="cap1"))]) - err = io.StringIO() - with tempfile.TemporaryDirectory() as td, contextlib.redirect_stderr(err): - code = run_mutation(("inbox", "drop"), "bd", Path(td), ["cap1", "--bogus"], {}, runner) - self.assertEqual(code, 2) - self.assertIn("unknown argument", err.getvalue()) - - def test_drop_returned_required_when_branch_exists(self): - runner = FakeRunner( - responses=[lambda args: ok(args, issue(id="cap1-wxyz"))], - git_responses=[ - lambda args: ok(args, "present\n"), - lambda args: ok(args, "present\n"), - ], - ) - err = io.StringIO() - with tempfile.TemporaryDirectory() as td, contextlib.redirect_stderr(err): - (Path(td) / ".git").mkdir() - code = run_mutation(("inbox", "drop"), "bd", Path(td), ["cap1-wxyz"], {}, runner) - self.assertEqual(code, 2) - self.assertIn("--returned keep", err.getvalue()) - self.assertNotIn(["bd", "close", "cap1-wxyz", "--reason", "wontfix"], runner.calls) - - def test_drop_returned_discard_closes_and_disposes(self): - runner = FakeRunner( - responses=[ - lambda args: ok(args, issue(id="cap1-wxyz")), - lambda args: ok(args), - lambda args: ok(args, issue(id="cap1-wxyz", status="closed", close_reason="wontfix")), - ], - git_responses=[ - lambda args: ok(args, "present\n"), - lambda args: ok(args, "present\n"), - lambda args: ok(args, "refs/heads/returned/wxyz\n"), - lambda args: ok(args, "", ""), - lambda args: ok(args), # fetch success (online) - lambda args: ok(args, "refs/remotes/origin/returned/wxyz\n"), - lambda args: ok(args, "", ""), # push --delete - lambda args: ok(args, "", ""), # update-ref -d - ], - ) - out = io.StringIO() - err = io.StringIO() - with tempfile.TemporaryDirectory() as td, contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): - code = run_mutation(("inbox", "drop"), "bd", Path(td), ["cap1-wxyz", "--returned", "discard"], {}, runner) - self.assertEqual(code, 0) - self.assertEqual(out.getvalue(), "clerk: dropped cap1-wxyz (wontfix)\n") - - def test_drop_other_holder_refused_exit_5(self): - runner = FakeRunner( - responses=[ - lambda args: ok(args, issue(id="cap1", assignee="Other")), - lambda args: ok(args, "Planner\n"), - ], - ) - err = io.StringIO() - with tempfile.TemporaryDirectory() as td, contextlib.redirect_stderr(err): - code = run_mutation(("inbox", "drop"), "bd", Path(td), ["cap1"], {}, runner) - self.assertEqual(code, 5) - self.assertIn("claimed by Other", err.getvalue()) - self.assertNotIn(err.getvalue(), "run 'clerk doctor'") - - def test_drop_allows_current_actor_holder(self): - runner = FakeRunner( - responses=[ - lambda args: ok(args, issue(id="cap1", assignee="Planner")), - lambda args: ok(args), - lambda args: ok(args, issue(id="cap1", status="closed", close_reason="wontfix")), - ], - git_responses=[lambda args: ok(args, "Planner\n")], - ) - with tempfile.TemporaryDirectory() as td: - code = run_mutation(("inbox", "drop"), "bd", Path(td), ["cap1"], {}, runner) - self.assertEqual(code, 0) - - def test_drop_gh_closes_bd_only(self): - runner = FakeRunner( - responses=[ - lambda args: ok(args, issue(id="cap1")), - lambda args: ok(args), - lambda args: ok(args, issue(id="cap1", status="closed", close_reason="wontfix")), - ], - ) - with tempfile.TemporaryDirectory() as td: - code = run_mutation(("inbox", "drop"), "gh", Path(td), ["cap1"], {}, runner) - self.assertEqual(code, 0) - # No gh invocation for drop. - self.assertFalse(any(c[0] == "gh" for c in runner.calls if c)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/clerk_python/test_text_mutations.py b/tests/clerk_python/test_text_mutations.py deleted file mode 100644 index d55245a..0000000 --- a/tests/clerk_python/test_text_mutations.py +++ /dev/null @@ -1,218 +0,0 @@ -import contextlib -import hashlib -import io -import json -import sys -import tempfile -import unittest -from pathlib import Path -from unittest import mock - -from clerk.commands import run_mutation -from clerk.proc import CommandResult - - -class FakeRunner: - def __init__(self, responses=None): - self.responses = list(responses or []) - self.calls = [] - - def run(self, args, *, cwd=None, env=None): - self.calls.append(list(args)) - if not self.responses: - return CommandResult(tuple(args), 0, "", "") - value = self.responses.pop(0) - if callable(value): - return value(args) - return value - - -def ok(args, stdout="", stderr=""): - return CommandResult(tuple(args), 0, stdout, stderr) - - -def fail(args, stderr="boom"): - return CommandResult(tuple(args), 1, "", stderr) - - -class TextMutationTests(unittest.TestCase): - def invoke(self, path, argv, responses, *, stdin="", backend="bd"): - runner = FakeRunner(responses) - out = io.StringIO() - err = io.StringIO() - with tempfile.TemporaryDirectory() as td, \ - contextlib.redirect_stdout(out), \ - contextlib.redirect_stderr(err), \ - mock.patch.object(sys, "stdin", io.StringIO(stdin)): - code = run_mutation(path, backend, Path(td), argv, {}, runner) - return code, out.getvalue(), err.getvalue(), runner.calls - - def test_capture_files_bd_capture_with_parent_blockers_type_and_stdin_then_self_verifies(self): - parent = [{"id": "p", "status": "open"}] - blocker = [{"id": "b", "status": "open", "parent": "p"}] - created = [{"id": "dotfiles-new"}] - code, out, err, calls = self.invoke( - ("capture",), - ["title", "--stdin", "--type", "bug", "--parent", "p", "--blocked-by", "b"], - [ - lambda args: ok(args, json.dumps(parent)), - lambda args: ok(args, json.dumps(blocker)), - lambda args: ok(args, "dotfiles-new\n"), - lambda args: ok(args, json.dumps(created)), - ], - ) - self.assertEqual(code, 0) - self.assertEqual(out, "clerk: filed dotfiles-new\n") - self.assertEqual(err, "") - self.assertEqual(calls, [ - ["bd", "show", "p", "--readonly", "--json"], - ["bd", "show", "b", "--readonly", "--json"], - ["bd", "create", "title", "--silent", "--stdin", "--type", "bug", "--parent", "p", "--deps", "b"], - ["bd", "show", "dotfiles-new", "--readonly", "--json"], - ]) - - def test_capture_removes_a_ready_label_inherited_from_its_parent_before_success(self): - parent = [{"id": "p", "status": "open", "labels": ["stage:ready"]}] - inherited_ready = [{"id": "dotfiles-new", "status": "open", "parent": "p", "labels": ["stage:ready"]}] - inbox_child = [{"id": "dotfiles-new", "status": "open", "parent": "p", "labels": []}] - code, out, err, calls = self.invoke( - ("capture",), - ["title", "--parent", "p"], - [ - lambda args: ok(args, json.dumps(parent)), - lambda args: ok(args, "dotfiles-new\n"), - lambda args: ok(args, json.dumps(inherited_ready)), - lambda args: ok(args), - lambda args: ok(args, json.dumps(inbox_child)), - ], - ) - self.assertEqual((code, out, err), (0, "clerk: filed dotfiles-new\n", "")) - self.assertEqual(calls[-2:], [ - ["bd", "update", "dotfiles-new", "--remove-label", "stage:ready"], - ["bd", "show", "dotfiles-new", "--readonly", "--json"], - ]) - - def test_capture_failed_self_verification_is_backend_failure_without_success_output(self): - code, out, err, calls = self.invoke( - ("capture",), - ["title"], - [lambda args: ok(args, "dotfiles-new\n"), lambda args: ok(args, json.dumps([{"id": "other"}]))], - ) - self.assertEqual(code, 5) - self.assertEqual(out, "") - self.assertIn("capture failed — dotfiles-new was not confirmed after creation", err) - self.assertIn("run 'clerk doctor'", err) - self.assertEqual(calls[-1], ["bd", "show", "dotfiles-new", "--readonly", "--json"]) - - def test_capture_impediment_self_provisions_type_and_reports_type_label(self): - code, out, err, calls = self.invoke( - ("capture",), - ["harness friction", "--impediment"], - [ - lambda args: ok(args, "types.custom (not set)\n"), - lambda args: ok(args, ""), - lambda args: ok(args, "dotfiles-imp\n"), - lambda args: ok(args, json.dumps([{"id": "dotfiles-imp"}])), - ], - ) - self.assertEqual(code, 0) - self.assertEqual(out, "clerk: filed dotfiles-imp (type: impediment)\n") - self.assertEqual(err, "") - self.assertEqual(calls[:3], [ - ["bd", "config", "get", "types.custom"], - ["bd", "config", "set", "types.custom", "impediment"], - ["bd", "create", "harness friction", "--silent", "--type", "impediment"], - ]) - - def test_backlog_resolve_closes_pickable_ready_work_and_self_verifies_note(self): - ready = [{"id": "item", "title": "No code", "status": "open", "labels": ["stage:ready"], "acceptance_criteria": "- satisfied"}] - closed = [{"id": "item", "status": "closed", "close_reason": "resolved without delivery", "notes": "missing resolution note"}] - code, out, err, calls = self.invoke( - ("backlog", "resolve"), - ["item", "--stdin"], - [ - lambda args: ok(args, json.dumps(ready)), - lambda args: ok(args), - lambda args: ok(args), - lambda args: ok(args, json.dumps(closed)), - ], - stdin="verified externally\n", - ) - - self.assertEqual(code, 5) - self.assertEqual(out, "") - self.assertIn("backlog resolve failed — resolution note was not confirmed for item", err) - self.assertEqual(calls[0], ["bd", "list", "--all", "--readonly", "--json", "--limit", "0"]) - self.assertEqual(calls[1][:4], ["bd", "update", "item", "--append-notes"]) - self.assertRegex(calls[1][4], r"^clerk-backlog-resolution: 20[0-9]{2}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z\nverified externally$") - self.assertEqual(calls[2], ["bd", "close", "item", "--reason", "resolved without delivery"]) - self.assertEqual(calls[3], ["bd", "show", "item", "--readonly", "--json"]) - - def test_inbox_pregrill_appends_structured_note_and_verifies_state_neutrality(self): - before = [{"id": "item", "status": "open", "labels": ["some-label"]}] - after = [{"id": "item", "status": "open", "labels": ["some-label"]}] - code, out, err, calls = self.invoke( - ("inbox", "pregrill"), - ["item", "--decision", "which backend", "--premise", "api stable|check changelog", "--criterion", "returns 200"], - [lambda args: ok(args, json.dumps(before)), lambda args: ok(args), lambda args: ok(args, json.dumps(after))], - ) - self.assertEqual(code, 0) - self.assertRegex(out, r"^clerk: pregrilled item \(dated 20[0-9]{2}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z\)\n$") - self.assertEqual(err, "") - note = calls[1][4] - self.assertEqual(calls[1][:4], ["bd", "update", "item", "--append-notes"]) - self.assertIn("Open decisions:\n- which backend", note) - self.assertIn("Premises:\n- api stable (verify: check changelog)", note) - self.assertIn("Draft acceptance criteria:\n- returns 200", note) - - def test_inbox_note_appends_nonempty_text_and_failed_self_verification_is_backend_failure(self): - before = [{"id": "item", "status": "open", "labels": []}] - changed = [{"id": "item", "status": "open", "labels": ["stage:ready"]}] - code, out, err, calls = self.invoke( - ("inbox", "note"), - ["item", "--stdin"], - [ - lambda args: ok(args, json.dumps(before)), - lambda args: ok(args, json.dumps(before)), - lambda args: ok(args), - lambda args: ok(args, json.dumps(changed)), - ], - stdin="plain note\n", - ) - self.assertEqual(code, 5) - self.assertEqual(out, "") - self.assertIn("inbox note failed — item state changed while appending note", err) - self.assertEqual(calls[2], ["bd", "update", "item", "--append-notes", "plain note"]) - - def test_inbox_update_replaces_guarded_body_and_verifies_requested_fields(self): - before_obj = {"id": "item", "title": "old", "issue_type": "task", "description": "old body", "updated_at": "2026-07-23T01:02:03Z"} - after_obj = {"id": "item", "title": "new title", "issue_type": "bug", "description": "new body", "updated_at": "2026-07-23T01:03:03Z"} - guard = hashlib.sha256(b"2026-07-23T01:02:03Z\0old body").hexdigest() - code, out, err, calls = self.invoke( - ("inbox", "update"), - ["item", "--title", "new title", "--type", "bug", "--stdin", "--body-guard", guard], - [lambda args: ok(args, json.dumps([before_obj])), lambda args: ok(args), lambda args: ok(args, json.dumps([after_obj]))], - stdin="new body\n", - ) - self.assertEqual(code, 0) - self.assertEqual(out, "clerk: updated item\n") - self.assertEqual(err, "") - self.assertEqual(calls[1], ["bd", "update", "item", "--title", "new title", "--type", "bug", "--description", "new body", "--allow-empty-description"]) - - def test_inbox_update_failed_self_verification_is_backend_failure(self): - before_obj = {"id": "item", "description": "old body", "updated_at": "2026-07-23T01:02:03Z"} - after_obj = {"id": "item", "description": "old body", "updated_at": "2026-07-23T01:03:03Z"} - guard = hashlib.sha256(b"2026-07-23T01:02:03Z\0old body").hexdigest() - code, out, err, _ = self.invoke( - ("inbox", "update"), - ["item", "--stdin", "--body-guard", guard], - [lambda args: ok(args, json.dumps([before_obj])), lambda args: ok(args), lambda args: ok(args, json.dumps([after_obj]))], - stdin="new body", - ) - self.assertEqual(code, 5) - self.assertEqual(out, "") - self.assertIn("inbox update failed — item was not confirmed updated", err) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/clerk_python/test_work_graph.py b/tests/clerk_python/test_work_graph.py deleted file mode 100644 index da093a5..0000000 --- a/tests/clerk_python/test_work_graph.py +++ /dev/null @@ -1,156 +0,0 @@ -import json -import unittest - -from clerk.proc import CommandResult -from clerk.work_graph import BdWorkGraphAdapter, WorkGraphBackendError - - -class FakeRunner: - def __init__(self, payload): - self.payload = payload - self.calls = [] - - def run(self, args, *, cwd=None, env=None): - self.calls.append(list(args)) - return CommandResult(tuple(args), 0, json.dumps(self.payload), "") - - -class DeliveryRunner: - def __init__(self): - self.item = {"id": "work-1", "title": "Work", "status": "in_progress", "labels": ["stage:ready"]} - self.calls = [] - self.push_failures = 0 - - def run(self, args, *, cwd=None, env=None): - self.calls.append(list(args)) - if args[:2] == ["bd", "list"]: - return CommandResult(tuple(args), 0, json.dumps([self.item]), "") - if args[:2] == ["bd", "show"]: - return CommandResult(tuple(args), 0, json.dumps([self.item]), "") - if args[:3] == ["bd", "dolt", "push"] and self.push_failures: - self.push_failures -= 1 - return CommandResult(tuple(args), 1, "", "push failed") - if args[:2] == ["bd", "close"]: - self.item = {**self.item, "status": "closed", "close_reason": args[-1]} - elif "--remove-label" in args: - self.item = {**self.item, "labels": []} - return CommandResult(tuple(args), 0, "", "") - - -class BdWorkGraphAdapterTests(unittest.TestCase): - def test_backlog_distinguishes_ready_pickable_and_waiting_in_one_snapshot(self): - payload = [ - {"id": "pick", "title": "Pick", "status": "open", "labels": ["stage:ready"], "acceptance_criteria": "- pick"}, - { - "id": "blocked", - "title": "Blocked", - "status": "open", - "labels": ["stage:ready"], - "acceptance_criteria": "- blocked", - "dependencies": [{"type": "blocks", "depends_on_id": "blocker"}], - }, - {"id": "blocker", "title": "Blocker", "status": "open"}, - {"id": "parent", "title": "Parent", "status": "open", "labels": ["stage:ready"], "acceptance_criteria": "- parent"}, - {"id": "child", "title": "Child", "status": "open", "parent": "parent"}, - {"id": "claimed", "title": "Claimed", "status": "open", "labels": ["stage:ready"], "acceptance_criteria": "- claimed", "assignee": "agent"}, - {"id": "inbox", "title": "Inbox", "status": "open"}, - ] - runner = FakeRunner(payload) - - backlog = BdWorkGraphAdapter(runner).backlog() - - self.assertEqual([item.id for item in backlog.ready], ["pick", "blocked", "parent", "claimed"]) - self.assertEqual([item.id for item in backlog.pickable], ["pick"]) - self.assertEqual( - [(item.work.id, item.blocker_count, item.child_count) for item in backlog.waiting], - [("blocked", 1, 0), ("parent", 0, 1)], - ) - self.assertEqual( - runner.calls, - [["bd", "list", "--all", "--readonly", "--json", "--limit", "0"]], - ) - - def test_graph_queries_and_frontier_share_domain_invariants(self): - payload = [ - {"id": "parent", "title": "Parent", "status": "open"}, - {"id": "free", "title": "Free", "status": "open", "parent": "parent"}, - { - "id": "blocked", - "title": "Blocked", - "status": "open", - "parent": "parent", - "dependencies": [{"type": "blocks", "depends_on_id": "free"}], - }, - {"id": "claimed", "title": "Claimed", "status": "open", "parent": "parent", "assignee": "agent"}, - {"id": "ready", "title": "Ready", "status": "open", "parent": "parent", "labels": ["stage:ready"]}, - ] - - graph = BdWorkGraphAdapter(FakeRunner(payload)).load() - parent = graph.require("parent") - free = graph.require("free") - - self.assertEqual([item.id for item in graph.children(parent)], ["free", "blocked", "claimed", "ready"]) - self.assertEqual([item.id for item in graph.blockers(graph.require("blocked"))], ["free"]) - self.assertEqual([item.id for item in graph.blocked_by(free)], ["blocked"]) - self.assertEqual([item.id for item in graph.frontier(parent)], ["free"]) - - def test_closed_children_and_blockers_stop_withholding_a_ready_parent(self): - payload = [ - { - "id": "parent", - "title": "Parent", - "status": "open", - "labels": ["stage:ready"], - "acceptance_criteria": "- parent", - "dependencies": [{"type": "blocks", "depends_on_id": "blocker"}], - }, - {"id": "blocker", "title": "Blocker", "status": "closed"}, - {"id": "child", "title": "Child", "status": "closed", "parent": "parent"}, - ] - - backlog = BdWorkGraphAdapter(FakeRunner(payload)).backlog() - - self.assertEqual([item.id for item in backlog.pickable], ["parent"]) - self.assertEqual(backlog.waiting, ()) - - def test_delivery_reconciliation_uses_adapter_and_is_idempotent(self): - runner = DeliveryRunner() - adapter = BdWorkGraphAdapter(runner) - - self.assertEqual([work.id for work in adapter.open_claims()], ["work-1"]) - adapter.finish_delivery("work-1", "delivered: PR #9 merged") - adapter.finish_delivery("work-1", "delivered: PR #9 merged") - - self.assertEqual(sum(call[:2] == ["bd", "close"] for call in runner.calls), 1) - self.assertEqual(sum("--remove-label" in call for call in runner.calls), 1) - self.assertEqual(sum(call[:3] == ["bd", "dolt", "push"] for call in runner.calls), 2) - - def test_delivery_reconciliation_retries_backend_push_after_local_state_changed(self): - runner = DeliveryRunner() - runner.push_failures = 1 - adapter = BdWorkGraphAdapter(runner) - - with self.assertRaises(WorkGraphBackendError): - adapter.finish_delivery("work-1", "delivered: PR #9 merged") - adapter.finish_delivery("work-1", "delivered: PR #9 merged") - - self.assertEqual(sum(call[:2] == ["bd", "close"] for call in runner.calls), 1) - self.assertEqual(sum("--remove-label" in call for call in runner.calls), 1) - self.assertEqual(sum(call[:3] == ["bd", "dolt", "push"] for call in runner.calls), 2) - - def test_backlog_excludes_ready_labels_without_acceptance_criteria(self): - payload = [ - {"id": "missing", "title": "Missing", "status": "open", "labels": ["stage:ready"]}, - {"id": "waiting", "title": "Waiting", "status": "open", "labels": ["stage:ready"], "dependencies": [{"type": "blocks", "depends_on_id": "blocker"}]}, - {"id": "blocker", "title": "Blocker", "status": "open"}, - {"id": "valid", "title": "Valid", "status": "open", "labels": ["stage:ready"], "acceptance_criteria": "- valid"}, - ] - - backlog = BdWorkGraphAdapter(FakeRunner(payload)).backlog() - - self.assertEqual([item.id for item in backlog.pickable], ["valid"]) - self.assertEqual([(item.work.id, item.blocker_count, item.child_count) for item in backlog.waiting], [("waiting", 1, 0)]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/phyllary/project-gate.bats b/tests/phyllary/project-gate.bats new file mode 100644 index 0000000..ab85733 --- /dev/null +++ b/tests/phyllary/project-gate.bats @@ -0,0 +1,41 @@ +#!/usr/bin/env bats + +setup() { + ADAPTER="$BATS_TEST_DIRNAME/../../phyllary/project-gate" +} + +make_worktree() { + local worktree=$1 shellcheck_status=$2 + mkdir -p "$worktree/bin" "$worktree/phyllary" "$worktree/tests/phyllary" + printf '%s\n' '#!/usr/bin/env bats' '@'"test \"fixture\" { true; }" >"$worktree/tests/phyllary/pass.bats" + cat >"$worktree/phyllary/project-gate" <<'SH' +#!/usr/bin/env bash +exit 0 +SH + cat >"$BATS_TEST_TMPDIR/shellcheck" <<SH +#!/usr/bin/env bash +exit $shellcheck_status +SH + chmod +x "$worktree/phyllary/project-gate" "$BATS_TEST_TMPDIR/shellcheck" + git init -q -b main "$worktree" + git -C "$worktree" config user.email phyllary@test + git -C "$worktree" config user.name phyllary + git -C "$worktree" add . + git -C "$worktree" commit -qm fixture +} + +@test "project gate returns passed for a passing dotfiles worktree" { + worktree="$BATS_TEST_TMPDIR/pass" + make_worktree "$worktree" 0 + run env PATH="$BATS_TEST_TMPDIR:$PATH" bash -c 'printf "%s" "{\"delivery\":{\"worktree\":\"$1\"}}" | "$2" run' _ "$worktree" "$ADAPTER" + [ "$status" -eq 0 ] + printf '%s\n' "$output" | tail -1 | jq -e '.status == "passed" and .assessed_commit != ""' >/dev/null +} + +@test "project gate returns failed when a project check fails" { + worktree="$BATS_TEST_TMPDIR/fail" + make_worktree "$worktree" 1 + run env PATH="$BATS_TEST_TMPDIR:$PATH" bash -c 'printf "%s" "{\"delivery\":{\"worktree\":\"$1\"}}" | "$2" run' _ "$worktree" "$ADAPTER" + [ "$status" -eq 0 ] + printf '%s\n' "$output" | tail -1 | jq -e '.status == "failed" and .assessed_commit != ""' >/dev/null +} diff --git a/umbel/CONTEXT.md b/umbel/CONTEXT.md index 34c3c62..5d67527 100644 --- a/umbel/CONTEXT.md +++ b/umbel/CONTEXT.md @@ -55,13 +55,13 @@ state, and provision everything the bundle needs to be fully utilised (tier mark per-repo skill defaults), adapting to what is already there. _Avoid_: install, apply, enable, pin -**Clerk**: +**Phyllary**: The workflow's single command facade — the desk-laborer that executes mechanism (filing, syncing, provisioning, reconciling) on the agent's behalf. The split is judgment vs paperwork: the agent -speaks a workflow verb and authors anything requiring judgment; the Clerk performs the menial, +speaks a workflow verb and authors anything requiring judgment; the Phyllary performs the menial, deterministic steps exactly, so mechanism lives in scripts rather than in prose the agent must -re-read and obey each session. The Clerk is **opaque**: skills and agent-facing instructions speak -only Clerk verbs and never name the backing store — which tracker holds the inbox is the Clerk's +re-read and obey each session. The Phyllary is **opaque**: skills and agent-facing instructions speak +only Phyllary verbs and never name the backing store — which tracker holds the inbox is the Phyllary's private business. _Avoid_: dispatcher, wrapper, helper, tool, facade (as a name) @@ -104,32 +104,32 @@ separate from dropping raw inbox work, returning a flawed refinement, or deliver _Avoid_: drop, return, submit **Project gate**: -A project-owned delivery validation pipeline, including its project-selected checks and any optional independent Acceptance-criteria verifier. Clerk invokes it at the workflow handoff and relays either an immediate verdict or a pending external run; it does not own the pipeline's policy, tools, models, prompts, budget, evidence, or artifact retention. -_Avoid_: Clerk gate, delivery-gate +A project-owned delivery validation pipeline, including its project-selected checks and any optional independent Acceptance-criteria verifier. Phyllary invokes it at the workflow handoff and relays either an immediate verdict or a pending external run; it does not own the pipeline's policy, tools, models, prompts, budget, evidence, or artifact retention. +_Avoid_: Phyllary gate, delivery-gate **Project gate adapter**: -A project-owned command boundary between Clerk and its Project gate. Its required `run` operation translates one Gate request into the gate's native interface and returns a Gate result; `status` is required only for a run that returned `pending`. A minimal adapter can be a small synchronous transform shim around a project command, without a run database or artifact store. +A project-owned command boundary between Phyllary and its Project gate. Its required `run` operation translates one Gate request into the gate's native interface and returns a Gate result; `status` is required only for a run that returned `pending`. A minimal adapter can be a small synchronous transform shim around a project command, without a run database or artifact store. _Avoid_: gate integration, gate plugin **Project gate configuration**: -A project-owned, committed configuration that defines its required Project gate adapter and validation policy. Clerk's manifest carries only a stable repository-relative reference to it and resolves both configuration and adapter from the trusted default branch, not the delivery branch it validates; absent configuration fails delivery submission closed. -_Avoid_: Clerk configuration, gate settings +A project-owned, committed configuration that defines its required Project gate adapter and validation policy. Phyllary's manifest carries only a stable repository-relative reference to it and resolves both configuration and adapter from the trusted default branch, not the delivery branch it validates; absent configuration fails delivery submission closed. +_Avoid_: Phyllary configuration, gate settings **Gate-run metadata**: -Clerk-owned structured metadata on a Work item that records a Project gate adapter identity and latest relayed status, summary, assessed commit, and optional run reference/URL. The Project gate remains authoritative for the run itself. +Phyllary-owned structured metadata on a Work item that records a Project gate adapter identity and latest relayed status, summary, assessed commit, and optional run reference/URL. The Project gate remains authoritative for the run itself. _Avoid_: gate notes, local gate state **Gate result**: -The one JSON document a Project gate adapter writes to stdout for `run` or, for an asynchronous run, `status`. It has required `status`, `summary`, and the exact assessed commit. `pending` additionally requires opaque `run.id`; terminal results may provide it. Optional fields include run URL, verbatim details, and delivery reference/URL plus lifecycle state. It represents a valid `passed`, `failed`, or `pending` verdict; an adapter process error is distinct and reported through a non-zero exit. A `passed` result authorizes only the assessed delivery head Clerk will hand off; its adapter is authoritative for delivery lifecycle state when it owns submission. +The one JSON document a Project gate adapter writes to stdout for `run` or, for an asynchronous run, `status`. It has required `status`, `summary`, and the exact assessed commit. `pending` additionally requires opaque `run.id`; terminal results may provide it. Optional fields include run URL, verbatim details, and delivery reference/URL plus lifecycle state. It represents a valid `passed`, `failed`, or `pending` verdict; an adapter process error is distinct and reported through a non-zero exit. A `passed` result authorizes only the assessed delivery head Phyllary will hand off; its adapter is authoritative for delivery lifecycle state when it owns submission. _Avoid_: adapter output, gate log **Gate request**: -The one structured stdin document Clerk sends to a Project gate adapter. It carries the Work item identity, title, full Acceptance criteria, and delivery branch, commit, worktree, and Submission ownership, so the adapter need not query Clerk's backend. +The one structured stdin document Phyllary sends to a Project gate adapter. It carries the Work item identity, title, full Acceptance criteria, and delivery branch, commit, worktree, and Submission ownership, so the adapter need not query Phyllary's backend. _Avoid_: adapter arguments, tracker lookup **Submission ownership**: -The project-selected owner of the push/PR/CI handoff after a delivery Claim. `clerk` means Clerk invokes the Project gate adapter before performing its Git/PR workflow; `project-gate` means the adapter performs the handoff and reports delivery lifecycle state for Clerk to reconcile. -_Avoid_: clerk-submit boolean, submission mode +The project-selected owner of the push/PR/CI handoff after a delivery Claim. `phyllary` means Phyllary invokes the Project gate adapter before performing its Git/PR workflow; `project-gate` means the adapter performs the handoff and reports delivery lifecycle state for Phyllary to reconcile. +_Avoid_: phyllary-submit boolean, submission mode **Claim**: The atomic, identity-independent acquisition of one pickable ready unit by a single worker before @@ -199,7 +199,7 @@ _Avoid_: friction, digest, taxonomy, audit - A **delivery** **Track** session opens by **Claim**ing one pickable ready unit, or may **Resolve** a pickable unit without code when its Acceptance criteria are already satisfied. The Claim is atomic, so concurrent workers — even sharing one identity — never take the same unit. -- The **Clerk** executes the mechanism of every workflow verb (**Capture** filing, **Claim**, +- The **Phyllary** executes the mechanism of every workflow verb (**Capture** filing, **Claim**, finish); the agent keeps the judgment half — deciding *which* verb, and authoring whatever the verb needs written. - An **Impediment** is a **Capture** whose subject is the workflow, not the task. It is recorded diff --git a/umbel/bundles/clerk-delivery-base.md b/umbel/bundles/clerk-delivery-base.md deleted file mode 100644 index 2962592..0000000 --- a/umbel/bundles/clerk-delivery-base.md +++ /dev/null @@ -1,38 +0,0 @@ ---- -name: clerk-delivery-base -description: >- - Delivery base contract using Clerk verbs: claim one ready unit, build only that unit, submit proof, finish through the reconciler. -skills: - - plannotator/annotate - - plannotator/last - - pocock/grill-with-docs -hooks: - - local/clerk-session-start -mcps: - - local/tuidriver ---- - -# clerk-delivery-base - -The invariant delivery contract is small because Clerk owns the paperwork. A delivery session works -one ready unit from claim to finish and leaves every judgment artifact visible in the pull request -and the unit record. - -## Session loop - -1. `clerk backlog next` to choose one ready unit. -2. `clerk backlog claim <id>` before editing; enter the path printed as the last line. -3. Build only that unit. Capture unrelated discoveries with `clerk capture`. -4. `clerk backlog submit <id>` when the change and evidence are ready. -5. `clerk backlog finish` until the reconciler says the unit is merged, waiting, or needs another - build loop. -6. If the unit cannot be fulfilled as refined, use `clerk backlog return <id>` with the reason. - -## Keys - -- Merge key: the platform gate decides when a submitted change may merge. -- Initiation key: a human or scheduler starts sessions. -- In-session key: the harness decides which Clerk verbs may run without a prompt. - -Use `clerk doctor` when the setup or next verb is unclear. Do not replace Clerk verbs with -mechanism copied from memory. diff --git a/umbel/bundles/clerk-discovery.md b/umbel/bundles/clerk-discovery.md deleted file mode 100644 index 6453315..0000000 --- a/umbel/bundles/clerk-discovery.md +++ /dev/null @@ -1,42 +0,0 @@ ---- -name: clerk-discovery -description: >- - Discovery track using Clerk verbs: capture raw input, pre-sort the inbox, refine keepers, and hand ready units to delivery. -skills: - - pocock/grill-me - - pocock/grill-with-docs - - pocock/zoom-out - - pocock/prototype - - pocock/handoff - - plannotator/annotate - - plannotator/last - - local/clerk-presort -hooks: - - local/clerk-session-start -mcps: - - local/tuidriver ---- - -# clerk-discovery - -Discovery shapes raw input into ready units. Speak through **Clerk**: use `clerk capture` for new -thoughts, `clerk inbox ...` for the inbox, and `clerk inbox ready` only after refinement has named -the work and the proof. - -## Applying - -Use `clerk doctor` first. If it reports missing setup, follow its prescription. Do not encode Clerk -mechanism in project instructions; keep the shared face focused on how to ask for work and how to -review results. - -## Refinement loop - -1. Capture raw input with `clerk capture "summary"` and a body when context matters. -2. Open a pass with `/presort`. It proposes drop / grill / ready / needs-input and may add - decision-free pregrill notes through `clerk inbox pregrill`. -3. Refine with the grill and architecture skills until each keeper has explicit acceptance - criteria. -4. Mark keepers ready with `clerk inbox ready`; drop the rest through Clerk. - -`clerk glean` may also file missed workflow signals; those return to the same inbox and are refined -like any other capture. diff --git a/umbel/bundles/phyllary-delivery-base.md b/umbel/bundles/phyllary-delivery-base.md new file mode 100644 index 0000000..4794bab --- /dev/null +++ b/umbel/bundles/phyllary-delivery-base.md @@ -0,0 +1,38 @@ +--- +name: phyllary-delivery-base +description: >- + Delivery base contract using Phyllary verbs: claim one ready unit, build only that unit, submit proof, finish through the reconciler. +skills: + - plannotator/annotate + - plannotator/last + - pocock/grill-with-docs +hooks: + - local/phyllary-session-start +mcps: + - local/tuidriver +--- + +# phyllary-delivery-base + +The invariant delivery contract is small because Phyllary owns the paperwork. A delivery session works +one ready unit from claim to finish and leaves every judgment artifact visible in the pull request +and the unit record. + +## Session loop + +1. `phyllary backlog next` to choose one ready unit. +2. `phyllary backlog claim <id>` before editing; enter the path printed as the last line. +3. Build only that unit. Capture unrelated discoveries with `phyllary capture`. +4. `phyllary backlog submit <id>` when the change and evidence are ready. +5. `phyllary backlog finish` until the reconciler says the unit is merged, waiting, or needs another + build loop. +6. If the unit cannot be fulfilled as refined, use `phyllary backlog return <id>` with the reason. + +## Keys + +- Merge key: the platform gate decides when a submitted change may merge. +- Initiation key: a human or scheduler starts sessions. +- In-session key: the harness decides which Phyllary verbs may run without a prompt. + +Use `phyllary doctor` when the setup or next verb is unclear. Do not replace Phyllary verbs with +mechanism copied from memory. diff --git a/umbel/bundles/clerk-delivery-superpowers.md b/umbel/bundles/phyllary-delivery-superpowers.md similarity index 69% rename from umbel/bundles/clerk-delivery-superpowers.md rename to umbel/bundles/phyllary-delivery-superpowers.md index ee500e4..6e3cb1a 100644 --- a/umbel/bundles/clerk-delivery-superpowers.md +++ b/umbel/bundles/phyllary-delivery-superpowers.md @@ -1,8 +1,8 @@ --- -name: clerk-delivery-superpowers +name: phyllary-delivery-superpowers description: >- - Superpowers delivery method on the Clerk delivery base: plan, test, verify, review, then finish with Clerk. -extends: [clerk-delivery-base] + Superpowers delivery method on the Phyllary delivery base: plan, test, verify, review, then finish with Phyllary. +extends: [phyllary-delivery-base] skills: - superpowers/brainstorming - superpowers/dispatching-parallel-agents @@ -20,16 +20,16 @@ skills: - superpowers/writing-skills --- -# clerk-delivery-superpowers +# phyllary-delivery-superpowers -This method adds the superpowers discipline to `clerk-delivery-base`. Clerk owns the session loop +This method adds the superpowers discipline to `phyllary-delivery-base`. Phyllary owns the session loop and reconciliation; superpowers owns the build craft between claim and submit. The skills are listed directly rather than brought in through the upstream bundle so this generation -has exactly one SessionStart hook: `clerk-session-start`. If you need the superpowers refresher, open +has exactly one SessionStart hook: `phyllary-session-start`. If you need the superpowers refresher, open `superpowers/using-superpowers`; it is available as a normal skill, not as an extra startup announcement. -Use the superpowers skills for planning, test-driven work, verification, and review. Keep the Clerk +Use the superpowers skills for planning, test-driven work, verification, and review. Keep the Phyllary loop intact: claim first, build in the claimed workspace, submit with evidence, then run finish until it converges or names the next action. diff --git a/umbel/bundles/phyllary-discovery.md b/umbel/bundles/phyllary-discovery.md new file mode 100644 index 0000000..f040cf4 --- /dev/null +++ b/umbel/bundles/phyllary-discovery.md @@ -0,0 +1,42 @@ +--- +name: phyllary-discovery +description: >- + Discovery track using Phyllary verbs: capture raw input, pre-sort the inbox, refine keepers, and hand ready units to delivery. +skills: + - pocock/grill-me + - pocock/grill-with-docs + - pocock/zoom-out + - pocock/prototype + - pocock/handoff + - plannotator/annotate + - plannotator/last + - local/phyllary-presort +hooks: + - local/phyllary-session-start +mcps: + - local/tuidriver +--- + +# phyllary-discovery + +Discovery shapes raw input into ready units. Speak through **Phyllary**: use `phyllary capture` for new +thoughts, `phyllary inbox ...` for the inbox, and `phyllary inbox ready` only after refinement has named +the work and the proof. + +## Applying + +Use `phyllary doctor` first. If it reports missing setup, follow its prescription. Do not encode Phyllary +mechanism in project instructions; keep the shared face focused on how to ask for work and how to +review results. + +## Refinement loop + +1. Capture raw input with `phyllary capture "summary"` and a body when context matters. +2. Open a pass with `/presort`. It proposes drop / grill / ready / needs-input and may add + decision-free pregrill notes through `phyllary inbox pregrill`. +3. Refine with the grill and architecture skills until each keeper has explicit acceptance + criteria. +4. Mark keepers ready with `phyllary inbox ready`; drop the rest through Phyllary. + +`phyllary glean` may also file missed workflow signals; those return to the same inbox and are refined +like any other capture. diff --git a/umbel/docs/adr/0016-delivery-gate-acceptance-proof-and-judgment-loops.md b/umbel/docs/adr/0016-delivery-gate-acceptance-proof-and-judgment-loops.md index b8859d3..12b81d1 100644 --- a/umbel/docs/adr/0016-delivery-gate-acceptance-proof-and-judgment-loops.md +++ b/umbel/docs/adr/0016-delivery-gate-acceptance-proof-and-judgment-loops.md @@ -24,10 +24,10 @@ Four proof classes, with a strict authority split: the PR body, failing on absence. Truth comes from C3 where a test surface exists; the gap is deliberate pressure — a repo's gate gains teeth exactly as fast as its tests do. - **C3 — executable proof**: run the repo's checks. This repo's first real test surface is the - epic's own deliverable (clerk's bats suite — printed output tested like exit codes — plus + epic's own deliverable (phyllary's bats suite — printed output tested like exit codes — plus shellcheck on `bin/`), so the no-CI floor is genuine CI, not a placeholder. - **C4 — acceptance proof**: Refinement's output is twofold — the work *and the proof it is done - as designed*. `clerk inbox ready` refuses units without acceptance criteria (presence is + as designed*. `phyllary inbox ready` refuses units without acceptance criteria (presence is structural; quality is grill judgment) but does **not** require the unit to be pickable: a blocked item or a parent with open children can still be refinement-complete. `submit` stamps the unit's criteria into the PR body and requires one evidence entry per criterion — delivery may add @@ -39,7 +39,7 @@ Four proof classes, with a strict authority split: Authority split: the server-side check is authoritative for what the server can see (C1–C3, and C4's criterion-evidence correspondence, which submit made server-visible); claim-state truth stays -clerk-side (`submit`/`finish` hold `bd` access; an Action cannot read the Dolt store). `clerk +phyllary-side (`submit`/`finish` hold `bd` access; an Action cannot read the Dolt store). `phyllary submit` runs the same gate script as a local preflight — fast feedback, never the authority. **Review-required branch protection is the attended dial** (the merge key, K1 of ADR 0015): @@ -48,7 +48,7 @@ review-required and leaving the check — a platform setting, not prompt discipl **The judgment-loop law**: every judgment point in the workflow declares its compounding loop — the signals that indict it, the glean category that carries them, and the guidance artifact its -lessons land in. One circuit for all loops: signals are filed ungated (clerk-filed ambient +lessons land in. One circuit for all loops: signals are filed ungated (phyllary-filed ambient captures; glean's transcript sweep) → they land in the ordinary inbox → pre-sort clusters them via `inbox dups` → one grill lands the cluster as a single compounded unit → the deliverable is a **gated edit to the guidance artifact**. The intent anchor is the human at the attended grill; the @@ -67,7 +67,7 @@ Delivery *build* craft is deliberately uncovered — that is the swappable metho methods declare their own loops under the law. **Pregrill** (the prep half of the loop): pre-sort's successor is decision-free with exactly one -write verb — `clerk inbox pregrill <id>` appends a dated, structured, state-neutral note (open +write verb — `phyllary inbox pregrill <id>` appends a dated, structured, state-neutral note (open decisions, premises each with a suggested verification, draft criteria) **onto the unit itself** (a bead exists to hold perishable context). Dispositions stay ephemeral per pass; prep persists. Pregrill fires per-delta (note missing or stale — body edited after note date, cluster grew), @@ -101,12 +101,12 @@ the pregrill's premises live. - The squash commit carries the criteria-evidence summary, so `git log` is the audit surface the `criteria-miss` glean reads. - Glean's category list grows to four; `/glean`'s harvest mechanism is unchanged (ADR 0012, - mechanics now `clerk glean` per ADR 0015). + mechanics now `phyllary glean` per ADR 0015). ## Amendment (2026-07-09): submit / delivery-gate operational contracts (dotfiles-dft.4) -`clerk backlog submit` and the delivery-gate use one gate implementation, exposed as the first-class -verb `clerk backlog gate`. `submit` invokes it locally as a preflight; the GitHub Actions required +`phyllary backlog submit` and the delivery-gate use one gate implementation, exposed as the first-class +verb `phyllary backlog gate`. `submit` invokes it locally as a preflight; the GitHub Actions required check invokes the same verb in CI. A gate run exits `0` only when every proof class passes and exits `6` when one or more proof classes fail. Gate failures report every failing class in one run, not only the first failure. @@ -155,9 +155,9 @@ file above. It **never arms PR auto-merge** in this generation. Review-required the attended merge dial; unattended auto-merge may be introduced only by a later ratified change once the gate has operated successfully in practice. -This repo's C3 scope for dotfiles-dft.4 is `bats tests/clerk` plus `shellcheck bin/`. The gate must -have parity tests proving the same fixture receives the same per-class verdict through both the local -preflight input mode and the CI input mode. +Phyllary's CLI contract suite now lives in its standalone repository. This dotfiles Project gate +runs its own `bats tests/phyllary` adapter checks plus `shellcheck bin/ phyllary/project-gate`; Phyllary +validates its workflow mechanism independently. ## Amendment (2026-07-10): solo merge posture for this repo @@ -170,7 +170,7 @@ Solo mode changes the platform dial only; it does not weaken the delivery-gate p still cannot merge normally without the required `delivery-gate` check passing, and `submit` still never arms PR auto-merge. Human attendance is the manual PR merge action after reading the PR body and gate result, not a GitHub review record. If a real second reviewer becomes available, the repo -may flip K1 back to review-required branch protection without changing the clerk contract. +may flip K1 back to review-required branch protection without changing the phyllary contract. ## Amendment (2026-07-13): returned-branch disposition is a fail-closed grill decision (dotfiles-5jw) @@ -180,10 +180,10 @@ material), but no later verb collected it: `claim` bases a fresh `delivery/<shor therefore orphan `returned/<short>` silently. The grill — already the named consumer of `returned/*` — now supplies an explicit disposition at -its exit points. `clerk inbox ready` and `clerk inbox drop` accept `--returned keep|discard` and +its exit points. `phyllary inbox ready` and `phyllary inbox drop` accept `--returned keep|discard` and refuse (exit 2) when `returned/<short>` exists and no disposition is given. `keep` leaves the branch untouched as evidence. `discard` deletes `returned/<short>` locally and from origin; if -origin is unreachable, Clerk deletes the local ref, prints a deferred-to-sync warning, and proceeds +origin is unreachable, Phyllary deletes the local ref, prints a deferred-to-sync warning, and proceeds with the ready/drop decision. This makes branch collection a fail-closed judgment, not a hidden side effect. @@ -193,12 +193,12 @@ lock, and the rename destroys the evidence ref that the impediment capture cites returned attempt as a re-delivery base is therefore a claim-side option (`claim --from-returned`, dotfiles-uky), not a returned-branch rename. -## Amendment (2026-07-24): Clerk Project-gate mechanism moved to its own context +## Amendment (2026-07-24): Phyllary Project-gate mechanism moved to its own context The Project-gate adapter/configuration and Gate-result contract is now owned by -[Clerk ADR 0019](../../../clerk/docs/adr/0019-project-gate-adapter-contract.md). It supersedes the -former Clerk-owned fixed C1–C4 delivery-gate policy and defines the portable boundary through which -Clerk invokes project-selected validation. +[Phyllary ADR 0019](https://github.com/vessux/phyllary/blob/main/docs/adr/0019-project-gate-adapter-contract.md). It supersedes the +former Phyllary-owned fixed C1–C4 delivery-gate policy and defines the portable boundary through which +Phyllary invokes project-selected validation. This Umbel ADR continues to own the discovery/delivery judgment-loop law and the rule that Acceptance criteria are authored in Refinement before an implementer exists. A Project gate may diff --git a/umbel/hooks/local/clerk-session-start/HOOK.md b/umbel/hooks/local/clerk-session-start/HOOK.md deleted file mode 100644 index b3f18a1..0000000 --- a/umbel/hooks/local/clerk-session-start/HOOK.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -name: clerk-session-start -description: Inject concise Clerk operating rules at session start and start an async glean sweep. -event: SessionStart -matcher: "startup|clear|compact" -command: ./session-start -async: false ---- - -SessionStart hook for the Clerk generation. It injects one concise Clerk grammar seed and starts -`clerk glean --async` without waiting for harvest work. The hook is shared by discovery and delivery -bundles; track shape comes from the verbs the session uses, not from separate hook copies. diff --git a/umbel/hooks/local/clerk-session-start/seed.md b/umbel/hooks/local/clerk-session-start/seed.md deleted file mode 100644 index ff471e7..0000000 --- a/umbel/hooks/local/clerk-session-start/seed.md +++ /dev/null @@ -1,30 +0,0 @@ -# Clerk operating rules - -Speak in Clerk verbs. Clerk does paperwork; you keep judgment. - -## Verbs - -- `clerk capture "title"` records raw context. -- `clerk inbox list|show|dups|ready|drop|pregrill` serves refinement. -- `clerk backlog next|show|claim|release|return|submit|finish` serves delivery. -- `clerk sync` reconciles already-authored work. -- `clerk doctor` explains setup and repairs safe local facts. -- `clerk glean` harvests missed workflow signals. - -## Discovery - -Capture first, then refine. Use `/presort` for an independent proposal over the inbox. A ready unit -must include acceptance criteria; a criteria-less candidate goes back to grill. `clerk inbox show` surfaces prior returned attempts; read the returned reason/subject before grilling that unit again. -Pregrill notes are additive and decision-free. - -## Delivery - -Claim one ready unit, enter the printed workspace, build only that unit, submit with evidence, then -repeat finish until the reconciler reports merged, waiting, or needing another build loop. Return the -unit instead of guessing when refinement is wrong. - -## Keys - -- Merge key: the platform gate controls merging. -- Initiation key: a human or scheduler starts sessions. -- In-session key: the harness prompts or allows Clerk verbs. diff --git a/umbel/hooks/local/phyllary-session-start/HOOK.md b/umbel/hooks/local/phyllary-session-start/HOOK.md new file mode 100644 index 0000000..41831e6 --- /dev/null +++ b/umbel/hooks/local/phyllary-session-start/HOOK.md @@ -0,0 +1,12 @@ +--- +name: phyllary-session-start +description: Inject concise Phyllary operating rules at session start and start an async glean sweep. +event: SessionStart +matcher: "startup|clear|compact" +command: ./session-start +async: false +--- + +SessionStart hook for the Phyllary generation. It injects one concise Phyllary grammar seed and starts +`phyllary glean --async` without waiting for harvest work. The hook is shared by discovery and delivery +bundles; track shape comes from the verbs the session uses, not from separate hook copies. diff --git a/umbel/hooks/local/phyllary-session-start/seed.md b/umbel/hooks/local/phyllary-session-start/seed.md new file mode 100644 index 0000000..0b17643 --- /dev/null +++ b/umbel/hooks/local/phyllary-session-start/seed.md @@ -0,0 +1,30 @@ +# Phyllary operating rules + +Speak in Phyllary verbs. Phyllary does paperwork; you keep judgment. + +## Verbs + +- `phyllary capture "title"` records raw context. +- `phyllary inbox list|show|dups|ready|drop|pregrill` serves refinement. +- `phyllary backlog next|show|claim|release|return|submit|finish` serves delivery. +- `phyllary sync` reconciles already-authored work. +- `phyllary doctor` explains setup and repairs safe local facts. +- `phyllary glean` harvests missed workflow signals. + +## Discovery + +Capture first, then refine. Use `/presort` for an independent proposal over the inbox. A ready unit +must include acceptance criteria; a criteria-less candidate goes back to grill. `phyllary inbox show` surfaces prior returned attempts; read the returned reason/subject before grilling that unit again. +Pregrill notes are additive and decision-free. + +## Delivery + +Claim one ready unit, enter the printed workspace, build only that unit, submit with evidence, then +repeat finish until the reconciler reports merged, waiting, or needing another build loop. Return the +unit instead of guessing when refinement is wrong. + +## Keys + +- Merge key: the platform gate controls merging. +- Initiation key: a human or scheduler starts sessions. +- In-session key: the harness prompts or allows Phyllary verbs. diff --git a/umbel/hooks/local/clerk-session-start/session-start b/umbel/hooks/local/phyllary-session-start/session-start similarity index 62% rename from umbel/hooks/local/clerk-session-start/session-start rename to umbel/hooks/local/phyllary-session-start/session-start index 6d4ad65..6223e8b 100755 --- a/umbel/hooks/local/clerk-session-start/session-start +++ b/umbel/hooks/local/phyllary-session-start/session-start @@ -15,18 +15,18 @@ escape_for_json() { } start_glean() { - if command -v clerk >/dev/null 2>&1; then - (clerk glean --async >/dev/null 2>&1 || true) & + if command -v phyllary >/dev/null 2>&1; then + (phyllary glean --async >/dev/null 2>&1 || true) & fi } start_glean content="$(cat "$SEED")" -context="<clerk-operating-rules> -These are the Clerk workflow rules for this session. Follow them as procedure; explicit user and project instructions still win. +context="<phyllary-operating-rules> +These are the Phyllary workflow rules for this session. Follow them as procedure; explicit user and project instructions still win. $content -</clerk-operating-rules>" +</phyllary-operating-rules>" escaped="$(escape_for_json "$context")" printf '{\n "hookSpecificOutput": {\n "hookEventName": "SessionStart",\n "additionalContext": "%s"\n }\n}\n' "$escaped" diff --git a/umbel/skills/local/clerk-presort/SKILL.md b/umbel/skills/local/phyllary-presort/SKILL.md similarity index 81% rename from umbel/skills/local/clerk-presort/SKILL.md rename to umbel/skills/local/phyllary-presort/SKILL.md index 25a4b6e..28fd69a 100644 --- a/umbel/skills/local/clerk-presort/SKILL.md +++ b/umbel/skills/local/phyllary-presort/SKILL.md @@ -1,7 +1,7 @@ --- name: presort description: >- - Open a Clerk refinement pass with an independent read of the inbox. Propose drop / grill / + Open a Phyllary refinement pass with an independent read of the inbox. Propose drop / grill / ready / needs-input, and add decision-free pregrill notes only when missing or stale. context: fork agent: general-purpose @@ -11,13 +11,13 @@ disallowed-tools: [Write, Edit, NotebookEdit] # presort -You are the **pre-sort** fork for a Clerk refinement pass. Your purpose is independence: read the +You are the **pre-sort** fork for a Phyllary refinement pass. Your purpose is independence: read the inbox fresh, propose what should happen, and prepare grill cases without deciding them. Use the cheapest available capable fork/model. Escalate only when classification depends on subtle architecture, ambiguous product judgment, or evidence the cheap fork cannot inspect. -You may make exactly one kind of change: `clerk inbox pregrill <id> ...`. It appends additive, +You may make exactly one kind of change: `phyllary inbox pregrill <id> ...`. It appends additive, state-neutral prep to the unit. Everything else is read-only. ## Scope @@ -25,11 +25,11 @@ state-neutral prep to the unit. Everything else is read-only. Start with: ```sh -clerk inbox list -clerk inbox dups +phyllary inbox list +phyllary inbox dups ``` -Classify only entries shown by `clerk inbox list`. Use `clerk inbox show <id>` for the full text; +Classify only entries shown by `phyllary inbox list`. Use `phyllary inbox show <id>` for the full text; when it reports a prior returned attempt, read that returned subject/reason before proposing grill, ready, or drop. Read project files only as needed to verify whether a premise is true, stale, or already handled. @@ -50,7 +50,7 @@ clear, draft criteria in a pregrill note. ## Typed captures and clusters -`clerk inbox dups` is part of the pass. When related captures form a cluster, propose the cluster as +`phyllary inbox dups` is part of the pass. When related captures form a cluster, propose the cluster as one compounded grill unit instead of many tiny ready units. This matters especially for workflow signals such as `criteria-miss`, `sort-miss`, `prep-miss`, and `impediment`: the deliverable is a guidance change, not each signal in isolation. @@ -66,7 +66,7 @@ Judgment guidance: ## Pregrill notes: per-delta only -`clerk inbox list` prints `[pregrill:absent]`, `[pregrill:stale]`, or `[pregrill:present]`. +`phyllary inbox list` prints `[pregrill:absent]`, `[pregrill:stale]`, or `[pregrill:present]`. - If the marker is `absent` or `stale`, you may run one pregrill command for that unit. - If the marker is `present`, do not run pregrill again unless the current pass uncovered a new @@ -76,7 +76,7 @@ Judgment guidance: Shape the command as: ```sh -clerk inbox pregrill <id> \ +phyllary inbox pregrill <id> \ --decision "<open decision>" \ --premise "<premise>|<how to verify it>" \ --criterion "<draft acceptance criterion>" @@ -86,7 +86,7 @@ Use as many flags as the case needs; omit empty sections. A pregrill note is pre ## Output -Your final answer is a proposal list in Clerk grammar. Do not mention storage tools or raw tracker +Your final answer is a proposal list in Phyllary grammar. Do not mention storage tools or raw tracker commands. Copy each title verbatim. ```md @@ -114,4 +114,4 @@ End with a count summary whose total equals the bullets. - Do not drop, ready, claim, release, return, submit, finish, or edit a unit. - Do not create new captures from this fork; report possible captures to the main session. -- If unsure whether a Clerk command changes state, do not run it. +- If unsure whether a Phyllary command changes state, do not run it.