# Work

> Use when the user says "work this", "run a work loop", "do this properly", "take this through clarify plan and verify", "run it through the gate", "/work", or hands over a substantial change that has no domain workflow of its own and should be planned, approved and independently verified before it lands. NEGATIVE ROUTING: a code change or bug fix is /dev; a dataset, table, figure or number is /ds; long-form prose is /writing; a talk built from a research paper is /workshop; lecture notes or course slides are teaching:notes and teaching:slides; a skill, workflow or plugin in this repo is skill-creator, workflow-creator or plugin-creator. Each of those is this loop plus a domain gate, and work is only the fallback when none of them fits.

- Skill: `edwinhu/work` (Agent Skill, multi-file: 86 files)
- Install (CLI): `npx get-skill add edwinhu/work`
- Raw SKILL.md: https://api.skillmd.com/api/skills/edwinhu/work/raw
- Safety review: pending
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: AI & ML
- Author: edwinhu (https://skillmd.com/u/edwinhu)
- Updated: 2026-11-12
- Page: https://skillmd.com/skills/edwinhu/work

---


# `work` — clarify → plan → goal → workflow → human review

**What this skill carries** — grep `references/` for any subject the names below miss:
!`d=${CLAUDE_SKILL_DIR}; command -v skill-toc >/dev/null 2>&1 && exec skill-toc "$d"; s=$HOME/.claude/skills/plugin-utils/bin/skill-toc; [ -x "$s" ] && exec "$s" "$d"; echo "(skill-toc unavailable: references and scripts are NOT listed here — install the plugin-utils plugin, or start a new session so its bin/ reaches PATH)"`

A structured loop for tasks worth doing properly: clarify with the user, draft a plan they
edit and approve, self-set a goal, run `workflow.js` — dispatched through farm-out — to implement
and independently verify, then put the result in front of the human in tuicr. Human rejection
routes back to CLARIFY.

```
CLARIFY ─► PLAN ─► GOAL ─► workflow.js ──PASS──► HUMAN REVIEW (tuicr)
   ▲                           ▲    │              │
   └── human REJECT ────────────┼────┼──────────────┤
                               └─fix┘ FAIL        └─ findings → fix → re-run

work-round.sh (agents only where judgement is needed; every exit code is a script):
dispatch: red-before + red-suite hashes (work-dispatch.sh, no agent)
  ─► workflow.js AGENTS: IMPLEMENT waves ─► [VERIFY (no-acceptanceCmd tasks) ∥ RULE ∥ SCORED ∥ ATTEMPTS]
  ─► work-checks.sh: red-after ∥ acceptanceCmds ∥ mechanicalChecks ∥ red-suite re-hash
  ─► work-stage.mjs digest ─► ONE lens = one farm.sh --tasks row, kind review ─► workflow.js gate
                                 RED: diagnose and route; GREEN: open-ended pass
FAIL selectors: tasksThatFlagged + mechanicalThatFailed + rulesThatFailed + lensesThatFlagged + planFindings
```

No agent runs a command. The red probes, every `acceptanceCmd` (which replaces that task's verifier)
and every mechanical check are exit codes recorded by scripts; a red-suite file whose hash moved
between dispatch and the checks is a CRITICAL owned by the task whose `writablePaths` reach it, else
`plan`. The lens reads a digest — failures first with command, exit, tail and owner; green checks
marked settled and never re-run; a per-task `git diff --stat`; out-of-scope paths pre-flagged — and
runs as ONE `farm.sh --tasks` row of kind review on the routed provider and `lens.model`. RED means a
task flagged or a check failed: the lens diagnoses each failure into `routes`, naming its
owner task or `"plan"`. GREEN means those checks passed: the lens makes one open-ended pass. Both
modes rule on carried findings. Scored results are advisory; they do not choose the mode or decide
the gate. There is no refuter leg.

**Plan review is computed and happens before dispatch, not inside it** — `plan-lint.ts` over the
built args and `plan-preflight.ts` executing their commands at baseline, enforced by
`work-dispatch.sh` while the run is still armed. No agent reads the plan markdown for defects
(see *Plan review*).

Everything lives in this skill directory — `workflow.js`, `scripts/work-dispatch.sh` (Phase 3+4 in
one call), `scripts/work-pending.sh` (is a dispatch owed?), `scripts/compose-goal.sh` (the objective
and its ceiling), `scripts/human-review-gate.sh`, `scripts/work-result.sh`.
Nothing here depends on any plugin.

**The gate has a test suite; run it after touching `workflow.js`** — `node --check` proves only that
the file parses. `scripts/workflow-harness.mjs` executes the script for real against stubbed hooks,
and `scripts/workflow.test.ts` asserts the invariants that decide PASS/FAIL: fail-closed on every
dead agent, the three `redCommand` verdicts, `overallPass === false` implying a non-empty selector,
the `readOnly` n/a dimensions. `scripts/plan-review.test.ts` guards the computed plan-review rules
and the absence of the judged layer. Add both to `mechanicalChecks` on a run that edits the spine:

```bash
${CLAUDE_PLUGIN_ROOT}/scripts/test.sh ${CLAUDE_PLUGIN_ROOT}/skills/work/scripts/   # absolute path:
# a bare relative path is read as a NAME FILTER and exits 1 having matched nothing
```

`${CLAUDE_PLUGIN_ROOT}/scripts/test.sh` runs test files in parallel with a per-run TMPDIR; with no argument it runs the
whole suite (~1 min).

## State

Two locations, one owner each:

| Path | Holds | Owner |
|---|---|---|
| `<plansDirectory>/<slug>.md` | the approved plan — **the run's authority**, the file that gets hashed | plan mode (native); `work` only reads and hashes it |
| `.work/<run-id>/` | args, verdict JSON, and `plan-<hash12>.md` — the archived bytes each round ran under | `work` |

`plansDirectory` decides where that plan lives, and `work` **honours whatever it is set to** —
`"./.claude/plans"` and `"./.planning"` (what the domain workflows use) are
equally valid. The value is resolved relative to the project root, so the plan is project-local and
`work` hashes it in place — no copy. Unset at every tier, the default is `.claude/plans`. `run-id` is
a short date-slug like `0806-fix-auth`. Both `.work/` and the plans directory want to be
gitignored — add them before the
first run if the repo would otherwise track them. Clean up `.work/<run-id>/` when the run
completes, unless the user wants provenance kept; leave the plan file alone either way, it's plan
mode's. **The plan file is not durable and `work` does not own it** — plan mode memoizes one slug per
session, so re-entering plan mode overwrites the plan in place, and the directory is gitignored. So
dispatch archives the bytes it hashed to `.work/<run-id>/plan-<hash12>.md` (content-addressed: an
amended round adds one, never overwrites). That archive is the only copy of what a run was approved
with — if the plan matters beyond the run, `git add -f` it before cleaning the run dir. There is no `goal.md`: the plan holds the success criteria, and the goal is a
session-level condition (Phase 3), not a file.

## Phase 1 — CLARIFY

**Before any task reconnaissance**, AskUserQuestion on the axes that shape the plan (skip axes
the request already answers; batch up to 4 per call):

1. Desired outcome — what does done look like?
2. Exclusions — what must NOT change?
3. Constraints — style, deps, compatibility.
4. Observable success criteria — what command/check proves it? *A command with a meaningful
   exit code becomes a `mechanicalChecks` entry in the plan's Run sizing block.*
5. Review surface — working tree (default), commit range, or PR?
6. **Which provider runs the review lens?** — routed (default: `kinds.review` in `routing.json`) /
   claude / codex / gemini. *A non-routed answer sets `args.lensProvider`, which the dispatcher
   resolves through `route.ts` to that provider's review candidate. It cannot be combined with an
   explicit `lens.model` or `lensModel`.*
7. **Read-only runs only — use an agent team for discovery? (default yes.)** Ask this axis only
   when the run is an audit (`readOnly: true`); for a run that writes, the answer is always no and
   the axis is skipped. The honest tradeoff: a team of communicating auditors covers more **cross-file**
   surface than one lens reading alone, because its members can hand each other what they found. The
   cost is that a team's findings are **correlated**, so the adjudication — the lens ruling each claim
   `open|closed` with evidence — stays **outside** the team. Answering no is a real option; it costs
   discovery breadth, not gate integrity. For where the team runs and how its findings reach the gate,
   see *Where the agent team lives*.

Gate: you can plan without guessing. If answers surface a trivial task, say so and exit the
loop — see red flags.

## Phase 2 — PLAN

EnterPlanMode. Explore, then draft a plan that MUST contain:

- **Task table**: `(id, name, work, writable paths, acceptance)` — acceptance is a checkable
  criterion per task, not a vibe. Add **`dependsOn`** to any row whose refs or inputs are files
  another row writes: it is the only thing that orders IMPLEMENT, and rows without it are
  implemented concurrently (so their writable paths must be disjoint).
- **Every claim is a `tasks[].acceptance` clause or a `mechanicalChecks` entry**, plus the review
  surface. A criterion belonging to no task belongs nowhere: it is a sentence nothing runs, and it is
  the largest defect surface a plan has. Whole-deliverable facts become a mechanicalCheck; per-task
  facts become that task's acceptance. Prose may explain WHY, never assert WHAT — the moment prose
  states a criterion there are two representations of one fact, and they drift within one amendment.
  `plan-lint`'s `prose-command` rule enforces the executable half: a command in prose that no
  acceptance, redCommand or mechanicalCheck runs is a MAJOR.
- **Run sizing** — the scrutiny the gate will apply (Phase 4 documents what each knob costs):

  ```
  ## Run sizing
  Review lens:       <the dimensions the ONE lens judges — merge every named risk into that one prompt>
  Mechanical checks: <name> — `<exact command>`              (omit the section if none)
  Rule checks:       <name> — `<exact command>` blockAt <val> (opt-in, omit if none)
  Scored checks:     <key> — <what it scores>, ADVISORY: never gates  (opt-in, no default; omit if none)
  Test-first:        <task id> — `<redCommand>`               (one line per red-gated task; omit if none)
  Red dispositions:  <task id> — <why this task carries no red gate>  (one line per dispositioned task; omit if none)
  Lens provider:     <provider>                              (only when axis 6 is not routed)
  ```

Each active task costs 1 implementer, plus 1 verifier only if it has no `acceptanceCmd`. **The
review lens is exactly 1 agent**; it rules on both `carriedFindings` and external `priorFindings`
without additional agents. Red probes, `acceptanceCmd`s, mechanical checks and rule checks cost
**no** agent — scripts run them. Each scored item and attempt costs one agent. Above ~50, split the
plan into sequenced work runs. Four acceptanceCmd tasks: 4 implementers + 1 lens = 5 agents.

**This is enforced, not advised.** `workflow.js` computes the fan-out
(`activeTasks + tasksWithoutAcceptanceCmd + 1 (the lens) + scoredItems + attempts`;
task counts are zero under `readOnly` or `onlyTasks: []`)
at arg-validation and **throws before dispatching anything** if it exceeds `maxAgents` (default 50);
the error prints the per-dimension breakdown. Raising `maxAgents` is legitimate; raising it silently
at dispatch time is what the throw prevents, because sizing is the user's call at approval time.

**Sizing lives in the plan because it shapes the gate.** Rewriting the lens or dropping a mechanical
check after approval would weaken the verdict without changing a byte the user signed off on — the
hash covers the `work:dispatch` spec block, so anything that decides PASS/FAIL has to be inside it.

**An audit needs a plan too.** `readOnly` still requires `planPath` + `specHash`, and the plan it
hashes is a **charter**, not a work order: what is being audited, what the lens judges it against, which
mechanical checks run, and the standing instruction that nothing may be written. The task table may
be empty. Do **not** shortcut by hashing the artifact under audit instead: the AUTHORITY block tells
every agent the hashed file is its *only authority*, so hashing the audited file would tell each lens
that the thing it is judging is the standard it judges against.

**A domain workflow's plan opens with YAML frontmatter `workflow: <name>`** (`dev`, `ds`, `writing`,
`workshop`, or plugin-qualified like `teaching:notes`) — it is what the re-seeded `Implement the
following plan:` prompt shows first, and what routes that session back to the owning skill.

**Arm the run before calling ExitPlanMode.** The plan must carry a dispatch block — every
`workflow.js` arg except `planPath`/`specHash`, which `work-dispatch.sh` injects because a block
cannot state its own hash:

```
<!-- work:dispatch
{"runId": "0813-slug", "goalTurns": 12, "args": { … }}
-->
```

Writing it is what arms the run, and the plan is the only file plan mode may write — which is also
the only thing that survives approval. **Claude Code clears the context when a plan is approved near
the ceiling** and re-seeds a bare `Implement the following plan:` session with no `work` in it, which
will otherwise implement in the main thread. While a plan is armed AND APPROVED — an ExitPlanMode
for that file returned without error in this session's transcript, or in the one a re-seeded session
names (`work-pending.sh`) — and no run dir records its hash (`.work/`, the block's `projectDir`, or
any `--run-dir`, found through `$TMPDIR/work-dispatch.log`), `~/.claude/hooks/main-thread-guard.sh`
denies Edit/Write/Agent in that project —
resolving the project from the nearest ancestor of `cwd`, so a `cd` cannot disarm it — and blocks the
turn from ending once; both name the dispatch command. It denies only what some task's
`writablePaths` covers (`work-dispatch.sh --covers`, failing closed when the spec cannot decide):
a path no implementer may write is not the run's output, which is what leaves the **red suite
authorable** here and nowhere else. For the one case that rule cannot reach — a path that IS a
task's output and must still exist before wave 1 — the plan declares `scaffoldPaths`, and
`work-dispatch.sh --scaffold` tells the guard to allow it. Without that list the only exit was
`--abandon`, which releases the guard for the **whole rest of the session** and silences the Stop
nudge along with it, so a plan defect became a disarmed run. A `readOnly` run never writes, so
there the Stop nudge is the only thing that fires. **A plan written but not approved is staged**: no
guard, no nudge, until ExitPlanMode or an explicit `work-dispatch.sh <plan>`. `--abandon` un-stages
an approved one and records that in `$TMPDIR/work-dispatch.log`, never in the project tree. Derive the prose Run sizing block from the JSON;
`work-dispatch.sh` prints the fan-out it computes, so drift shows up before anything is dispatched.

The user edits the plan file and approves via ExitPlanMode. Then **hash the plan where plan mode
actually wrote it** — resolve the path, don't assume it:

```bash
# The configured location — plansDirectory, project-root-relative, default .claude/plans.
PLANS=$(jq -r '.plansDirectory // empty' .claude/settings.local.json .claude/settings.json \
  ~/.claude/settings.json 2>/dev/null | head -1); PLANS=${PLANS:-.claude/plans}
PLAN=$(ls -t "$PLANS"/*.md 2>/dev/null | head -1)
[ -n "$PLAN" ] || PLAN=$(ls -t ~/.claude/plans/*.md | head -1)   # fallback: a pre-setting session
bash ~/.claude/skills/workflows/skills/work/scripts/work-dispatch.sh --spec-hash "$PLAN"   # 64-hex spec hash
```

Whichever it resolves to is `planPath`. **Never copy the plan** — one file, hashed in place, is the
run's authority. A copy creates a second file that can drift from the one the user edits. (The run
dir's `plan-<hash12>.md` is not that: it is a dead snapshot named by its own hash, written by
dispatch and never read as authority, so nothing can edit it or drift from it.)

