source: .claude/lib/README.md · generated — edit the markdown, not this file

.claude/lib/ — Shared Hook + Command Helpers

Helpers used by hooks, commands, skills and CI in this harness. Lives outside hooks/ and commands/ because helpers don’t run on their own as Claude Code events — a hook, a command, CI or a developer calls them. Some are sourced shell helpers; most are invoked directly; the table below says which.

Exception — command payload subdirectories (e.g. forge-deliver/): stage-loaded markdown payloads extracted from heavy command bodies, so each loads only at the stage that needs it. They are read by the orchestrator mid-command, not sourced, and the shell-helper convention below does not apply to them. They live here rather than under .claude/commands/<name>/ because Claude Code registers .md files in commands/ subdirectories as namespaced slash commands — payloads must never appear in the command palette.

Exception — agent includes (agents/): markdown that more than one agent definition reads, so the text is written once. agents/implementer-common.md holds the bug-fix dispatch mode and the sibling-WI rules that backend-implementer and frontend-implementer share; each agent names it in its reading order. They live here, not under .claude/agents/, because every .md file there is registered as an agent.

Exception — Node scripts (render-docs-html.js, format-html.js, serve-static.js) and the minified libraries in vendor/: invoked with node (or loaded by the renderer), not sourced, and they share none of the shell-helper conventions.

Convention for shell helpers

  • Each helper is a single .sh file under lib/.
  • A sourced helper defines one or more shell functions and uses the BASH_SOURCE[0] = $0 check to differentiate sourced-mode from invoked-mode; a helper meant only to be invoked does its work in main or at the top level.
  • Each helper that checks or parses something has a --self-test mode, and CI runs it (§ Self-test discipline).
  • Helpers are set -u-safe: every variable expansion uses ${var:-} or guards against unset state.
  • A sourced helper returns n/a (or another sentinel) on missing inputs rather than exit-ing — let the caller decide what to do.

Current helpers

The Self-test column says whether the file has a --self-test mode; every one marked yes runs in the Repo hygiene workflow, except check-test-stats.py (.forge/owed.md).

