diff --git a/bin/clerk b/bin/clerk
index 0f77852..ad33ecf 100755
--- a/bin/clerk
+++ b/bin/clerk
@@ -1,6 +1,5 @@
#!/usr/bin/env bash
-# clerk public launcher: resolve this checkout and hand off to the stdlib Python
-# Clerk project, or to the preserved legacy shell implementation when explicitly forced.
+# clerk public launcher: resolve this checkout and hand off to stdlib Python.
set -uo pipefail
clerk_error() {
@@ -40,13 +39,8 @@ if ! repo_root=$(cd -P -- "$bin_dir/.." 2>/dev/null && pwd); then
exit 4
fi
-legacy_path=$repo_root/clerk/legacy/clerk.bash
python_src=$repo_root/clerk/src
-if [ -n "${CLERK_FORCE_LEGACY:-}" ] && [ "${CLERK_FORCE_LEGACY:-}" != 0 ]; then
- exec "$legacy_path" "$@"
-fi
-
find_python() {
local candidate
for candidate in "${CLERK_PYTHON:-}" python3 python; do
@@ -66,7 +60,7 @@ PY
if ! python_bin=$(find_python); then
clerk_error "Python 3.11 or newer is required to run Clerk" \
- "install Python 3.11+, set CLERK_PYTHON to its path, or rerun with CLERK_FORCE_LEGACY=1" \
+ "install Python 3.11+ or set CLERK_PYTHON to its path" \
"then run 'clerk doctor' if setup is still unclear"
exit 4
fi
@@ -74,5 +68,4 @@ fi
PYTHONDONTWRITEBYTECODE=1 \
PYTHONPATH="$python_src${PYTHONPATH:+:$PYTHONPATH}" \
CLERK_REPO_ROOT="$repo_root" \
-CLERK_LEGACY_PATH="$legacy_path" \
exec "$python_bin" -m clerk "$@"
diff --git a/clerk/docs/adr/0015-clerk-opaque-workflow-verb-facade.md b/clerk/docs/adr/0015-clerk-opaque-workflow-verb-facade.md
index 0addd98..9cd3d7e 100644
--- a/clerk/docs/adr/0015-clerk-opaque-workflow-verb-facade.md
+++ b/clerk/docs/adr/0015-clerk-opaque-workflow-verb-facade.md
@@ -32,14 +32,11 @@ contract at the command boundary. Callers may rely on successful mutations being
before a success line is printed, and on repeated reconciliation converging rather than duplicating
work.
-The current `bin/clerk` Bash implementation is **v0 implementation detail** and is now being
-retired via a strangler port to a self-contained, stdlib-only Python 3.11+ implementation. The
-public `clerk` command remains the launcher and compatibility boundary: callers continue to 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.
-During migration, the Bash implementation is preserved temporarily as the legacy fallback for
-unported verb paths. Compatibility is proven at the public CLI contract, especially the command
-boundary tests, not by preserving shell functions, shell helper APIs, or other Bash internals.
+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
@@ -88,10 +85,8 @@ verb grammar. Large changes require a focused grill before delivery resumes.
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 Bash script is the v0 executable form and is
- intentionally portable in this dotfiles repo, but the CLI contract above is what survives the
- stdlib-only Python 3.11+ strangler port. The public command remains the launcher and contract
- boundary while unported verb paths fall back to the preserved Bash implementation.
+- **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
@@ -216,13 +211,15 @@ verb grammar. Large changes require a focused grill before delivery resumes.
## 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 is being moved from
- Bash to stdlib-only Python 3.11+ behind the existing public command; the current Bash
- implementation remains only as a temporary legacy fallback during migration. Compatibility is
- judged at the public CLI contract and command boundary, not by retaining shell internals.
+- 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
diff --git a/clerk/legacy/clerk.bash b/clerk/legacy/clerk.bash
deleted file mode 100755
index 6954127..0000000
--- a/clerk/legacy/clerk.bash
+++ /dev/null
@@ -1,3938 +0,0 @@
-#!/usr/bin/env bash
-# clerk — the workflow's single keyless verb facade (ADR 0015). The agent speaks workflow
-# verbs; the clerk executes mechanism exactly, in code that cannot drift from itself.
-#
-# This is the CORE (unit dotfiles-dft.1): noun-verb dispatch, `.clerk` marker resolution
-# (ADR 0017: backlog location is a committed marker at the repo root), `doctor`, and
-# `--explain`. Every other roster verb refuses with exit 3 until its unit in the
-# dotfiles-dft epic lands — a refusal distinct from an unknown verb (exit 2 + roster).
-#
-# Exit codes:
-# 0 success
-# 1 doctor found problems
-# 2 usage error / verb-level refusal (bad args, unknown verb (roster printed), a
-# criteria-less `backlog claim`, `backlog return` without --reason, `backlog release`
-# of a branch that carries unsubmitted work)
-# 3 known verb, not yet implemented in this generation
-# 4 dispatch refused: no git repo, or .clerk marker missing/invalid
-# 5 a backend command failed / a mutation could not be confirmed (dft.2); for
-# `backlog claim` specifically, a CLAIM CONFLICT — the unit is already occupied or the
-# push-CAS race was lost (dft.3) — a refusal, not an operational failure, so it carries
-# its own prescriptive text instead of backend_fail's "run clerk doctor"
-# 6 a delivery-gate ran successfully and found one or more failed proof classes
-#
-# Output discipline (ADR 0015): printed output is load-bearing — every refusal prescribes
-# the next action, and everything is tested verbatim. 16-color ANSI only (30-37/90-97,
-# bold, reset; never 38;5/38;2) so terminal themes recolor it. Colour is capability-gated:
-# the refusal / roster / doctor strings are parsed and logged downstream, so they must never
-# carry escapes into a pipe or file — emit colour only for a real TTY, NO_COLOR (set, any
-# value) suppresses it unconditionally, and CLICOLOR_FORCE re-enables it on a non-TTY.
-set -uo pipefail
-
-CLERK_VERSION="0.1.0" # single source of truth: --version and doctor both read this line
-
-if [ -n "${NO_COLOR+x}" ]; then
- _clerk_color=0
-elif [ -n "${CLICOLOR_FORCE:-}" ] && [ "$CLICOLOR_FORCE" != 0 ]; then
- _clerk_color=1
-elif [ -t 1 ]; then
- _clerk_color=1
-else
- _clerk_color=0
-fi
-if [ "$_clerk_color" -eq 1 ]; then
- C_BOLD=$'\033[1m' C_RED=$'\033[31m' C_GRN=$'\033[32m' C_YLW=$'\033[33m' C_RST=$'\033[0m'
-else
- C_BOLD='' C_RED='' C_GRN='' C_YLW='' C_RST=''
-fi
-
-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"
-
-print_roster() {
- printf '%s\n' \
- 'Known verbs:' \
- ' capture "
" [--stdin|--type |--impediment|--parent |--blocked-by ]' \
- ' 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 ' to see what a verb does."
-}
-
-usage_error() {
- printf '%s\n' "$1" >&2
- exit 2
-}
-
-# A backend command (bd/gh) failed, or a mutation could not be confirmed. Exit 5 keeps
-# this distinct from doctor's exit 1 (health check) and usage errors (exit 2) — a scripted
-# caller can tell "the tracker backend is broken" from "you passed a bad id" (ADR 0015).
-backend_fail() {
- printf 'clerk: %s\n' "$1" >&2
- printf " run 'clerk doctor' to check the backend\n" >&2
- exit 5
-}
-
-unknown_verb() {
- printf "clerk: unknown verb '%s'\n" "$1" >&2
- print_roster >&2
- exit 2
-}
-
-not_implemented() {
- printf "clerk: '%s' is not yet implemented in this generation (see dotfiles-dft epic)\n" "$1" >&2
- exit 3
-}
-
-repo_root() {
- git rev-parse --show-toplevel 2>/dev/null
-}
-
-# Parse the .clerk marker at $1. Echoes the backend (bd|gh) on success.
-# Returns 1 when the file is missing, 2 when present but invalid.
-# Format (ADR 0017 manifest v1): one `backlog: bd|gh` directive and an optional
-# `project-gate: ` directive; surrounding whitespace
-# and `#` comments are tolerated. The Python Project-gate boundary validates paths.
-read_marker() {
- local file="$1" line backend="" project_gate="" value
- [ -f "$file" ] || return 1
- while IFS= read -r line || [ -n "$line" ]; do
- line="${line%%#*}" # strip comments
- line="${line#"${line%%[![:space:]]*}"}" # ltrim
- line="${line%"${line##*[![:space:]]}"}" # rtrim
- [ -n "$line" ] || continue
- case "$line" in
- backlog:*)
- [ -z "$backend" ] || return 2
- value="${line#backlog:}"
- value="${value#"${value%%[![:space:]]*}"}"
- case "$value" in bd | gh) backend="$value" ;; *) return 2 ;; esac
- ;;
- project-gate:*)
- [ -z "$project_gate" ] || return 2
- value="${line#project-gate:}"
- value="${value#"${value%%[![:space:]]*}"}"
- [ -n "$value" ] || return 2
- project_gate="$value"
- ;;
- *) return 2 ;;
- esac
- done <"$file"
- [ -n "$backend" ] || return 2
- printf '%s\n' "$backend"
-}
-
-# Dispatch gate: every verb except doctor and --explain forms passes through here.
-# Refuses (exit 4) unless we are in a git repo with a valid .clerk marker — and always
-# prescribes `clerk doctor`, which owns diagnosis and provisioning (ADR 0017).
-marker_gate() {
- local root rc=0
- if ! root=$(repo_root); then
- printf "clerk: not inside a git repository — cd into the target repo, then run 'clerk doctor'\n" >&2
- exit 4
- fi
- read_marker "$root/.clerk" >/dev/null || rc=$?
- case "$rc" in
- 0) ;;
- 1)
- printf "clerk: missing .clerk marker at %s/.clerk — run 'clerk doctor' to provision it\n" "$root" >&2
- exit 4
- ;;
- *)
- printf "clerk: invalid .clerk marker at %s/.clerk — run 'clerk doctor' to diagnose it\n" "$root" >&2
- exit 4
- ;;
- esac
-}
-
-# --explain: the human-terminal window into the facade (ADR 0015) — prints the underlying
-# commands a verb runs plus its ADR pointer. Works for every roster verb, implemented or
-# not, marker or no marker.
-explain_verb() {
- case "$1" in
- capture)
- printf '%s\n' \
- 'clerk capture — file one raw capture into the bd inbox' \
- ' usage: clerk capture "" [--stdin|--type |--impediment|--parent |--blocked-by ...]' \
- ' runs: bd create "" [--stdin] [--type ...] [--parent ...] [--deps ...] (backlog: bd|gh)' \
- ' (GitHub-backed repos use GitHub only after inbox ready promotion)' \
- " see: $ADR15"
- ;;
- sync)
- printf '%s\n' \
- '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' \
- " see: $ADR15"
- ;;
- doctor)
- printf '%s\n' \
- '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' \
- " see: $ADR17"
- ;;
- glean)
- printf '%s\n' \
- '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' \
- " see: $ADR15"
- ;;
- 'inbox list')
- printf '%s\n' \
- 'clerk inbox list — list the unrefined bd capture pool' \
- ' usage: clerk inbox list [--limit ]' \
- ' runs: bd list, filtered to open minus stage:ready (backlog: bd|gh)' \
- ' --limit forwards to bd; 0 = unlimited' \
- " see: $ADR15"
- ;;
- 'inbox show')
- printf '%s\n' \
- 'clerk inbox show — show one bd-backed inbox item' \
- ' usage: clerk inbox show [--json|--pretty]' \
- ' runs: bd show (backlog: bd|gh)' \
- " see: $ADR15"
- ;;
- 'inbox dups')
- printf '%s\n' \
- 'clerk inbox dups — cluster duplicate bd captures for pre-sort' \
- ' runs: bd duplicates (backlog: bd|gh)' \
- " see: $ADR16"
- ;;
- 'inbox ready')
- printf '%s\n' \
- 'clerk inbox ready — write refinement output, then promote a groomed bd capture' \
- ' usage: clerk inbox ready [--design-file ] [--acceptance-file ] [--returned keep|discard]' \
- ' (gh: --title "" --body-file )' \
- ' runs: for bd, optional bd update --design-file / --acceptance, then refuses' \
- ' units still lacking acceptance criteria (ADR 0016); if returned/ 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' \
- " see: $ADR16"
- ;;
- 'inbox drop')
- printf '%s\n' \
- 'clerk inbox drop — close a bd capture as not worth doing' \
- ' usage: clerk inbox drop [--returned keep|discard]' \
- ' runs: if returned/ exists, requires --returned keep|discard; discard deletes' \
- ' that evidence branch, keep preserves it; then bd close --reason wontfix' \
- ' (backlog: bd|gh)' \
- " see: $ADR16"
- ;;
- 'inbox pregrill')
- printf '%s\n' \
- 'clerk inbox pregrill — append prep notes onto a bd capture before its grill' \
- ' runs: bd update --notes "" (backlog: bd|gh)' \
- ' note carries open decisions, premises with suggested verifications, draft criteria' \
- " see: $ADR16"
- ;;
- 'inbox children' | 'inbox frontier' | 'inbox blockers' | 'inbox blocked')
- printf '%s\n' \
- "clerk $1 — query inbox graph relationships as Clerk-owned JSON" \
- ' usage: clerk inbox children|frontier|blockers|blocked [--pretty]' \
- ' runs: bd show --readonly --json and normalizes parent-child / blocks edges' \
- " see: $ADR15"
- ;;
- 'inbox parent' | 'inbox dep' | 'inbox claim' | 'inbox release' | 'inbox note' | 'inbox update' | 'inbox resolve')
- printf '%s\n' \
- "clerk $1 — mutate generic inbox graph/planning state" \
- ' usage: clerk inbox parent set|clear ...; clerk inbox dep add|remove ...; clerk inbox claim|release ; clerk inbox note|update|resolve ...' \
- ' runs: bd update / bd dep / bd close behind validated Clerk guards' \
- " see: $ADR15"
- ;;
- 'backlog next')
- printf '%s\n' \
- 'clerk backlog next — pick the next pickable ready unit' \
- ' runs: bd list --status open --label stage:ready --no-assignee --readonly --json, then filters no open blockers/children (backlog: bd)' \
- ' gh issue list --label ready-for-agent (backlog: gh)' \
- " see: $ADR17"
- ;;
- 'backlog show')
- printf '%s\n' \
- 'clerk backlog show — show one backlog unit' \
- ' runs: bd show (backlog: bd)' \
- ' gh issue view (backlog: gh)' \
- " see: $ADR15"
- ;;
- 'backlog waiting')
- printf '%s\n' \
- 'clerk backlog waiting — list refined-ready work that is waiting on graph state' \
- ' runs: bd list --status open --label stage:ready --no-assignee --readonly --json, then reports open blocker/child counts (backlog: bd)' \
- ' gh issue list --label ready-for-agent (backlog: gh; no graph waiting view yet)' \
- " see: $ADR17"
- ;;
- 'backlog claim')
- printf '%s\n' \
- 'clerk backlog claim — take the claim lock on a unit' \
- ' usage: clerk backlog claim [--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/ branch' \
- ' (first push wins — the universal CAS lock, exit 5 if occupied or the race is' \
- ' lost); on success, bd update --claim as the online fast-path record' \
- ' (backlog: bd); offline: local-only branch + claim, attended only; finally' \
- ' git worktree add .worktrees/, printing its absolute path; with returned/,' \
- ' plain claim refuses until you choose --from-returned (reuse and keep evidence)' \
- ' or --fresh --returned keep|discard (start from main explicitly)' \
- " see: $ADR17"
- ;;
- 'backlog release')
- printf '%s\n' \
- 'clerk backlog release — give a claim back without finishing (unit stays stage:ready)' \
- ' runs: refuses if delivery/ carries commits beyond main (prescribes submit or' \
- ' return instead); else git worktree remove + git branch -D delivery/,' \
- ' plus git push origin --delete delivery/ when reachable; then' \
- ' bd update --status open --assignee "" (backlog: bd)' \
- ' gh issue edit --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' \
- " see: $ADR15"
- ;;
- 'backlog resolve')
- printf '%s\n' \
- 'clerk backlog resolve — close a pickable ready unit without delivery code' \
- ' usage: clerk backlog resolve [--returned keep|discard] [--file |--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)' \
- " see: $ADR16"
- ;;
- 'backlog proof')
- printf '%s\n' \
- 'clerk backlog proof — print the JSON proof skeleton consumed by submit' \
- ' usage: clerk backlog proof ' \
- ' runs: bd show --readonly --json / gh issue view , then prints proof-only JSON:' \
- ' {"acceptance":[{"text":"","evidence":""}]}' \
- " see: $ADR16"
- ;;
- 'backlog submit')
- printf '%s\n' \
- 'clerk backlog submit — open the unit'"'"'s PR (once per unit; iteration repeats finish)' \
- ' usage: clerk backlog submit (legacy: --body-file )' \
- ' runs: consumes proof JSON, renders the PR body with the unit criteria and Clerk-run checks, runs clerk backlog gate as a local preflight, pushes delivery/, then gh pr create; never arms auto-merge' \
- " see: $ADR16"
- ;;
- 'backlog gate')
- printf '%s\n' \
- 'clerk backlog gate — validate delivery proof classes C1-C4' \
- ' runs: C1 branch/link/current protocol checks; C2 PR-body verification schema check; C3 bats tests/clerk (parallel with --jobs when GNU parallel/rush is available) plus shellcheck bin/; C4 one evidence line per acceptance criterion' \
- ' local mode: --branch delivery/ --body-file ; CI mode: reads GITHUB_* and gh pr view' \
- " see: $ADR16"
- ;;
- 'backlog finish')
- printf '%s\n' \
- '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' \
- " see: $ADR15"
- ;;
- 'backlog return')
- printf '%s\n' \
- 'clerk backlog return — send a unit back to discovery (verdict: cannot be fulfilled as designed)' \
- ' runs: requires --reason ""; renames delivery/ -> returned/ (local; pushes' \
- ' the new ref and deletes delivery/ on origin when reachable) so the attempt' \
- ' survives as grill evidence, then git worktree remove; bd update --status open' \
- ' --remove-label stage:ready --assignee "" (backlog: bd)' \
- ' gh issue reopen + edit --remove-label ready-for-agent --remove-assignee (backlog: gh)' \
- ' then files the reason verbatim as an impediment-typed capture referencing' \
- ' returned/: 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' \
- " see: $ADR16"
- ;;
- *)
- unknown_verb "$1"
- ;;
- esac
-}
-
-# ---------------------------------------------------------- capture + inbox ----
-# unit dotfiles-dft.2: `capture` and the six `inbox` verbs. The `.clerk` marker's backend
-# (already validated by marker_gate before any of this runs) selects the per-backend branch
-# in each cmd_* function below. Contract points C-a..C-g referenced in comments are this
-# unit's resolved divergence points (see the unit body / delivery notes for the full list).
-
-# C-e (acceptance-criteria detection, `inbox ready`): presence of a structural section only
-# — never a quality judgment, which stays grill's job (ADR 0016 C4). A markdown heading (any
-# '#' depth) or a bare "Acceptance Criteria[:]" line counts; prose that merely mentions the
-# phrase does not, so a capture whose body says "no acceptance criteria yet" is still refused.
-has_acceptance_criteria_section() {
- grep -qiE '^#{1,6}[[:space:]]*acceptance criteria|^acceptance criteria:?[[:space:]]*$' <<<"$1"
-}
-
-# C-c (impediment type): bd rejects any --type outside its built-in set unless the type is
-# registered via the `types.custom` config key (bd create --help: "custom types require
-# types.custom config" — verified empirically: `bd create --type impediment` fails
-# "invalid issue type: impediment" against a fresh db). Rather than push a one-time
-# repo-setup step onto `clerk doctor` (core, not this unit's to touch), capture
-# self-provisions the config idempotently the first time --impediment is used: `bd config
-# get` prints the literal sentinel " (not set)" when absent (exit 0, not an error), so
-# we normalize that to empty, check whether "impediment" is already one of the
-# comma-separated values, and merge it in if not. This makes `capture --impediment` work
-# unconditionally, including against a brand-new bd db with zero prior setup — no separate
-# fixture step required (the test fixture may still pre-set it; either order works).
-bd_ensure_impediment_type() {
- local current
- current=$(bd config get types.custom 2>/dev/null)
- case "$current" in
- *'(not set)'*) current="" ;;
- esac
- local -a values=()
- if [ -n "$current" ]; then
- IFS=',' read -ra values <<<"$current"
- fi
- local v
- for v in "${values[@]+"${values[@]}"}"; do
- [ "$v" = impediment ] && return 0
- done
- if [ -z "$current" ]; then
- bd config set types.custom impediment >/dev/null 2>&1
- else
- bd config set types.custom "$current,impediment" >/dev/null 2>&1
- fi
-}
-
-bd_custom_types_csv() {
- local current
- current=$(bd config get types.custom 2>/dev/null || true)
- case "$current" in
- *'(not set)'*) current="" ;;
- esac
- printf '%s' "$current"
-}
-
-clerk_type_valid() { # $1=canonical type
- local t="$1" current v
- case "$t" in
- bug | feature | task | epic | chore | decision) return 0 ;;
- esac
- current=$(bd_custom_types_csv)
- IFS=',' read -ra _clerk_custom_types <<<"$current"
- for v in "${_clerk_custom_types[@]+"${_clerk_custom_types[@]}"}"; do
- v="${v#"${v%%[![:space:]]*}"}"
- v="${v%"${v##*[![:space:]]}"}"
- [ "$v" = "$t" ] && return 0
- done
- [ "$t" = impediment ] && return 0
- return 1
-}
-
-clerk_json_emit() { # $1=pretty(0|1), stdin=json
- if [ "$1" -eq 1 ]; then
- jq .
- else
- jq -c .
- fi
-}
-
-bd_issue_json_or_usage() { # $1=verb label $2=id; echoes a single bd issue object
- local verb="$1" id="$2" json
- json=$(bd show "$id" --readonly --json 2>/dev/null || true)
- if [ -z "$json" ] || [ "$json" = null ] ||
- ! printf '%s' "$json" | jq -e 'if type != "array" then false else (length > 0) end' >/dev/null 2>&1; then
- usage_error "$verb: $id not found — check the id ('clerk inbox list' shows open units)"
- fi
- printf '%s' "$json" | jq -c '.[0]'
-}
-
-issue_json_is_ready_promoted() { # stdin/object or $1 object
- local obj="${1:-}"
- [ -n "$obj" ] || obj=$(cat)
- printf '%s' "$obj" | jq -e '(((.labels // []) | index("stage:ready")) != null) or ((.close_reason // "") | startswith("promoted"))' >/dev/null 2>&1
-}
-
-issue_json_is_open_inbox() { # stdin/object or $1 object: open and not stage:ready
- local obj="${1:-}"
- [ -n "$obj" ] || obj=$(cat)
- printf '%s' "$obj" | jq -e '.status == "open" and (((.labels // []) | index("stage:ready")) == null)' >/dev/null 2>&1
-}
-
-issue_json_is_active_inbox() { # stdin/object or $1 object: open/in_progress and not stage:ready
- local obj="${1:-}"
- [ -n "$obj" ] || obj=$(cat)
- printf '%s' "$obj" | jq -e '(.status == "open" or .status == "in_progress") and (((.labels // []) | index("stage:ready")) == null)' >/dev/null 2>&1
-}
-
-issue_json_is_nonclosed_work() { # stdin/object or $1 object: any Work graph item that is not closed
- local obj="${1:-}"
- [ -n "$obj" ] || obj=$(cat)
- printf '%s' "$obj" | jq -e '(.status // "") != "" and (.status != "closed")' >/dev/null 2>&1
-}
-
-planning_holder_refusal() { # $1=verb $2=root $3=json-object; allows unclaimed or claimed by current actor
- local verb="$1" root="$2" obj="$3" id holder me
- id=$(printf '%s' "$obj" | jq -r '.id // ""')
- holder=$(printf '%s' "$obj" | jq -r '.assignee // ""')
- [ -z "$holder" ] && return 0
- me=$(claim_current_actor "$root")
- [ "$holder" = "$me" ] && return 0
- printf 'clerk: %s refused — %s is claimed by %s\n' "$verb" "$id" "$holder" >&2
- exit 5
-}
-
-issue_parent_id() { # $1=id
- bd_issue_json_or_usage 'clerk inbox graph' "$1" | jq -r '.parent // ""'
-}
-
-issue_has_open_blockers() { # $1=id; status absent/non-closed is fail-closed
- local obj
- obj=$(bd_issue_json_or_usage 'clerk inbox graph' "$1")
- printf '%s' "$obj" | jq -e '(.dependencies // []) | any(.dependency_type == "blocks" and ((.status // "open") != "closed"))' >/dev/null
-}
-
-issue_has_open_children() { # $1=id; missing/non-closed child status fails closed as open
- local obj
- obj=$(bd_issue_json_or_usage 'clerk inbox graph' "$1")
- printf '%s' "$obj" | jq -e '(.dependents // []) | any(.dependency_type == "parent-child" and ((.status // "open") != "closed"))' >/dev/null
-}
-
-issue_blocker_ids() { # $1=id; prints direct blocker ids, one per line
- bd_issue_json_or_usage 'clerk inbox graph' "$1" | jq -r '(.dependencies // [])[] | select(.dependency_type == "blocks") | .id'
-}
-
-issue_blocked_ids() { # $1=id; prints directly blocked ids, one per line
- bd_issue_json_or_usage 'clerk inbox graph' "$1" | jq -r '(.dependents // [])[] | select(.dependency_type == "blocks") | .id'
-}
-
-# C-d (pregrill marker: absent|present|stale): derived cheaply from metadata already
-# present on every `bd list --json` / `gh issue list --json` row — no extra per-issue fetch.
-# A pregrill note carries a full-timestamp tag line ("clerk-pregrill: "); present
-# iff the issue's updated-at is within a few seconds of that tag (i.e. the pregrill append
-# itself was the most recent write — the tolerance absorbs that write's own commit latency,
-# empirically a few seconds on slower CI hosts, so a freshly-filed pregrill never reads
-# as stale against itself); stale iff updated-at moved meaningfully later, meaning some
-# other write landed since; absent iff no tag line exists at all. The other half of C-d's
-# staleness definition ("OR its dup-cluster gained members since") is deliberately not
-# implemented: computing cluster membership is a `bd find-duplicates` pass, and running
-# that on every `inbox list` call is exactly the expense "keep it cheap (metadata only)"
-# rules out — dup-driven staleness stays a documented gap, not a silent wrong answer.
-PREGRILL_STALE_TOLERANCE_S=${CLERK_PREGRILL_STALE_TOLERANCE_S:-10}
-pregrill_marker() { # $1 = last pregrill-tag timestamp (or ""), $2 = issue updated-at
- local note_ts="$1" upd_ts="$2" note_epoch upd_epoch
- if [ -z "$note_ts" ]; then
- printf 'absent'
- return
- fi
- note_epoch=$(date -u -d "$note_ts" +%s 2>/dev/null) || { printf 'stale'; return; }
- upd_epoch=$(date -u -d "$upd_ts" +%s 2>/dev/null) || { printf 'stale'; return; }
- if [ $((upd_epoch - note_epoch)) -gt "$PREGRILL_STALE_TOLERANCE_S" ]; then
- printf 'stale'
- else
- printf 'present'
- fi
-}
-
-# Builds the dated, structured, state-neutral pregrill note body (ADR 0016): open
-# decisions, premises each with a suggested verification, draft acceptance criteria. Array
-# arguments are passed by name (nameref) since bash cannot pass arrays by value.
-build_pregrill_note() { # $1=ts $2=decisions-arrayname $3=premises-arrayname $4=criteria-arrayname
- local -n _decisions="$2" _premises="$3" _criteria="$4"
- local note="clerk-pregrill: $1"
- note+=$'\n'"Open decisions:"
- if [ "${#_decisions[@]}" -eq 0 ]; then
- note+=$'\n'"- (none)"
- else
- local d
- for d in "${_decisions[@]}"; do note+=$'\n'"- $d"; done
- fi
- note+=$'\n'"Premises:"
- if [ "${#_premises[@]}" -eq 0 ]; then
- note+=$'\n'"- (none)"
- else
- local p ptext pverify
- for p in "${_premises[@]}"; do
- case "$p" in
- *'|'*)
- ptext="${p%%|*}"
- pverify="${p#*|}"
- ;;
- *)
- ptext="$p"
- pverify="not yet specified"
- ;;
- esac
- note+=$'\n'"- $ptext (verify: $pverify)"
- done
- fi
- note+=$'\n'"Draft acceptance criteria:"
- if [ "${#_criteria[@]}" -eq 0 ]; then
- note+=$'\n'"- (none)"
- else
- local c
- for c in "${_criteria[@]}"; do note+=$'\n'"- $c"; done
- fi
- printf '%s' "$note"
-}
-
-# clerk capture "" [--stdin|--type |--impediment|--parent |--blocked-by ...]
-cmd_capture() {
- local backend="$1"
- shift 2
- if [ $# -eq 0 ]; then
- usage_error 'clerk capture: missing title — usage: clerk capture "" [--stdin|--type |--impediment|--parent |--blocked-by ]'
- fi
- local title="$1"
- shift
- local use_stdin=0 use_impediment=0 issue_type="" parent=""
- local -a blockers=()
- while [ $# -gt 0 ]; do
- case "$1" in
- --stdin) use_stdin=1 ;;
- --impediment) use_impediment=1 ;;
- --type)
- [ $# -ge 2 ] || usage_error 'clerk capture: --type needs a value'
- issue_type="$2"
- shift
- ;;
- --parent)
- [ $# -ge 2 ] || usage_error 'clerk capture: --parent needs a Work graph id'
- parent="$2"
- shift
- ;;
- --blocked-by)
- [ $# -ge 2 ] || usage_error 'clerk capture: --blocked-by needs a Work graph sibling id'
- blockers+=("$2")
- shift
- ;;
- *) usage_error "clerk capture: unknown argument '$1' — usage: clerk capture \"\" [--stdin|--type |--impediment|--parent |--blocked-by ]" ;;
- esac
- shift
- done
- if [ "$use_impediment" -eq 1 ] && [ -n "$issue_type" ]; then
- usage_error 'clerk capture: --impediment is compatibility sugar for --type impediment; do not combine them'
- fi
- [ "$use_impediment" -eq 1 ] && issue_type=impediment
- if [ -n "$issue_type" ] && ! clerk_type_valid "$issue_type"; then
- usage_error "clerk capture: invalid --type '$issue_type' — use a canonical core type or configure types.custom"
- fi
- if [ "${#blockers[@]}" -gt 0 ] && [ -z "$parent" ]; then
- usage_error 'clerk capture: --blocked-by requires --parent so the new dependency edge is sibling-only'
- fi
-
- case "$backend" in
- bd | gh)
- # Even when the delivery backlog is GitHub, raw captures live in bd; GitHub is
- # only the ready backlog surface after `clerk inbox ready` promotes a capture.
- [ "$issue_type" = impediment ] && bd_ensure_impediment_type
- if [ -n "$parent" ]; then
- local parent_json
- parent_json=$(bd_issue_json_or_usage 'clerk capture' "$parent")
- if ! issue_json_is_nonclosed_work "$parent_json"; then
- usage_error "clerk capture: --parent $parent must name a non-closed Work graph item"
- fi
- fi
- local blocker blocker_json blocker_parent
- for blocker in "${blockers[@]+"${blockers[@]}"}"; do
- blocker_json=$(bd_issue_json_or_usage 'clerk capture' "$blocker")
- if ! issue_json_is_nonclosed_work "$blocker_json"; then
- usage_error "clerk capture: --blocked-by $blocker must name a non-closed Work graph item"
- fi
- if [ -n "$parent" ]; then
- blocker_parent=$(printf '%s' "$blocker_json" | jq -r '.parent // ""')
- [ "$blocker_parent" = "$parent" ] || usage_error "clerk capture: --blocked-by $blocker must be a sibling under $parent"
- fi
- done
- local -a args=(bd create "$title" --silent)
- [ "$use_stdin" -eq 1 ] && args+=(--stdin)
- [ -z "$issue_type" ] || args+=(--type "$issue_type")
- [ -z "$parent" ] || args+=(--parent "$parent")
- for blocker in "${blockers[@]+"${blockers[@]}"}"; do args+=(--deps "$blocker"); done
- local id
- if ! id=$("${args[@]}"); then
- backend_fail "capture failed — bd create did not succeed for \"$title\""
- fi
- # mutation self-verify (ADR 0015): confirm the id landed before declaring success
- local seen
- seen=$(bd show "$id" --readonly --json 2>/dev/null | jq -c '.[0] // empty')
- if [ "$(jq -r '.id // empty' <<<"$seen")" != "$id" ]; then
- backend_fail "capture failed — $id was not confirmed after creation"
- fi
- if [ "$(jq -r '(.labels // []) | index("stage:ready") != null' <<<"$seen")" = true ]; then
- if ! bd update "$id" --remove-label stage:ready >/dev/null; then
- backend_fail "capture failed — $id could not be restored to the Inbox"
- fi
- seen=$(bd show "$id" --readonly --json 2>/dev/null | jq -c '.[0] // empty')
- if [ "$(jq -r '.id // empty' <<<"$seen")" != "$id" ] || [ "$(jq -r '(.labels // []) | index("stage:ready") != null' <<<"$seen")" = true ]; then
- backend_fail "capture failed — $id remained ready after creation"
- fi
- fi
- if [ "$issue_type" = impediment ]; then
- printf '%sclerk:%s filed %s (type: impediment)\n' "$C_GRN" "$C_RST" "$id"
- else
- printf '%sclerk:%s filed %s\n' "$C_GRN" "$C_RST" "$id"
- fi
- ;;
- esac
-}
-
-# clerk inbox list — the pool is OPEN minus stage:ready (ADR 0015: the definition moves
-# from presort prose into this code), plus the per-unit pregrill marker (C-d).
-cmd_inbox_list() {
- local backend="$1"
- shift 2
- local limit="" arg
- while [ $# -gt 0 ]; do
- case "$1" in
- --limit)
- [ $# -ge 2 ] || usage_error 'clerk inbox list: --limit needs a value — usage: clerk inbox list [--limit ]'
- arg="$2"
- case "$arg" in
- '' | *[!0-9]*) usage_error 'clerk inbox list: --limit must be a non-negative integer' ;;
- esac
- limit="$arg"
- shift
- ;;
- *) usage_error "clerk inbox list: unknown argument '$1' — usage: clerk inbox list [--limit ]" ;;
- esac
- shift
- done
- case "$backend" in
- bd | gh)
- # Inbox storage is bd for both backlog bindings. In `backlog: gh` repos this keeps
- # pre-promotion captures visible instead of confusing them with GitHub delivery issues.
- # stdout only: stderr is left to flow straight to the terminal (bd's own error
- # text lands there on failure) rather than being folded into $json, which must
- # stay pure JSON on success — a stray warning on stderr would otherwise corrupt
- # the jq parse below.
- local json
- local -a bd_args=(bd list --status open --exclude-label stage:ready --readonly --json)
- [ -z "$limit" ] || bd_args+=(--limit "$limit")
- if ! json=$("${bd_args[@]}"); then
- backend_fail "inbox list failed — bd list did not succeed"
- fi
- local count
- count=$(printf '%s' "$json" | jq 'length')
- printf 'Inbox (open, not ready) — %s item(s):\n' "$count"
- if [ "$count" -eq 0 ]; then
- printf ' (empty)\n'
- return 0
- fi
- # Field separator is \x1f (ASCII unit separator), NOT a tab: bash's `read` always
- # collapses runs of IFS *whitespace* characters (space/tab/newline) and trims
- # them at the edges, even when IFS is set to just one of them — so a genuinely
- # empty middle field (the common case here: no pregrill tag yet) silently merges
- # with its neighbour and shifts every later field left. \x1f is not whitespace,
- # so empty fields survive intact.
- local id title note_ts upd_ts marker
- while IFS=$'\x1f' read -r id title note_ts upd_ts; do
- marker=$(pregrill_marker "$note_ts" "$upd_ts")
- printf ' %s [pregrill:%s] %s\n' "$id" "$marker" "$title"
- done < <(printf '%s' "$json" | jq -r '
- def pregrill_ts: (.notes // "")
- | [scan("clerk-pregrill: ([0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z)")] as $m
- | if ($m|length)==0 then "" else $m[-1][0] end;
- .[] | [.id, .title, pregrill_ts, (.updated_at // "")] | join("\u001f")')
- ;;
- esac
-}
-
-returned_attempt_banner() { # $1=root $2=short $3=id $4=dispose-verb-hint
- local root="$1" short="$2" id="$3" dispose_hint="$4" main_root ref local_present=0 remote_present=0 presence behind subject
- main_root=$(primary_repo_root "$root")
- if git -C "$main_root" show-ref --verify --quiet "refs/heads/returned/$short"; then
- local_present=1
- ref="returned/$short"
- fi
- if git -C "$main_root" show-ref --verify --quiet "refs/remotes/origin/returned/$short"; then
- remote_present=1
- [ -n "${ref:-}" ] || ref="origin/returned/$short"
- fi
- [ "$local_present" -eq 1 ] || [ "$remote_present" -eq 1 ] || return 0
- case "$local_present:$remote_present" in
- 1:1) presence=local+origin ;;
- 1:0) presence=local ;;
- 0:1) presence=origin ;;
- esac
- behind=$(git -C "$main_root" rev-list --count "$ref..main" 2>/dev/null || printf '?')
- subject=$(git -C "$main_root" log -1 --format=%s "$ref" 2>/dev/null || printf '(unknown subject)')
- printf '\nclerk: returned attempt: returned/%s (%s; %s commit(s) behind main)\n' "$short" "$presence" "$behind"
- printf ' subject: %s\n' "$subject"
- case "$dispose_hint" in
- 'backlog claim')
- printf ' reuse via: clerk backlog claim %s --from-returned\n' "$id"
- printf ' fresh via: clerk backlog claim %s --fresh --returned keep|discard\n' "$id"
- ;;
- *)
- printf ' dispose via: clerk %s %s --returned keep|discard\n' "$dispose_hint" "$id"
- ;;
- esac
-}
-
-# clerk inbox show [--json|--pretty]
-cmd_inbox_show() {
- local backend="$1" root="$2"
- shift 2
- local id="${1:-}" json_mode=0 pretty=0
- if [ -z "$id" ]; then
- usage_error 'clerk inbox show: missing id — usage: clerk inbox show [--json|--pretty]'
- fi
- shift
- while [ $# -gt 0 ]; do
- case "$1" in
- --json) json_mode=1 ;;
- --pretty) json_mode=1; pretty=1 ;;
- *) usage_error "clerk inbox show: unknown argument '$1' — usage: clerk inbox show [--json|--pretty]" ;;
- esac
- shift
- done
- case "$backend" in
- bd | gh)
- if [ "$json_mode" -eq 1 ]; then
- local obj updated body guard
- obj=$(bd_issue_json_or_usage 'clerk inbox show' "$id")
- updated=$(printf '%s' "$obj" | jq -r '.updated_at // ""')
- body=$(printf '%s' "$obj" | jq -r '.description // ""')
- guard=$(printf '%s\0%s' "$updated" "$body" | sha256sum | awk '{print $1}')
- printf '%s' "$obj" | jq --arg body_guard "$guard" '{id,title,status,type:.issue_type,assignee:(.assignee // ""),labels:(.labels // []),parent:(.parent // null),body:(.description // ""),body_guard:$body_guard,notes:(.notes // ""),design:(.design // ""),acceptance:(.acceptance_criteria // ""),created_at,updated_at}' | clerk_json_emit "$pretty"
- else
- bd show "$id" --readonly
- returned_attempt_banner "$root" "$(returned_short_from_id "$id")" "$id" 'inbox ready|drop'
- fi
- ;;
- esac
-}
-
-# clerk inbox dups — cross-pool by design: a capture duplicating an already-ready bead is
-# a real duplicate, so this never pre-filters to the inbox pool (unlike `inbox list`).
-cmd_inbox_dups() {
- local backend="$1"
- shift 2
- case "$backend" in
- bd | gh)
- local json
- if ! json=$(bd find-duplicates --readonly --json); then
- backend_fail "inbox dups failed — bd find-duplicates did not succeed"
- fi
- local count
- count=$(printf '%s' "$json" | jq -r '.count // 0')
- printf 'Duplicate candidates — %s pair(s):\n' "$count"
- if [ "$count" -eq 0 ]; then
- printf ' (none)\n'
- return 0
- fi
- printf '%s' "$json" | jq -r '.pairs[] | " \(.issue_a_id) \"\(.issue_a_title)\" ~ \(.issue_b_id) \"\(.issue_b_title)\" (score: \(.similarity))"'
- ;;
- esac
-}
-
-returned_short_from_id() { # $1=id; echoes the token used by returned/
- local id="$1"
- id="${id#\#}"
- case "$id" in
- *-*) printf '%s\n' "${id#*-}" ;;
- *) printf '%s\n' "$id" ;;
- esac
-}
-
-returned_branch_exists() { # $1=root $2=short
- local main_root short
- main_root=$(primary_repo_root "$1")
- short="$2"
- git -C "$main_root" show-ref --verify --quiet "refs/heads/returned/$short" && return 0
- git -C "$main_root" show-ref --verify --quiet "refs/remotes/origin/returned/$short" && return 0
- return 1
-}
-
-dispose_returned() { # $1=root $2=short
- local main_root short local_refs remote_refs offline=0 ref branch
- main_root=$(primary_repo_root "$1")
- short="$2"
- local_refs=$(git -C "$main_root" for-each-ref --format='%(refname:short)' \
- "refs/heads/returned/$short" "refs/heads/returned/$short-*" 2>/dev/null || true)
- remote_refs=$(git -C "$main_root" for-each-ref --format='%(refname:short)' \
- "refs/remotes/origin/returned/$short" "refs/remotes/origin/returned/$short-*" 2>/dev/null || true)
- if [ -z "$local_refs" ] && [ -z "$remote_refs" ]; then
- return 0
- fi
- while IFS= read -r ref; do
- [ -n "$ref" ] || continue
- git -C "$main_root" branch -D "$ref" >/dev/null 2>&1 ||
- backend_fail "returned disposition failed — could not delete local $ref"
- done <<<"$local_refs"
- if ! (GIT_TERMINAL_PROMPT=0 timeout 10 git -C "$main_root" fetch origin >/dev/null 2>&1); then
- offline=1
- fi
- if [ "$offline" -eq 1 ]; then
- printf 'clerk: OFFLINE - returned/%s and archives deleted locally only; the remote branch delete is deferred to sync (clerk sync will finish it at the next reconnect).\n' "$short" >&2
- return 0
- fi
- remote_refs=$(git -C "$main_root" for-each-ref --format='%(refname:short)' \
- "refs/remotes/origin/returned/$short" "refs/remotes/origin/returned/$short-*" 2>/dev/null || true)
- while IFS= read -r ref; do
- [ -n "$ref" ] || continue
- branch="${ref#origin/}"
- git -C "$main_root" push origin --delete "$branch" >/dev/null 2>&1 ||
- backend_fail "returned disposition failed — could not delete origin $branch"
- git -C "$main_root" update-ref -d "refs/remotes/origin/$branch" >/dev/null 2>&1 || true
- done <<<"$remote_refs"
-}
-
-handle_returned_disposition() { # $1=verb-label $2=root $3=short $4=keep|discard|empty
- local verb="$1" root="$2" short="$3" disposition="$4"
- case "$disposition" in
- "" )
- if returned_branch_exists "$root" "$short"; then
- usage_error "clerk $verb: returned/$short exists — choose --returned keep or --returned discard"
- fi
- ;;
- keep) ;;
- discard) dispose_returned "$root" "$short" ;;
- *) usage_error "clerk $verb: --returned must be keep or discard" ;;
- esac
-}
-
-# clerk inbox ready [--design-file ] [--acceptance-file ] [--returned keep|discard]
-# gh: clerk inbox ready --title "" --body-file
-cmd_inbox_ready() {
- local backend="$1" root="$2"
- shift 2
- if [ $# -eq 0 ]; then
- usage_error 'clerk inbox ready: missing id — usage: clerk inbox ready [--design-file ] [--acceptance-file ]'
- fi
- local id="$1"
- shift
- local title="" body_file="" design_file="" acceptance_file="" returned_disposition=""
- while [ $# -gt 0 ]; do
- case "$1" in
- --title)
- [ $# -ge 2 ] || usage_error "clerk inbox ready: --title needs a value"
- title="$2"
- shift
- ;;
- --body-file)
- [ $# -ge 2 ] || usage_error "clerk inbox ready: --body-file needs a value"
- body_file="$2"
- shift
- ;;
- --design-file)
- [ $# -ge 2 ] || usage_error "clerk inbox ready: --design-file needs a path"
- design_file="$2"
- shift
- ;;
- --acceptance-file)
- [ $# -ge 2 ] || usage_error "clerk inbox ready: --acceptance-file needs a path"
- acceptance_file="$2"
- shift
- ;;
- --returned)
- [ $# -ge 2 ] || usage_error "clerk inbox ready: --returned needs keep or discard"
- returned_disposition="$2"
- shift
- ;;
- *) usage_error "clerk inbox ready: unknown argument '$1'" ;;
- esac
- shift
- done
-
- case "$backend" in
- bd)
- [ -z "$title" ] || usage_error 'clerk inbox ready: --title is only for gh-backed promotion; use --design-file/--acceptance-file for bd'
- [ -z "$body_file" ] || usage_error 'clerk inbox ready: --body-file is only for gh-backed promotion; use --design-file/--acceptance-file for bd'
- [ -z "$design_file" ] || [ -f "$design_file" ] || usage_error "clerk inbox ready: design file not found: $design_file"
- [ -z "$acceptance_file" ] || [ -f "$acceptance_file" ] || usage_error "clerk inbox ready: acceptance file not found: $acceptance_file"
- local json
- json=$(bd show "$id" --readonly --json 2>/dev/null)
- # bd 1.0.4 signals a missing id not with empty stdout or literal `null` but with
- # an ERROR OBJECT on stdout (`{"error":"no issues found...","schema_version":1}`,
- # nonzero exit — discarded by `$(...)`). A successful lookup is always a non-empty
- # JSON array. So "not an array, or an empty one" is the not-found test; checking
- # for the object shape directly (rather than relying on the later jq calls to fail
- # into empty strings) keeps this guard accurate instead of accidental.
- if [ -z "$json" ] || [ "$json" = null ] ||
- ! printf '%s' "$json" | jq -e 'if type != "array" then false else (length > 0) end' >/dev/null 2>&1; then
- usage_error "clerk inbox ready: $id not found — check the id ('clerk inbox list' shows open units)"
- fi
- local obj short
- obj=$(printf '%s' "$json" | jq -c '.[0]')
- issue_json_is_active_inbox "$obj" || usage_error "clerk inbox ready: $id must be an open inbox item (not ready/promoted/closed)"
- planning_holder_refusal 'inbox ready' "$root" "$obj"
- short=$(returned_short_from_id "$id")
- handle_returned_disposition 'inbox ready' "$root" "$short" "$returned_disposition"
- # C-e also covers bd's first-class `acceptance_criteria` field (populated by
- # `bd create --acceptance`/`--acceptance-file`), not just prose in description or
- # design: that dedicated field IS the structural section by construction, so its
- # mere non-empty presence satisfies C-e without re-scanning it for a heading.
- local desc design ac acceptance_text="" design_text=""
- if [ -n "$design_file" ] || [ -n "$acceptance_file" ]; then
- local -a update_args=(bd update "$id")
- if [ -n "$design_file" ]; then
- design_text=$(cat "$design_file")
- update_args+=(--design-file "$design_file")
- fi
- if [ -n "$acceptance_file" ]; then
- acceptance_text=$(cat "$acceptance_file")
- update_args+=(--acceptance "$acceptance_text")
- fi
- if ! "${update_args[@]}" >/dev/null; then
- backend_fail "inbox ready failed — bd update did not succeed for $id"
- fi
- json=$(bd show "$id" --readonly --json 2>/dev/null)
- if [ -n "$design_file" ] && [ "$(printf '%s' "$json" | jq -r '.[0].design // ""')" != "$design_text" ]; then
- backend_fail "inbox ready failed — design was not confirmed after writing $design_file"
- fi
- if [ -n "$acceptance_file" ] && [ "$(printf '%s' "$json" | jq -r '.[0].acceptance_criteria // ""')" != "$acceptance_text" ]; then
- backend_fail "inbox ready failed — acceptance criteria were not confirmed after writing $acceptance_file"
- fi
- fi
- desc=$(printf '%s' "$json" | jq -r '.[0].description // ""')
- design=$(printf '%s' "$json" | jq -r '.[0].design // ""')
- ac=$(printf '%s' "$json" | jq -r '.[0].acceptance_criteria // ""')
- if [ -z "$ac" ] && ! has_acceptance_criteria_section "$desc"$'\n'"$design"; then
- usage_error "clerk inbox ready: $id has no 'Acceptance Criteria' section — rerun with --acceptance-file (and optionally --design-file ) before promoting it"
- fi
- if ! bd update "$id" --status open --assignee "" --add-label stage:ready >/dev/null; then
- backend_fail "inbox ready failed — bd update did not succeed for $id"
- fi
- # mutation self-verify (ADR 0015)
- local has_label
- has_label=$(bd show "$id" --readonly --json 2>/dev/null | jq -r '(.[0].labels // []) | index("stage:ready")')
- if [ "$has_label" = null ]; then
- backend_fail "inbox ready failed — $id was not confirmed stage:ready after promotion"
- fi
- printf '%sclerk:%s promoted %s to stage:ready\n' "$C_GRN" "$C_RST" "$id"
- ;;
- gh)
- [ -z "$design_file" ] || usage_error 'clerk inbox ready: --design-file is only for bd-backed promotion; use --title/--body-file for gh'
- [ -z "$acceptance_file" ] || usage_error 'clerk inbox ready: --acceptance-file is only for bd-backed promotion; use --title/--body-file for gh'
- if [ -z "$title" ] || [ -z "$body_file" ]; then
- usage_error "clerk inbox ready: gh backend needs both --title \"\" and --body-file — rerun as 'clerk inbox ready $id --title \"\" --body-file '"
- fi
- [ -f "$body_file" ] || usage_error "clerk inbox ready: body file not found: $body_file"
- local json
- json=$(bd show "$id" --readonly --json 2>/dev/null)
- if [ -z "$json" ] || [ "$json" = null ] ||
- ! printf '%s' "$json" | jq -e 'if type != "array" then false else (length > 0) end' >/dev/null 2>&1; then
- usage_error "clerk inbox ready: $id not found — check the id ('clerk inbox list' shows open units)"
- fi
- local obj short
- obj=$(printf '%s' "$json" | jq -c '.[0]')
- issue_json_is_active_inbox "$obj" || usage_error "clerk inbox ready: $id must be an open inbox item (not ready/promoted/closed)"
- planning_holder_refusal 'inbox ready' "$root" "$obj"
- short=$(returned_short_from_id "$id")
- handle_returned_disposition 'inbox ready' "$root" "$short" "$returned_disposition"
- local url
- if ! url=$(gh issue create --title "$title" --body-file "$body_file" --label ready-for-agent); then
- backend_fail "inbox ready failed — gh issue create did not succeed"
- fi
- local num="${url##*/}"
- if ! bd close "$id" --reason "promoted to GitHub #$num" >/dev/null; then
- backend_fail "inbox ready failed — bd close did not succeed for $id"
- fi
- local status close_reason
- json=$(bd show "$id" --readonly --json 2>/dev/null)
- status=$(printf '%s' "$json" | jq -r '.[0].status // ""')
- close_reason=$(printf '%s' "$json" | jq -r '.[0].close_reason // ""')
- if [ "$status" != closed ] || [ "$close_reason" != "promoted to GitHub #$num" ]; then
- backend_fail "inbox ready failed — $id was not confirmed closed after promotion"
- fi
- printf '%sclerk:%s promoted %s to #%s (%s)\n' "$C_GRN" "$C_RST" "$id" "$num" "$url"
- ;;
- esac
-}
-
-# clerk inbox drop
-cmd_inbox_drop() {
- local backend="$1" root="$2"
- shift 2
- local id="${1:-}"
- if [ -z "$id" ]; then
- usage_error 'clerk inbox drop: missing id — usage: clerk inbox drop [--returned keep|discard]'
- fi
- shift
- local returned_disposition=""
- while [ $# -gt 0 ]; do
- case "$1" in
- --returned)
- [ $# -ge 2 ] || usage_error "clerk inbox drop: --returned needs keep or discard"
- returned_disposition="$2"
- shift
- ;;
- *) usage_error "clerk inbox drop: unknown argument '$1'" ;;
- esac
- shift
- done
- case "$backend" in
- bd | gh)
- local obj short
- obj=$(bd_issue_json_or_usage 'clerk inbox drop' "$id")
- planning_holder_refusal 'inbox drop' "$root" "$obj"
- short=$(returned_short_from_id "$id")
- handle_returned_disposition 'inbox drop' "$root" "$short" "$returned_disposition"
- if ! bd close "$id" --reason wontfix >/dev/null; then
- backend_fail "inbox drop failed — bd close did not succeed for $id"
- fi
- local status
- status=$(bd show "$id" --readonly --json 2>/dev/null | jq -r '.[0].status // ""')
- if [ "$status" != closed ]; then
- backend_fail "inbox drop failed — $id was not confirmed closed"
- fi
- printf '%sclerk:%s dropped %s (wontfix)\n' "$C_GRN" "$C_RST" "$id"
- ;;
- esac
-}
-
-# clerk inbox pregrill [--decision ""]... [--premise "|"]... [--criterion ""]...
-# The SINGLE write verb of the inbox (ADR 0016 ruling 20): bd's only mutation is
-# --append-notes (C-b) and the result is self-verified state-neutral (status/labels
-# byte-identical before/after) before success is reported (ADR 0015 mutation self-verify).
-cmd_inbox_pregrill() {
- local backend="$1"
- shift 2
- if [ $# -eq 0 ]; then
- usage_error 'clerk inbox pregrill: missing id — usage: clerk inbox pregrill [--decision ""]... [--premise "|"]... [--criterion ""]...'
- fi
- local id="$1"
- shift
- local -a decisions=() premises=() criteria=()
- while [ $# -gt 0 ]; do
- case "$1" in
- --decision)
- [ $# -ge 2 ] || usage_error "clerk inbox pregrill: --decision needs a value"
- decisions+=("$2")
- shift
- ;;
- --premise)
- [ $# -ge 2 ] || usage_error "clerk inbox pregrill: --premise needs a value"
- premises+=("$2")
- shift
- ;;
- --criterion)
- [ $# -ge 2 ] || usage_error "clerk inbox pregrill: --criterion needs a value"
- criteria+=("$2")
- shift
- ;;
- *) usage_error "clerk inbox pregrill: unknown argument '$1'" ;;
- esac
- shift
- done
-
- local ts note
- ts=$(date -u +%Y-%m-%dT%H:%M:%SZ)
- note=$(build_pregrill_note "$ts" decisions premises criteria)
-
- case "$backend" in
- bd | gh)
- local before after
- before=$(bd show "$id" --readonly --json 2>/dev/null | jq -c '.[0] | {status, labels}' 2>/dev/null)
- if [ -z "$before" ] || [ "$before" = null ]; then
- usage_error "clerk inbox pregrill: $id not found — check the id ('clerk inbox list' shows open units)"
- fi
- if ! bd update "$id" --append-notes "$note" >/dev/null; then
- backend_fail "inbox pregrill failed — bd update --append-notes did not succeed for $id"
- fi
- after=$(bd show "$id" --readonly --json 2>/dev/null | jq -c '.[0] | {status, labels}' 2>/dev/null)
- if [ "$before" != "$after" ]; then
- backend_fail "inbox pregrill failed — $id status/labels changed (not state-neutral)"
- fi
- printf '%sclerk:%s pregrilled %s (dated %s)\n' "$C_GRN" "$C_RST" "$id" "$ts"
- ;;
- esac
-}
-
-normalize_graph_items_jq='def norm: {id,title,status,type:.issue_type,assignee:(.assignee // ""),labels:(.labels // []),parent:(.parent // null),created_at,updated_at};'
-
-cmd_inbox_children() {
- local _backend="$1" _root="$2" id="" pretty=0
- shift 2
- id="${1:-}"
- [ -n "$id" ] || usage_error 'clerk inbox children: missing parent id — usage: clerk inbox children [--pretty]'
- shift
- while [ $# -gt 0 ]; do
- case "$1" in --pretty) pretty=1 ;; *) usage_error "clerk inbox children: unknown argument '$1' — usage: clerk inbox children [--pretty]" ;; esac
- shift
- done
- local parent child_id child items_file
- parent=$(bd_issue_json_or_usage 'clerk inbox children' "$id")
- items_file=$(mktemp)
- while IFS= read -r child_id; do
- [ -n "$child_id" ] || continue
- child=$(bd_issue_json_or_usage 'clerk inbox children' "$child_id")
- printf '%s\n' "$child" | jq -c "$normalize_graph_items_jq norm" >>"$items_file"
- done < <(printf '%s' "$parent" | jq -r '(.dependents // [])[] | select(.dependency_type == "parent-child") | .id')
- jq -n --argjson parent "$(printf '%s' "$parent" | jq -c "$normalize_graph_items_jq norm")" --slurpfile items "$items_file" '{parent:$parent,items:$items}' | clerk_json_emit "$pretty"
- rm -f "$items_file"
-}
-
-cmd_inbox_blockers() {
- local _backend="$1" _root="$2" id="" pretty=0
- shift 2
- id="${1:-}"
- [ -n "$id" ] || usage_error 'clerk inbox blockers: missing id — usage: clerk inbox blockers [--pretty]'
- shift
- while [ $# -gt 0 ]; do
- case "$1" in --pretty) pretty=1 ;; *) usage_error "clerk inbox blockers: unknown argument '$1' — usage: clerk inbox blockers [--pretty]" ;; esac
- shift
- done
- local item blocker_id blocker items_file
- item=$(bd_issue_json_or_usage 'clerk inbox blockers' "$id")
- items_file=$(mktemp)
- while IFS= read -r blocker_id; do
- [ -n "$blocker_id" ] || continue
- blocker=$(bd_issue_json_or_usage 'clerk inbox blockers' "$blocker_id")
- printf '%s\n' "$blocker" | jq -c "$normalize_graph_items_jq norm" >>"$items_file"
- done < <(printf '%s' "$item" | jq -r '(.dependencies // [])[] | select(.dependency_type == "blocks") | .id')
- jq -n --argjson item "$(printf '%s' "$item" | jq -c "$normalize_graph_items_jq norm")" --slurpfile items "$items_file" '{item:$item,items:$items}' | clerk_json_emit "$pretty"
- rm -f "$items_file"
-}
-
-cmd_inbox_blocked() {
- local _backend="$1" _root="$2" id="" pretty=0
- shift 2
- id="${1:-}"
- [ -n "$id" ] || usage_error 'clerk inbox blocked: missing id — usage: clerk inbox blocked [--pretty]'
- shift
- while [ $# -gt 0 ]; do
- case "$1" in --pretty) pretty=1 ;; *) usage_error "clerk inbox blocked: unknown argument '$1' — usage: clerk inbox blocked [--pretty]" ;; esac
- shift
- done
- local item blocked_id blocked items_file
- item=$(bd_issue_json_or_usage 'clerk inbox blocked' "$id")
- items_file=$(mktemp)
- while IFS= read -r blocked_id; do
- [ -n "$blocked_id" ] || continue
- blocked=$(bd_issue_json_or_usage 'clerk inbox blocked' "$blocked_id")
- printf '%s\n' "$blocked" | jq -c "$normalize_graph_items_jq norm" >>"$items_file"
- done < <(printf '%s' "$item" | jq -r '(.dependents // [])[] | select(.dependency_type == "blocks") | .id')
- jq -n --argjson item "$(printf '%s' "$item" | jq -c "$normalize_graph_items_jq norm")" --slurpfile items "$items_file" '{item:$item,items:$items}' | clerk_json_emit "$pretty"
- rm -f "$items_file"
-}
-
-cmd_inbox_frontier() {
- local _backend="$1" _root="$2" id="" pretty=0
- shift 2
- id="${1:-}"
- [ -n "$id" ] || usage_error 'clerk inbox frontier: missing parent id — usage: clerk inbox frontier [--pretty]'
- shift
- while [ $# -gt 0 ]; do
- case "$1" in --pretty) pretty=1 ;; *) usage_error "clerk inbox frontier: unknown argument '$1' — usage: clerk inbox frontier [--pretty]" ;; esac
- shift
- done
- local parent child_id child items_file
- parent=$(bd_issue_json_or_usage 'clerk inbox frontier' "$id")
- if ! issue_json_is_nonclosed_work "$parent"; then
- usage_error "clerk inbox frontier: $id must be a non-closed Work graph parent"
- fi
- items_file=$(mktemp)
- while IFS= read -r child_id; do
- [ -n "$child_id" ] || continue
- child=$(bd_issue_json_or_usage 'clerk inbox frontier' "$child_id")
- issue_json_is_open_inbox "$child" || continue
- [ -z "$(printf '%s' "$child" | jq -r '.assignee // ""')" ] || continue
- # A frontier child is takeable only when every direct blocker is closed; missing
- # blocker status fails closed by treating the blocker as still open.
- if printf '%s' "$child" | jq -e '(.dependencies // []) | any(.dependency_type == "blocks" and ((.status // "open") != "closed"))' >/dev/null; then
- continue
- fi
- printf '%s\n' "$child" | jq -c "$normalize_graph_items_jq norm" >>"$items_file"
- done < <(printf '%s' "$parent" | jq -r '(.dependents // [])[] | select(.dependency_type == "parent-child") | .id')
- jq -n --argjson parent "$(printf '%s' "$parent" | jq -c "$normalize_graph_items_jq norm")" --slurpfile items "$items_file" '{parent:$parent,items:$items}' | clerk_json_emit "$pretty"
- rm -f "$items_file"
-}
-
-invalid_dep_edges_for_parent_move() { # $1=child $2=new-parent; prints "dependent blocker" pairs to remove
- local child="$1" new_parent="$2" other other_parent
- while IFS= read -r other; do
- [ -n "$other" ] || continue
- other_parent=$(issue_parent_id "$other")
- if [ -z "$new_parent" ] || [ "$other_parent" != "$new_parent" ]; then
- printf '%s %s\n' "$child" "$other"
- fi
- done < <(issue_blocker_ids "$child")
- while IFS= read -r other; do
- [ -n "$other" ] || continue
- other_parent=$(issue_parent_id "$other")
- if [ -z "$new_parent" ] || [ "$other_parent" != "$new_parent" ]; then
- printf '%s %s\n' "$other" "$child"
- fi
- done < <(issue_blocked_ids "$child")
-}
-
-parent_cycle_would_form() { # $1=child $2=parent
- local child="$1" cur="$2"
- while [ -n "$cur" ]; do
- [ "$cur" = "$child" ] && return 0
- cur=$(issue_parent_id "$cur")
- done
- return 1
-}
-
-cmd_inbox_parent() {
- local _backend="$1" _root="$2" action="${3:-}" child="${4:-}" parent="${5:-}" drop=0
- shift 2
- action="${1:-}"; shift || true
- case "$action" in
- set)
- child="${1:-}"; parent="${2:-}"; [ -n "$child" ] && [ -n "$parent" ] || usage_error 'clerk inbox parent set: usage: clerk inbox parent set [--drop-invalid-deps]'
- shift 2
- ;;
- clear)
- child="${1:-}"; [ -n "$child" ] || usage_error 'clerk inbox parent clear: usage: clerk inbox parent clear [--drop-invalid-deps]'
- parent=""
- shift
- ;;
- *) usage_error 'clerk inbox parent: usage: clerk inbox parent set | clerk inbox parent clear ' ;;
- esac
- while [ $# -gt 0 ]; do
- case "$1" in --drop-invalid-deps) drop=1 ;; *) usage_error "clerk inbox parent $action: unknown argument '$1'" ;; esac
- shift
- done
- local child_json parent_json invalid_file line dependent blocker
- child_json=$(bd_issue_json_or_usage "clerk inbox parent $action" "$child")
- issue_json_is_open_inbox "$child_json" || usage_error "clerk inbox parent $action: $child must be an open inbox item"
- if [ -n "$parent" ]; then
- parent_json=$(bd_issue_json_or_usage 'clerk inbox parent set' "$parent")
- issue_json_is_open_inbox "$parent_json" || usage_error "clerk inbox parent set: $parent must be an open inbox parent"
- parent_cycle_would_form "$child" "$parent" && usage_error "clerk inbox parent set: refusing parent cycle ($child under $parent)"
- fi
- invalid_file=$(mktemp)
- invalid_dep_edges_for_parent_move "$child" "$parent" >"$invalid_file"
- if [ -s "$invalid_file" ] && [ "$drop" -eq 0 ]; then
- rm -f "$invalid_file"
- usage_error "clerk inbox parent $action: move would leave non-sibling dependency edges — rerun with --drop-invalid-deps to remove them"
- fi
- while read -r dependent blocker; do
- [ -n "${dependent:-}" ] || continue
- bd dep remove "$dependent" "$blocker" >/dev/null || backend_fail "inbox parent $action failed — could not drop invalid dependency $dependent -> $blocker"
- done <"$invalid_file"
- rm -f "$invalid_file"
- bd update "$child" --parent "$parent" >/dev/null || backend_fail "inbox parent $action failed — bd update --parent did not succeed for $child"
- local actual
- actual=$(issue_parent_id "$child")
- [ "$actual" = "$parent" ] || backend_fail "inbox parent $action failed — parent was not confirmed for $child"
- if [ -n "$parent" ]; then
- printf '%sclerk:%s parent set %s -> %s\n' "$C_GRN" "$C_RST" "$child" "$parent"
- else
- printf '%sclerk:%s parent cleared %s\n' "$C_GRN" "$C_RST" "$child"
- fi
-}
-
-dep_path_exists() { # $1=start $2=target over blocks edges
- local start="$1" target="$2" seen_file next
- seen_file=$(mktemp)
- _dep_path_exists_inner "$start" "$target" "$seen_file"
- local rc=$?
- rm -f "$seen_file"
- return "$rc"
-}
-
-_dep_path_exists_inner() {
- local start="$1" target="$2" seen_file="$3" next
- grep -Fxq "$start" "$seen_file" 2>/dev/null && return 1
- printf '%s\n' "$start" >>"$seen_file"
- while IFS= read -r next; do
- [ -n "$next" ] || continue
- [ "$next" = "$target" ] && return 0
- _dep_path_exists_inner "$next" "$target" "$seen_file" && return 0
- done < <(issue_blocker_ids "$start")
- return 1
-}
-
-cmd_inbox_dep() {
- local _backend="$1" _root="$2" action="${3:-}" child="" blocker=""
- shift 2
- action="${1:-}"; shift || true
- case "$action" in
- add | remove) child="${1:-}"; blocker="${2:-}"; [ -n "$child" ] && [ -n "$blocker" ] || usage_error "clerk inbox dep $action: usage: clerk inbox dep $action "; shift 2 ;;
- *) usage_error 'clerk inbox dep: usage: clerk inbox dep add | clerk inbox dep remove ' ;;
- esac
- [ $# -eq 0 ] || usage_error "clerk inbox dep $action: unknown argument '$1'"
- [ "$child" != "$blocker" ] || usage_error "clerk inbox dep $action: an item cannot block itself"
- local child_json blocker_json child_parent blocker_parent
- child_json=$(bd_issue_json_or_usage "clerk inbox dep $action" "$child")
- blocker_json=$(bd_issue_json_or_usage "clerk inbox dep $action" "$blocker")
- issue_json_is_open_inbox "$child_json" || usage_error "clerk inbox dep $action: $child must be an open inbox item"
- issue_json_is_ready_promoted "$blocker_json" && usage_error "clerk inbox dep $action: $blocker must be an inbox item, not a ready/promoted item"
- child_parent=$(printf '%s' "$child_json" | jq -r '.parent // ""')
- blocker_parent=$(printf '%s' "$blocker_json" | jq -r '.parent // ""')
- [ -n "$child_parent" ] && [ "$child_parent" = "$blocker_parent" ] || usage_error "clerk inbox dep $action: dependency edges are sibling-only; $child and $blocker must share the same immediate parent"
- if [ "$action" = add ]; then
- dep_path_exists "$blocker" "$child" && usage_error "clerk inbox dep add: refusing dependency cycle ($child blocked by $blocker)"
- bd dep add "$child" "$blocker" >/dev/null || backend_fail "inbox dep add failed — bd dep add did not succeed for $child <- $blocker"
- bd_issue_json_or_usage 'clerk inbox dep add' "$child" | jq -e --arg blocker "$blocker" '(.dependencies // []) | any(.dependency_type == "blocks" and .id == $blocker)' >/dev/null || backend_fail "inbox dep add failed — edge was not confirmed for $child <- $blocker"
- printf '%sclerk:%s dependency added %s blocked-by %s\n' "$C_GRN" "$C_RST" "$child" "$blocker"
- else
- bd dep remove "$child" "$blocker" >/dev/null || backend_fail "inbox dep remove failed — bd dep remove did not succeed for $child <- $blocker"
- if bd_issue_json_or_usage 'clerk inbox dep remove' "$child" | jq -e --arg blocker "$blocker" '(.dependencies // []) | any(.dependency_type == "blocks" and .id == $blocker)' >/dev/null; then
- backend_fail "inbox dep remove failed — edge still exists for $child <- $blocker"
- fi
- printf '%sclerk:%s dependency removed %s blocked-by %s\n' "$C_GRN" "$C_RST" "$child" "$blocker"
- fi
-}
-
-read_nonempty_text_arg() { # $1=verb; remaining args: [--file path|--stdin]; echoes body
- local verb="$1" input_source=stdin input_seen=0 file=""
- shift
- while [ $# -gt 0 ]; do
- case "$1" in
- --file)
- [ $# -ge 2 ] || usage_error "$verb: --file needs a path"
- [ "$input_seen" -eq 0 ] || usage_error "$verb: choose only one input source"
- input_source=file; input_seen=1; file="$2"; shift
- ;;
- --stdin)
- [ "$input_seen" -eq 0 ] || usage_error "$verb: choose only one input source"
- input_source=stdin; input_seen=1
- ;;
- *) usage_error "$verb: unknown argument '$1'" ;;
- esac
- shift
- done
- local text
- if [ "$input_source" = file ]; then
- [ -f "$file" ] || usage_error "$verb: file not found: $file"
- text=$(cat "$file")
- else
- text=$(cat)
- fi
- printf '%s' "$text" | grep -q '[^[:space:]]' || usage_error "$verb: note text must be non-empty"
- printf '%s' "$text"
-}
-
-cmd_inbox_claim() {
- local _backend="$1" root="$2" id="${3:-}" obj holder me check
- shift 2
- id="${1:-}"; [ -n "$id" ] || usage_error 'clerk inbox claim: missing id — usage: clerk inbox claim '
- shift
- [ $# -eq 0 ] || usage_error "clerk inbox claim: unknown argument '$1' — usage: clerk inbox claim "
- obj=$(bd_issue_json_or_usage 'clerk inbox claim' "$id")
- issue_json_is_active_inbox "$obj" || usage_error "clerk inbox claim: $id must be an open inbox item (not ready/promoted/closed)"
- me=$(claim_current_actor "$root")
- holder=$(printf '%s' "$obj" | jq -r '.assignee // ""')
- if [ -n "$holder" ]; then
- if [ "$holder" = "$me" ]; then
- printf '%sclerk:%s %s already claimed by you\n' "$C_GRN" "$C_RST" "$id"
- return 0
- fi
- printf 'clerk: inbox claim refused — %s is already claimed by %s\n' "$id" "$holder" >&2
- exit 5
- fi
- issue_json_is_open_inbox "$obj" || usage_error "clerk inbox claim: $id must be an open inbox item (not already in progress)"
- issue_has_open_blockers "$id" && usage_error "clerk inbox claim: $id has open blockers — claim an unblocked frontier item"
- issue_has_open_children "$id" && usage_error "clerk inbox claim: $id has open children — claim a leaf item, not its parent"
- if ! bd update "$id" --claim >/dev/null; then
- holder=$(bd_issue_json_or_usage 'clerk inbox claim' "$id" | jq -r '.assignee // ""')
- if [ -n "$holder" ] && [ "$holder" != "$me" ]; then
- printf 'clerk: inbox claim refused — %s is already claimed by %s\n' "$id" "$holder" >&2
- exit 5
- fi
- backend_fail "inbox claim failed — bd update --claim did not succeed for $id"
- fi
- check=$(bd_issue_json_or_usage 'clerk inbox claim' "$id" | jq -r '.assignee // ""')
- [ "$check" = "$me" ] || backend_fail "inbox claim failed — $id was not confirmed claimed by $me"
- printf '%sclerk:%s claimed %s\n' "$C_GRN" "$C_RST" "$id"
-}
-
-cmd_inbox_release() {
- local _backend="$1" root="$2" id="${3:-}" obj holder me check
- shift 2
- id="${1:-}"; [ -n "$id" ] || usage_error 'clerk inbox release: missing id — usage: clerk inbox release '
- shift
- [ $# -eq 0 ] || usage_error "clerk inbox release: unknown argument '$1' — usage: clerk inbox release "
- obj=$(bd_issue_json_or_usage 'clerk inbox release' "$id")
- me=$(claim_current_actor "$root")
- holder=$(printf '%s' "$obj" | jq -r '.assignee // ""')
- if [ -z "$holder" ]; then
- printf '%sclerk:%s %s is not claimed — nothing to release\n' "$C_GRN" "$C_RST" "$id"
- return 0
- fi
- if [ "$holder" != "$me" ]; then
- printf 'clerk: inbox release refused — %s is claimed by %s\n' "$id" "$holder" >&2
- exit 5
- fi
- bd update "$id" --status open --assignee "" >/dev/null || backend_fail "inbox release failed — bd update --status open --assignee did not succeed for $id"
- check=$(bd_issue_json_or_usage 'clerk inbox release' "$id" | jq -r '.assignee // ""')
- [ -z "$check" ] || backend_fail "inbox release failed — $id was not confirmed unclaimed"
- printf '%sclerk:%s released %s\n' "$C_GRN" "$C_RST" "$id"
-}
-
-cmd_inbox_note() {
- local _backend="$1" _root="$2" id="${3:-}" text before after
- shift 2
- id="${1:-}"; [ -n "$id" ] || usage_error 'clerk inbox note: missing id — usage: clerk inbox note [--file |--stdin]'
- shift
- bd_issue_json_or_usage 'clerk inbox note' "$id" >/dev/null
- text=$(read_nonempty_text_arg 'clerk inbox note' "$@")
- before=$(bd_issue_json_or_usage 'clerk inbox note' "$id" | jq -c '{status,labels}')
- bd update "$id" --append-notes "$text" >/dev/null || backend_fail "inbox note failed — bd update --append-notes did not succeed for $id"
- after=$(bd_issue_json_or_usage 'clerk inbox note' "$id" | jq -c '{status,labels}')
- [ "$before" = "$after" ] || backend_fail "inbox note failed — $id state changed while appending note"
- printf '%sclerk:%s noted %s\n' "$C_GRN" "$C_RST" "$id"
-}
-
-cmd_inbox_update() {
- local _backend="$1" _root="$2" id="${3:-}" title="" type="" body_file="" use_stdin=0 guard="" body="" have_body=0
- shift 2
- id="${1:-}"; [ -n "$id" ] || usage_error 'clerk inbox update: missing id — usage: clerk inbox update [--title ] [--type ] [--body-file |--stdin --body-guard ]'
- shift
- while [ $# -gt 0 ]; do
- case "$1" in
- --title) [ $# -ge 2 ] || usage_error 'clerk inbox update: --title needs a value'; title="$2"; shift ;;
- --type) [ $# -ge 2 ] || usage_error 'clerk inbox update: --type needs a value'; type="$2"; shift ;;
- --body-file)
- [ $# -ge 2 ] || usage_error 'clerk inbox update: --body-file needs a path'
- [ "$have_body" -eq 0 ] || usage_error 'clerk inbox update: choose only one of --stdin or --body-file'
- body_file="$2"; have_body=1; shift
- ;;
- --stdin)
- [ "$have_body" -eq 0 ] || usage_error 'clerk inbox update: choose only one of --stdin or --body-file'
- use_stdin=1; have_body=1
- ;;
- --body-guard) [ $# -ge 2 ] || usage_error 'clerk inbox update: --body-guard needs a value from clerk inbox show --json'; guard="$2"; shift ;;
- *) usage_error "clerk inbox update: unknown argument '$1'" ;;
- esac
- shift
- done
- [ -n "$title" ] || [ -n "$type" ] || [ "$have_body" -eq 1 ] || usage_error 'clerk inbox update: nothing to update'
- if [ -n "$type" ]; then
- clerk_type_valid "$type" || usage_error "clerk inbox update: invalid --type '$type' — use a canonical core type or configure types.custom"
- [ "$type" = impediment ] && bd_ensure_impediment_type
- fi
- local obj updated current_body current_guard
- obj=$(bd_issue_json_or_usage 'clerk inbox update' "$id")
- updated=$(printf '%s' "$obj" | jq -r '.updated_at // ""')
- current_body=$(printf '%s' "$obj" | jq -r '.description // ""')
- current_guard=$(printf '%s\0%s' "$updated" "$current_body" | sha256sum | awk '{print $1}')
- local -a update_args=(bd update "$id")
- [ -z "$title" ] || update_args+=(--title "$title")
- [ -z "$type" ] || update_args+=(--type "$type")
- if [ "$have_body" -eq 1 ]; then
- [ -n "$guard" ] || usage_error 'clerk inbox update: replacing the body requires --body-guard from clerk inbox show --json'
- [ "$guard" = "$current_guard" ] || usage_error 'clerk inbox update: stale body guard — rerun clerk inbox show --json and retry'
- if [ -n "$body_file" ]; then
- [ -f "$body_file" ] || usage_error "clerk inbox update: body file not found: $body_file"
- body=$(cat "$body_file")
- else
- body=$(cat)
- fi
- update_args+=(--description "$body" --allow-empty-description)
- fi
- "${update_args[@]}" >/dev/null || backend_fail "inbox update failed — bd update did not succeed for $id"
- printf '%sclerk:%s updated %s\n' "$C_GRN" "$C_RST" "$id"
-}
-
-cmd_inbox_resolve() {
- local _backend="$1" _root="$2" id="${3:-}" text ts
- shift 2
- id="${1:-}"; [ -n "$id" ] || usage_error 'clerk inbox resolve: missing id — usage: clerk inbox resolve [--file |--stdin]'
- shift
- local obj
- obj=$(bd_issue_json_or_usage 'clerk inbox resolve' "$id")
- issue_json_is_active_inbox "$obj" || usage_error "clerk inbox resolve: $id must be an open inbox item (not ready/promoted/closed)"
- local holder me
- holder=$(printf '%s' "$obj" | jq -r '.assignee // ""')
- me=$(claim_current_actor "$_root")
- if [ -n "$holder" ] && [ "$holder" != "$me" ]; then
- printf 'clerk: inbox resolve refused — %s is claimed by %s\n' "$id" "$holder" >&2
- exit 5
- fi
- issue_has_open_blockers "$id" && usage_error "clerk inbox resolve: $id has open blockers — resolve blockers first"
- issue_has_open_children "$id" && usage_error "clerk inbox resolve: $id has open children — resolve or reparent children first"
- text=$(read_nonempty_text_arg 'clerk inbox resolve' "$@")
- ts=$(date -u +%Y-%m-%dT%H:%M:%SZ)
- bd update "$id" --append-notes "clerk-resolution: $ts"$'\n'"$text" >/dev/null || backend_fail "inbox resolve failed — could not append resolution note for $id"
- bd close "$id" --reason resolved >/dev/null || backend_fail "inbox resolve failed — bd close did not succeed for $id"
- [ "$(bd_issue_json_or_usage 'clerk inbox resolve' "$id" | jq -r '.status // ""')" = closed ] || backend_fail "inbox resolve failed — $id was not confirmed closed"
- printf '%sclerk:%s resolved %s\n' "$C_GRN" "$C_RST" "$id"
-}
-
-# ------------------------------------------------------------------ backlog ----
-# unit dotfiles-dft.3 plus dotfiles-db4n: read-only windows onto refined-ready work.
-# `stage:ready` means refinement-complete; pickability is computed here as open + ready +
-# unclaimed + no open blockers + no open direct children. `backlog next` shows only pickable
-# items; `backlog waiting` shows ready items withheld by graph state.
-
-backlog_pickable_filter_jq='
- def edge_type: (.dependency_type // .type // "");
- def open_blockers: [(.dependencies // [])[] | select(edge_type == "blocks" and ((.status // "open") != "closed"))];
- def open_children: [(.dependents // [])[] | select(edge_type == "parent-child" and ((.status // "open") != "closed"))];
- map(select(.status == "open"
- and (((.labels // []) | index("stage:ready")) != null)
- and ((.assignee // "") == "")
- and ((open_blockers | length) == 0)
- and ((open_children | length) == 0)))'
-
-backlog_waiting_filter_jq='
- def edge_type: (.dependency_type // .type // "");
- def open_blockers: [(.dependencies // [])[] | select(edge_type == "blocks" and ((.status // "open") != "closed"))];
- def open_children: [(.dependents // [])[] | select(edge_type == "parent-child" and ((.status // "open") != "closed"))];
- map(select(.status == "open"
- and (((.labels // []) | index("stage:ready")) != null)
- and ((.assignee // "") == "")
- and (((open_blockers | length) + (open_children | length)) > 0))
- | {id,title,blockers:(open_blockers | length),children:(open_children | length)})'
-
-backlog_bd_ready_unclaimed_details_json() { # echoes JSON array of bd show objects for open ready unassigned candidates
- local list id obj tmp
- if ! list=$(bd list --status open --label stage:ready --no-assignee --readonly --json); then
- return 1
- fi
- tmp=$(mktemp)
- while IFS= read -r id; do
- [ -n "$id" ] || continue
- obj=$(bd show "$id" --readonly --json 2>/dev/null | jq -c '.[0]' 2>/dev/null) || { rm -f "$tmp"; return 1; }
- printf '%s\n' "$obj" >>"$tmp"
- done < <(printf '%s' "$list" | jq -r '.[].id')
- jq -s . "$tmp"
- rm -f "$tmp"
-}
-
-backlog_bd_pickability_reason() { # $1=id; echoes reason text iff not pickable
- local id="$1" obj status holder blockers children has_label reason=""
- obj=$(bd_issue_json_or_usage 'clerk backlog pickability' "$id")
- status=$(printf '%s' "$obj" | jq -r '.status // ""')
- holder=$(printf '%s' "$obj" | jq -r '.assignee // ""')
- has_label=$(printf '%s' "$obj" | jq -r '((.labels // []) | index("stage:ready")) != null')
- blockers=$(printf '%s' "$obj" | jq '[ (.dependencies // [])[] | select(.dependency_type == "blocks" and ((.status // "open") != "closed")) ] | length')
- children=$(printf '%s' "$obj" | jq '[ (.dependents // [])[] | select(.dependency_type == "parent-child" and ((.status // "open") != "closed")) ] | length')
- [ "$status" = open ] || reason="${reason:+$reason, }status is $status"
- [ "$has_label" = true ] || reason="${reason:+$reason, }not stage:ready"
- [ -z "$holder" ] || reason="${reason:+$reason, }claimed by $holder"
- [ "$blockers" -eq 0 ] || reason="${reason:+$reason, }$blockers open blocker(s)"
- [ "$children" -eq 0 ] || reason="${reason:+$reason, }$children open child(ren)"
- printf '%s' "$reason"
-}
-
-backlog_refuse_not_pickable() { # $1=verb $2=id $3=reason
- local verb="$1" id="$2" reason="$3"
- usage_error "clerk backlog $verb: $id is not pickable — $reason"
-}
-
-# clerk backlog next — the pickable ready pool: open + stage:ready + unclaimed + no open blockers
-# + no open direct children. gh's ready-for-agent label is the near-passthrough analogue.
-cmd_backlog_next() {
- local backend="$1"
- shift 2
- case "$backend" in
- bd)
- local json pickable
- if ! json=$(backlog_bd_ready_unclaimed_details_json); then
- backend_fail "backlog next failed — bd list/show did not succeed"
- fi
- pickable=$(printf '%s' "$json" | jq "$backlog_pickable_filter_jq")
- local count
- count=$(printf '%s' "$pickable" | jq 'length')
- printf 'Backlog (ready) — %s item(s):\n' "$count"
- if [ "$count" -eq 0 ]; then
- printf ' (empty)\n'
- return 0
- fi
- printf '%s' "$pickable" | jq -r '.[] | " \(.id) \(.title)"'
- ;;
- gh)
- local json
- if ! json=$(gh issue list --label ready-for-agent --json number,title); then
- backend_fail "backlog next failed — gh issue list did not succeed"
- fi
- local count
- count=$(printf '%s' "$json" | jq 'length')
- printf 'Backlog (ready) — %s item(s):\n' "$count"
- if [ "$count" -eq 0 ]; then
- printf ' (empty)\n'
- return 0
- fi
- printf '%s' "$json" | jq -r '.[] | " #\(.number) \(.title)"'
- ;;
- esac
-}
-
-# clerk backlog waiting — read-only view of refined-ready work waiting on graph state.
-cmd_backlog_waiting() {
- local backend="$1"
- shift 2
- case "$backend" in
- bd)
- local json waiting count
- if ! json=$(bd list --all --readonly --json --limit 0); then
- backend_fail "backlog waiting failed — bd list did not succeed"
- fi
- waiting=$(printf '%s' "$json" | jq '
- def edge_type: (.dependency_type // .type // "");
- [ .[] as $work
- | select($work.status == "open"
- and ((($work.labels // []) | index("stage:ready")) != null)
- and (($work.assignee // "") == ""))
- | ([($work.dependencies // [])[] | select(((.dependency_type // .type // "") == "blocks") and ((.status // "open") != "closed"))] | length) as $blockers
- | ([.[] | select((.parent == $work.id) and ((.status // "open") != "closed"))] | length) as $children
- | select(($blockers + $children) > 0)
- | {id: $work.id, title: $work.title, blockers: $blockers, children: $children}
- ]')
- count=$(printf '%s' "$waiting" | jq 'length')
- printf 'Backlog waiting — %s item(s):\n' "$count"
- if [ "$count" -eq 0 ]; then
- printf ' (empty)\n'
- return 0
- fi
- printf '%s' "$waiting" | jq -r '.[] | " \(.id) blockers:\(.blockers) children:\(.children) \(.title)"'
- ;;
- gh)
- printf 'Backlog waiting — 0 item(s):\n (empty)\n'
- ;;
- esac
-}
-
-# clerk backlog show
-cmd_backlog_show() {
- local backend="$1" root="$2"
- shift 2
- local id="${1:-}"
- if [ -z "$id" ]; then
- usage_error 'clerk backlog show: missing id — usage: clerk backlog show '
- fi
- case "$backend" in
- bd)
- bd show "$id" --readonly
- returned_attempt_banner "$root" "$(returned_short_from_id "$id")" "$id" 'backlog claim'
- ;;
- gh)
- gh issue view "$id"
- returned_attempt_banner "$root" "$(returned_short_from_id "$id")" "$id" 'backlog claim'
- ;;
- esac
-}
-
-# unit dotfiles-dft.3: `backlog claim` — provisions the workspace for a ready unit. Resolves
-# the caller's id (short or full) to the project's canonical short token, gates on acceptance
-# criteria (C4, reusing dft.2's structural detector), short-circuits an idempotent re-claim,
-# then uses a first-push-wins git branch (`delivery/`) as the universal CAS lock before
-# recording the claim on the backend (`bd update --claim`) and provisioning
-# `.worktrees/`. Exit 5 here means CLAIM CONFLICT (unit occupied, or the push-CAS race
-# was lost) — distinct from backend_fail's exit 5 (an outright backend failure) — so it is
-# never routed through backend_fail, which would wrongly tell the caller to run `clerk doctor`
-# over a normal contention outcome.
-
-# The identity bd's own `--claim` records as assignee absent an explicit --actor (bd's actor
-# resolution order per `bd update --help`: $BEADS_ACTOR, git user.name, $USER) — mirrored here
-# so re-claim / holder comparisons need no extra bd round-trip.
-claim_current_actor() { # $1=root
- if [ -n "${BEADS_ACTOR:-}" ]; then
- printf '%s\n' "$BEADS_ACTOR"
- return 0
- fi
- local name
- name=$(git -C "$1" config user.name 2>/dev/null)
- if [ -n "$name" ]; then
- printf '%s\n' "$name"
- else
- printf '%s\n' "${USER:-}"
- fi
-}
-
-claim_current_gh_login() {
- gh api user --jq .login 2>/dev/null
-}
-
-# JOB-CONTEXT: env CLERK_JOB non-empty, or CI truthy (anything but unset/empty/a falsy word).
-claim_in_job_context() {
- [ -n "${CLERK_JOB:-}" ] && return 0
- case "${CI:-}" in
- '' | 0 | false | False | FALSE | no | No | NO) return 1 ;;
- *) return 0 ;;
- esac
-}
-
-# Resolves $2 (a bd/gh id, short or full — either form is accepted, ADR 0017) against backend
-# $1. On success sets CLAIM_SHORT/CLAIM_FULL/CLAIM_TITLE/CLAIM_HOLDER/CLAIM_STATUS/
-# CLAIM_DESC/CLAIM_DESIGN/CLAIM_AC and returns 0; on not-found returns 1 and leaves those
-# cleared. Never exits — the caller owns the refusal (usage_error), so this stays safe to call
-# directly (no subshell-swallowed exit).
-claim_resolve_id() {
- local backend="$1" id_arg="$2"
- CLAIM_SHORT="" CLAIM_FULL="" CLAIM_TITLE="" CLAIM_HOLDER="" CLAIM_STATUS="" CLAIM_DESC="" CLAIM_DESIGN="" CLAIM_AC=""
- case "$backend" in
- bd)
- local json
- json=$(bd show "$id_arg" --readonly --json 2>/dev/null)
- # Same not-found shape `inbox ready` guards against (C-e sibling check): bd 1.0.4
- # signals a missing id with an error OBJECT on stdout, not empty output or `null`.
- if [ -z "$json" ] || [ "$json" = null ] ||
- ! printf '%s' "$json" | jq -e 'if type != "array" then false else (length > 0) end' >/dev/null 2>&1; then
- return 1
- fi
- CLAIM_FULL=$(printf '%s' "$json" | jq -r '.[0].id')
- CLAIM_SHORT="${CLAIM_FULL#*-}"
- CLAIM_TITLE=$(printf '%s' "$json" | jq -r '.[0].title // .[0].id')
- CLAIM_STATUS=$(printf '%s' "$json" | jq -r '.[0].status // ""')
- CLAIM_DESC=$(printf '%s' "$json" | jq -r '.[0].description // ""')
- CLAIM_DESIGN=$(printf '%s' "$json" | jq -r '.[0].design // ""')
- CLAIM_AC=$(printf '%s' "$json" | jq -r '.[0].acceptance_criteria // ""')
- CLAIM_HOLDER=$(printf '%s' "$json" | jq -r '.[0].assignee // ""')
- ;;
- gh)
- local json
- json=$(gh issue view "$id_arg" --json number,title,body,assignees 2>/dev/null) || return 1
- CLAIM_FULL=$(printf '%s' "$json" | jq -r '.number')
- CLAIM_SHORT="$CLAIM_FULL"
- CLAIM_TITLE=$(printf '%s' "$json" | jq -r '.title // (.number | tostring)')
- CLAIM_STATUS=$(printf '%s' "$json" | jq -r '.state // ""')
- CLAIM_DESC=$(printf '%s' "$json" | jq -r '.body // ""')
- CLAIM_HOLDER=$(printf '%s' "$json" | jq -r '.assignees[0].login // ""')
- ;;
- esac
- [ -n "$CLAIM_SHORT" ] || return 1
- return 0
-}
-
-# Ensures .worktrees/ exists off local branch delivery/, echoing its absolute
-# path on success and returning 1 (never exiting — see the command-substitution note on
-# claim_resolve_id) on failure. `worktree prune` first: a worktree directory removed by hand
-# (`rm -rf` instead of `git worktree remove`) leaves git believing it is still checked out
-# there, so a bare `add` would otherwise refuse with "missing but already registered".
-claim_ensure_worktree() { # $1=root $2=short
- local root="$1" short="$2"
- local wt="$root/.worktrees/$short"
- if [ -d "$wt" ]; then
- printf '%s\n' "$wt"
- return 0
- fi
- git -C "$root" worktree prune >/dev/null 2>&1
- if git -C "$root" worktree add "$wt" "delivery/$short" >/dev/null 2>&1; then
- printf '%s\n' "$wt"
- return 0
- fi
- # Local branch missing (rare — e.g. bd still shows the claim as yours but the branch was
- # lost) — fall back to a remote copy if the sync-check step found one.
- if git -C "$root" show-ref --verify --quiet "refs/remotes/origin/delivery/$short" &&
- git -C "$root" worktree add -b "delivery/$short" "$wt" "origin/delivery/$short" >/dev/null 2>&1; then
- printf '%s\n' "$wt"
- return 0
- fi
- return 1
-}
-
-# CLAIM CONFLICT (exit 5): unit occupied, or the push-CAS race was lost. Its own prescriptive
-# text (never backend_fail's "run clerk doctor" — the backend is not broken, someone else just
-# got there first).
-# Provision a worktree's host-local Beads state before exposing it to the caller. The
-# tracked config identifies the project; metadata.json is deliberately host-local.
-claim_provision_and_verify_beads() { # $1=root $2=worktree $3=full-id
- local wt="$2" full="$3" source="$1/.beads/metadata.json"
- if [ -f "$wt/.beads/config.yaml" ] && [ ! -f "$wt/.beads/metadata.json" ]; then
- [ -r "$source" ] || return 1
- cp "$source" "$wt/.beads/metadata.json" || return 1
- [ -f "$wt/.beads/metadata.json" ] || return 1
- fi
- (cd "$wt" && bd show "$full" --readonly --json | jq -e --arg id "$full" \
- 'type == "array" and .[0].id == $id' >/dev/null 2>&1)
-}
-
-claim_conflict() { # $1=short $2=holder $3=reason-phrase, e.g. "is already claimed"/"was just claimed"
- local short="$1" holder="${2:-someone else}" reason="$3"
- printf 'clerk: backlog claim refused — delivery/%s %s by %s\n' "$short" "$reason" "$holder" >&2
- printf " wait for %s to release or finish it, or pick a different unit ('clerk backlog next')\n" "$holder" >&2
- exit 5
-}
-
-# bd's online/offline claim record: `--claim` (atomic, idempotent-if-yours), then a mutation
-# self-verify (ADR 0015) before letting the caller report success.
-claim_record_bd() { # $1=root $2=full-id
- local root="$1" full="$2"
- bd update "$full" --claim >/dev/null 2>&1 || return 1
- local check
- check=$(bd show "$full" --readonly --json 2>/dev/null | jq -r '.[0].assignee // ""')
- [ "$check" = "$(claim_current_actor "$root")" ]
-}
-
-claim_returned_ref() { # $1=root $2=short; echoes local/remote canonical returned ref
- local root="$1" short="$2"
- if git -C "$root" show-ref --verify --quiet "refs/heads/returned/$short"; then
- printf 'returned/%s\n' "$short"
- return 0
- fi
- if git -C "$root" show-ref --verify --quiet "refs/remotes/origin/returned/$short"; then
- printf 'origin/returned/%s\n' "$short"
- return 0
- fi
- return 1
-}
-
-claim_replay_returned() { # $1=root $2=worktree $3=short $4=base-sha
- local root="$1" wt="$2" short="$3" base_sha="$4" ref conflicts
- if ! ref=$(claim_returned_ref "$root" "$short"); then
- usage_error "clerk backlog claim: --from-returned requested but returned/$short was not found"
- fi
- if [ -z "$(git -C "$wt" rev-list --reverse "$base_sha..$ref" 2>/dev/null)" ]; then
- return 0
- fi
- if git -C "$wt" cherry-pick "$base_sha..$ref" >/dev/null 2>&1; then
- return 0
- fi
- conflicts=$(git -C "$wt" diff --name-only --diff-filter=U 2>/dev/null | paste -sd ' ' -)
- printf 'clerk: claim --from-returned hit conflicts while replaying returned/%s onto delivery/%s\n' "$short" "$short" >&2
- printf ' resolve in %s, run git cherry-pick --continue, then clerk backlog submit; conflicted paths: %s\n' "$wt" "${conflicts:-unknown}" >&2
- return 2
-}
-
-claim_returned_choice_refusal() { # $1=full-id $2=short
- local full="$1" short="$2"
- printf 'clerk backlog claim: returned/%s exists — choose how to claim\n' "$short" >&2
- printf ' reuse returned work: clerk backlog claim %s --from-returned\n' "$full" >&2
- printf ' start fresh: clerk backlog claim %s --fresh --returned keep|discard\n' "$full" >&2
- return 2
-}
-
-# clerk backlog claim [--from-returned|--fresh [--returned keep|discard]]
-cmd_backlog_claim() {
- local backend="$1" root="$2"
- shift 2
- if [ $# -eq 0 ]; then
- usage_error 'clerk backlog claim: missing id — usage: clerk backlog claim '
- fi
- local id_arg="$1" from_returned=0 fresh=0 returned_disposition=""
- shift
- while [ $# -gt 0 ]; do
- case "$1" in
- --from-returned) from_returned=1 ;;
- --fresh) fresh=1 ;;
- --returned)
- [ $# -ge 2 ] || usage_error 'clerk backlog claim: --returned needs keep or discard'
- returned_disposition="$2"
- shift
- ;;
- *) usage_error "clerk backlog claim: unknown argument '$1' — usage: clerk backlog claim [--from-returned|--fresh --returned keep|discard]" ;;
- esac
- shift
- done
- if [ "$from_returned" -eq 1 ] && [ "$fresh" -eq 1 ]; then
- usage_error 'clerk backlog claim: choose only one of --from-returned or --fresh'
- fi
- if [ "$from_returned" -eq 1 ] && [ -n "$returned_disposition" ]; then
- usage_error 'clerk backlog claim: --returned is only valid with --fresh'
- fi
- if [ "$fresh" -eq 0 ] && [ -n "$returned_disposition" ]; then
- usage_error 'clerk backlog claim: --returned is only valid with --fresh'
- fi
- case "$returned_disposition" in
- "" | keep | discard) ;;
- *) usage_error 'clerk backlog claim: --returned must be keep or discard' ;;
- esac
-
- # 1. Resolve to the canonical short id -----------------------------------------
- if ! claim_resolve_id "$backend" "$id_arg"; then
- usage_error "clerk backlog claim: $id_arg not found — check the id ('clerk backlog next' shows ready units)"
- fi
- local short="$CLAIM_SHORT" full="$CLAIM_FULL" holder="$CLAIM_HOLDER"
-
- # 2. C4 GATE (ADR 0016): presence-only structural check — never a quality judgment.
- if [ -z "$CLAIM_AC" ] && ! has_acceptance_criteria_section "$CLAIM_DESC"$'\n'"$CLAIM_DESIGN"; then
- usage_error "clerk backlog claim: $full has no 'Acceptance Criteria' section — it needs a grill pass first (e.g. 'clerk inbox pregrill $full', then add the section) before it can be claimed"
- fi
-
- # 3. RE-CLAIM short-circuit: backend assignee already you, or a local branch you hold —
- # no network touched, so this works offline too.
- local me=""
- case "$backend" in
- bd) me=$(claim_current_actor "$root") ;;
- gh) me=$(claim_current_gh_login) ;;
- esac
- local mine=0
- if [ -n "$holder" ] && [ -n "$me" ] && [ "$holder" = "$me" ]; then
- mine=1
- fi
- if git -C "$root" show-ref --verify --quiet "refs/heads/delivery/$short"; then
- mine=1
- fi
- if [ "$mine" -eq 1 ]; then
- local wt
- if ! wt=$(claim_ensure_worktree "$root" "$short"); then
- backend_fail "claim failed — could not provision the worktree at $root/.worktrees/$short for delivery/$short"
- fi
- if [ "$backend" = bd ] && ! claim_provision_and_verify_beads "$root" "$wt" "$full"; then
- backend_fail "claim failed — could not provision or verify the worktree at $wt"
- fi
- printf '%sclerk:%s %s already claimed by you — worktree ready\n' "$C_GRN" "$C_RST" "$full"
- printf '%s\n' "$wt"
- return 0
- fi
- if [ -n "$holder" ]; then
- claim_conflict "$short" "$holder" 'is already claimed'
- fi
- if [ "$backend" = bd ]; then
- local not_pickable
- not_pickable=$(backlog_bd_pickability_reason "$full")
- [ -z "$not_pickable" ] || backlog_refuse_not_pickable claim "$full" "$not_pickable"
- fi
-
- # 4. SYNC-CHECK: `git fetch origin`'s failure (bounded by a short timeout, so an
- # unreachable remote refuses promptly instead of hanging the claim) is the OFFLINE signal.
- local offline=0 base_sha=""
- if ! (GIT_TERMINAL_PROMPT=0 timeout 10 git -C "$root" fetch origin >/dev/null 2>&1); then
- offline=1
- fi
-
- local has_returned=0
- if claim_returned_ref "$root" "$short" >/dev/null; then
- has_returned=1
- fi
- if [ "$from_returned" -eq 1 ] && [ "$has_returned" -eq 0 ]; then
- usage_error "clerk backlog claim: --from-returned requested but returned/$short was not found"
- fi
- if [ "$has_returned" -eq 1 ] && [ "$from_returned" -eq 0 ]; then
- if [ "$fresh" -eq 0 ] || [ -z "$returned_disposition" ]; then
- claim_returned_choice_refusal "$full" "$short"
- return 2
- fi
- fi
-
- if [ "$offline" -eq 1 ]; then
- if claim_in_job_context; then
- printf "clerk: OFFLINE in a job context - refusing %s: the claim lock needs the remote and no attendant can accept the staleness hazard. Retry when origin is reachable.\n" "$short" >&2
- return 2
- fi
- # ATTENDED: proceed locally-only — the branch is the lock, CAS'd at first reconnect.
- if ! git -C "$root" show-ref --verify --quiet refs/heads/main; then
- backend_fail "claim failed — no local 'main' branch to base delivery/$short on"
- fi
- base_sha=$(git -C "$root" rev-parse main 2>/dev/null) ||
- backend_fail "claim failed — could not resolve local main for delivery/$short"
- if ! git -C "$root" branch "delivery/$short" main 2>/dev/null; then
- backend_fail "claim failed — could not create local branch delivery/$short from main"
- fi
- if [ "$backend" = bd ] && ! claim_record_bd "$root" "$full"; then
- backend_fail "claim failed — delivery/$short was created locally but the bd claim did not confirm for $full"
- fi
- local wt
- if ! wt=$(claim_ensure_worktree "$root" "$short"); then
- backend_fail "claim failed — could not provision the worktree at $root/.worktrees/$short for delivery/$short"
- fi
- if [ "$backend" = bd ] && ! claim_provision_and_verify_beads "$root" "$wt" "$full"; then
- backend_fail "claim failed — could not provision or verify the worktree at $wt"
- fi
- if [ "$from_returned" -eq 1 ]; then
- claim_replay_returned "$root" "$wt" "$short" "$base_sha" || return $?
- elif [ "$fresh" -eq 1 ] && [ "$returned_disposition" = discard ]; then
- dispose_returned "$root" "$short"
- fi
- printf "clerk: OFFLINE - 'delivery/%s' 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 %s meanwhile, that push wins and this local work is discarded. Proceeding, attended.\n" "$short" "$short" >&2
- printf '%s\n' "$wt"
- return 0
- fi
-
- # ONLINE: occupied? (holder was already read fresh in step 1, before any of this ran)
- if git -C "$root" show-ref --verify --quiet "refs/remotes/origin/delivery/$short"; then
- claim_conflict "$short" "$holder" 'is already claimed'
- fi
-
- # 5. PUSH = the universal CAS lock (first-push-wins). Pushed from a raw SHA, not a local
- # branch, so a lost race leaves nothing local to clean up (no orphan worktree/claim).
- base_sha=$(git -C "$root" rev-parse origin/main 2>/dev/null) || base_sha=$(git -C "$root" rev-parse main 2>/dev/null)
- if [ -z "$base_sha" ]; then
- backend_fail "claim failed — could not resolve a base commit (origin/main or main) for delivery/$short"
- fi
- if ! git -C "$root" push origin "$base_sha:refs/heads/delivery/$short" 2>/dev/null; then
- git -C "$root" fetch origin >/dev/null 2>&1
- claim_conflict "$short" "$holder" 'was just claimed'
- fi
-
- # 6+7. Record the win locally (branch), then on the backend, then provision the worktree.
- if ! git -C "$root" branch "delivery/$short" "$base_sha" 2>/dev/null; then
- backend_fail "claim failed — delivery/$short is pushed but the local branch could not be created"
- fi
- git -C "$root" branch --set-upstream-to="origin/delivery/$short" "delivery/$short" >/dev/null 2>&1 || true
-
- case "$backend" in
- bd)
- if ! claim_record_bd "$root" "$full"; then
- backend_fail "claim failed — delivery/$short is pushed but the bd claim did not confirm for $full"
- fi
- ;;
- gh)
- local login
- login=$(claim_current_gh_login)
- [ -n "$login" ] && gh issue edit "$full" --add-assignee "$login" >/dev/null 2>&1
- ;;
- esac
-
- local wt
- if ! wt=$(claim_ensure_worktree "$root" "$short"); then
- backend_fail "claim failed — could not provision the worktree at $root/.worktrees/$short for delivery/$short"
- fi
- if [ "$backend" = bd ] && ! claim_provision_and_verify_beads "$root" "$wt" "$full"; then
- backend_fail "claim failed — could not provision or verify the worktree at $wt"
- fi
- if [ "$from_returned" -eq 1 ]; then
- claim_replay_returned "$root" "$wt" "$short" "$base_sha" || return $?
- elif [ "$fresh" -eq 1 ] && [ "$returned_disposition" = discard ]; then
- dispose_returned "$root" "$short"
- fi
-
- # 8. Print the absolute worktree path as the LAST stdout line.
- printf '%sclerk:%s claimed %s — delivery/%s pushed, worktree ready\n' "$C_GRN" "$C_RST" "$full" "$short"
- printf '%s\n' "$wt"
- return 0
-}
-
-# clerk backlog resolve [--returned keep|discard] [--file |--stdin]
-cmd_backlog_resolve() {
- local backend="$1" root="$2"
- shift 2
- local id="${1:-}"
- [ -n "$id" ] || usage_error 'clerk backlog resolve: missing id — usage: clerk backlog resolve [--returned keep|discard] [--file |--stdin]'
- shift
- local returned_disposition="" input_args=()
- while [ $# -gt 0 ]; do
- case "$1" in
- --returned)
- [ $# -ge 2 ] || usage_error 'clerk backlog resolve: --returned needs keep or discard'
- returned_disposition="$2"; shift
- ;;
- --file | --stdin)
- input_args+=("$1")
- if [ "$1" = --file ]; then
- [ $# -ge 2 ] || usage_error 'clerk backlog resolve: --file needs a path'
- input_args+=("$2"); shift
- fi
- ;;
- *) usage_error "clerk backlog resolve: unknown argument '$1' — usage: clerk backlog resolve [--returned keep|discard] [--file |--stdin]" ;;
- esac
- shift
- done
- case "$returned_disposition" in "" | keep | discard) ;; *) usage_error 'clerk backlog resolve: --returned must be keep or discard' ;; esac
-
- case "$backend" in
- bd)
- if ! claim_resolve_id "$backend" "$id"; then
- usage_error "clerk backlog resolve: $id not found — check the id ('clerk backlog next' shows ready units)"
- fi
- local full="$CLAIM_FULL" short="$CLAIM_SHORT" not_pickable text ts status close_reason
- if [ -z "$CLAIM_AC" ] && ! has_acceptance_criteria_section "$CLAIM_DESC"$'\n'"$CLAIM_DESIGN"; then
- usage_error "clerk backlog resolve: $full has no 'Acceptance Criteria' section — it needs a grill pass before no-code resolution"
- fi
- not_pickable=$(backlog_bd_pickability_reason "$full")
- if git -C "$root" show-ref --verify --quiet "refs/heads/delivery/$short" || git -C "$root" show-ref --verify --quiet "refs/remotes/origin/delivery/$short"; then
- not_pickable="${not_pickable:+$not_pickable, }claimed by delivery/$short"
- fi
- [ -z "$not_pickable" ] || backlog_refuse_not_pickable resolve "$full" "$not_pickable"
- handle_returned_disposition 'backlog resolve' "$root" "$short" "$returned_disposition"
- text=$(read_nonempty_text_arg 'clerk backlog resolve' "${input_args[@]+"${input_args[@]}"}")
- local text_rc=$?
- [ "$text_rc" -eq 0 ] || exit "$text_rc"
- ts=$(date -u +%Y-%m-%dT%H:%M:%SZ)
- bd update "$full" --append-notes "clerk-backlog-resolution: $ts"$'\n'"$text" >/dev/null || backend_fail "backlog resolve failed — could not append resolution note for $full"
- bd close "$full" --reason 'resolved without delivery' >/dev/null || backend_fail "backlog resolve failed — bd close did not succeed for $full"
- status=$(bd_issue_json_or_usage 'clerk backlog resolve' "$full" | jq -r '.status // ""')
- close_reason=$(bd_issue_json_or_usage 'clerk backlog resolve' "$full" | jq -r '.close_reason // ""')
- [ "$status" = closed ] && [ "$close_reason" = 'resolved without delivery' ] || backend_fail "backlog resolve failed — $full was not confirmed closed as resolved without delivery"
- printf '%sclerk:%s resolved %s without delivery\n' "$C_GRN" "$C_RST" "$full"
- ;;
- gh)
- not_implemented 'backlog resolve (gh)'
- ;;
- esac
-}
-
-# unit dotfiles-dft.3 (this group): `backlog release` and `backlog return` — the two ways to
-# give a claim back. `release` is the no-verdict path (unit stays exactly as ready as it
-# was); `return` is the verdict path (the unit could not be fulfilled as designed, so it goes
-# back to discovery with a mandatory, verbatim-preserved reason). Both reuse
-# `claim_resolve_id`/`claim_current_actor`/`claim_current_gh_login`/`claim_in_job_context`
-# from `backlog claim` above rather than re-deriving id/holder/offline logic.
-
-# True (exit 0) iff the caller already holds this unit's claim from here — either the
-# backend-recorded holder is them, or a local delivery/ branch exists. Mirrors
-# `cmd_backlog_claim`'s own "already yours" test (step 3 there) so release/return agree with
-# claim about what "held" means, without claim having to expose its internals for reuse.
-backlog_is_mine() { # $1=backend $2=root $3=short $4=holder
- local backend="$1" root="$2" short="$3" holder="$4" me=""
- case "$backend" in
- bd) me=$(claim_current_actor "$root") ;;
- gh) me=$(claim_current_gh_login) ;;
- esac
- if [ -n "$holder" ] && [ -n "$me" ] && [ "$holder" = "$me" ]; then
- return 0
- fi
- git -C "$root" show-ref --verify --quiet "refs/heads/delivery/$short"
-}
-
-# Commits sitting on delivery/ beyond its base — the signal `release` uses to tell "a
-# clean claim, safe to fold up" from "unsubmitted work, do not discard it silently". The base
-# MUST agree with what `cmd_backlog_claim` actually built delivery/ from: claim pushes
-# it from origin/main (falling back to local main only when origin/main is unresolvable), so
-# release measures against the same ref — never bare local `main`, which routinely lags
-# origin/main and would miscount a clean claim as "carrying work" (dotfiles-dft.3 review).
-# Echoes 0 (never errors) when the branch does not exist, so callers need no extra guard.
-delivery_ahead_count() { # $1=root $2=short
- local root="$1" short="$2" base=main
- if git -C "$root" show-ref --verify --quiet refs/remotes/origin/main; then
- base=origin/main
- fi
- git -C "$root" rev-list --count "$base..delivery/$short" 2>/dev/null || printf '0'
-}
-
-# clerk backlog release — give the claim back without finishing (ADR 0015): only claim
-# state moves here, never triage state, so stage:ready is left exactly as it was. Refuses if
-# delivery/ carries commits beyond main — that is real work, and a silent release must
-# never be how it gets discarded — pointing the caller at `submit` (save it) or `return`
-# (abandon it on purpose, with a lesson) instead. Idempotent: releasing a unit not claimed
-# here reports cleanly (exit 0) rather than erroring, the same way `claim`'s own re-claim
-# short-circuit treats "already in the state you asked for" as success. Offline mirrors
-# `claim`'s SYNC-CHECK: local teardown proceeds attended (only the remote branch delete is
-# deferred to the next sync); a job context refuses outright, the same staleness hazard
-# `claim` refuses on.
-cmd_backlog_release() {
- local backend="$1" root="$2"
- shift 2
- if [ $# -eq 0 ]; then
- usage_error 'clerk backlog release: missing id — usage: clerk backlog release '
- fi
- local id_arg="$1"
- shift
- if [ $# -gt 0 ]; then
- usage_error "clerk backlog release: unknown argument '$1' — usage: clerk backlog release "
- fi
-
- if ! claim_resolve_id "$backend" "$id_arg"; then
- usage_error "clerk backlog release: $id_arg not found — check the id ('clerk backlog next' shows ready units)"
- fi
- local short="$CLAIM_SHORT" full="$CLAIM_FULL" holder="$CLAIM_HOLDER"
-
- if ! backlog_is_mine "$backend" "$root" "$short" "$holder"; then
- printf '%sclerk:%s %s is not claimed here (no local delivery/%s) — nothing to release\n' "$C_GRN" "$C_RST" "$full" "$short"
- return 0
- fi
-
- # SYNC-CHECK (mirrors claim), run BEFORE the ahead-count check below: a reachable origin
- # refreshes the same origin/main ref `cmd_backlog_claim` based delivery/ on, so a
- # clean claim is never miscounted as "carrying work" just because local `main` has drifted
- # behind origin/main (dotfiles-dft.3 review).
- local offline=0
- if ! (GIT_TERMINAL_PROMPT=0 timeout 10 git -C "$root" fetch origin >/dev/null 2>&1); then
- offline=1
- fi
-
- local ahead
- ahead=$(delivery_ahead_count "$root" "$short")
- if [ "$ahead" -gt 0 ]; then
- printf 'clerk: backlog release refused — delivery/%s has %s commit(s) beyond main\n' "$short" "$ahead" >&2
- printf " run 'clerk backlog submit %s' to save the work, or 'clerk backlog return %s --reason \"\"' to abandon it\n" "$full" "$full" >&2
- return 2
- fi
-
- if [ "$offline" -eq 1 ] && claim_in_job_context; then
- printf "clerk: OFFLINE in a job context - refusing to release %s: the remote teardown needs origin and no attendant can accept the staleness hazard. Retry when origin is reachable.\n" "$short" >&2
- return 2
- fi
-
- # Worktree removal is the fail-prone step (git refuses on any uncommitted/untracked file)
- # so it MUST run before any remote mutation: deleting the origin branch first and then
- # failing here would release the CAS lock while this side still holds the local
- # branch/worktree/bd claim — the exact double-claim the lock exists to prevent
- # (dotfiles-dft.3 review). It also must precede the local branch delete: git refuses to
- # delete a branch checked out in a linked worktree.
- local wt="$root/.worktrees/$short"
- if [ -d "$wt" ]; then
- if ! git -C "$root" worktree remove "$wt" 2>/dev/null; then
- backend_fail "release failed — could not remove the worktree at $wt (commit or stash local changes first)"
- fi
- else
- git -C "$root" worktree prune >/dev/null 2>&1
- fi
-
- if [ "$offline" -eq 0 ] && git -C "$root" show-ref --verify --quiet "refs/remotes/origin/delivery/$short"; then
- if ! git -C "$root" push origin --delete "delivery/$short" >/dev/null 2>&1; then
- backend_fail "release failed — could not delete origin delivery/$short"
- fi
- fi
-
- if git -C "$root" show-ref --verify --quiet "refs/heads/delivery/$short"; then
- if ! git -C "$root" branch -D "delivery/$short" >/dev/null 2>&1; then
- backend_fail "release failed — could not delete local branch delivery/$short"
- fi
- fi
-
- case "$backend" in
- bd)
- if ! bd update "$full" --status open --assignee "" >/dev/null; then
- backend_fail "release failed — bd update did not succeed for $full"
- fi
- # mutation self-verify (ADR 0015)
- local json status assignee
- json=$(bd show "$full" --readonly --json 2>/dev/null)
- status=$(printf '%s' "$json" | jq -r '.[0].status // ""')
- assignee=$(printf '%s' "$json" | jq -r '.[0].assignee // ""')
- if [ "$status" != open ] || [ -n "$assignee" ]; then
- backend_fail "release failed — $full was not confirmed open/unassigned after release"
- fi
- ;;
- gh)
- local login
- login=$(claim_current_gh_login)
- [ -n "$login" ] && gh issue edit "$full" --remove-assignee "$login" >/dev/null 2>&1
- ;;
- esac
-
- if [ "$offline" -eq 1 ]; then
- printf 'clerk: OFFLINE - delivery/%s deleted locally only; the remote branch delete is deferred to sync (clerk claim/sync will finish it at the next reconnect).\n' "$short" >&2
- fi
- printf '%sclerk:%s released %s — delivery/%s torn down, unit reopened (stage:ready kept)\n' "$C_GRN" "$C_RST" "$full" "$short"
- return 0
-}
-
-# clerk backlog return --reason "" — verdict: the unit cannot be fulfilled as
-# designed (ADR 0016's counterpart to `submit`'s C4 evidence path). Unlike `release`, this
-# never discards anything: delivery/ is renamed to returned/ so the attempt
-# survives as grill evidence (`sync`/`finish` must never touch returned/* — only a grill,
-# once it has extracted the lesson, deletes it). The reason is mandatory and is filed
-# verbatim as an impediment-typed capture (reusing dft.2's `bd_ensure_impediment_type`/
-# `--type impediment` path) so it re-enters the ordinary inbox pipeline instead of sitting as
-# free-floating prose on the reopened unit.
-archive_existing_returned() { # $1=main-root $2=short $3=offline(0|1)
- local main_root="$1" short="$2" offline="$3" prior_sha archive
- if ! git -C "$main_root" show-ref --verify --quiet "refs/heads/returned/$short"; then
- if git -C "$main_root" show-ref --verify --quiet "refs/remotes/origin/returned/$short"; then
- git -C "$main_root" branch "returned/$short" "origin/returned/$short" >/dev/null 2>&1 ||
- backend_fail "return failed — could not materialize origin/returned/$short for archiving"
- else
- return 0
- fi
- fi
- prior_sha=$(git -C "$main_root" rev-parse --short "returned/$short") ||
- backend_fail "return failed — could not resolve returned/$short before archiving"
- archive="returned/$short-$prior_sha"
- git -C "$main_root" branch -M "returned/$short" "$archive" >/dev/null 2>&1 ||
- backend_fail "return failed — could not archive returned/$short as $archive"
- if [ "$offline" -eq 0 ]; then
- git -C "$main_root" push origin "$archive" >/dev/null 2>&1 ||
- backend_fail "return failed — could not push $archive to origin"
- if git -C "$main_root" show-ref --verify --quiet "refs/remotes/origin/returned/$short"; then
- git -C "$main_root" push origin --delete "returned/$short" >/dev/null 2>&1 ||
- backend_fail "return failed — could not delete origin returned/$short before replacing it"
- git -C "$main_root" update-ref -d "refs/remotes/origin/returned/$short" >/dev/null 2>&1 || true
- fi
- fi
-}
-
-cmd_backlog_return() {
- local backend="$1" root="$2"
- shift 2
- if [ $# -eq 0 ]; then
- usage_error 'clerk backlog return: missing id — usage: clerk backlog return --reason ""'
- fi
- local id_arg="$1"
- shift
- local reason=""
- while [ $# -gt 0 ]; do
- case "$1" in
- --reason)
- [ $# -ge 2 ] || usage_error "clerk backlog return: --reason needs a value"
- reason="$2"
- shift
- ;;
- *) usage_error "clerk backlog return: unknown argument '$1' — usage: clerk backlog return --reason \"\"" ;;
- esac
- shift
- done
- if [ -z "$reason" ]; then
- usage_error "clerk backlog return: missing --reason — usage: clerk backlog return $id_arg --reason \"\""
- fi
-
- if ! claim_resolve_id "$backend" "$id_arg"; then
- usage_error "clerk backlog return: $id_arg not found — check the id ('clerk backlog next' shows ready units)"
- fi
- local short="$CLAIM_SHORT" full="$CLAIM_FULL" main_root
- main_root=$(primary_repo_root "$root")
-
- if ! git -C "$main_root" show-ref --verify --quiet "refs/heads/delivery/$short"; then
- usage_error "clerk backlog return: no local delivery/$short — claim it first ('clerk backlog claim $full')"
- fi
-
- # SYNC-CHECK (mirrors claim): fetch's failure within a short timeout is the OFFLINE signal.
- local offline=0
- if ! (GIT_TERMINAL_PROMPT=0 timeout 10 git -C "$main_root" fetch origin >/dev/null 2>&1); then
- offline=1
- fi
-
- if [ "$offline" -eq 1 ] && claim_in_job_context; then
- printf "clerk: OFFLINE in a job context - refusing to return %s: preserving the branch needs origin and no attendant can accept the staleness hazard. Retry when origin is reachable.\n" "$short" >&2
- return 2
- fi
-
- local sha
- sha=$(git -C "$main_root" rev-parse "delivery/$short")
-
- # The checkout itself is disposable — the worktree only ever pointed at the branch, which
- # will go on living as returned/ regardless. Removal is the fail-prone step (git
- # refuses on any uncommitted/untracked file), so it MUST run BEFORE the rename/remote
- # mutation below: doing the rename+push first and failing here would half-return the unit —
- # delivery/ gone, returned/ live, but the unit never reopened, stage:ready
- # never stripped, and the mandatory reason never filed, with no way to re-run return
- # (dotfiles-dft.3 review). Running it first means a failure here leaves delivery/
- # completely untouched — fix the worktree, rerun `return` normally.
- local wt="$main_root/.worktrees/$short"
- # If return is invoked from inside the disposable worktree, leave that cwd before removing
- # it; all following git operations must use the primary checkout because the linked
- # worktree path may no longer exist after this point.
- cd "$main_root" || backend_fail "return failed — could not cd to $main_root before cleanup"
- if [ -d "$wt" ]; then
- if ! git -C "$main_root" worktree remove "$wt" 2>/dev/null; then
- backend_fail "return failed — could not remove the worktree at $wt (commit or stash local changes first)"
- fi
- else
- git -C "$main_root" worktree prune >/dev/null 2>&1
- fi
-
- # PRESERVE THE ATTEMPT: rename, never delete — the commits are the grill evidence.
- # If a previous returned attempt exists, archive it first so the new return can take the
- # canonical returned/ name without discarding any evidence.
- archive_existing_returned "$main_root" "$short" "$offline"
- if ! git -C "$main_root" branch -m "delivery/$short" "returned/$short" 2>/dev/null; then
- backend_fail "return failed — could not rename delivery/$short to returned/$short"
- fi
-
- if [ "$offline" -eq 0 ]; then
- if ! git -C "$main_root" push origin "returned/$short" >/dev/null 2>&1; then
- backend_fail "return failed — could not push returned/$short to origin"
- fi
- if git -C "$main_root" show-ref --verify --quiet "refs/remotes/origin/delivery/$short"; then
- if ! git -C "$main_root" push origin --delete "delivery/$short" >/dev/null 2>&1; then
- backend_fail "return failed — could not delete origin delivery/$short"
- fi
- fi
- fi
-
- case "$backend" in
- bd)
- if ! bd update "$full" --status open --remove-label stage:ready --assignee "" >/dev/null; then
- backend_fail "return failed — bd update did not succeed for $full"
- fi
- # mutation self-verify (ADR 0015)
- local json status has_label
- json=$(bd show "$full" --readonly --json 2>/dev/null)
- status=$(printf '%s' "$json" | jq -r '.[0].status // ""')
- has_label=$(printf '%s' "$json" | jq -r '(.[0].labels // []) | index("stage:ready")')
- if [ "$status" != open ] || [ "$has_label" != null ]; then
- backend_fail "return failed — $full was not confirmed open/not-ready after return"
- fi
- ;;
- gh)
- gh issue reopen "$full" >/dev/null 2>&1
- gh issue edit "$full" --remove-label ready-for-agent >/dev/null 2>&1
- local login
- login=$(claim_current_gh_login)
- [ -n "$login" ] && gh issue edit "$full" --remove-assignee "$login" >/dev/null 2>&1
- ;;
- esac
-
- # The reason capture: verbatim reason, plus the delivery/evidence trail back to
- # returned/ (ADR 0016 — this is the grill's raw material, so nothing is summarized).
- local body
- body="$reason"$'\n\n'"returned from delivery of $full"$'\n'"evidence: returned/$short @ $sha"
- local capture_id=""
- case "$backend" in
- bd)
- bd_ensure_impediment_type
- if ! capture_id=$(bd create "backlog return: $full" --description "$body" --type impediment --silent); then
- backend_fail "return failed — could not file the reason capture for $full"
- fi
- local seen
- seen=$(bd show "$capture_id" --readonly --json 2>/dev/null | jq -r '.[0].id // empty')
- if [ "$seen" != "$capture_id" ]; then
- backend_fail "return failed — reason capture $capture_id was not confirmed after filing"
- fi
- ;;
- gh)
- if ! capture_id=$(gh issue create --title "backlog return: $full" --body "$body" --label type:impediment 2>/dev/null); then
- backend_fail "return failed — could not file the reason capture for $full"
- fi
- ;;
- esac
-
- if [ "$offline" -eq 1 ]; then
- printf 'clerk: OFFLINE - returned/%s created locally only; pushing it and deleting delivery/%s on origin is deferred to sync (clerk claim/sync will finish it at the next reconnect).\n' "$short" "$short" >&2
- fi
- printf '%sclerk:%s returned %s — returned/%s preserved, reopened, reason filed as %s\n' "$C_GRN" "$C_RST" "$full" "$short" "$capture_id"
- return 0
-}
-
-# ------------------------------------------------------ submit + gate (dft.4) ----
-
-GATE_FAILED=0
-GATE_FAILURES=""
-
-gate_fail() { # $1 = already-prefixed failure line
- GATE_FAILED=1
- GATE_FAILURES="${GATE_FAILURES} $1
-"
-}
-
-gate_finish() {
- if [ "$GATE_FAILED" -eq 0 ]; then
- printf '%sclerk:%s delivery gate passed\n' "$C_GRN" "$C_RST"
- return 0
- fi
- printf 'clerk: delivery gate failed\n' >&2
- printf '%s' "$GATE_FAILURES" >&2
- return 6
-}
-
-extract_acceptance_section() {
- awk '
- BEGIN { in_section = 0 }
- /^[[:space:]]{0,3}#{1,6}[[:space:]]*[Aa][Cc][Cc][Ee][Pp][Tt][Aa][Nn][Cc][Ee][[:space:]]+[Cc][Rr][Ii][Tt][Ee][Rr][Ii][Aa][[:space:]]*$/ || /^[[:space:]]*[Aa][Cc][Cc][Ee][Pp][Tt][Aa][Nn][Cc][Ee][[:space:]]+[Cc][Rr][Ii][Tt][Ee][Rr][Ii][Aa]:?[[:space:]]*$/ { in_section = 1; next }
- in_section && /^[[:space:]]{0,3}#{1,6}[[:space:]]+/ { in_section = 0 }
- in_section { print }
- ' <<<"$1"
-}
-
-criteria_bullets_from_text() {
- awk '
- function trim(s) {
- sub(/^[[:space:]]+/, "", s)
- sub(/[[:space:]]+$/, "", s)
- return s
- }
- function emit(s) {
- s = trim(s)
- if (s != "") {
- print "- " s
- seen = 1
- }
- }
- /^[[:space:]]{0,3}#{1,6}[[:space:]]*[Aa][Cc][Cc][Ee][Pp][Tt][Aa][Nn][Cc][Ee][[:space:]]+[Cc][Rr][Ii][Tt][Ee][Rr][Ii][Aa][[:space:]]*$/ { next }
- /^[[:space:]]*[Aa][Cc][Cc][Ee][Pp][Tt][Aa][Nn][Cc][Ee][[:space:]]+[Cc][Rr][Ii][Tt][Ee][Rr][Ii][Aa]:?[[:space:]]*$/ { next }
- /^[[:space:]]*-[[:space:]]+/ {
- s = $0
- sub(/^[[:space:]]*-[[:space:]]+/, "", s)
- emit(s)
- next
- }
- /^[[:space:]]*[0-9]+[.)][[:space:]]+/ {
- s = $0
- sub(/^[[:space:]]*[0-9]+[.)][[:space:]]+/, "", s)
- emit(s)
- next
- }
- trim($0) != "" { fallback = (fallback == "" ? trim($0) : fallback "\n" trim($0)); fallback_count++ }
- END { if (!seen && fallback_count == 1) print "- " fallback }
- ' <<<"$1"
-}
-
-unit_acceptance_bullets() {
- local text bullets
- # bd's first-class acceptance_criteria field is criteria by construction; normalize the
- # supported authoring shapes (dash bullets, numbered items, or a single bare criterion) to
- # the dash-bullet contract consumed by PR stamping and the delivery gate. This keeps
- # `inbox ready` and `backlog submit` aligned: a non-empty first-class criteria field that
- # was accepted at ready time cannot become empty only because it used numbered items.
- text="$CLAIM_AC"
- bullets=$(criteria_bullets_from_text "$text")
- if [ -z "$bullets" ]; then
- text=$(extract_acceptance_section "$CLAIM_DESC"$'\n'"$CLAIM_DESIGN")
- bullets=$(criteria_bullets_from_text "$text")
- fi
- printf '%s\n' "$bullets" | sed '/^$/d'
-}
-
-body_has_bullet() { # $1=body $2=literal bullet
- grep -Fx -- "$2" <<<"$1" >/dev/null 2>&1
-}
-
-stamp_body_with_unit_criteria() { # $1=body-file $2=criteria-file $3=output-file
- local body_file="$1" criteria_file="$2" out_file="$3" body missing=0 bullet
- body=$(cat "$body_file")
- cp "$body_file" "$out_file"
- while IFS= read -r bullet || [ -n "$bullet" ]; do
- [ -n "$bullet" ] || continue
- if ! body_has_bullet "$body" "$bullet"; then
- if [ "$missing" -eq 0 ]; then
- {
- printf '\n## Acceptance criteria\n'
- } >>"$out_file"
- missing=1
- fi
- printf '%s\n' "$bullet" >>"$out_file"
- fi
- done <"$criteria_file"
-}
-
-gate_load_body() { # echoes body, returns non-zero on failure
- local body_file="$1"
- [ -f "$body_file" ] || return 1
- cat "$body_file"
-}
-
-gate_body_from_ci() { # echoes body, returns non-zero on failure
- local pr="${GITHUB_EVENT_NUMBER:-}"
- if [ -z "$pr" ] && [ -n "${GITHUB_EVENT_PATH:-}" ] && [ -f "$GITHUB_EVENT_PATH" ]; then
- pr=$(jq -r '.pull_request.number // .number // empty' "$GITHUB_EVENT_PATH" 2>/dev/null)
- fi
- [ -n "$pr" ] || return 1
- gh pr view "$pr" --json body --jq .body 2>/dev/null
-}
-
-gate_check_body_schema() { # $1=body
- local body="$1"
- grep -qiE '^#{1,6}[[:space:]]*verification[[:space:]]*$' <<<"$body" || gate_fail 'C2 verification: missing ## Verification section'
- grep -qE '^Unit:[[:space:]]*dotfiles-[^[:space:]]+[[:space:]]*$' <<<"$body" || gate_fail 'C2 verification: missing Unit: dotfiles-'
- grep -qE '^Checks:[[:space:]]*$' <<<"$body" || gate_fail 'C2 verification: missing Checks: block'
-}
-
-gate_check_linkage() { # $1=branch $2=body
- local branch="$1" body="$2" branch_short unit_lines unit_count unit_short
- case "$branch" in
- delivery/*) branch_short="${branch#delivery/}" ;;
- *)
- gate_fail "C1 protocol: branch must be delivery/ (got $branch)"
- branch_short=""
- ;;
- esac
- unit_lines=$(grep -E '^Unit:[[:space:]]*dotfiles-[^[:space:]]+[[:space:]]*$' <<<"$body" || true)
- unit_count=$(printf '%s\n' "$unit_lines" | sed '/^$/d' | wc -l | tr -d ' ')
- case "$unit_count" in
- 0) gate_fail 'C1 protocol: no linked unit (expected exactly one Unit: dotfiles-)' ;;
- 1)
- unit_short=$(printf '%s\n' "$unit_lines" | sed -E 's/^Unit:[[:space:]]*dotfiles-([^[:space:]]+)[[:space:]]*$/\1/')
- if [ -n "$branch_short" ] && [ "$unit_short" != "$branch_short" ]; then
- gate_fail "C1 protocol: linked unit dotfiles-$unit_short does not match branch delivery/$branch_short"
- fi
- ;;
- *) gate_fail 'C1 protocol: two linked units (expected exactly one Unit: dotfiles-)' ;;
- esac
-}
-
-gate_check_currency() { # $1=branch $2=base-ref $3=head-ref
- local branch="$1" base_ref="$2" head_ref="$3" base_sha merge_base base_branch
- case "$base_ref" in
- origin/*)
- base_branch="${base_ref#origin/}"
- git -C "$GATE_ROOT" fetch origin "$base_branch:refs/remotes/origin/$base_branch" >/dev/null 2>&1 || true
- ;;
- *) git -C "$GATE_ROOT" fetch origin >/dev/null 2>&1 || true ;;
- esac
- if ! base_sha=$(git -C "$GATE_ROOT" rev-parse "$base_ref" 2>/dev/null); then
- gate_fail "C1 protocol: could not resolve base $base_ref — fetch origin and retry"
- return 0
- fi
- if ! git -C "$GATE_ROOT" rev-parse "$head_ref" >/dev/null 2>&1; then
- gate_fail "C1 protocol: could not resolve branch $branch — check out delivery/${branch#delivery/} and retry"
- return 0
- fi
- if ! merge_base=$(git -C "$GATE_ROOT" merge-base "$head_ref" "$base_ref" 2>/dev/null); then
- gate_fail "C1 protocol: could not compare $branch with $base_ref"
- return 0
- fi
- if [ "$merge_base" != "$base_sha" ]; then
- gate_fail "C1 protocol: branch is behind $base_ref — run 'git rebase $base_ref'"
- fi
-}
-
-gate_check_acceptance_evidence() { # $1=body
- local body="$1" section failures criterion
- if ! has_acceptance_criteria_section "$body"; then
- gate_fail 'C4 acceptance: missing Acceptance criteria section'
- return 0
- fi
- section=$(extract_acceptance_section "$body")
- failures=$(awk '
- function miss() { if (pending != "") print pending; pending = "" }
- /^- / { miss(); pending = $0; next }
- pending != "" && /^[[:space:]]+evidence:[[:space:]]*[^[:space:]]/ { pending = ""; next }
- pending != "" { miss() }
- END { miss() }
- ' <<<"$section")
- while IFS= read -r criterion || [ -n "$criterion" ]; do
- [ -n "$criterion" ] || continue
- gate_fail "C4 acceptance: criterion lacks immediate evidence line: $criterion"
- done <<<"$failures"
-}
-
-gate_bats_jobs() {
- printf '%s\n' "${CLERK_BATS_JOBS:-4}"
-}
-
-gate_bats_parallel_available() {
- command -v parallel >/dev/null 2>&1 || command -v rush >/dev/null 2>&1
-}
-
-gate_bats_command() {
- if gate_bats_parallel_available; then
- printf 'bats --jobs %s tests/clerk\n' "$(gate_bats_jobs)"
- else
- printf 'bats tests/clerk\n'
- fi
-}
-
-gate_run_bats() {
- if gate_bats_parallel_available; then
- bats --jobs "$(gate_bats_jobs)" tests/clerk
- else
- bats tests/clerk
- fi
-}
-
-gate_check_executable() {
- local log bats_cmd
- log=$(mktemp)
- bats_cmd=$(gate_bats_command)
- if ! (cd "$GATE_ROOT" && gate_run_bats) >"$log" 2>&1; then
- gate_fail "C3 executable: $bats_cmd failed"
- while IFS= read -r line || [ -n "$line" ]; do
- gate_fail "C3 bats: $line"
- done <"$log"
- fi
- : >"$log"
- if ! (cd "$GATE_ROOT" && shellcheck -S error bin/*) >"$log" 2>&1; then
- gate_fail 'C3 executable: shellcheck bin/ failed'
- while IFS= read -r line || [ -n "$line" ]; do
- gate_fail "C3 shellcheck: $line"
- done <"$log"
- fi
- rm -f "$log"
-}
-
-cmd_backlog_gate() {
- local _backend="$1" root="$2"
- shift 2
- GATE_ROOT="$root"
- GATE_FAILED=0
- GATE_FAILURES=""
- local branch="" body_file="" base_ref="" ci=0 body head_ref
- while [ $# -gt 0 ]; do
- case "$1" in
- --branch)
- [ $# -ge 2 ] || usage_error 'clerk backlog gate: --branch needs a value — usage: clerk backlog gate --branch delivery/ --body-file '
- branch="$2"
- shift
- ;;
- --body-file)
- [ $# -ge 2 ] || usage_error 'clerk backlog gate: --body-file needs a path — usage: clerk backlog gate --branch delivery/ --body-file '
- body_file="$2"
- shift
- ;;
- --base)
- [ $# -ge 2 ] || usage_error 'clerk backlog gate: --base needs a ref'
- base_ref="$2"
- shift
- ;;
- --ci) ci=1 ;;
- *) usage_error "clerk backlog gate: unknown argument '$1' — usage: clerk backlog gate --branch delivery/ --body-file " ;;
- esac
- shift
- done
-
- if [ -z "$body_file" ]; then
- if [ "$ci" -eq 1 ] || [ -n "${GITHUB_ACTIONS:-}" ] || [ -n "${GITHUB_EVENT_NAME:-}" ]; then
- ci=1
- else
- usage_error 'clerk backlog gate: missing --body-file — usage: clerk backlog gate --branch delivery/ --body-file '
- fi
- fi
-
- if [ "$ci" -eq 1 ]; then
- branch="${branch:-${GITHUB_HEAD_REF:-}}"
- base_ref="${base_ref:-origin/${GITHUB_BASE_REF:-main}}"
- head_ref="HEAD"
- if ! body=$(gate_body_from_ci); then
- backend_fail 'gate failed — could not read the PR body with gh pr view'
- fi
- else
- if [ -z "$branch" ]; then
- branch=$(git -C "$root" symbolic-ref --quiet --short HEAD 2>/dev/null || true)
- fi
- [ -n "$branch" ] || usage_error 'clerk backlog gate: missing --branch — usage: clerk backlog gate --branch delivery/ --body-file '
- base_ref="${base_ref:-origin/main}"
- head_ref="$branch"
- if ! body=$(gate_load_body "$body_file"); then
- usage_error "clerk backlog gate: body file not found: $body_file"
- fi
- fi
-
- gate_check_linkage "$branch" "$body"
- gate_check_currency "$branch" "$base_ref" "$head_ref"
- gate_check_body_schema "$body"
- gate_check_acceptance_evidence "$body"
- gate_check_executable
- gate_finish
-}
-
-cmd_backlog_proof() {
- local backend="$1" _root="$2"
- shift 2
- if [ $# -eq 0 ]; then
- usage_error 'clerk backlog proof: missing id — usage: clerk backlog proof '
- fi
- local id_arg="$1"
- shift
- if [ $# -gt 0 ]; then
- usage_error "clerk backlog proof: unknown argument '$1' — usage: clerk backlog proof "
- fi
- if ! claim_resolve_id "$backend" "$id_arg"; then
- usage_error "clerk backlog proof: $id_arg not found — check the id ('clerk backlog next' shows ready units)"
- fi
- local criteria_file
- criteria_file=$(mktemp)
- unit_acceptance_bullets >"$criteria_file"
- if [ ! -s "$criteria_file" ]; then
- rm -f "$criteria_file"
- usage_error "clerk backlog proof: $CLAIM_FULL has no acceptance criteria — return it to discovery before submitting"
- fi
- jq -Rn '
- {acceptance: [inputs | select(length > 0) | sub("^- "; "") | {text: ., evidence: ""}]}
- ' <"$criteria_file"
- rm -f "$criteria_file"
-}
-
-proof_evidence_nonempty() { # $1=evidence
- grep -q '[^[:space:]]' <<<"$1"
-}
-
-render_body_from_proof() { # $1=full-id $2=short $3=proof-file $4=criteria-file $5=output-file
- local full="$1" short="$2" proof_file="$3" criteria_file="$4" out_file="$5" expected_count actual_count idx=0 bullet expected actual evidence first=1 line
- if ! jq -e '.acceptance | type == "array"' "$proof_file" >/dev/null 2>&1; then
- usage_error 'clerk backlog submit: proof JSON must contain an acceptance array'
- fi
- expected_count=$(sed '/^$/d' "$criteria_file" | wc -l | tr -d ' ')
- actual_count=$(jq '.acceptance | length' "$proof_file")
- if [ "$actual_count" -ne "$expected_count" ]; then
- usage_error "clerk backlog submit: proof JSON acceptance count $actual_count does not match $expected_count criterion/criteria — rerun 'clerk backlog proof $full'"
- fi
- {
- printf '## Verification\n\n'
- printf 'Unit: dotfiles-%s\n\n' "$short"
- printf 'Checks:\n'
- printf -- '- `%s` passed\n' "$(gate_bats_command)"
- printf -- '- `shellcheck -S error bin/*` passed\n\n'
- printf '## Acceptance criteria\n'
- } >"$out_file"
- while IFS= read -r bullet || [ -n "$bullet" ]; do
- [ -n "$bullet" ] || continue
- expected="${bullet#- }"
- actual=$(jq -r --argjson i "$idx" '.acceptance[$i].text // ""' "$proof_file")
- if [ "$actual" != "$expected" ]; then
- usage_error "clerk backlog submit: proof JSON is stale at acceptance[$idx]
-expected: $expected
-got: $actual
-rerun: clerk backlog proof $full"
- fi
- evidence=$(jq -r --argjson i "$idx" '.acceptance[$i].evidence // ""' "$proof_file")
- if ! proof_evidence_nonempty "$evidence"; then
- usage_error "clerk backlog submit: missing evidence for criterion: $expected"
- fi
- printf -- '- %s\n' "$expected" >>"$out_file"
- first=1
- while IFS= read -r line || [ -n "$line" ]; do
- if [ "$first" -eq 1 ]; then
- printf ' evidence: %s\n' "$line" >>"$out_file"
- first=0
- else
- printf ' %s\n' "$line" >>"$out_file"
- fi
- done <<<"$evidence"
- idx=$((idx + 1))
- done <"$criteria_file"
-}
-
-cmd_backlog_submit() {
- local backend="$1" root="$2"
- shift 2
- if [ $# -eq 0 ]; then
- usage_error 'clerk backlog submit: missing id — usage: clerk backlog submit '
- fi
- local id_arg="$1" body_file="" proof_file=""
- shift
- while [ $# -gt 0 ]; do
- case "$1" in
- --body-file)
- [ $# -ge 2 ] || usage_error 'clerk backlog submit: --body-file needs a path — usage: clerk backlog submit --body-file '
- [ -z "$proof_file" ] || usage_error 'clerk backlog submit: choose either proof JSON or --body-file, not both'
- body_file="$2"
- shift
- ;;
- -)
- [ -z "$body_file" ] || usage_error 'clerk backlog submit: choose either proof JSON or --body-file, not both'
- [ -z "$proof_file" ] || usage_error 'clerk backlog submit: only one proof JSON input is allowed'
- proof_file="-"
- ;;
- *)
- [ -z "$body_file" ] || usage_error 'clerk backlog submit: choose either proof JSON or --body-file, not both'
- [ -z "$proof_file" ] || usage_error 'clerk backlog submit: only one proof JSON input is allowed'
- proof_file="$1"
- ;;
- esac
- shift
- done
- if [ -z "$body_file" ] && [ -z "$proof_file" ]; then
- usage_error 'clerk backlog submit: missing proof JSON — usage: clerk backlog submit '
- fi
- if [ -n "$body_file" ]; then
- [ -f "$body_file" ] || usage_error "clerk backlog submit: body file not found: $body_file"
- elif [ "$proof_file" != - ]; then
- [ -f "$proof_file" ] || usage_error "clerk backlog submit: proof JSON not found: $proof_file"
- fi
-
- if ! claim_resolve_id "$backend" "$id_arg"; then
- usage_error "clerk backlog submit: $id_arg not found — check the id ('clerk backlog next' shows ready units)"
- fi
- local short="$CLAIM_SHORT" full="$CLAIM_FULL" title="$CLAIM_TITLE" branch current_branch
- branch="delivery/$short"
- current_branch=$(git -C "$root" symbolic-ref --quiet --short HEAD 2>/dev/null || true)
- if [ "$current_branch" != "$branch" ]; then
- usage_error "clerk backlog submit: not inside $branch — cd to $root/.worktrees/$short after 'clerk backlog claim $full'"
- fi
-
- local criteria_file stamped_body proof_tmp=""
- criteria_file=$(mktemp)
- stamped_body=$(mktemp)
- unit_acceptance_bullets >"$criteria_file"
- if [ ! -s "$criteria_file" ]; then
- rm -f "$criteria_file" "$stamped_body"
- usage_error "clerk backlog submit: $full has no acceptance criteria — return it to discovery before submitting"
- fi
- if [ -n "$body_file" ]; then
- stamp_body_with_unit_criteria "$body_file" "$criteria_file" "$stamped_body"
- else
- if [ "$proof_file" = - ]; then
- proof_tmp=$(mktemp)
- cat >"$proof_tmp"
- proof_file="$proof_tmp"
- fi
- render_body_from_proof "$full" "$short" "$proof_file" "$criteria_file" "$stamped_body"
- fi
-
- "$0" backlog gate --branch "$branch" --body-file "$stamped_body"
- local rc=$?
- if [ "$rc" -ne 0 ]; then
- rm -f "$criteria_file" "$stamped_body" "$proof_tmp"
- if [ "$rc" -eq 6 ]; then
- return 6
- fi
- return "$rc"
- fi
-
- if ! git -C "$root" push -u origin "$branch" >/dev/null 2>&1; then
- rm -f "$criteria_file" "$stamped_body" "$proof_tmp"
- backend_fail "submit failed — could not push $branch to origin"
- fi
- if ! gh pr create --head "$branch" --base main --title "$title (dotfiles-$short)" --body-file "$stamped_body"; then
- rm -f "$criteria_file" "$stamped_body" "$proof_tmp"
- backend_fail 'submit failed — gh pr create did not succeed'
- fi
- rm -f "$criteria_file" "$stamped_body" "$proof_tmp"
- printf '%sclerk:%s submitted %s — PR created; awaiting review\n' "$C_GRN" "$C_RST" "$full"
- return 0
-}
-
-# ----------------------------------------------------- finish + sync (dft.5) ----
-
-# The reconciler is intentionally stateless (ADR 0015): every run derives the phase from
-# observed git + PR + backlog state. Squash merge means branch ancestry is never proof of
-# delivery (ADR 0017 ruling 11); only the PR's state/mergedAt can say a unit is merged.
-
-primary_repo_root() { # $1 = any worktree root; echoes the common/main worktree root
- local root="$1" common
- common=$(git -C "$root" rev-parse --path-format=absolute --git-common-dir 2>/dev/null) || {
- printf '%s\n' "$root"
- return 0
- }
- case "$common" in
- */.git) dirname "$common" ;;
- *) printf '%s\n' "$root" ;;
- esac
-}
-
-finish_current_short() { # echoes delivery/'s short token, or empty outside one
- local branch
- branch=$(git symbolic-ref --quiet --short HEAD 2>/dev/null || true)
- case "$branch" in
- delivery/*) printf '%s\n' "${branch#delivery/}" ;;
- esac
-}
-
-finish_resolve_unit() { # $1=backend $2=id-or-empty
- local backend="$1" id_arg="${2:-}" short inferred=0
- if [ -z "$id_arg" ]; then
- inferred=1
- short=$(finish_current_short)
- [ -n "$short" ] || return 1
- # bd accepts the short token directly (e.g. `bd show dft.5` resolves dotfiles-dft.5),
- # so never fabricate a prefix from the clone directory name. If the local bd view cannot
- # resolve the short id, refuse below and ask for the explicit full id / refreshed state.
- id_arg="$short"
- fi
- if claim_resolve_id "$backend" "$id_arg"; then
- return 0
- fi
- if [ "$inferred" -eq 1 ] && [ "$backend" = bd ] && [ -n "${short:-}" ]; then
- printf "clerk: could not resolve bead for delivery/%s — run 'bd dolt pull' to refresh local state or rerun 'clerk backlog finish '\n" "$short" >&2
- fi
- return 1
-}
-
-finish_pr_json() { # $1=branch; echoes the active/merged PR JSON object, or empty
- local branch="$1"
- # A branch can have stale CLOSED PRs (closed without merge, then reopened as a fresh PR).
- # Reconciliation must prefer an active OPEN PR, then the most recent MERGED PR for cleanup,
- # and ignore CLOSED/non-merged PRs. `updatedAt` gives deterministic newest-first choice.
- gh pr list --head "$branch" --state all --json number,url,state,mergedAt,reviewDecision,statusCheckRollup,headRefName,isDraft,updatedAt \
- --jq '([.[] | select(.state == "OPEN")] | sort_by(.updatedAt) | reverse) as $open | ([.[] | select(.state == "MERGED" or (.mergedAt // "") != "")] | sort_by(.updatedAt) | reverse) as $merged | ($open[0] // $merged[0] // empty)' 2>/dev/null
-}
-
-finish_check_failures() { # $1=pr-json
- jq -r '
- .statusCheckRollup // [] | .[] |
- (.name // .context // .workflowName // "unnamed check") as $name |
- ((.conclusion // "") | ascii_upcase) as $conclusion |
- ((.status // "") | ascii_upcase) as $status |
- select(
- $conclusion == "FAILURE" or $conclusion == "TIMED_OUT" or
- $conclusion == "CANCELLED" or $conclusion == "ACTION_REQUIRED" or
- ($status == "COMPLETED" and $conclusion != "" and
- $conclusion != "SUCCESS" and $conclusion != "SKIPPED" and $conclusion != "NEUTRAL")
- ) |
- $name
- ' <<<"$1"
-}
-
-finish_check_pending() { # $1=pr-json
- jq -r '
- .statusCheckRollup // [] | .[] |
- (.name // .context // .workflowName // "unnamed check") as $name |
- ((.conclusion // "") | ascii_upcase) as $conclusion |
- ((.status // "") | ascii_upcase) as $status |
- select($conclusion == "" and $status != "COMPLETED") |
- $name
- ' <<<"$1"
-}
-
-finish_push_if_needed() { # $1=root $2=short
- local root="$1" short="$2" base_sha merge_base
- if git -C "$root" show-ref --verify --quiet "refs/heads/delivery/$short" &&
- ! git -C "$root" show-ref --verify --quiet "refs/remotes/origin/delivery/$short"; then
- git -C "$root" fetch origin main >/dev/null 2>&1 || true
- if base_sha=$(git -C "$root" rev-parse origin/main 2>/dev/null) &&
- merge_base=$(git -C "$root" merge-base "delivery/$short" origin/main 2>/dev/null) &&
- [ "$merge_base" != "$base_sha" ]; then
- printf "clerk: backlog finish refused — delivery/%s is behind origin/main\n" "$short" >&2
- printf " run 'git rebase origin/main', then rerun 'clerk backlog finish'\n" >&2
- return 2
- fi
- git -C "$root" push -u origin "delivery/$short" >/dev/null 2>&1 ||
- backend_fail "finish failed — could not push delivery/$short to origin"
- git -C "$root" fetch origin >/dev/null 2>&1 || true
- fi
-}
-
-finish_cleanup_merged() { # $1=backend $2=root $3=full $4=short $5=pr-number
- local backend="$1" root="$2" full="$3" short="$4" pr_number="$5" main_root wt status
- main_root=$(primary_repo_root "$root")
- # If finish is invoked from inside the worktree it is about to remove, leave that cwd first.
- cd "$main_root" || backend_fail "finish failed — could not cd to $main_root before cleanup"
- wt="$main_root/.worktrees/$short"
- if [ -d "$wt" ]; then
- if ! git -C "$main_root" worktree remove "$wt" >/dev/null 2>&1; then
- backend_fail "finish failed — could not remove the worktree at $wt (commit or stash local changes first)"
- fi
- else
- git -C "$main_root" worktree prune >/dev/null 2>&1 || true
- fi
- if git -C "$main_root" show-ref --verify --quiet "refs/heads/delivery/$short"; then
- git -C "$main_root" branch -D "delivery/$short" >/dev/null 2>&1 ||
- backend_fail "finish failed — could not delete local branch delivery/$short"
- fi
- if git -C "$main_root" ls-remote --exit-code --heads origin "delivery/$short" >/dev/null 2>&1; then
- git -C "$main_root" push origin --delete "delivery/$short" >/dev/null 2>&1 ||
- backend_fail "finish failed — could not delete origin delivery/$short"
- if git -C "$main_root" ls-remote --exit-code --heads origin "delivery/$short" >/dev/null 2>&1; then
- backend_fail "finish failed — origin still advertises delivery/$short after deletion"
- fi
- fi
- case "$backend" in
- bd)
- status="$CLAIM_STATUS"
- if [ "$status" != closed ]; then
- bd close "$full" --reason "delivered: PR #$pr_number merged" >/dev/null ||
- backend_fail "finish failed — bd close did not succeed for $full"
- fi
- local json has_label
- json=$(bd show "$full" --readonly --json 2>/dev/null) ||
- backend_fail "finish failed — could not read $full after finish"
- status=$(printf '%s' "$json" | jq -r '.[0].status // ""')
- [ "$status" = closed ] || backend_fail "finish failed — $full was not confirmed closed after finish"
- bd update "$full" --remove-label stage:ready >/dev/null ||
- backend_fail "finish failed — could not remove stage:ready from $full"
- json=$(bd show "$full" --readonly --json 2>/dev/null) ||
- backend_fail "finish failed — could not read $full after removing stage:ready"
- has_label=$(printf '%s' "$json" | jq -r '(.[0].labels // []) | index("stage:ready")')
- [ "$has_label" = null ] || backend_fail "finish failed — $full was not confirmed without stage:ready after finish"
- bd dolt push >/dev/null || backend_fail 'finish failed — bd dolt push did not succeed'
- ;;
- gh)
- gh issue edit "$full" --remove-label ready-for-agent >/dev/null 2>&1 || true
- ;;
- esac
- printf '%sclerk:%s finished %s — PR #%s merged, delivery/%s cleaned up, unit closed\n' "$C_GRN" "$C_RST" "$full" "$pr_number" "$short"
-}
-
-finish_reconcile_unit() { # $1=backend $2=root $3=id-or-empty $4=watch(0|1) $5=sync(0|1)
- local backend="$1" root="$2" id_arg="$3" watch="$4" sync_mode="$5"
- if ! finish_resolve_unit "$backend" "$id_arg"; then
- if [ "$sync_mode" -eq 1 ]; then
- printf 'clerk: sync: skipped an unresolvable claim id %s\n' "${id_arg:-}"
- return 0
- fi
- usage_error "clerk backlog finish: not inside delivery/ and no id was supplied — cd into the claimed worktree or run 'clerk backlog finish '"
- fi
- local full="$CLAIM_FULL" short="$CLAIM_SHORT" branch="delivery/$CLAIM_SHORT" pr_json pr_number pr_state merged_at failures pending review
- finish_push_if_needed "$root" "$short"
- local push_rc=$?
- [ "$push_rc" -eq 0 ] || return "$push_rc"
- pr_json=$(finish_pr_json "$branch")
- if [ -z "$pr_json" ]; then
- if [ "$sync_mode" -eq 1 ]; then
- if ! git -C "$root" show-ref --verify --quiet "refs/heads/$branch" &&
- ! git -C "$root" show-ref --verify --quiet "refs/remotes/origin/$branch"; then
- printf 'clerk: sync: %s is claimed but has no delivery/%s branch/worktree — no PR created\n' "$full" "$short"
- else
- printf "clerk: sync: %s has delivery/%s but no PR — no PR created; run 'clerk backlog submit %s --body-file '\n" "$full" "$short" "$full"
- fi
- return 0
- fi
- printf 'clerk: backlog finish refused — no PR found for delivery/%s\n' "$short" >&2
- printf " run 'clerk backlog submit %s --body-file '\n" "$full" >&2
- return 2
- fi
- pr_number=$(jq -r '.number // empty' <<<"$pr_json")
- pr_state=$(jq -r '.state // ""' <<<"$pr_json")
- merged_at=$(jq -r '.mergedAt // ""' <<<"$pr_json")
- if [ "$pr_state" = MERGED ] || [ -n "$merged_at" ]; then
- finish_cleanup_merged "$backend" "$root" "$full" "$short" "$pr_number"
- return 0
- fi
- if [ "$watch" -eq 1 ]; then
- gh pr checks "$pr_number" --watch || backend_fail "finish failed — gh pr checks --watch failed for PR #$pr_number"
- pr_json=$(finish_pr_json "$branch")
- fi
- failures=$(finish_check_failures "$pr_json")
- if [ -n "$failures" ]; then
- printf 'clerk: PR #%s for %s has failing checks\n' "$pr_number" "$full"
- while IFS= read -r line || [ -n "$line" ]; do
- [ -n "$line" ] || continue
- printf ' %s\n' "$line"
- done <<<"$failures"
- return 1
- fi
- pending=$(finish_check_pending "$pr_json")
- if [ -n "$pending" ]; then
- printf "clerk: PR #%s for %s has pending checks — run 'clerk backlog finish %s --watch' to wait\n" "$pr_number" "$full" "$full"
- while IFS= read -r line || [ -n "$line" ]; do
- [ -n "$line" ] || continue
- printf ' %s\n' "$line"
- done <<<"$pending"
- return 0
- fi
- review=$(jq -r '.reviewDecision // ""' <<<"$pr_json")
- case "$review" in
- REVIEW_REQUIRED | CHANGES_REQUESTED)
- printf 'clerk: PR #%s for %s is awaiting review — finish will complete after review\n' "$pr_number" "$full"
- return 0
- ;;
- esac
- if ! gh pr merge "$pr_number" --squash --delete-branch=false >/dev/null 2>&1; then
- backend_fail "finish failed — gh pr merge --squash did not succeed for PR #$pr_number"
- fi
- pr_json=$(finish_pr_json "$branch")
- pr_state=$(jq -r '.state // ""' <<<"$pr_json")
- merged_at=$(jq -r '.mergedAt // ""' <<<"$pr_json")
- if [ "$pr_state" != MERGED ] && [ -z "$merged_at" ]; then
- backend_fail "finish failed — PR #$pr_number was not confirmed merged after gh pr merge"
- fi
- finish_cleanup_merged "$backend" "$root" "$full" "$short" "$pr_number"
-}
-
-cmd_backlog_finish() {
- local backend="$1" root="$2"
- shift 2
- local watch=0 id_arg=""
- while [ $# -gt 0 ]; do
- case "$1" in
- --watch) watch=1 ;;
- *)
- [ -z "$id_arg" ] || usage_error "clerk backlog finish: unknown argument '$1' — usage: clerk backlog finish [] [--watch]"
- id_arg="$1"
- ;;
- esac
- shift
- done
- finish_reconcile_unit "$backend" "$root" "$id_arg" "$watch" 0
-}
-
-cmd_sync() {
- local backend="$1" root="$2"
- shift 2
- [ $# -eq 0 ] || usage_error "clerk sync: unknown argument '$1' — usage: clerk sync"
- case "$backend" in
- bd)
- local json count id
- if ! json=$(bd list --status in_progress --json); then
- backend_fail 'sync failed — bd list did not succeed'
- fi
- count=$(jq 'length' <<<"$json")
- printf 'clerk: sync scanning %s open claim(s)\n' "$count"
- while IFS= read -r id || [ -n "$id" ]; do
- [ -n "$id" ] || continue
- finish_reconcile_unit "$backend" "$root" "$id" 0 1 || true
- done < <(jq -r '.[].id' <<<"$json")
- ;;
- gh)
- printf 'clerk: sync: gh-backed claim sweep is not available in this generation; skipping\n' >&2
- return 0
- ;;
- esac
-}
-
-# ---------------------------------------------------------------- doctor ----
-
-DOCTOR_FAILS=0
-
-d_ok() { printf ' %s[ ok ]%s %s\n' "$C_GRN" "$C_RST" "$1"; }
-d_warn() { printf ' %s[warn]%s %s\n' "$C_YLW" "$C_RST" "$1"; }
-d_fail() {
- printf ' %s[fail]%s %s\n' "$C_RED" "$C_RST" "$1"
- DOCTOR_FAILS=$((DOCTOR_FAILS + 1))
-}
-d_hint() { printf ' %s\n' "$1"; }
-
-# Symlink-resolved path for comparisons only; raw paths are what we print.
-canon() {
- readlink -f -- "$1" 2>/dev/null || printf '%s\n' "$1"
-}
-
-cmd_doctor() {
- local fix=0 backend=""
- while [ $# -gt 0 ]; do
- case "$1" in
- --fix) fix=1 ;;
- --backend)
- [ $# -ge 2 ] || usage_error "clerk doctor: --backend needs a value — use --backend bd or --backend gh"
- backend="$2"
- shift
- ;;
- --backend=*) backend="${1#--backend=}" ;;
- *) usage_error "clerk doctor: unknown argument '$1' — usage: clerk doctor [--fix --backend bd|gh]" ;;
- esac
- shift
- done
- if [ "$fix" -eq 1 ]; then
- case "$backend" in
- bd | gh) ;;
- '') usage_error "clerk doctor: --fix requires --backend bd|gh — rerun as 'clerk doctor --fix --backend bd' (or gh)" ;;
- *) usage_error "clerk doctor: unknown backend '$backend' — use --backend bd or --backend gh" ;;
- esac
- elif [ -n "$backend" ]; then
- # --backend without --fix would silently do nothing — refuse and prescribe the fix.
- usage_error "clerk doctor: --backend applies only with --fix — rerun with --fix, e.g. 'clerk doctor --fix --backend bd'"
- fi
-
- local root=""
- root=$(repo_root) || root=""
- if [ -n "$root" ]; then
- printf '%sclerk doctor%s — %s\n' "$C_BOLD" "$C_RST" "$root"
- else
- printf '%sclerk doctor%s\n' "$C_BOLD" "$C_RST"
- fi
-
- # (a) .clerk marker — doctor owns provisioning (ADR 0017)
- if [ -z "$root" ]; then
- d_fail ".clerk marker: not inside a git repository"
- d_hint "cd into the target repo, then rerun 'clerk doctor'"
- else
- local found="" mrc=0
- found=$(read_marker "$root/.clerk") || mrc=$?
- if [ "$mrc" -eq 0 ]; then
- d_ok ".clerk marker: backlog: $found ($root/.clerk)"
- elif [ "$fix" -eq 1 ]; then
- # Guard the write AND re-validate through read_marker before claiming success —
- # a false "all clear" here dead-ends the dispatch→doctor→dispatch recovery loop.
- if printf 'backlog: %s\n' "$backend" 2>/dev/null >"$root/.clerk" &&
- found=$(read_marker "$root/.clerk"); then
- d_ok ".clerk marker: provisioned backlog: $found ($root/.clerk)"
- d_hint "commit .clerk so worktrees and clones see it: git add .clerk && git commit"
- else
- d_fail ".clerk marker: could not provision ($root/.clerk)"
- d_hint "check that $root is writable and .clerk is not a directory"
- fi
- elif [ "$mrc" -eq 1 ]; then
- d_fail ".clerk marker: missing ($root/.clerk)"
- d_hint "provision it: clerk doctor --fix --backend bd (or --backend gh)"
- else
- d_fail ".clerk marker: invalid ($root/.clerk)"
- d_hint "expected a single line 'backlog: bd' or 'backlog: gh' (comments after # are fine)"
- d_hint "rewrite it: clerk doctor --fix --backend bd (or --backend gh)"
- fi
- fi
-
- # (b) bd shim PATH ordering — a system bd that wins over the shim silently drops the
- # auto-sync the shim exists for (ADR 0013), so a shadowed shim is a hard fail.
- local resolved shim="" cand is_shim=0
- # ${HOME:-} so an unset HOME does not trip `set -u` (cron/systemd have no HOME).
- local -a candidates=("${HOME:-}/.config/bin/bd")
- [ -n "$root" ] && candidates+=("$root/bin/bd")
- resolved=$(command -v bd 2>/dev/null || true)
- for cand in "${candidates[@]}"; do
- [ -x "$cand" ] && { shim="$cand"; break; }
- done
- if [ -z "$resolved" ]; then
- d_warn "bd shim: no 'bd' on PATH — bd-backed verbs will not work until one is installed"
- else
- for cand in "${candidates[@]}"; do
- if [ "$(canon "$resolved")" = "$(canon "$cand")" ]; then
- is_shim=1
- break
- fi
- done
- if [ "$is_shim" -eq 1 ]; then
- d_ok "bd shim: $resolved (shim wins PATH resolution)"
- elif [ -n "$shim" ]; then
- d_fail "bd shim: SHADOWED — 'bd' resolves to $resolved, expected shim $shim"
- d_hint "fix: put $(dirname "$shim") before $(dirname "$resolved") in PATH"
- else
- d_warn "bd shim: 'bd' resolves to $resolved and no clerk-managed shim exists (~/.config/bin/bd or /bin/bd)"
- fi
- fi
-
- # (c) version parity — one variable at the top of this script feeds both surfaces
- d_ok "version: clerk $CLERK_VERSION (clerk --version reports the same string)"
-
- # (d) gh auth — non-fatal report
- if ! command -v gh >/dev/null 2>&1; then
- d_warn "gh auth: gh not on PATH (non-fatal) — install gh before using gh-backed verbs"
- elif gh auth status >/dev/null 2>&1; then
- d_ok "gh auth: authenticated"
- else
- d_warn "gh auth: not authenticated (non-fatal) — run 'gh auth login' before gh-backed verbs"
- fi
-
- if [ "$DOCTOR_FAILS" -eq 0 ]; then
- printf '%sclerk doctor: all clear%s\n' "$C_GRN" "$C_RST"
- return 0
- fi
- printf '%sclerk doctor: %d problem(s) — fix the [fail] lines above%s\n' "$C_RED" "$DOCTOR_FAILS" "$C_RST"
- return 1
-}
-
-# ---------------------------------------------------------------- glean (dft.6) ---
-
-# Watermark state directory. Tests may override with CLERK_GLEAN_STATE_DIR.
-GLEAN_STATE_DIR="${CLERK_GLEAN_STATE_DIR:-${HOME:-}/.local/state/clerk}"
-
-# Minimum chunk size (lines) to trigger a judgment fork. Tests may override.
-GLEAN_MIN_CHUNK_LINES="${CLERK_GLEAN_MIN_CHUNK_LINES:-50}"
-
-# Transcript project directory. Tests may override with one scratch transcript directory;
-# production derives the current repo/worktree's Claude Code project slug instead of
-# sweeping the whole archive.
-GLEAN_PROJECTS_ROOT="${CLERK_GLEAN_PROJECTS_ROOT:-${HOME:-}/.config/claude-code/projects}"
-
-# Flock lock file for single-instance guarantee
-GLEAN_LOCK_FILE="${GLEAN_STATE_DIR}/glean.lock"
-
-# Ensure state directory exists
-glean_ensure_state_dir() {
- mkdir -p "$GLEAN_STATE_DIR"
-}
-
-# Acquire flock lock (non-blocking). Returns 0 if acquired, 1 if another instance holds it.
-glean_acquire_lock() {
- # Create lock file if it doesn't exist
- touch "$GLEAN_LOCK_FILE" 2>/dev/null || return 1
- # Try to acquire exclusive non-blocking lock on fd 9
- exec 9<>"$GLEAN_LOCK_FILE"
- if flock -n 9; then
- return 0
- else
- exec 9>&-
- return 1
- fi
-}
-
-# Release flock lock
-glean_release_lock() {
- exec 9>&- 2>/dev/null || true
-}
-
-# Read watermark for a transcript file. Returns the line offset (0 if never harvested).
-glean_read_watermark() {
- local transcript_file="$1"
- local watermark_file
- watermark_file="$(glean_watermark_path "$transcript_file")"
- [ -f "$watermark_file" ] || { printf '0'; return 0; }
- cat "$watermark_file" 2>/dev/null || printf '0'
-}
-
-# Write watermark for a transcript file (atomic via temp file)
-glean_write_watermark() {
- local transcript_file="$1" offset="$2"
- local watermark_file
- watermark_file="$(glean_watermark_path "$transcript_file")"
- local tmp_file
- tmp_file="$(mktemp "${watermark_file}.tmp.XXXXXX")" || return 1
- printf '%s' "$offset" >"$tmp_file" || { rm -f "$tmp_file"; return 1; }
- mv "$tmp_file" "$watermark_file" || { rm -f "$tmp_file"; return 1; }
-}
-
-# Compute watermark file path from transcript file path
-glean_watermark_path() {
- local transcript_file="$1"
- # Use a hash of the absolute path to avoid collisions
- local abs_path hash
- abs_path=$(readlink -f "$transcript_file" 2>/dev/null || printf '%s' "$transcript_file")
- hash=$(printf '%s' "$abs_path" | sha256sum | cut -d' ' -f1)
- printf '%s/%s.watermark' "$GLEAN_STATE_DIR" "$hash"
-}
-
-# Claude Code's project transcript slug is the absolute cwd with slashes replaced by dashes
-# (e.g. /home/me/repo -> -home-me-repo). Worktrees get their own slugs, which is exactly
-# where their session transcripts live.
-glean_project_slug() { # $1=root
- local root="$1"
- root=$(cd "$root" 2>/dev/null && pwd -P) || printf '%s' "$root"
- printf '%s' "$root" | tr '/' '-'
-}
-
-glean_transcript_dirs() { # $1=root, NUL-separated output
- local root="$1" slug
- if [ -n "${CLERK_GLEAN_TRANSCRIPT_DIR:-}" ]; then
- printf '%s\0' "$CLERK_GLEAN_TRANSCRIPT_DIR"
- return 0
- fi
- slug=$(glean_project_slug "$root")
- printf '%s\0' "$GLEAN_PROJECTS_ROOT/$slug"
-}
-
-# Build the judgment fork prompt for a chunk of transcript lines
-glean_build_judgment_prompt() {
- local chunk_file="$1" transcript_file="$2" chunk_start="$3" chunk_end="$4"
- cat <<'EOF'
-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": "",
- "body": "",
- "transcript_file": "",
- "chunk_lines": "-"
-}
-
-If you find no impediments, output exactly one JSON object:
-{"type":"none","reason":""}
-
-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`.
-
-EOF
- printf 'TRANSCRIPT CHUNK (lines %s-%s of %s):\n' "$chunk_start" "$chunk_end" "$transcript_file"
- cat "$chunk_file"
-}
-
-# Spawn judgment fork for a chunk. Returns capture IDs on success, empty on an explicit
-# no-findings result, and non-zero on malformed/failed judgment or filing.
-glean_judgment_fork() {
- local chunk_file="$1" transcript_file="$2" chunk_start="$3" chunk_end="$4"
- local prompt_file output_file candidates_file capture_id
- prompt_file=$(mktemp)
- output_file=$(mktemp)
- candidates_file=$(mktemp)
- glean_build_judgment_prompt "$chunk_file" "$transcript_file" "$chunk_start" "$chunk_end" >"$prompt_file"
-
- # Invoke the judgment fork. Tests may set CLERK_GLEAN_JUDGMENT_CMD to a deterministic
- # command that reads the prompt on stdin and emits JSONL. Production requires a model
- # runner; no output / malformed output is a failed harvest, not a successful no-op.
- local rc=0
- if [ -n "${CLERK_GLEAN_JUDGMENT_CMD:-}" ]; then
- bash -c "$CLERK_GLEAN_JUDGMENT_CMD" <"$prompt_file" >"$output_file" || rc=$?
- elif command -v claude >/dev/null 2>&1; then
- claude -p \
- --model "${CLERK_GLEAN_MODEL:-haiku}" \
- --max-budget-usd "${CLERK_GLEAN_MAX_BUDGET_USD:-0.05}" \
- <"$prompt_file" >"$output_file" || rc=$?
- else
- printf 'clerk glean: no judgment runner available (expected claude on PATH)\n' >&2
- rm -f "$prompt_file" "$output_file" "$candidates_file"
- return 5
- fi
- if [ "$rc" -ne 0 ]; then
- rm -f "$prompt_file" "$output_file" "$candidates_file"
- return "$rc"
- fi
- if ! grep -q '[^[:space:]]' "$output_file"; then
- printf 'clerk glean: judgment fork produced no JSONL; watermark not advanced\n' >&2
- rm -f "$prompt_file" "$output_file" "$candidates_file"
- return 5
- fi
-
- local candidate ctype title body seen_any=0 seen_none=0 seen_impediment=0
- while IFS= read -r candidate || [ -n "$candidate" ]; do
- [[ "$candidate" =~ [^[:space:]] ]] || continue
- seen_any=1
- if ! printf '%s' "$candidate" | jq -e 'type == "object" and (.type == "none" or .type == "impediment")' >/dev/null 2>&1; then
- printf 'clerk glean: malformed judgment JSONL; watermark not advanced\n' >&2
- rm -f "$prompt_file" "$output_file" "$candidates_file"
- return 5
- fi
- ctype=$(printf '%s' "$candidate" | jq -r '.type')
- case "$ctype" in
- none)
- seen_none=1
- ;;
- impediment)
- title=$(printf '%s' "$candidate" | jq -r '.title // empty')
- body=$(printf '%s' "$candidate" | jq -r '.body // empty')
- if [ -z "$title" ] || [ -z "$body" ]; then
- printf 'clerk glean: impediment candidate missing title/body; watermark not advanced\n' >&2
- rm -f "$prompt_file" "$output_file" "$candidates_file"
- return 5
- fi
- printf '%s\n' "$candidate" >>"$candidates_file"
- seen_impediment=1
- ;;
- esac
- done <"$output_file"
-
- if [ "$seen_any" -eq 0 ] || { [ "$seen_none" -eq 1 ] && [ "$seen_impediment" -eq 1 ]; }; then
- printf 'clerk glean: ambiguous judgment output; watermark not advanced\n' >&2
- rm -f "$prompt_file" "$output_file" "$candidates_file"
- return 5
- fi
- if [ "$seen_none" -eq 1 ]; then
- rm -f "$prompt_file" "$output_file" "$candidates_file"
- return 0
- fi
-
- while IFS= read -r candidate || [ -n "$candidate" ]; do
- local source_key
- title=$(printf '%s' "$candidate" | jq -r '.title')
- body=$(printf '%s' "$candidate" | jq -r '.body')
- source_key=$(printf '%s\n%s:%s-%s' "$candidate" "$transcript_file" "$chunk_start" "$chunk_end" | sha256sum | cut -d' ' -f1)
- if ! capture_id=$(glean_file_capture "$title" "$body" impediment "glean-source:$source_key"); then
- rm -f "$prompt_file" "$output_file" "$candidates_file"
- return 5
- fi
- printf '%s\n' "$capture_id"
- done <"$candidates_file"
- rm -f "$prompt_file" "$output_file" "$candidates_file"
-}
-
-glean_existing_capture() { # $1=source-key
- local source_key="$1"
- case "${GLEAN_BACKEND:-bd}" in
- bd) bd search --desc-contains "$source_key" --readonly --json 2>/dev/null | jq -r '.[0].id // empty' ;;
- gh) gh issue list --search "$source_key" --json url --jq '.[0].url // empty' 2>/dev/null ;;
- esac
-}
-
-# File a capture through the repo's configured clerk backend (used after the judgment fork
-# emits JSONL candidates). A deterministic glean-source key makes retries idempotent when
-# a later candidate in the same chunk fails before the chunk watermark can advance.
-glean_file_capture() {
- local title="$1" body="$2" type="${3:-impediment}" source_key="$4"
- local existing body_file
- existing=$(glean_existing_capture "$source_key")
- if [ -n "$existing" ]; then
- printf '%s\n' "$existing"
- return 0
- fi
- body_file=$(mktemp)
- printf '%s\n\n%s\n' "$body" "$source_key" >"$body_file" || { rm -f "$body_file"; return 1; }
- case "${GLEAN_BACKEND:-bd}" in
- bd)
- [ "$type" = impediment ] && bd_ensure_impediment_type
- local id seen
- id=$(bd create "$title" --body-file "$body_file" --type "$type" --silent) || { rm -f "$body_file"; return 1; }
- seen=$(bd show "$id" --readonly --json 2>/dev/null | jq -r '.[0].id // empty')
- [ "$seen" = "$id" ] || { rm -f "$body_file"; return 1; }
- printf '%s\n' "$id"
- ;;
- gh)
- local url
- url=$(gh issue create --title "$title" --body-file "$body_file" --label "type:$type") || { rm -f "$body_file"; return 1; }
- printf '%s\n' "$url"
- ;;
- esac
- rm -f "$body_file"
-}
-
-# Process a single transcript file: harvest unharvested chunks
-glean_process_transcript() {
- local transcript_file="$1"
- [ -f "$transcript_file" ] || return 0
- [ -s "$transcript_file" ] || return 0
-
- local watermark_offset
- watermark_offset=$(glean_read_watermark "$transcript_file")
-
- local total_lines
- total_lines=$(wc -l <"$transcript_file")
- [ "$watermark_offset" -lt "$total_lines" ] || return 0 # Nothing new
-
- local chunk_start=$((watermark_offset + 1))
- local chunk_end=0
- local line_num=0
- local chunk_file
-
- chunk_file=$(mktemp)
-
- while IFS= read -r line || [ -n "$line" ]; do
- line_num=$((line_num + 1))
- [ "$line_num" -le "$watermark_offset" ] && continue
-
- printf '%s\n' "$line" >>"$chunk_file"
- chunk_end=$line_num
-
- # Check if chunk is large enough to process
- local chunk_size=$((chunk_end - chunk_start + 1))
- if [ "$chunk_size" -ge "$GLEAN_MIN_CHUNK_LINES" ]; then
- # Spawn judgment fork for this chunk
- local capture_id
- if ! capture_id=$(glean_judgment_fork "$chunk_file" "$transcript_file" "$chunk_start" "$chunk_end"); then
- printf 'glean: judgment fork failed for %s lines %s-%s; watermark not advanced\n' "$transcript_file" "$chunk_start" "$chunk_end" >&2
- rm -f "$chunk_file"
- return 1
- fi
- if [ -n "$capture_id" ]; then
- printf ' filed %s (lines %s-%s)\n' "$capture_id" "$chunk_start" "$chunk_end"
- else
- printf ' judgment fork returned no capture for lines %s-%s\n' "$chunk_start" "$chunk_end"
- fi
-
- # ADVANCE WATERMARK ONLY AFTER SUCCESSFUL FILING (crash-safe)
- glean_write_watermark "$transcript_file" "$chunk_end" || {
- printf 'glean: failed to write watermark for %s\n' "$transcript_file" >&2
- rm -f "$chunk_file"
- return 1
- }
-
- # Reset for next chunk
- chunk_start=$((chunk_end + 1))
- : >"$chunk_file"
- fi
- done <"$transcript_file"
-
- # Handle final sub-threshold chunk (log skip, don't harvest)
- if [ "$chunk_start" -le "$total_lines" ]; then
- local remaining=$((total_lines - chunk_start + 1))
- if [ "$remaining" -gt 0 ] && [ "$remaining" -lt "$GLEAN_MIN_CHUNK_LINES" ]; then
- printf 'glean: sub-threshold chunk skipped (%s lines, min %s) in %s\n' "$remaining" "$GLEAN_MIN_CHUNK_LINES" "$transcript_file"
- fi
- fi
-
- rm -f "$chunk_file"
- return 0
-}
-
-# Main glean command
-glean_main() {
- local root="$1"
- shift
- local async=0
- while [ $# -gt 0 ]; do
- case "$1" in
- --async) async=1 ;;
- *) usage_error "clerk glean: unknown argument '$1' — usage: clerk glean [--async]" ;;
- esac
- shift
- done
-
- glean_ensure_state_dir
-
- if [ "$async" -eq 1 ]; then
- local log_file="$GLEAN_STATE_DIR/glean.log"
- ("$0" glean >>"$log_file" 2>&1 &)
- printf 'glean: async harvest started (log: %s)\n' "$log_file"
- return 0
- fi
-
- # Single-instance flock guard
- if ! glean_acquire_lock; then
- printf 'glean: another instance is running — exiting\n' >&2
- return 0 # Not an error, just another instance won
- fi
-
- # Release the lock on normal exit, but terminate immediately on signals. A TERM/INT
- # during the judgment fork must never continue into watermark advancement.
- trap glean_release_lock EXIT
- trap 'glean_release_lock; exit 130' INT
- trap 'glean_release_lock; exit 143' TERM
-
- local -a transcript_files=() transcript_dirs=()
- local dir dirs_display=""
-
- while IFS= read -r -d '' dir; do
- transcript_dirs+=("$dir")
- done < <(glean_transcript_dirs "$root")
- for dir in "${transcript_dirs[@]}"; do
- dirs_display+="${dirs_display:+ }$dir"
- [ -d "$dir" ] || continue
- # Find all .jsonl files (main + subagent transcripts)
- while IFS= read -r -d '' file; do
- transcript_files+=("$file")
- done < <(find "$dir" -type f -name '*.jsonl' -print0 2>/dev/null)
- done
-
- if [ "${#transcript_files[@]}" -eq 0 ]; then
- printf 'glean: no transcript files found in %s\n' "$dirs_display"
- return 0
- fi
-
- printf 'glean: scanning %s transcript file(s)\n' "${#transcript_files[@]}"
-
- local file
- for file in "${transcript_files[@]}"; do
- printf ' harvesting %s\n' "$file"
- glean_process_transcript "$file" || {
- printf 'glean: failed to process %s\n' "$file" >&2
- # Don't exit - continue with other files
- }
- done
-
- printf 'glean: harvest complete\n'
- return 0
-}
-
-cmd_glean() {
- local backend="$1" _root="$2"
- shift 2
- GLEAN_BACKEND="$backend"
- glean_main "$_root" "$@"
-}
-
-# ------------------------------------------------------------------ main ----
-
-main() {
- # --explain / --help may sit anywhere in the argument list; strip them, keep the verb path.
- local explain=0 help=0 a
- local -a args=()
- for a in "$@"; do
- case "$a" in
- --explain) explain=1 ;;
- --help | -h) help=1 ;;
- *) args+=("$a") ;;
- esac
- done
- set -- ${args[@]+"${args[@]}"}
-
- if [ $# -eq 0 ]; then
- if [ "$explain" -eq 1 ]; then
- usage_error "clerk: --explain needs a verb — e.g. 'clerk --explain backlog claim'"
- fi
- if [ "$help" -eq 1 ]; then
- printf 'clerk %s — workflow verb facade (ADR 0015)\n' "$CLERK_VERSION"
- print_roster
- exit 0
- fi
- printf 'clerk: missing verb\n' >&2
- print_roster >&2
- exit 2
- fi
-
- case "$1" in
- --version | -V)
- printf 'clerk %s\n' "$CLERK_VERSION"
- exit 0
- ;;
- esac
-
- local verb="" noun sub roster w sub_known gate_root
- case "$1" in
- capture | sync | doctor | glean)
- verb="$1"
- shift
- ;;
- inbox | backlog)
- noun="$1"
- shift
- if [ $# -eq 0 ]; then
- printf "clerk: '%s' needs a verb\n" "$noun" >&2
- print_roster >&2
- exit 2
- fi
- sub="$1"
- if [ "$noun" = inbox ]; then
- roster="list show dups ready drop pregrill children frontier blockers blocked parent dep claim release note update resolve"
- else
- roster="next show waiting claim release resolve proof submit gate finish return"
- fi
- # Exact-word match — a glob over " $roster " would misread one argument
- # equal to two adjacent roster words (e.g. 'list show') as a known verb.
- sub_known=0
- for w in $roster; do
- if [ "$sub" = "$w" ]; then
- sub_known=1
- break
- fi
- done
- if [ "$sub_known" -eq 1 ]; then
- verb="$noun $sub"
- shift
- else
- unknown_verb "$noun $sub"
- fi
- ;;
- *) unknown_verb "$1" ;;
- esac
-
- if [ "$explain" -eq 1 ] || [ "$help" -eq 1 ]; then
- explain_verb "$verb"
- exit 0
- fi
-
- if [ "$verb" = doctor ]; then
- cmd_doctor "$@"
- exit "$?"
- fi
-
- # The delivery-gate is server-side proof over git/PR-visible state. It deliberately does
- # not read the backlog marker or backend; GitHub Actions must be able to run it before the
- # repo's `.clerk` cutover (ADR 0016, dotfiles-dft.4).
- if [ "$verb" = "backlog gate" ]; then
- gate_root=$(repo_root) || {
- printf "clerk: not inside a git repository — cd into the target repo, then rerun 'clerk backlog gate'\n" >&2
- exit 4
- }
- cmd_backlog_gate "" "$gate_root" "$@"
- exit "$?"
- fi
-
- # Everything else dispatches on the .clerk marker (ADR 0017) …
- marker_gate
- # … and, for the verbs this generation implements (dotfiles-dft.2), on the marker's
- # backend. Every cmd_* callee takes (backend, root, …verb-args…) uniformly, even the
- # ones that do not need root, so this dispatch line stays one shape for all seven.
- local root backend
- root=$(repo_root)
- backend=$(read_marker "$root/.clerk")
- case "$verb" in
- capture)
- cmd_capture "$backend" "$root" "$@"
- exit "$?"
- ;;
- sync)
- cmd_sync "$backend" "$root" "$@"
- exit "$?"
- ;;
- "inbox list")
- cmd_inbox_list "$backend" "$root" "$@"
- exit "$?"
- ;;
- "inbox show")
- cmd_inbox_show "$backend" "$root" "$@"
- exit "$?"
- ;;
- "inbox dups")
- cmd_inbox_dups "$backend" "$root"
- exit "$?"
- ;;
- "inbox ready")
- cmd_inbox_ready "$backend" "$root" "$@"
- exit "$?"
- ;;
- "inbox drop")
- cmd_inbox_drop "$backend" "$root" "$@"
- exit "$?"
- ;;
- "inbox pregrill")
- cmd_inbox_pregrill "$backend" "$root" "$@"
- exit "$?"
- ;;
- "inbox children")
- cmd_inbox_children "$backend" "$root" "$@"
- exit "$?"
- ;;
- "inbox frontier")
- cmd_inbox_frontier "$backend" "$root" "$@"
- exit "$?"
- ;;
- "inbox blockers")
- cmd_inbox_blockers "$backend" "$root" "$@"
- exit "$?"
- ;;
- "inbox blocked")
- cmd_inbox_blocked "$backend" "$root" "$@"
- exit "$?"
- ;;
- "inbox parent")
- cmd_inbox_parent "$backend" "$root" "$@"
- exit "$?"
- ;;
- "inbox dep")
- cmd_inbox_dep "$backend" "$root" "$@"
- exit "$?"
- ;;
- "inbox claim")
- cmd_inbox_claim "$backend" "$root" "$@"
- exit "$?"
- ;;
- "inbox release")
- cmd_inbox_release "$backend" "$root" "$@"
- exit "$?"
- ;;
- "inbox note")
- cmd_inbox_note "$backend" "$root" "$@"
- exit "$?"
- ;;
- "inbox update")
- cmd_inbox_update "$backend" "$root" "$@"
- exit "$?"
- ;;
- "inbox resolve")
- cmd_inbox_resolve "$backend" "$root" "$@"
- exit "$?"
- ;;
- "backlog next")
- cmd_backlog_next "$backend" "$root"
- exit "$?"
- ;;
- "backlog show")
- cmd_backlog_show "$backend" "$root" "$@"
- exit "$?"
- ;;
- "backlog waiting")
- cmd_backlog_waiting "$backend" "$root" "$@"
- exit "$?"
- ;;
- "backlog claim")
- cmd_backlog_claim "$backend" "$root" "$@"
- exit "$?"
- ;;
- "backlog release")
- cmd_backlog_release "$backend" "$root" "$@"
- exit "$?"
- ;;
- "backlog resolve")
- cmd_backlog_resolve "$backend" "$root" "$@"
- exit "$?"
- ;;
- "backlog return")
- cmd_backlog_return "$backend" "$root" "$@"
- exit "$?"
- ;;
- "backlog gate")
- cmd_backlog_gate "$backend" "$root" "$@"
- exit "$?"
- ;;
- "backlog proof")
- cmd_backlog_proof "$backend" "$root" "$@"
- exit "$?"
- ;;
- "backlog submit")
- cmd_backlog_submit "$backend" "$root" "$@"
- exit "$?"
- ;;
- "backlog finish")
- cmd_backlog_finish "$backend" "$root" "$@"
- exit "$?"
- ;;
- glean)
- cmd_glean "$backend" "$root" "$@"
- exit "$?"
- ;;
- esac
- # … and the rest is delivered by a later unit of the dotfiles-dft epic.
- not_implemented "$verb"
-}
-
-main "$@"
diff --git a/clerk/src/clerk/cli.py b/clerk/src/clerk/cli.py
index 13b5fbc..97300a7 100644
--- a/clerk/src/clerk/cli.py
+++ b/clerk/src/clerk/cli.py
@@ -11,37 +11,18 @@
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 .legacy import run_legacy
from .manifest import ManifestStatus, read_manifest
from .proc import CommandRunner
-from .project_gate import cmd_backlog_gate, cmd_backlog_submit
+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
-# The Python core owns diagnostics, help/explain/version, manifest gating,
-# doctor, read-only item query windows, Capture/text-based Inbox mutations,
-# Planning graph mutations/claims, the Inbox ready/drop bridge, the Backlog
-# Claim lifecycle, delivery reconciliation, and Glean. Unported workflow verb
-# bodies remain on the shell fallback.
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", "submit"), ("backlog", "gate")})
-
-LEGACY_WORKFLOW_VERBS: frozenset[tuple[str, ...]] = frozenset(
- ({("capture",), ("sync",), ("glean",)} | {(noun, verb) for noun, verbs in NOUN_VERBS.items() for verb in verbs})
- - PYTHON_QUERY_VERBS
- - PYTHON_MUTATION_VERBS
- - PYTHON_PROJECT_GATE_VERBS
- - RECONCILIATION_VERBS
- - {("glean",)}
+PYTHON_PROJECT_GATE_VERBS: frozenset[tuple[str, ...]] = frozenset(
+ {("backlog", "proof"), ("backlog", "submit"), ("backlog", "gate")}
)
-# Kept explicit for the legacy public contract: unknown verbs are exit 2 with
-# roster; known-but-unimplemented verbs are exit 3 without roster. There are no
-# such stubs in this migration slice, but the distinction remains one table away.
-PYTHON_STUB_VERBS: frozenset[tuple[str, ...]] = frozenset()
-
-
def _print_roster(*, stream) -> None:
stream.write(roster_text())
@@ -57,14 +38,6 @@ def _unknown(label: str) -> int:
return 2
-def _not_implemented(path: tuple[str, ...]) -> int:
- print(
- f"clerk: '{verb_label(path)}' is not yet implemented in this generation (see dotfiles-dft epic)",
- file=sys.stderr,
- )
- return 3
-
-
def _split_control_flags(argv: Sequence[str]) -> tuple[list[str], bool, bool]:
explain = False
help_ = False
@@ -141,21 +114,10 @@ def _manifest_context(path: tuple[str, ...]) -> tuple[Path, str] | int:
return 4
-def _manifest_gate(path: tuple[str, ...]) -> int | None:
- context = _manifest_context(path)
- if isinstance(context, int):
- return context
- return None
-
-
def main(argv: Sequence[str] | None = None) -> int:
- """Dispatch public Clerk argv to Python-owned handlers or legacy fallback."""
+ """Dispatch public Clerk argv to its Python command handlers."""
original_args = list(sys.argv[1:] if argv is None else argv)
-
- if os.environ.get("CLERK_FORCE_LEGACY") not in {None, "", "0"}:
- return run_legacy(original_args)
-
args, explain, help_ = _split_control_flags(original_args)
if not args:
@@ -186,9 +148,6 @@ def main(argv: Sequence[str] | None = None) -> int:
if path == ("doctor",):
return run_doctor(remaining)
- if path in PYTHON_STUB_VERBS:
- return _not_implemented(path)
-
if path in PYTHON_QUERY_VERBS:
context = _manifest_context(path)
if isinstance(context, int):
@@ -209,6 +168,8 @@ def main(argv: Sequence[str] | None = None) -> 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:
@@ -228,10 +189,4 @@ def main(argv: Sequence[str] | None = None) -> int:
root, backend = context
return run_glean(backend, root, remaining)
- if path in LEGACY_WORKFLOW_VERBS:
- refused = _manifest_gate(path)
- if refused is not None:
- return refused
- return run_legacy(original_args)
-
return _unknown(verb_label(path))
diff --git a/clerk/src/clerk/legacy.py b/clerk/src/clerk/legacy.py
deleted file mode 100644
index 355dc53..0000000
--- a/clerk/src/clerk/legacy.py
+++ /dev/null
@@ -1,39 +0,0 @@
-"""Legacy shell fallback for unported Clerk verb paths."""
-
-from __future__ import annotations
-
-import os
-import sys
-from collections.abc import Mapping, Sequence
-from pathlib import Path
-
-
-def legacy_path(env: Mapping[str, str] = os.environ) -> Path:
- """Return the preserved shell implementation path supplied by the launcher."""
-
- configured = env.get("CLERK_LEGACY_PATH")
- if configured:
- return Path(configured)
-
- repo_root = env.get("CLERK_REPO_ROOT")
- if repo_root:
- return Path(repo_root) / "clerk" / "legacy" / "clerk.bash"
-
- # Developer fallback for `PYTHONPATH=clerk/src python -m clerk` from a checkout.
- return Path(__file__).resolve().parents[2] / "legacy" / "clerk.bash"
-
-
-def run_legacy(argv: Sequence[str], env: Mapping[str, str] = os.environ) -> int:
- """Replace this process with the shell Clerk implementation."""
-
- path = legacy_path(env)
- if not path.exists():
- print(
- f"clerk: legacy implementation not found at {path} — run 'clerk doctor' from the dotfiles checkout",
- file=sys.stderr,
- )
- return 4
-
- process_env = dict(os.environ)
- os.execve(str(path), [str(path), *argv], process_env)
- raise AssertionError("os.execve returned unexpectedly")
diff --git a/clerk/src/clerk/ownership.py b/clerk/src/clerk/ownership.py
index 4c52d35..19ec4f2 100644
--- a/clerk/src/clerk/ownership.py
+++ b/clerk/src/clerk/ownership.py
@@ -1,14 +1,4 @@
-"""Static migration ownership for public Clerk verb paths.
-
-This slice moves Clerk's command-boundary diagnostics, read-only item query
-windows, Capture/text-based Inbox mutations, Planning graph mutations/claims,
-the Inbox ready/drop bridge, the Backlog Claim lifecycle, delivery
-reconciliation, and Glean to Python while leaving later delivery workflow verb
-bodies on the legacy shell fallback.
-Ownership is therefore split: Python owns global help/explain/version, manifest
-gating, doctor, and the explicit command tables; unported workflow mutations
-are exec'd into the fallback after the Python gate accepts them.
-"""
+"""Static Python ownership for every public Clerk verb path."""
from __future__ import annotations
@@ -19,7 +9,17 @@
from .roster import NOUN_VERBS, TOP_LEVEL_VERBS
PYTHON_OWNED_DIRECT_PATHS: frozenset[tuple[str, ...]] = frozenset(
- {("doctor",), ("glean",), ("--version",), ("-V",), ("--help",), ("-h",), ("backlog", "submit"), ("backlog", "gate")}
+ {
+ ("doctor",),
+ ("glean",),
+ ("--version",),
+ ("-V",),
+ ("--help",),
+ ("-h",),
+ ("backlog", "proof"),
+ ("backlog", "submit"),
+ ("backlog", "gate"),
+ }
| set(QUERY_HANDLERS)
| set(MUTATION_HANDLERS)
| set(RECONCILIATION_VERBS)
diff --git a/clerk/src/clerk/project_gate.py b/clerk/src/clerk/project_gate.py
index c745538..b18df89 100644
--- a/clerk/src/clerk/project_gate.py
+++ b/clerk/src/clerk/project_gate.py
@@ -136,6 +136,34 @@ def _work(backend: str, runner: CommandRunner, id_: str, verb: str) -> tuple[str
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 ")
+ if len(argv) > 1:
+ usage(f"clerk backlog proof: unknown argument '{argv[1]}' — usage: clerk backlog proof ")
+ 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
diff --git a/tests/clerk/core.bats b/tests/clerk/core.bats
index 4e14c54..8ef909e 100644
--- a/tests/clerk/core.bats
+++ b/tests/clerk/core.bats
@@ -16,7 +16,6 @@ setup() {
# 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"
- NOT_IMPL="is not yet implemented in this generation (see dotfiles-dft epic)"
ALL_VERBS=(
"capture" "sync" "glean"
"inbox list" "inbox show" "inbox dups" "inbox ready" "inbox drop" "inbox pregrill"
@@ -25,10 +24,6 @@ setup() {
"backlog next" "backlog show" "backlog waiting" "backlog claim" "backlog release" "backlog resolve"
"backlog proof" "backlog submit" "backlog gate" "backlog finish" "backlog return"
)
- # dotfiles-dft.6 implements the final top-level stub (`glean`), so the stub matrix is
- # intentionally empty. Keep it as a matrix so a future generation gap can add entries
- # without reshaping the dispatcher tests.
- STUB_VERBS=()
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"
@@ -87,7 +82,7 @@ assert_no_python_bytecode() { # $1 = package root to inspect
# ------------------------------------------------------------- version ------
-@test "launcher invokes the Python Clerk project, which falls back to legacy behavior" {
+@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"
@@ -110,9 +105,8 @@ EOF
@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" "$fresh/clerk/legacy"
+ mkdir -p "$fresh/bin" "$fresh/clerk/src"
cp "$REPO_ROOT/bin/clerk" "$fresh/bin/clerk"
- cp "$REPO_ROOT/clerk/legacy/clerk.bash" "$fresh/clerk/legacy/clerk.bash"
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
@@ -132,20 +126,6 @@ EOF
[ "$output" = "clerk 0.1.0" ]
}
-@test "force-legacy override bypasses the Python runtime" {
- fake_python="$BATS_TEST_TMPDIR/python3"
- cat >"$fake_python" <<'EOF'
-#!/bin/sh
-echo "python should not run" >&2
-exit 99
-EOF
- chmod +x "$fake_python"
-
- run env -i CLERK_FORCE_LEGACY=1 CLERK_PYTHON="$fake_python" PATH="/usr/bin:/bin" "$CLERK" --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"
@@ -154,7 +134,7 @@ EOF
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+, set CLERK_PYTHON to its path, or rerun with CLERK_FORCE_LEGACY=1" ]
+ [ "${lines[1]}" = " install Python 3.11+ or set CLERK_PYTHON to its path" ]
[ "${lines[2]}" = " then run 'clerk doctor' if setup is still unclear" ]
}
@@ -166,23 +146,6 @@ EOF
# -------------------------------------------- dispatch: root vs worktree ----
-@test "matrix: every still-stubbed roster verb resolves the repo identically from root and worktree" {
- repo=$(make_repo matrix "backlog: bd")
- wt=$(make_worktree "$repo" wt1)
- for v in "${STUB_VERBS[@]}"; do
- cd "$repo"
- # shellcheck disable=SC2086 # word-split $v into noun + verb on purpose
- run "$CLERK" $v
- [ "$status" -eq 3 ]
- [ "$output" = "clerk: '$v' $NOT_IMPL" ]
- cd "$wt"
- # shellcheck disable=SC2086 # word-split $v into noun + verb on purpose
- run "$CLERK" $v
- [ "$status" -eq 3 ]
- [ "$output" = "clerk: '$v' $NOT_IMPL" ]
- done
-}
-
@test "dispatch resolves the repo from a nested subdirectory of a worktree" {
repo=$(make_repo nested "backlog: bd")
wt=$(make_worktree "$repo" wt1)
@@ -238,14 +201,6 @@ EOF
[ "$output" = "clerk: invalid .clerk marker at $repo/.clerk — run 'clerk doctor' to diagnose it" ]
}
-@test "legacy workflow fallback accepts the optional project-gate directive" {
- repo=$(make_repo legacy_gate $'backlog: bd\nproject-gate: gate.json')
- cd "$repo"
- run env CLERK_FORCE_LEGACY=1 "$CLERK" backlog finish
- [ "$status" -eq 2 ]
- [[ "$output" != *"invalid .clerk marker"* ]]
-}
-
@test "marker tolerates surrounding whitespace and # comments" {
repo=$(make_repo losemarker -)
printf '%s\n' \
diff --git a/tests/clerk/inbox-graph.bats b/tests/clerk/inbox-graph.bats
index 41c3de0..fd94a96 100644
--- a/tests/clerk/inbox-graph.bats
+++ b/tests/clerk/inbox-graph.bats
@@ -54,66 +54,46 @@ make_bd_repo() {
[ "$(bd show "$custom" --readonly --json | jq -r '.[0].issue_type')" = research ]
}
-@test "capture keeps a child of ready Work in the Inbox in both command paths" {
- for force_legacy in 0 1; do
- repo=$(make_bd_repo "capture_ready_parent_$force_legacy")
- cd "$repo"
- parent=$(bd create "ready parent" --acceptance "parent ac" --silent)
- "$CLERK" inbox ready "$parent" >/dev/null
-
- if [ "$force_legacy" -eq 1 ]; then
- run env CLERK_FORCE_LEGACY=1 "$CLERK" capture "new child" --parent "$parent"
- else
- run "$CLERK" capture "new child" --parent "$parent"
- fi
- [ "$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 ]
-
- if [ "$force_legacy" -eq 1 ]; then
- run env CLERK_FORCE_LEGACY=1 "$CLERK" backlog next
- else
- run "$CLERK" backlog next
- fi
- [ "$status" -eq 0 ]
- [[ "$output" != *"$child"* ]]
-
- printf 'child design\n' >"$repo/design"
- printf '%s\n' '- child acceptance' >"$repo/acceptance"
- if [ "$force_legacy" -eq 1 ]; then
- run env CLERK_FORCE_LEGACY=1 "$CLERK" inbox ready "$child" --design-file "$repo/design" --acceptance-file "$repo/acceptance"
- else
- run "$CLERK" inbox ready "$child" --design-file "$repo/design" --acceptance-file "$repo/acceptance"
- fi
- [ "$status" -eq 0 ]
- json=$(bd show "$child" --readonly --json)
- [ "$(jq -r '.[0].labels | index("stage:ready")' <<<"$json")" != null ]
- done
+@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 in both command paths" {
- for force_legacy in 0 1; do
- repo=$(make_bd_repo "capture_ready_parent_blocked_$force_legacy")
- 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
-
- if [ "$force_legacy" -eq 1 ]; then
- run env CLERK_FORCE_LEGACY=1 "$CLERK" capture "new blocked child" --parent "$parent" --blocked-by "$ready_sibling"
- else
- run "$CLERK" capture "new blocked child" --parent "$parent" --blocked-by "$ready_sibling"
- fi
- [ "$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 ]
- done
+@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" {
diff --git a/tests/clerk_python/test_core_contracts.py b/tests/clerk_python/test_core_contracts.py
index b69e50d..63e5489 100644
--- a/tests/clerk_python/test_core_contracts.py
+++ b/tests/clerk_python/test_core_contracts.py
@@ -12,21 +12,14 @@
class CliBoundaryTests(unittest.TestCase):
- def invoke(self, argv, *, env=None, legacy_code=77):
+ def invoke(self, argv, *, env=None):
out = io.StringIO()
err = io.StringIO()
- calls = []
-
- def fake_legacy(args):
- calls.append(list(args))
- return legacy_code
-
- with mock.patch("clerk.cli.run_legacy", side_effect=fake_legacy), \
- mock.patch.dict(os.environ, env or {}, clear=True), \
+ 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(), calls
+ return code, out.getvalue(), err.getvalue(), []
def test_no_arguments_prints_public_roster_without_legacy(self):
code, out, err, calls = self.invoke([])
@@ -120,7 +113,7 @@ def fake_mutation(path, backend, root, remaining):
try:
os.chdir(td)
with mock.patch("clerk.cli.run_mutation", side_effect=fake_mutation):
- code, out, err, calls = self.invoke(["capture", "title"], legacy_code=77)
+ code, out, err, calls = self.invoke(["capture", "title"])
finally:
os.chdir(cwd)
self.assertEqual((code, out, err, calls), (0, "", "", []))
@@ -140,13 +133,13 @@ def fake_query(path, backend, root, remaining):
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"], legacy_code=77)
+ 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_legacy(self):
+ 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()
@@ -160,6 +153,26 @@ def test_known_workflow_verb_with_bad_manifest_refuses_before_legacy(self):
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):
diff --git a/tests/clerk_python/test_ownership.py b/tests/clerk_python/test_ownership.py
index 743d0c9..1c8982f 100644
--- a/tests/clerk_python/test_ownership.py
+++ b/tests/clerk_python/test_ownership.py
@@ -1,13 +1,6 @@
import unittest
-from pathlib import Path
-
-from clerk.legacy import legacy_path
from clerk.ownership import is_python_owned, public_verb_path
-
-
-class LegacyPathTests(unittest.TestCase):
- def test_direct_module_invocation_finds_the_preserved_shell_script(self):
- self.assertTrue((legacy_path({})).samefile(Path("clerk/legacy/clerk.bash")))
+from clerk.roster import all_public_verb_paths
class OwnershipTests(unittest.TestCase):
@@ -73,6 +66,11 @@ def test_delivery_reconciliation_is_python_owned(self):
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"))
diff --git a/tests/clerk_python/test_proof.py b/tests/clerk_python/test_proof.py
new file mode 100644
index 0000000..5aecf9a
--- /dev/null
+++ b/tests/clerk_python/test_proof.py
@@ -0,0 +1,36 @@
+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()