**Ensure `plansDirectory` is set.** Plans belong inside `projectDir`, alongside the work and the
agents. `plansDirectory` is [relative to the project
root](https://code.claude.com/docs/en/settings), so any project-relative value puts them there —
`"./.claude/plans"` and `"./.planning"` both work, and `work` resolves whichever is set:

```bash
rg -n '"plansDirectory"' .claude/settings.local.json .claude/settings.json ~/.claude/settings.json 2>/dev/null
```

If no tier sets it, add one — `"plansDirectory": "./.claude/plans"` is this skill's default,
`"./.planning"` is what the domain workflows use — to the project's
`.claude/settings.json`, and gitignore that directory. Setting it at the user tier covers every
project at once, which is usually what you want. Precedence is Claude Code's own:
`.claude/settings.local.json` beats `.claude/settings.json` beats `~/.claude/settings.json`.

**It takes effect next session, not this one.** Plan mode fixes the plan's path when you enter it, so
a session that started before the setting was live still writes to `~/.claude/plans/` — which is why
the snippet above resolves the real path instead of asserting one. Do not stop the run over it, and
do not copy the file to make the path look right.

The plan's `work:dispatch` spec block is the sole authority every dispatched agent gets; the prose
around it explains but never binds. Nothing re-derives it: the agents re-run `--spec-hash` themselves
and stop on mismatch, so an amended spec halts the run instead of silently changing the contract,
while fixing a typo in the rationale costs nothing.

## Phase 3 — THE HOLD

**The dispatch arms a hold ON THIS SESSION** — in the main chat, not in the farmed child, which
runs one `workflow.js` and exits. The hold is what carries the outer loop (gate FAIL → fix → re-run;
tuicr findings → fix → re-review): on every Stop it blocks while the goal is not met, and it survives a
run that dies.

| | |
|---|---|
| **`args.goalCheck`** (optional) | the ONE command that settles the whole plan. Armed as the hold's check. NEVER a round verdict — `plan-lint` runs it through `hold-lint.ts` and a CRITICAL blocks the dispatch |
| no `goalCheck` | the hold is **check-less**: the judge alone on `args.goal`, bounded by `maxRounds` and `compose-goal.sh --minutes` |
| **`args.goalSettledBy`** (optional) | the facts that settle `args.goal` with no judge: `red:ID`, `mechanical:NAME`, `lens`, `rules`. All settled releases; any unsettled blocks naming it |
| `--run <run-dir>` | recorded by the arm. While the round is in flight a stop is ALLOWED and costs no round: a detached process is doing the work. Once its verdict lands the judge reads only that `result.json`'s named facts (failing legs, `survivingBlocking`, failed rules) against the goal's own conditions, never the transcript |

**Under the hold, a failed round advances with `work-redispatch.sh <plan> <run>/args.json --dispatch`,
never a fresh `work-dispatch.sh`** — the first re-runs only the tasks that flagged and their dependents
and carries the rest; the second re-runs every task, throwing away the round's verified work. The
hold's first counted block and its `--brief` say so with the paths filled in — or, when the redispatch
would be refused at its Tier 1 gate (plan-routed items, unchanged spec hash), say that the plan blocks instead.

### The check command — the rules `hold-lint.ts` enforces

The check is the executable FLOOR; `args.goal` is the objective and the judge rules on it. Arm both
where both exist.

- **RED when armed, and able to run.** `work-hold.sh` refuses exit 0 (a hold on a passing check holds
  nothing) and exit above 1 (could-not-run is not a verdict, and would hold forever on a typo).
- **It names and prints the goal state** — a suite passing, a rate under a number, a count at zero —
  **never a milestone** (`test -f report.md` is true while the objective is unmet) and **never a round
  verdict** (`work-result.sh`, `result.json`: green on a FAIL the loop was going to fix, and it
  outlives an abandoned run).
- **One clause per claim**, so a failure names which half. **Runs in this session's own cwd** — a check
  whose paths live in another repo can only be released unmet. **Broad enough that one edit cannot
  close it.** **No apostrophes**: the check is one single-quoted argument.

`hold-lint.ts` settles the decidable part of that on the check and the goal text both; `plan-lint`
runs it one dispatch before the arm, and a CRITICAL blocks. `--probe` also RUNS the check twice —
two runs that disagree is an instrument, not a gate — and prices it, since the hook runs it on every Stop.

```bash
bun ${CLAUDE_PLUGIN_ROOT}/skills/work/scripts/hold-lint.ts '<CHECK>' --goal '<OBJECTIVE>' [--probe]
```

### Arming by hand, when no dispatch is doing it

A session that is not dispatching — an overnight hunt, a spawned agent's caller, a `visual-verify`
loop — arms the same hold itself:

```bash
A=${CLAUDE_PLUGIN_ROOT}/skills/work/scripts/work-hold.sh
bash $A '<CHECK>' --goal '<OBJECTIVE>' --rounds 4 --minutes 120
bash $A --goal '<OBJECTIVE>'    # CHECK-LESS: the judge alone, and an UNAVAILABLE judge BLOCKS
bash $A --status                # armed? check, run, rounds used, minutes left, recent exits, ledger
bash $A --disarm                # THE USER releases it: a tty prompt, or the permissions.ask prompt
```

Defaults are 4 rounds and 120 minutes; above either, the arm prints the per-wake context cost and the
equivalent `grind` command, then arms. A dispatch arms with `--rounds` = the block's `goalTurns`
(else `args.maxRounds`). A hold on a run counts the rounds the run DISPATCHED (`args.json` `rounds`),
never Stops; a hold with no run counts its red Stops. Each run keeps its
own hold in the one state object — a second dispatch queues the first run's hold rather than replacing
it, a re-dispatch of the SAME plan replaces its own, the Stop hook judges whichever held run is not in
flight, and a release promotes the next. A held run whose loop died without a verdict (its
farm-events pids all gone, no `result.json`) is dropped on the next Stop, said once, and holds nothing.
A hold writes nothing in a project tree, so it does not cap the auto-compact window: the only live cap
is the project's `.claude/settings.local.json` (managed needs root, `--settings` is startup-only).
`WORK_HOLD_COMPACT_WINDOW=250000` at arm time opts into that write, restored at release. Templates for the check, the nudge and an unattended brief:
[`references/hold-templates.md`](${CLAUDE_PLUGIN_ROOT}/skills/work/references/hold-templates.md).

**Release is not the session's to take.** Three layers, none sufficient alone:

| layer | reaches | the residual hole |
|---|---|---|
| `--disarm` — the tty prompt when there is a terminal, otherwise the `permissions.ask` rule `Bash(*work-hold.sh --disarm*)`, which prompts on phone and Remote Control too and records the verb `released by user (permission prompt)` | a human, wherever they are | the ask rule matches the command text AS WRITTEN, so a variable-indirected call slips past it — a tripwire, not a lock |
| the hook restoring a state file deleted without a sanctioned release | a `rm` instead of an argument | the ledger must be readable |
| `permissions.ask` on `*work-hold-*.json*` / `*work-hold-*.releases.log*` | an edit in place | same text-matching hole |

The honest move for a gate you think is wrong is to arm the right one, not to stop.

**A hold frozen at rounds 0 that never releases is usually version skew, not a stuck check.**
`--status` reports `never evaluated since arm Nm ago` when no Stop has reached `hooks/work-hold.ts`
since the arm — the session's Stop registration points somewhere else. `/reload-plugins`. Until then
`cron-delete-guard.ts` keeps refusing the heartbeat deletes, and says the same thing in its refusal.

**Done means the goal is met, not that the check is green.** The hold releases `passed-goal-met` only
when the judge agreed; `passed-unjudged` (no goal, or the judge was unreachable with a check to fall
back on) means nobody confirmed the objective — say so rather than reporting it as done, and leave any
heartbeat cron alive.

**The continuation rule, which the arm states on the first counted block and in `--brief`: when a
sub-run returns and the check still fails, TAKE the next action — do not propose it.** Every measured
stall happened at a moment of legitimate completion, which is the moment with the most information the
session will ever have. Two branches open: pick one, say why in a line, do it. The arm states the
standing authority with it — what the session may decide alone, unasked — because every decision left
open becomes a question asked into an empty room.

A round verdict is not the hold's business in either direction — it goes green on a FAIL the loop was
going to fix, and it outlives a run the user abandons. For a long loop whose target is
a computable command and needs no session, use grind instead.

**`work-dispatch.sh` does Phase 3 and Phase 4 in one call** — it reads the armed plan's dispatch
block, injects `planPath`/`specHash`, writes `args.json`, starts `workflow.js` detached and arms the
hold. Run it, then skip to the Monitor; the rest of these two phases is what it does and why,
and what to check when it reports something odd:

```bash
bash ${CLAUDE_PLUGIN_ROOT}/skills/work/scripts/work-dispatch.sh                    # armed plan; or pass one
bash ${CLAUDE_PLUGIN_ROOT}/skills/work/scripts/work-dispatch.sh --provider codex   # "run work through codex"
```

**The provider comes from the invocation, and every skill that wraps `work` forwards it.** A provider
named in `$ARGUMENTS`, however it is spelled — `--provider codex`, `--dispatch codex`, "run this on
gpt" — is `--provider codex` on the dispatch line, whether `work` was invoked directly or through `/dev`,
`/ds`, `/writing`, `/notes`, `/slides` or `/exams`. Those skills print their own dispatch recipe, so
each carries the flag too; dropping it silently routes the run by kind instead of on the named provider.
`--provider` is the ONE spelling: `work-dispatch.sh --dispatch` and `work-redispatch.sh --dispatch
codex` each exit 2 naming it, rather than dying on "unknown flag" or accepting a synonym.

**With no `--provider`, each step routes by kind through `${CLAUDE_PLUGIN_ROOT}/scripts/lib/routing.json`.** Before
`args.json` is written the dispatcher calls `route.ts --row` once per kind and injects the kind map
as `args.routing` (`kindModels`, `source`, per-kind `decisions`); the claude wrapper hosts the run and
`workflow.js` gives each step its kind's full model id — an implementer `judgement` or its task's
`kind`, the verifier and every probe `script`, the lens `review`. An explicit model arg still wins
(the model rows below). A `route.ts` refusal for any kind blocks the dispatch before anything runs.
**`--provider claude|codex|gemini` is the whole-run override**: that wrapper hosts every step,
`route.ts` is not consulted, `args.routing` is `{source: 'flag', provider}`, and the wrapper remaps
the tier names so every `'sonnet'` default follows — bar a `lensProvider` plan, whose review row is
the one `route.ts` call, recorded as `args.routing.lens` with its model in `args.lens.model`.
`work-redispatch.sh` takes the same flag and re-resolves `args.routing` every round, so a refreshed
table takes effect next round, and when a round repeats its predecessor's failure exactly, a different
provider is the lever for framing lock-in — `lensProvider` on the judge side
(`references/convergence.md`). Design: `docs/DESIGN-routing.md`.

It needs nothing from the session's context, which is the point: a run whose context was cleared at
plan approval is recovered by this one command, with no re-exploration.

**The plan-review gates run before `args.json` is written, exiting 3 with the run still armed and
every artifact byte-identical.** Tier 1 is `plan-lint.ts` on the built args. The two probe gates
execute disjoint command sets, each command exactly once: tier 2 runs active tasks' `redCommand`s
unless they carry proven `red-green` adjudications for that exact current command. Its classifier
refuses `red-not-red` (exit 0 — the gate already passes) and `could-not-run` (exit 127, a missing runner,
`pytest` exit 4/5, or no test output at
all), so only non-zero *with* a real test result proceeds; **tier 2b runs every `mechanicalChecks`
cmd** at baseline via `plan-preflight.ts --only mechanical`, where only a `critical` refuses.
Tier 2 also runs each active `acceptanceCmd` once, concurrently, into `acceptanceBefore`; it reports
(exit 0 prints a WARNING) and never refuses. readOnly runs skip it.
`--no-red-probe` drops tier 2, `--no-mech-probe` drops tier 2b, `--no-lint` drops all of them, and
`WORK_RED_PROBE_TIMEOUT` / `WORK_MECH_PROBE_TIMEOUT` (300s each) bound their own tier's commands.
A task whose work is already COMPLETE can satisfy neither gate —
a `redCommand` is refused `red-not-red`, omitting it is refused `redcommand-missing` — so it declares
`redDisposition` instead; both scripts echo `red: N gated, M dispositioned` with each disposition,
beside the wave graph.

### What WAKES the session, once it has gone quiet

A Stop hook reaches nothing when no turn is running, so the hold alone cannot restart a session that
has gone quiet. The **watcher mod** (`hooks/watch/watcher.ts`) does: it reads
`$TMPDIR/farm-events/$CLAUDE_CODE_SESSION_ID`, where `work-round.sh`, `work-loop.sh` and their
`farm.sh` file themselves, and wakes the main chat ONCE on the loop's exit (the round's verdict when
no loop runs) and on a run that dies without one. `farm-status`, run as a statusLine command, prints
the round and phase from the same files; set it with
`{"statusLine":{"type":"command","command":"farm-status","refreshInterval":5}}`, or a composing
script that calls it. `/farm` prints the table.