File What it does Self-test Used by
derive-phase.sh Sourced: derive_phase <harness-root> → discovery | architecture | foundation | engineering | n/a yes .claude/hooks/phase-scope-skills.sh, .claude/hooks/track-token-usage.sh, .claude/hooks/forge-recap.sh, .claude/lib/forge-statusline-segment.sh
check-md-frontmatter.sh Validates the YAML front-matter of Markdown files (skills, agents) — that it parses and that no unquoted value is truncated yes .github/workflows/repo-hygiene.yml, .claude/hooks/lint-and-typecheck.sh, .claude/hooks/verify-before-stop.sh; runnable directly
claim-check.py Invoked directly: <ticket> … [--release] [--json] → whether each bug or feature can be claimed (FREE, MINE, PENDING, TAKEN, CLOSED, NOT-FOUND; with --release, RELEASE, NOT-YOURS, IN-FLIGHT), from the tracker on origin/main and the open PRs and work branches of the four delivery repos; read-only yes .claude/commands/et-claim.md, .claude/commands/forge-deliver.md Stage 0
check-encoding-pins.py Fails when a Python read in this repo decodes with the platform’s locale encoding (no encoding= pin) — an AST check, so multi-line calls are seen (coding-standards.md §5.1) yes .github/workflows/repo-hygiene.yml; runnable directly
check-unique-ids.py Fails when an id in any series .claude/rules/id-numbering.md marks as checked is used twice — two open branches can each take the same number (.forge/lessons.md L-057); a reopened OQ may keep its number. --gaps lists the numbers each series skips and never fails, because a gap can be momentary while an open PR holds the number yes .github/workflows/repo-hygiene.yml; runnable directly
next-id.py Invoked directly: <bug|lesson|oq|prd-rev|ad|ds-rev> [--count <k>] [--ignore-pr <n>] → the next id (or next k ids, for several entries in one change) of that series: the lowest numbers that no entry on origin/main, no open harness PR (an added entry; for a bug also its title or branch) and no pushed branch with no PR holds (design .forge/design/harness/ids-on-pushed-branches.md) — for bugs the lowest free number, for the rest the highest + 1 unless a number below was freed. Reads main through check-unique-ids.py’s own collectors, so the two agree; diffs only the PRs that change the series’ files. Warns on stderr when two open PRs add the same number, or one adds a number main has. Read-only apart from git fetch; exits non-zero and prints no id when any read fails. --check-pr <n> instead fails when PR <n> adds an entry of any of the six series above a free number (the older of two PRs adding one number keeps it), printing the ids to use yes .claude/rules/id-numbering.md rules 1 and 5; Repo hygiene (--check-pr); /forge-reflect, /forge-prd-check, /forge-arch-probe, forge-prd-author, /forge-decompose; runnable directly
next-bug-id.sh Invoked directly: next-id.py bug, under the name the rules and the tracker cite (--count, --ignore-pr and --self-test pass through; falls back to a Python-3 python where there is no python3) yes .claude/rules/tracker.md § Bug Tracking; runnable directly
check-lesson-sync-labels.py Fails when a lesson in .forge/lessons.md has an invalid Sync target: or Synced: line, by the dashboard Lessons tile’s rules (.claude/rules/tracker.md § Lessons Entry Format) yes .github/workflows/repo-hygiene.yml; runnable directly
check-features-index.py Fails when a .forge/features.md row’s phase section, status (Phase column) or Blocked By disagrees with the feature in .forge/tracker.yaml, or a row and a tracker feature have no counterpart yes .github/workflows/repo-hygiene.yml; runnable directly
check-tracker-owners.py Fails when a feature’s or bug’s owner in .forge/tracker.yaml does not match its state: a started feature or an in-progress/fixed bug with no owner from delivery.team, an unstarted feature or open bug with one (taking it is a claim, /et-claim), a dropped feature or wontfix bug without owner: "N/A" and a decided_by (.claude/rules/tracker.md § Update Rules, § Bug Tracking) yes .github/workflows/repo-hygiene.yml; runnable directly
check-plain-english.py Lists the sentences over 30 words and the formal words in the files given, with their lines, so a client document or guide can be rewritten in simple English (.claude/rules/client-docs.md, Simple English); --summary gives one line per file. A writing aid: always exits 0 no .claude/rules/client-docs.md; runnable directly
check-done-acs.py Fails when a done feature’s spec has an acceptance criterion left unticked with no *Not met note (.claude/rules/specs.md § Spec Lifecycle); --feature <id> checks one feature whatever its phase yes .github/workflows/repo-hygiene.yml, forge-reflect step 5d, /forge-doctor Tier 2; runnable directly
check-test-stats.py Invoked directly: <wi-id>-test-verify.md … → fails when the file’s last forge-test-stats/v1 block does not parse, a run has no kebab-case run_label, or two runs share a (test_type, repo, run_label) (they would collapse into one ledger line) yes — Repo hygiene does not run it yet forge-test-verify (§ Test Stats, before Step 7), /forge-deliver Stage 12b; runnable directly
check-skill-phases.sh Fails when a skill’s SKILL.md has no phases: front-matter (unless it is in the script’s always-on list, with a reason) or names an unknown phase — .claude/hooks/phase-scope-skills.sh loads a skill without one in every phase yes .github/workflows/repo-hygiene.yml; runnable directly
check-workflow-timeouts.sh Fails when a job in .github/workflows/*.yml sets no timeout-minutes (GitHub’s default is 360 minutes of the shared Actions budget) yes .github/workflows/repo-hygiene.yml; runnable directly
forge-statusline-segment.sh forge_statusline_segment <statusLine-stdin-json> → one-line Forge segment, or empty when outside a harness yes Developer’s personal status-line script (direct-invoke mode) — see ../hooks/README.md §Status line segment
tracker-write.sh Invoked directly: begin → takes the tracker lock and snapshots .forge/tracker.yaml; finish <n> → passes if at most n lines were removed and n added and the file still parses, otherwise restores the snapshot and exits 1; release → drops the lock. Wraps the Edit-tool edits that write tracker fields — the replacement for yq -i writes (.forge/lessons.md L-003) yes Every skill and command that writes .forge/tracker.yaml (.claude/rules/tracker.md § Update Rules; git grep -l tracker-write.sh -- .claude/skills .claude/commands lists them); runnable directly
forge-review-record.sh Invoked directly: <owner/repo> <pr> <head-sha> <approve|block> <summary-file> or … --skip "<reason>" [--over-block "<reason>"] → writes the review record for an app-repo PR: one PR comment (edited in place per writer) and the Forge review commit status on the PR’s head. Refuses a commit that is not the head, a base other than main or release/*, a summary that does not name the reviewer agent, an approve without a Security pass: line or with an Open Blocker / Open Important line, a block that lists no open finding, a PR that is not open, and a skip over a block without --over-block. The self-test stubs gh (needs jq). Design: forge-review-gate.md yes /forge-review-pr (after its fixes), /forge-deliver Stages 10 and 12 through it; a developer’s skip; runnable directly
forge-estimate.sh Invoked directly (never sourced from zsh): bash forge-estimate.sh baselines or range --waves N --wis M [--include-spec false]; the same functions can be sourced from a bash script. forge_estimate_baselines → effective per-metric baselines JSON (project-own medians outrank baked org values at ≥5 samples); forge_estimate_range --waves N --wis M [--include-spec bool] → {low_days, high_days, basis} range JSON. Refuses (error JSON) when baselines are uncalibrated — never fabricates yes forge-estimate skill, /forge-decompose step 10 (advisory forecast annotation), /forge-set-dates step 2 (suggested anchor)
harness-graph.py Read-only reference analyzer over the whole repo — dangling refs, orphans, Reference-Map coverage (--convention), Mermaid (--mermaid), D3 graph (--html). Paths that exist in an app repo checked out beside the harness, gitignored files, and paths in plans, specs and records are counted apart from “Hard dangling”; in CI, where the app repos are absent, app-repo paths stay in it. --write is the only writing mode and regenerates both .forge/dashboard/harness-reference-graph.{html,md}. Output is deterministic by design — the rules that keep it so are in the module docstring, and any edit must preserve them no — CI runs it on the tree (Reference graph, Generators run clean) .claude/hooks/regen-reference-graph.sh (Stop), .githooks/pre-commit, pages-build.sh; runnable directly
render-docs-html.js Renders the human-read documentation set to the gitignored docs-html/ mirror no — CI runs it on the tree (Generators run clean) .claude/hooks/regen-docs-html.sh (Stop), .githooks/pre-commit, pages-build.sh, forge-start.sh; runnable directly
format-html.js Indent-only HTML formatter (never adds line breaks between inline siblings, so rendered spacing never shifts) no render-docs-html.js
serve-static.js node serve-static.js <port> <directory> → a dependency-free static file server on 127.0.0.1. Exists because launch.json is shared and python3 is not a command on Windows (nor python on macOS) — node is the one runtime spelled the same on all three no .claude/launch.json (every entry: the two prototypes and the dashboard); runnable directly
nightly/run-nightly.py The nightly full run of the three app repos on the lead’s Mac (design .forge/design/harness/test-run-cost.md N-1 to N-4, S-4): gitleaks and Trivy in every repo every night, the backend build, the frontends’ static checks and build, both Vitest suites and both browser gates on origin/main in locked worktrees under $WS/worktrees/nightly/, the CRM’s gate against a backend on the et-nightly isolated stack; a red suite opens or comments on a nightly-red issue assigned to the team, a green night closes it, and each night writes one comment on the harness issue labelled nightly-log. Takes the machine’s heavy-run lock; runs nothing when it starts after 05:00. --now, --only, --dry-run, --no-report; --status prints the session-start lines (N-2). Installed as a LaunchAgent by nightly/install.sh yes the LaunchAgent; .claude/hooks/inject-gate-state.sh (--status); runnable directly
heavy-run.py Invoked directly: [--no-wait] -- <command> [args...] → runs one heavy command (a Gradle build or test run, a multi-file vitest run, a timing measurement) under the machine’s heavy-run lock, et-heavy-run.lock in the temp folder, which the records, the browser gate and the nightly run also take; waits while another run holds it, or while the nightly run has reserved the next turn (et-heavy-run.next, BUG-521) (--no-wait exits 75 instead), keeps the machine awake while it holds it, releases it when the command ends, and on macOS and Linux ends the command on a stop signal (SIGTERM, SIGHUP). The command sees ET_HEAVY_RUN_LOCK_HOLDER, so a record it starts inherits the lock. Resolves pnpm.CMD and gradlew.BAT on Windows. The lock steps copy forge-et-be scripts/local-build-evidence.py’s (design .forge/design/harness/test-run-cost.md M-5; L-315) yes — Repo hygiene does not run it yet (.forge/owed.md) .claude/rules/test-record.md § One heavy run at a time, .claude/rules/git-conventions.md, .claude/lib/forge-deliver/agent-prompt-template.md § Shared machine lock, /forge-deliver Stage 7, .forge/test-strategy.md; runnable directly
pages-build.sh The Cloudflare Pages build: runs the dashboard hooks, the graph and the renderer so the hosted site is built from main rather than from committed output no The Publish dashboard workflow; runnable directly
cleanup.sh Invoked directly, not sourced: fetches every ET repo, fast-forwards every branch that is only behind its upstream (inside a linked worktree only when that worktree is idle), removes the worktrees and branches (local and remote) whose work is in the base branch, and the worktrees and local branches whose tip is exactly on origin and unchanged for a day, reports unmerged remote branches gone stale (review stale-branch) and merged worktrees whose uncommitted changes are a week old (review dirty-worktree, removed with --discard-changes) for one decision by the user, removes empty folders under worktrees/ and .claude/worktrees/ with rmdir and reports every other leftover there; then removes the Docker leftovers of finished ET work (stopped stacks of merged or removed worktrees, stopped Testcontainers containers, unused anonymous volumes, images an ET repo stopped naming, build cache unused for a day) and reports a repo’s running stack whose image its compose.yaml no longer names, a stopped et-local-* stack beside its folder’s default stack, and a compose network left with no project. App session worktrees are only reported (review) unless named with --remove-app-worktree; forge-et-iaac follows the same rules against its base, dev. Exits 1 on any error. Dry run by default; --apply acts, --local-only keeps remote branches, --no-docker leaves Docker alone, --min-idle-minutes N sets how long a worktree must be unused and a stack or container stopped. The header lists every keep rule; it fails closed when gh cannot list a repo’s PRs no /et-cleanup; runnable directly

Adding a new helper

  1. Create <name>.sh (or .py) and, if it checks or parses anything, a --self-test mode that proves it catches each case — “no findings” is also what a checker that sees nothing reports.
  2. Document signature, return value, and failure modes at the top of the file.
  3. Add a row to the table above.
  4. Add its --self-test (and, for a check, the check itself) to .github/workflows/repo-hygiene.yml.
  5. A sourced helper is loaded from the caller using leading-dot + space:
    . "$PROJECT_DIR/.claude/lib/<name>.sh"
    result=$(<function_name> "$arg")
    

Why a separate directory

Hooks (.claude/hooks/) are scripts that Claude Code invokes on its own. Commands (.claude/commands/) are markdown files Claude reads when the user types /<name>. Neither is the right home for a helper that runs only when another script, CI or a developer calls it. lib/ is the natural separation, and keeps the hooks/ README focused on what actually runs.

Self-test discipline

Run a helper’s --self-test after any change to it:

./.claude/lib/derive-phase.sh --self-test

The Repo hygiene workflow runs every --self-test in the table, so a failing one fails the PR: the helper’s contract changed and downstream hooks may break. To find them: grep -l -- '--self-test' .claude/lib/*.

Generated from .claude/lib/README.md by .claude/lib/render-docs-html.js. Markdown is canonical.