**Nothing wakes a session that is not running.** A run that finishes while no session is open is
reported only when the session next starts, so a restarted loop can sit with nothing
to wake. So the cron is the **backstop, on by default**: the dispatch
prints an hourly `CronCreate` call (`WORK_LOOP_INTERVAL_MINUTES` sets the period) whose prompt is a
nudge (`and? (work run <runid>)`) — a few words, and a tick mid-round is allowed through uncounted by
the hold, so it is cheap. **Make that call before your next action and report the job id**; `CronList`
is the only thing that proves it exists. `--no-cron` opts out, and then the dispatch says in one line
that the watcher mod is the only wake.

Nothing is typed into this session and nothing is queued, so there is no send to verify, no transport
to fall back to, and no ordering constraint against Phase 4.

**`work-result.sh` is the round's verdict, and only the round's.** Exit 0 is PASS, 1 is FAIL, 2 is
could-not-run; a `readOnly` run closes on either verdict, because an audit's gate legitimately FAILs.
The escapes the objective states — the round counter and the wall clock — are read from `args.json`
and `work-elapsed.sh`.

**If the USER abandons the run**, retire it with
`bash ${CLAUDE_PLUGIN_ROOT}/skills/work/scripts/work-abandon.sh <run-dir> --why '<reason>'`: it writes
the run's verdict (`overallPass=false, abandoned=true`), releases that run's hold (others stay), and allows the `CronDelete`
a `cron-delete-guard` deny would otherwise refuse. It is the only sanctioned way out of an armed hold
short of the user confirming `work-hold.sh --disarm` at a terminal.

**Name the plan by PATH, never by a fixed sha256.** A pinned digest self-invalidates the first time
the FAIL loop does what this file prescribes: fix, **amend the plan, re-hash**, re-dispatch. The run
then PASSes against a hash the condition does not name, and the evaluator correctly reports the goal
unmet on finished work. The path is stable; the hash is the thing the loop is expected to change.

**Write `args.goalCheck` so a COMMAND settles the PLAN, not the round.** Nothing reads the
conversation to decide whether the work is done, and `work-result.sh` settles one round only. A plan
that has no such command states none and gets the judge-only hold; what it must not state is a check
reading `result.json`, which `plan-lint` blocks.

Phase 4 dispatches **in the same turn** — `work-dispatch.sh` does both, so there is nothing to
sequence and no queued message to wait out.

## Phase 4 — workflow.js

The args, annotated — write them to the args file as **plain JSON**, no comments, since the workflow
`JSON.parse`s it:

This fence is `work`'s ARGUMENT SCHEMA, not a workflow declaring its own gate.
`mechanicalChecks: [{name, cmd}, ...]` documents the parameter `work` ACCEPTS; `work` is the
engine that RUNS a workflow's checks and has none of its own to collapse, so P10 — which
governs what a generated workflow declares — is declared away for this region only:

<!-- wc-probe: ignore-entry-point:start -->
```js
{
  projectDir, planPath: "<the path $PLAN resolved to in Phase 2>", specHash: "<64-hex>",
  goal: "<one sentence>",
  tasks: [{id, name, work, writablePaths, acceptance, refs, redCommand|redDisposition, agentType?}, ...], // from the plan's task table
  lensProvider: "codex",           // ONLY if CLARIFY axis 6 named a provider; else omit (routed)
  mechanicalChecks: [{name: "node-check", cmd: "node --check foo.js"}, ...],  // optional
  scoredChecks: [{key, items, prompt, schema, components, passthrough, refs, agentType}, ...], // optional; advisory, never gates; an item is a string or {text, inputs: [paths]} (carry-forward)
  lens: {prompt: "<what the ONE review judges>", refs: [], agentType: "Explore",
         effort: "high", sandbox: true},      // optional; ONE object; a `model` here pins it over the kind map
  attempts: [{key: "a1", prompt: "<task for the blind probe>", refs: [], agentType: "Explore"}], // optional
  authorityExtra: "<domain rule appended to every agent's AUTHORITY block>",  // optional
  implementerAgentType: "…", verifierAgentType: "Explore",        // optional
  readOnly: true,                                                 // optional; audit an existing tree
  priorFindings: [{id, title, severity, detail, file, ownerTask}, ...],  // optional; claims made OUTSIDE this run
  carriedFindings: [...same shape...], taskFixes: {"<taskId>": [...]},   // derived by work-redispatch.sh
  onlyTasks: ["<taskId>"], priorResults: {implemented: [], verified: [], red: []}, // derived re-run scope
  // onlyTasks: [] is a zero-implementer round only when every task has carried records
  freezeFindingSet: true, maxRounds: 6,                           // freeze is derived; cap defaults to 6
  maxAgents: 50,                                                  // optional; fan-out ceiling — throws if the floor exceeds it
  implementerEffort: "xhigh", verifierEffort: "medium",           // optional; null omits the key and inherits
  scoredEffort: "low",                                            // optional; null omits the key and inherits
}
```
<!-- wc-probe: ignore-entry-point:end -->

**Dispatch through farm-out, never the built-in `Workflow` tool** — the guard at
`~/.claude/hooks/main-thread-guard.sh` denies it unconditionally, so an in-session call is
dead. `farm.sh` sets `FARM_OUT_CHILD=1`, which is what lets its child make the call.
`work-dispatch.sh` runs exactly this and prints the wait loop with the run's paths filled in; what
follows is what it does, for when you are reading its output or a dispatch has gone wrong.

```bash
R=.work/<run-id>; mkdir -p "$R"          # the runner refuses if --out's directory does not exist
# write the args object above to "$R/args.json" as JSON
# DETACHED, never foreground: a real gate runs 20-60 min and a foreground tool call caps out
# and kills it mid-run, as does a harness-tracked background task.
setsid nohup bash ${CLAUDE_PLUGIN_ROOT}/skills/farm-out/scripts/farm.sh \
  --workflow ${CLAUDE_PLUGIN_ROOT}/skills/work/workflow.js \
  --args "$PWD/$R/args.json" --out "$PWD/$R/result.json" --cwd "$PWD" \
  > "$R/run.log" 2>&1 < /dev/null &
# Wait for it: work-result.sh is one-shot and knows nothing about the dispatch. Watch BOTH the
# artifact and the process — a watcher that only greps for success is silent through a crash — and
# key liveness on THIS run's --out path, or a concurrent dispatch reads as proof ours is alive.
# farm-alive.sh keys on the RUN, not the runner's filename: the runner's event file carries
# out=<this run's --out> and its filename is the pid, so a rename cannot break the check.
while :; do
  [ -s "$PWD/$R/result.json" ] && break
  bash ${CLAUDE_PLUGIN_ROOT}/skills/work/scripts/farm-alive.sh "$PWD/$R/result.json" > /dev/null \
    || { echo "dispatch died with no verdict — see $R/run.log" >&2; exit 1; }
  sleep 30
done
bash ${CLAUDE_PLUGIN_ROOT}/skills/work/scripts/work-result.sh "$PWD/$R/result.json"
```

`--loops N` launches `work-loop.sh` detached to execute that wait and drive redispatch, recording
its exit code in `<run-dir>/loop.exit`. It checks liveness, adjudicates each verdict and consults
`converge-check.ts` each round, up to N rounds. N defaults to the args `maxRounds` value, or 6 when
absent; a non-numeric value is refused with exit 2 naming the flag. `--loops 0` prints the wait loop
instead and exits 0.

The driver's exit codes: **0** PASS; **exit 9** the dispatch died with no verdict (see the run log it
names; never 1, which is `work-result.sh`'s FAIL); **exit 2** `work-result.sh` refused the verdict; **exit 3** `work-redispatch.sh` refused the round at its Tier 1 gate (a human-owned plan decision); **exit 5** `converge-check.ts` reported NOT
CONVERGING, which is evidence about the BRIEF — re-plan rather than spend the remaining rounds;
**exit 6** the round cap was reached; **exit 7** a plan defect needs a scope decision, which is a
human's to make; **exit 8** a `readOnly` run reached its verdict on its first adjudicated round (an
audit's FAIL is its answer), and the hold releases on it.

**Run that wait as a `Monitor`, not a foreground Bash call** — Bash caps at 10 minutes and a gate
runs 20-60. Pass the loop body as Monitor's `command` with `persistent: true` (no deadline), keeping
both terminal states: result written, and process gone without one. Then call `work-result.sh` when
it fires. Fall back to the loop across turns only where Monitor is unavailable — Bedrock, Vertex,
Foundry, or `DISABLE_TELEMETRY`/`CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` set. A Monitor dies with
the session; the detached run does not, and the hold is a file, so the hold is what survives a restart.

**When `work-result.sh` returns the verdict, send a `PushNotification` carrying the OUTCOME** —
"elide gate PASS, 33pp, both readings", never "the run finished". A run is a deliverable and takes
up to an hour, so the user has probably walked away; a notification that only reports completion
makes them come back to ask what happened, which is the thing it was supposed to save them. Here
only — not at dispatch, not at round boundaries.

`farm.sh` exits 2 on a malformed call (`--workflow` without `--out`, an `--args` file that is not
readable JSON) and non-zero when `--out` came back missing or not a JSON object. `work-result.sh`
then refuses (exit 2) unless the file is one object carrying `overallPass`, `verdict`, `scoreTable`,
`findings`, `tasksThatFlagged`, `mechanicalThatFailed`, `lensesThatFlagged` and `rulesThatFailed`
with the right types, and prints the verdict and the score table on success. Those four selectors are
REQUIRED: a return dropping one channel would make a FAIL carried solely by that channel read as a
clean run. It also refuses (exit 2) an `overallPass: true` beside any non-empty selector. `routes`
and `planFindings` are **optional and type-checked when present**, so an older verdict on disk still
reads — but a FAIL with a non-empty `planFindings` is the one a re-dispatch cannot close, so consume
it too.

**State the residual plainly: mechanical claims are adjudicated, the rest is shape, not fidelity.**
A model transcribes the workflow's returned object into `--out`, so a fabricated object with the
right keys — outside the re-run mechanical claims — passes both checks. Reconcile the score table
against the plan's Run sizing: counts that cannot be squared with what the run was sized to dispatch
make the result unverified, not a PASS.

| param | type | effect |
|---|---|---|
| `goalCheck` | `string` (optional) | The ONE command that settles the whole PLAN — not a round. `workflow.js` never reads it; `work-dispatch.sh` arms the hold on it, so it is a specification and is linted as one: `plan-lint` runs it through `hold-lint.ts` and a CRITICAL (a round verdict, an apostrophe, milestone phrasing, a human-closed clause) BLOCKS the dispatch, one step before the arm. Omit it when the plan has no such command and the hold becomes the judge alone on `goal`; a declared-but-empty string is refused rather tha

…(truncated)
