@mayurdluffy/ccwf 0.6.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -11,7 +11,7 @@ All loop state lives in files, never only in your context: the tickets' `**Statu
11
11
 
12
12
  ## Start or resume
13
13
 
14
- 0. **Confirm the roster first, every session.** Read `workers.conf` (the user's last decision: agent, model and effort per worker). Ask the user once (AskUserQuestion): keep it, or change it? `npx @mayurdluffy/ccwf@latest stats` shows how each model has done in this repo. On a change, rewrite the rows and the `decided:` line, and log the question and answer in `docs/DECISIONS.md` if the project has one. Never assign a ticket before this answer.
14
+ 0. **Confirm the roster first, every session.** Read `workers.conf` (the user's last decision: agent, model and effort per worker). Ask the user once (AskUserQuestion): keep it, or change it? `npx @mayurdluffy/ccwf@latest stats` shows how each model has done in this repo. On a change, rewrite the rows and the `decided:` line, and log the question and answer in `docs/DECISIONS.md` if the project has one. Never assign a ticket before this answer. If the roster has the row `isolation worktree`, read `ISOLATION.md` now.
15
15
  1. Read `.scratch/<feature>/progress.md` (table plus its `## Resume` section). Do not re-read the spec; workers read it.
16
16
  2. Run `.agents/skills/orchestrate-workers/grid.sh`: it builds the `workers` tab in your own herdr space, or prints the workers when that tab is already there. If a worker is mid-ticket, restart its watcher (step 4 of the loop) instead of reassigning.
17
17
  3. Act on `## Resume` → "Next action".
@@ -20,7 +20,7 @@ All loop state lives in files, never only in your context: the tickets' `**Statu
20
20
 
21
21
  1. **Pick a wave.** Run `.agents/skills/orchestrate-workers/tickets.sh ready .scratch/<feature>`: it prints the tickets that can start, lowest number first. Take the first ones, at most 4. If it names a ticket whose blockers it cannot read, fix that `**Blocked by:**` line (numbers only), then run it again. Do not work out readiness by reading tickets. A wave can hold fewer than 4; never start a blocked ticket to fill a slot.
22
22
  2. **Check overlap.** Tickets in one wave share the working tree (with `isolation worktree` they do not, but overlapping edits still end in a conflict, so the same rule holds). If two would edit the same files, move the higher-numbered one to the next wave. Adding or upgrading a dependency counts as editing the same files (`package.json`, `package-lock.json`): at most one such ticket per wave.
23
- 3. **Assign.** One ticket per worker; set each ticket's status with `.agents/skills/orchestrate-workers/tickets.sh set <ticket> in-progress` (every status change goes through this script) and update its progress row.
23
+ 3. **Assign.** One ticket per worker; set each ticket's status with `.agents/skills/orchestrate-workers/tickets.sh set <ticket> in-progress` (every status change goes through this script, which writes the progress row's status too) and fill in the row's wave and worker.
24
24
  4. **Wait.** One background watcher per worker, started right after its job file is written:
25
25
  `ALLOW='\.agents/skills/verify-ui/(run|probe|ab)\.sh ' .agents/skills/orchestrate-workers/watch.sh <name>`
26
26
  (that `ALLOW` covers the browser checks, which Codex must run outside its sandbox to reach localhost)
@@ -28,15 +28,15 @@ All loop state lives in files, never only in your context: the tickets' `**Statu
28
28
  - `DONE` (turn finished) → review. With the guardrails module it also says `checks: passed`.
29
29
  - `FAILED` (turn finished, but the project checks fail). The watcher already sent the worker back once. Read the printed lines: in this ticket's area, send it back with a note; in another running ticket's area, go on with the review and run the checks again when the wave is quiet. `checks: not run` means `.agents/guardrails` differs from the last commit: read that diff before you commit or restore it.
30
30
  - `EXITED` (agent closed, pane idle). If the lines show `[name] ERROR:`, the job never ran: fix what it names (usually the `workers.conf` row) and assign again. Otherwise check the ticket for a report before treating it as finished.
31
- - `GATE` → approve with `.agents/skills/orchestrate-workers/approve.sh <name>` (it presses the key that agent expects: Claude ignores `y`) only if the command is local and safe (installing a dependency: first check the `package.json` diff for new packages), then start the watcher again. Never answer a product decision; that goes to the user. So does the question whether to trust this folder: the user answers it in the pane, once per repo.
31
+ - `GATE` → approve only if the command is local and safe (installing a dependency: first check the `package.json` diff for new packages). Approve and watch again in one command, as the same background task as before: `.agents/skills/orchestrate-workers/approve.sh <name> && ALLOW='...' .agents/skills/orchestrate-workers/watch.sh <name>` (`approve.sh` presses the key that agent expects: Claude ignores `y`). Do not approve in one call and restart the watcher in another: each call re-reads your whole context. Never answer a product decision; that goes to the user. So does the question whether to trust this folder: the user answers it in the pane, once per repo.
32
32
  - `TIMEOUT` (50 minutes) → read the printed lines: still working, start the watcher again; stuck or looping, end the session and reassign with a note of what went wrong.
33
33
  - `STUCK` or `GONE` → the pane is dead: rebuild the tab with `grid.sh --rebuild` (see "The workers tab").
34
34
 
35
- Do not use `hc wait` (it never returns for cursor-agent) and do not `hc read` busy workers. Routine-command allowlists: `.cursor/cli.json` (Cursor), `claude-worker-settings.json` in this folder (Claude); Codex runs sandboxed and asks only to leave the sandbox. Claude workers run `npm test`, `npm run` and the verify-ui scripts without asking; `npx`, `node` and `npm install` ask, because they can run anything. If the project uses other commands for its checks (`pnpm test`, `npx tsc --noEmit`), add those exact commands to the file, never a whole runner such as `npx *`. These lists prevent accidents; they are not a sandbox.
35
+ Do not use `hc wait` (it never returns for cursor-agent) and do not `hc read` busy workers. Allowlists: `.cursor/cli.json` (Cursor) and `claude-worker-settings.json` here (Claude); Codex asks only to leave its sandbox. Add the project's other check commands to them as exact commands (`pnpm test`), never a runner such as `npx *`. They prevent accidents; they are not a sandbox.
36
36
  5. **Review each ticket as its worker finishes** (see Review). Send defects back to the same worker session. Other workers keep running. Set the ticket to `in-review` while you do.
37
- 6. **Human check per ticket.** When a reviewed ticket has anything a person should see or judge (see "Human verification"), stop and ask the user right then; the other workers keep running. Otherwise set it to `reviewed` with `tickets.sh set`, update its progress row, and move on.
37
+ 6. **Human check per ticket.** When a reviewed ticket has anything a person should see or judge (see "Human verification"), stop and ask the user right then; the other workers keep running. Otherwise set it to `reviewed` with `tickets.sh set` (the progress row follows), update `## Resume`, and move on.
38
38
  7. **Wave done.** When every ticket of the wave is reviewed, end each worker session and report (see Report). Then wait.
39
- 8. **On the user's go-ahead**, commit with the `commit` skill (one commit per ticket where the files separate cleanly), set the tickets to `done`, update `docs/FEATURES.md` and `progress.md`, check context (see Context), and start the next wave. Never commit before the go-ahead.
39
+ 8. **On the user's go-ahead**, commit with the `commit` skill (one commit per ticket where the files separate cleanly), set the tickets to `done`, update `docs/FEATURES.md` and `progress.md`, then hand off (see Context limits): the next wave starts in a fresh session. Never commit before the go-ahead.
40
40
  9. **On a bug report**, send it to the worker that owns the ticket (a fresh session if the old one ended), re-review, and stop again.
41
41
 
42
42
  ## Human verification
@@ -49,18 +49,25 @@ Stop and ask the user to verify a ticket when it has any of:
49
49
 
50
50
  Pure refactors, schema or domain logic fully covered by tests, and docs need no separate stop; they are covered by the wave report.
51
51
 
52
- The ask is short: the ticket, what to open or run (exact URL or command), what they should see, and "reply ok or describe the bug". Set the ticket to `awaiting-user` with `tickets.sh set` and in its progress row.
52
+ The ask is short: the ticket, what to open or run (exact URL or command), what they should see, and "reply ok or describe the bug". Set the ticket to `awaiting-user` with `tickets.sh set` (the progress row follows), and put the question in `## Resume` → Waiting on user. When they answer, set the ticket's status again at once and take the question out.
53
53
 
54
- ## Context
54
+ ## Context limits
55
55
 
56
- You cannot run `/compact` or start a session yourself; the user does. Watch for: Claude Code's context warning, a long session (roughly two waves done in one session, or many large tool outputs), or you no longer remembering details you need without re-reading.
56
+ Limits are fixed numbers, not judgment. `context.conf` holds them: a working window of 200k tokens (a budget, not the model's maximum), a warning at 50% and a hand-off at 65%. In Claude Code, and in Codex once the user has approved its hooks (`/hooks`), hooks measure the session after every tool call and prompt and print `CONTEXT nn%` notices. Cursor is not measured, so for it only the wave rule below applies. Workers have their own window and limits (`WORKER_*` in `context.conf`: 300k, 70% and 85%): ordinary tickets stay under them, and a worker's notice is an order to the worker, not to you. You cannot run `/compact` or `/clear` yourself; the user does.
57
57
 
58
- - **Mid-wave and context is getting full:** first bring `progress.md` → `## Resume` up to date, then ask the user to run exactly:
59
- `/compact Orchestrating .scratch/<feature> with orchestrate-workers. Keep: wave N tickets and their workers, review findings not yet fixed, pending user questions. State is in progress.md.`
60
- Continue the wave after it.
61
- - **Wave done and context is full (or nearly):** after the commit, update `## Resume`, then ask the user to start a new session (`/clear` or a new terminal) and paste exactly:
62
- `Use the orchestrate-workers skill. Feature: .scratch/<feature>. Resume from progress.md.`
63
- Do not start the next wave in the old session.
58
+ | When | You do |
59
+ |---|---|
60
+ | **A wave is committed**, at any percentage | Hand off at once (below). The next wave starts in a fresh session. |
61
+ | **`CONTEXT` notice at 50%** | Finish the review in hand. Assign nothing and start no review. Hand off at the next point listed below. |
62
+ | **`CONTEXT` notice at 65%** | Finish only the step in hand, then hand off. Start nothing, and read nothing that is not needed to write `## Resume`. From here a hook refuses `assign.sh` and `review.sh` until the user resets the session; `tickets.sh`, `watch.sh`, `approve.sh`, `end.sh` and `context.js` stay open. |
63
+
64
+ **Never change `context.conf`, `.claude/settings.json` or a hook to get past a limit or a refusal.** Only the user sets limits.
65
+
66
+ **Where you may stop:** only after every result so far is in a file: review findings in the ticket under `## Review findings`, statuses set with `tickets.sh set`, and `## Resume` rewritten (see below). Never between `assign.sh` and starting that worker's watcher, and never in the middle of a review whose result is not yet recorded.
67
+
68
+ **Hand off:** run `.agents/skills/orchestrate-workers/context.js handoff .scratch/<feature>`. It refuses, and names what is wrong, until `tickets.sh check` passes. When it passes it prints the one command for the user: `/clear` plus a paste line when no worker is mid-ticket, or `/compact` with the exact keep list when one is. Give the user that text unchanged. Then do nothing else in this session. After `/clear` or `/compact` a hook puts `## Resume` back as the first thing the new session sees.
69
+
70
+ **What survives a reset is what is in files:** the ticket statuses, `progress.md` (the table and `## Resume`), the review findings in the tickets, `workers.conf`, and `docs/DECISIONS.md`. **What is dropped on purpose:** worker screens, diffs already reviewed, command output, earlier discussion. If you need something after the reset that is in none of those files, write it into `## Resume` Notes before you hand off; do not count on a compaction summary to keep it.
64
71
 
65
72
  ## progress.md
66
73
 
@@ -68,6 +75,7 @@ You cannot run `/compact` or start a session yourself; the user does. Watch for:
68
75
  | Ticket | Wave | Worker (model, effort) | Status | Commit | status: in-progress | in-review | reviewed | awaiting-user | done
69
76
  ...
70
77
  ## Resume
78
+ - State (<date>): <one line: where the effort stands>
71
79
  - Next action: <one line: what the next session does first>
72
80
  - Workers: <name → ticket, or idle>; tab built: yes/no; roster confirmed this session: yes/no
73
81
  - Waiting on user: <questions or checks asked, or none>
@@ -75,15 +83,17 @@ You cannot run `/compact` or start a session yourself; the user does. Watch for:
75
83
  - Notes: <environment facts the next session needs, e.g. dev server terminal>
76
84
  ```
77
85
 
78
- Update `## Resume` whenever the next action changes: after assigning, after each review, before asking the user anything, before any compact or handoff.
86
+ **Keep `## Resume` true, in the same step as the change that makes it untrue.** `tickets.sh set` writes the ticket's row in the table for you and then reminds you of this; rewrite State, Next action, Waiting on user and Workers right then, one line each:
87
+ - after assigning, and after each review;
88
+ - **when the user answers something you were waiting on**: set the ticket's status first (`in-progress`, `in-review`, `reviewed` or `done`; never leave `awaiting-user` once they have replied) and take the answered question out of Waiting on user;
89
+ - after a commit: record its hash in the row and set the ticket `done`;
90
+ - before asking the user anything, and before any compact or handoff.
79
91
 
80
- ## The workers tab
81
-
82
- Four workers, by pane: `alpha` top left, `beta` top right, `gamma` bottom left, `delta` bottom right. Which agent, model and effort each one runs is in `workers.conf`, not here: `pane.sh` reads its row fresh for every ticket, so a roster change applies from each worker's next ticket without rebuilding the tab. Supported agents: `codex`, `cursor`, `claude`, in any mix. A row that cannot start (unknown agent, missing CLI, an agent that quits within 20 seconds on a bad model id or login) leaves `[name] ERROR: ...` above the pane's idle line, and the watcher prints it.
92
+ Then run `.agents/skills/orchestrate-workers/tickets.sh check .scratch/<feature>` and fix every line it prints. It finds a row that says another status than its ticket, a done ticket with no commit recorded, a missing Resume line, and notes that still say to commit or start what is already done. The user may watch these lines live (herdr-workstation's Board shows the table and these four lines), so a stale one is a false alarm for them.
83
93
 
84
- The tab is named `workers`, lives in your own herdr space (the one holding your terminal) and is always a 2x2 grid. Manage it only with `.agents/skills/orchestrate-workers/grid.sh`: no argument builds it or reports the one already there; `--rebuild` closes your space's `workers` tab and builds a new one, and refuses while any worker is busy. Other spaces have their own orchestrators and `workers` tabs (other repos, other features): never close, reuse, send to or read their tabs, and never call `herdr-app do tab.close` or `space.close` yourself. Each pane runs `pane.sh <name>`: it starts one agent per job file, returns to idle when the agent exits, and reloads itself after every ticket. Each pane writes its terminal address to `.git/hc-workers/<name>.t`: `assign.sh`, `watch.sh`, `approve.sh` and `end.sh` take the worker name directly; for hc use `hc send $(<.git/hc-workers/alpha.t) '...'`. (herdr only names a terminal started with `hc run --name`, and those cannot be placed in a grid, so the grid panes stay unnamed in herdr; the pane shows `[name]` and its title.)
94
+ ## The workers tab
85
95
 
86
- After `ccwf update` changes this skill, run `grid.sh --rebuild` once every worker is idle, so the panes run the new scripts (a tab from before the rename to `workers` and `delta` is replaced the same way).
96
+ Four workers in a 2x2 tab named `workers` in your own herdr space: `alpha` top left, `beta` top right, `gamma` bottom left, `delta` bottom right. `workers.conf` says which agent, model and effort each runs; `pane.sh` reads its row fresh for every ticket. Manage the tab only with `.agents/skills/orchestrate-workers/grid.sh` (no argument builds or reports it; `--rebuild` refuses while any worker is busy). Never close, reuse, send to or read another space's `workers` tab, and never call `herdr-app do tab.close` or `space.close` yourself. A row that cannot start leaves `[name] ERROR: ...` above the idle line, and the watcher prints it. Terminal addresses, `hc send`, and what to do after `ccwf update`: `TAB.md`.
87
97
 
88
98
  **Assign** with `assign.sh` (the pane picks the job up within 2 seconds). Always pass the prompt in a quoted heredoc: inside double quotes the shell runs anything in backticks and silently drops it from the prompt. `assign.sh` writes the job file in one rename, so the pane never reads half of it, and refuses when that worker already has a job waiting.
89
99
 
@@ -95,7 +105,7 @@ EOF
95
105
 
96
106
  The second argument is the effort: `default` (the roster's) or `low | medium | high | xhigh`. Assign only to a pane that shows `idle`; `assign.sh` says `queued` when an agent is still running there, and that job starts by itself when the agent exits.
97
107
 
98
- Effort: use the roster's (`default`). Only when the roster says `auto` do you pick per ticket: `medium` normally, `high` for tickets that set a pattern others copy or touch auth, crypto, webhooks or shared behaviour other tickets build on, `low` for mechanical renames. Name the chosen effort in the progress row. Give the riskiest ticket of a wave to the strongest free worker, not just the first.
108
+ Effort: use the roster's (`default`). Only when the roster says `auto` do you pick per ticket: read `OPTIONS.md` first.
99
109
 
100
110
  **End a session** (required before the worker's next ticket): `.agents/skills/orchestrate-workers/end.sh <name>`. It prints `idle` when the pane is back to waiting; on `STILL RUNNING`, read the lines it prints before trying again.
101
111
 
@@ -105,26 +115,7 @@ Do not start workers with full-access flags (`danger-full-access`, `--force`, `-
105
115
 
106
116
  ## A folder per worker (optional)
107
117
 
108
- Only when `workers.conf` has the row `isolation worktree`. Change it only while every worker is idle and no worker folder is left. Then each worker gets its own folder, `../<repo>-workers/<name>`: a copy of the main folder as it is at that moment, uncommitted work included. What changes in the loop:
109
-
110
- - **Assign** as always: `assign.sh` creates the folder first. The worker must be idle (no queueing). In the prompt, write "none" for the other tickets, and add: "Write the scenario file but do not run the browser suite: the dev server shows another folder."
111
- - **Status** changes stay in the main folder (`tickets.sh set`). The worker's report, its ticked boxes and your `## Review findings` go in the ticket file in the worker's folder; they come over with the merge.
112
- - **Review** in two parts. In the worker's folder (`cd "$(.agents/skills/orchestrate-workers/worktree.sh path <name>)"`, then back): steps 1, 2, 3 and 5. `git diff HEAD` there is exactly this ticket. When that passes, merge from the main folder, one ticket at a time: `.agents/skills/orchestrate-workers/worktree.sh merge <name>`. Then run the completion checks and step 4 (the browser suite) in the main folder. Only then is the ticket `reviewed`.
113
- - `CONFLICT`: the main folder is unchanged. Run `worktree.sh update <name>`, tell the worker which files hold conflict markers and which ticket the other side is from, start its watcher, then review and merge again.
114
- - Exit 4 (`checks: failed`): the tickets do not work together. Send the worker back; its folder now holds the merged state. Merge again after the fix.
115
- - **Nothing is committed** by the merge. The user's go-ahead and the commits work as before.
116
- - **Clean-up is automatic.** `end.sh` deletes the folder when its work is merged, and `grid.sh` deletes what a crashed session left. `KEPT` names work that is not merged: merge it, or ask the user before `worktree.sh discard <name>`. Never delete these folders by hand. After a later bug report, assign again: the worker gets a fresh folder.
117
-
118
- A new folder has no ignored files: no `node_modules`, no `.env`. If the project needs them, write `worktree-setup.sh` beside this file, show it to the user, and commit it executable. It runs in each new folder with `MAIN` (the main folder) and `WORKER` set:
119
-
120
- ```sh
121
- #!/bin/sh
122
- set -e
123
- [ ! -f "$MAIN/.env" ] || cp "$MAIN/.env" .env
124
- cp -cR "$MAIN/node_modules" . 2>/dev/null || npm ci # -c on a Mac: a copy that takes almost no disk space
125
- ```
126
-
127
- Monorepos have more than one `node_modules`: use the package manager's own install there.
118
+ Only when `workers.conf` has the row `isolation worktree`: read `ISOLATION.md` in this folder before the first assignment. It changes assigning, status, review, merging and clean-up. Without that row, ignore it.
128
119
 
129
120
  ## Worker prompt
130
121
 
@@ -134,8 +125,10 @@ Send this, filled in. Keep it short; the ticket and `AGENTS.md` carry the detail
134
125
  You are worker <name>. Do exactly one ticket: <ticket path>. Read it, then only the parts of <spec path> it needs. Follow AGENTS.md.
135
126
  TDD: first write failing tests for the ticket's checkboxes and run them to see them fail; then write the minimum code to pass; then tidy. Tests go through public interfaces only.
136
127
  Scope: only this ticket. Other workers are editing this same tree right now on: <other tickets, or "none">. Do not edit or revert files outside your ticket's area. Do not commit, stash, reset or checkout. Do not start other agents. Do not start or restart the dev server (`BASE_URL` in `.agents/skills/verify-ui/verify-ui.conf`); if it needs a restart, say so in your report.
128
+ Reading: find with `rg -n`, then read only the lines you need with `sed -n 'A,Bp'`. Never print a whole file over 200 lines. End any command that can print a lot with `| head -80` (`| tail -40` for test, lint and build output). When the codebase-memory tools are available, locate code with them before searching by hand.
137
129
  Finish: run build, lint and tests (`.agents/guardrails/check.sh` when it exists). If the ticket has browser- or API-visible behaviour, follow .agents/skills/verify-ui/SKILL.md: write its scenario file, run it and the whole suite. Tick the ticket's checkboxes that are truly met; append a short report under `## Comments` in the ticket file: files changed, tests added, commands run with one-line results, anything unverified or risky.
138
130
  If a product decision is missing, do not guess: write the question under `## Comments` and stop.
131
+ A `CONTEXT nn%` notice is an order: obey it at once. When the ticket is not met, say under `## Comments` what is done, what is left and what is unverified, and stop.
139
132
  ```
140
133
 
141
134
  For a fix round, write the numbered findings into the ticket file under `## Review findings` (below the worker's report), then send the same worker one plain line in single quotes, with no backticks, quotes or `$` in it:
@@ -144,7 +137,7 @@ For a fix round, write the numbered findings into the ticket file under `## Revi
144
137
  hc send $(<.git/hc-workers/<name>.t) 'Review findings for ticket NN are in the ticket file under the heading Review findings. Fix each with a failing test first, rerun build, lint and tests, then update your report.'
145
138
  ```
146
139
 
147
- Then start its watcher again.
140
+ Then start its watcher again. **At most two fix rounds per ticket.** If the second round's review still finds a real defect, send no third: write what is still wrong under `## Review findings`, end that worker (`end.sh <name>`), and assign the ticket again to a fresh session with the findings, or ask the user when a fresh session would hit the same wall.
148
141
 
149
142
  ## Review
150
143
 
@@ -155,7 +148,7 @@ In order, stopping at the first failure to send it back:
155
148
  3. `git diff --stat`, then read only the diffs that carry the ticket's logic and tests. Check: tests existed and assert behaviour through public interfaces; nothing outside the ticket's scope changed; `AGENTS.md` rules hold.
156
149
  4. Run the browser suite: `.agents/skills/verify-ui/run.sh .scratch/<feature>/verify`. Read each new scenario: it must prove the ticket's browser checkboxes, not only that a page opens. A failing scenario of an earlier ticket is a regression: find which ticket caused it. Diagnose a failure from its evidence folder and `.agents/skills/verify-ui/PLAYBOOK.md`.
157
150
 
158
- 5. When `workers.conf` has a `reviewer` row, run `.agents/skills/orchestrate-workers/review.sh <ticket> <files this ticket changed>` (a few minutes, so in the background). It asks a fresh agent that sees only the ticket and the diff. Exit 1: check each finding in the code yourself; send back the real ones and drop the others with one line of why in the ticket. Exit 2 is not a pass: read why and run it again. Run it once per ticket, and again only after a fix that changed the logic.
151
+ 5. When `workers.conf` has a `reviewer` row, run `review.sh` as `OPTIONS.md` says (an independent review; exit 1 means findings, exit 2 is not a pass).
159
152
 
160
153
  Report findings with file and line. Fix nothing yourself beyond a one-line slip (or a scenario line that uses a wrong selector); send the rest back.
161
154
 
@@ -0,0 +1,9 @@
1
+ # The workers tab
2
+
3
+ Details of the herdr tab, for building or rebuilding it. Part of the `orchestrate-workers` skill.
4
+
5
+ Four workers, by pane: `alpha` top left, `beta` top right, `gamma` bottom left, `delta` bottom right. Which agent, model and effort each one runs is in `workers.conf`, not here: `pane.sh` reads its row fresh for every ticket, so a roster change applies from each worker's next ticket without rebuilding the tab. Supported agents: `codex`, `cursor`, `claude`, in any mix. A row that cannot start (unknown agent, missing CLI, an agent that quits within 20 seconds on a bad model id or login) leaves `[name] ERROR: ...` above the pane's idle line, and the watcher prints it.
6
+
7
+ The tab is named `workers`, lives in your own herdr space (the one holding your terminal) and is always a 2x2 grid. Manage it only with `.agents/skills/orchestrate-workers/grid.sh`: no argument builds it or reports the one already there; `--rebuild` closes your space's `workers` tab and builds a new one, and refuses while any worker is busy. Other spaces have their own orchestrators and `workers` tabs (other repos, other features): never close, reuse, send to or read their tabs, and never call `herdr-app do tab.close` or `space.close` yourself. Each pane runs `pane.sh <name>`: it starts one agent per job file, returns to idle when the agent exits, and reloads itself after every ticket. Each pane writes its terminal address to `.git/hc-workers/<name>.t`: `assign.sh`, `watch.sh`, `approve.sh` and `end.sh` take the worker name directly; for hc use `hc send $(<.git/hc-workers/alpha.t) '...'`. (herdr only names a terminal started with `hc run --name`, and those cannot be placed in a grid, so the grid panes stay unnamed in herdr; the pane shows `[name]` and its title.)
8
+
9
+ After `ccwf update` changes this skill, run `grid.sh --rebuild` once every worker is idle, so the panes run the new scripts (a tab from before the rename to `workers` and `delta` is replaced the same way).
@@ -0,0 +1,18 @@
1
+ # Context limits, read by context.js (the hooks in .claude/settings.json). Your decision: ccwf never overwrites this file.
2
+ # WINDOW is the budget you want to work within, in tokens, not the model's maximum. Answers get worse
3
+ # long before a large window is full, and every turn re-reads the whole context.
4
+ WINDOW=200000
5
+ # At WARN_PCT of WINDOW the agent finishes what it has in hand and starts nothing new.
6
+ WARN_PCT=50
7
+ # At HANDOFF_PCT it must stop and hand off to a fresh context (context.js handoff). At most 90.
8
+ HANDOFF_PCT=65
9
+ # A worker does one ticket in a fresh session, and real ones peak much higher than an orchestrator should (56 Codex workers: median
10
+ # 179k tokens, 90th percentile 244k; 21 Claude workers: median 89k, most 169k), so it has its own window. The limits below stop a
11
+ # runaway session, not an ordinary one. At WORKER_WARN_PCT of WORKER_WINDOW a worker stops exploring; at WORKER_HANDOFF_PCT (at
12
+ # most 90) it stops adding work and writes down where it stands under ## Comments.
13
+ WORKER_WINDOW=300000
14
+ WORKER_WARN_PCT=70
15
+ WORKER_HANDOFF_PCT=85
16
+ # At HANDOFF_PCT a hook also refuses assign.sh and review.sh (new work) until the session is reset with /clear or /compact.
17
+ # on | off. Yours alone to change: agents are told never to edit this file.
18
+ GATE=on
@@ -0,0 +1,337 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ // Context guard: measures how full the session is and says what to do at each limit.
4
+ // An agent cannot see its own context size, so hooks run this: Claude Code (.claude/settings.json) and Codex (.codex/hooks.json).
5
+ // It reads either transcript format. Cursor has no hooks or transcript this can use, so it is not measured.
6
+ // check hook (PostToolUse, UserPromptSubmit): silent below WARN_PCT, a notice at it, an order to hand off at HANDOFF_PCT
7
+ // gate hook (PreToolUse on Bash): at the hand-off limit, refuses assign.sh and review.sh, the commands that start new work
8
+ // resume hook (SessionStart after /clear or /compact): puts progress.md "## Resume" back into the new context
9
+ // handoff <feature> the only way out at the limit: refuses until progress.md is in step with the tickets, then prints what to run
10
+ // status [file] the percentage for this repo's newest session (or the transcript file given)
11
+ // Limits: context.conf beside this file (WINDOW, WARN_PCT, HANDOFF_PCT), or CCWF_CONTEXT_WINDOW / _WARN_PCT / _HANDOFF_PCT.
12
+ // A hook never fails the agent: any problem prints nothing and exits 0. Only handoff and status report errors.
13
+ const fs = require("fs");
14
+ const os = require("os");
15
+ const path = require("path");
16
+ const { spawnSync } = require("child_process");
17
+
18
+ const HERE = __dirname;
19
+ // A worker does one ticket in a fresh session. Real ones peak far higher than the orchestrator should: 56 Codex workers had a median
20
+ // peak of 179k tokens and a 90th percentile of 244k, 21 Claude workers a median of 89k and a maximum of 169k. So a worker has its own window
21
+ // and its limits stop a runaway session, not an ordinary one. Both pairs of percentages are of their own window.
22
+ const DEFAULTS = { WINDOW: 200000, WARN_PCT: 50, HANDOFF_PCT: 65, WORKER_WINDOW: 300000, WORKER_WARN_PCT: 70, WORKER_HANDOFF_PCT: 85 };
23
+ const TICKETS = path.join(HERE, "tickets.sh");
24
+
25
+ function parseConf(text) {
26
+ const out = {};
27
+ for (const raw of String(text || "").split("\n")) {
28
+ const m = /^\s*([A-Z_]+)\s*=\s*(\S+)\s*$/.exec(raw);
29
+ if (m) out[m[1]] = m[2];
30
+ }
31
+ return out;
32
+ }
33
+
34
+ // Returns { window, warn, handoff, gate } or throws with the reason a number is not usable.
35
+ function limits(env = process.env) {
36
+ let file = {};
37
+ try {
38
+ file = parseConf(fs.readFileSync(path.join(HERE, "context.conf"), "utf8"));
39
+ } catch {}
40
+ const pick = (key, envKey) => {
41
+ const raw = env[envKey] || file[key] || DEFAULTS[key]; // an empty variable is not set
42
+ const n = Number(raw);
43
+ if (!Number.isFinite(n) || n <= 0) throw new Error(`context.conf: ${key} is '${raw}', not a number above 0`);
44
+ return n;
45
+ };
46
+ const l = {
47
+ window: pick("WINDOW", "CCWF_CONTEXT_WINDOW"),
48
+ warn: pick("WARN_PCT", "CCWF_CONTEXT_WARN_PCT"),
49
+ handoff: pick("HANDOFF_PCT", "CCWF_CONTEXT_HANDOFF_PCT"),
50
+ workerWindow: pick("WORKER_WINDOW", "CCWF_CONTEXT_WORKER_WINDOW"),
51
+ workerWarn: pick("WORKER_WARN_PCT", "CCWF_CONTEXT_WORKER_WARN_PCT"),
52
+ workerHandoff: pick("WORKER_HANDOFF_PCT", "CCWF_CONTEXT_WORKER_HANDOFF_PCT"),
53
+ };
54
+ l.gate = !/^(off|0|no|false)$/i.test(String(env.CCWF_CONTEXT_GATE || file.GATE || "on"));
55
+ if (l.window < 20000 || l.workerWindow < 20000) throw new Error("context.conf: WINDOW and WORKER_WINDOW below 20000 tokens leave no room to work");
56
+ for (const [w, h, names] of [[l.warn, l.handoff, "WARN_PCT and HANDOFF_PCT"], [l.workerWarn, l.workerHandoff, "WORKER_WARN_PCT and WORKER_HANDOFF_PCT"]]) {
57
+ if (!(w < h && h <= 90)) throw new Error(`context.conf: ${names}: the warning must be below the hand-off, and the hand-off at most 90`);
58
+ }
59
+ return l;
60
+ }
61
+
62
+ // A transcript line, parsed only when a cheap test says it can matter: these files reach tens of megabytes.
63
+ function parse(line) {
64
+ try {
65
+ return JSON.parse(line);
66
+ } catch {
67
+ return null;
68
+ }
69
+ }
70
+
71
+ // Does this line mark a compaction? Claude Code: a system entry "compact_boundary", then a user entry with isCompactSummary.
72
+ // Codex: a top-level entry of type "compacted". Both are checked on the parsed line, never on text that merely mentions them.
73
+ function isCompaction(line) {
74
+ if (!line.includes('"compact_boundary"') && !line.includes('"isCompactSummary":true') && !line.includes('"compacted"')) return false;
75
+ const e = parse(line);
76
+ return !!e && (e.subtype === "compact_boundary" || e.isCompactSummary === true || e.type === "compacted");
77
+ }
78
+
79
+ // The size of the model call a line records, or null. Claude Code: an assistant entry with message.usage (what it read plus what it
80
+ // wrote is the next call's input). Codex: an event_msg token_count whose last_token_usage is that call.
81
+ function callSize(line) {
82
+ if (line.includes('"usage"')) {
83
+ const e = parse(line);
84
+ const u = e && e.type === "assistant" && e.message && e.message.model !== "<synthetic>" ? e.message.usage : null;
85
+ if (u) return (u.input_tokens || 0) + (u.cache_read_input_tokens || 0) + (u.cache_creation_input_tokens || 0) + (u.output_tokens || 0);
86
+ }
87
+ if (line.includes('"token_count"')) {
88
+ const e = parse(line);
89
+ const u = e && e.payload && e.payload.type === "token_count" && e.payload.info ? e.payload.info.last_token_usage : null;
90
+ if (u) return (u.input_tokens || 0) + (u.output_tokens || 0);
91
+ }
92
+ return null;
93
+ }
94
+
95
+ // Tool output written after the last model call is not in any usage figure yet. Estimated at 4 characters a token, and one entry
96
+ // is capped (an image is base64 text but a few thousand tokens), so a big read right before a decision is not missed.
97
+ const OUTPUT = /"tool_result"|"function_call_output"|"custom_tool_call_output"/;
98
+ const PER_ENTRY_CHARS = 100000;
99
+
100
+ // Tokens the last model call carried, plus what it wrote, plus an estimate of tool output since: the size of the next call's input.
101
+ // Returns null when unknown: no call recorded, or a compaction since the last call (that call's figure is from before it).
102
+ // Reads only the end of the transcript; this runs after every tool call.
103
+ function lastContext(file) {
104
+ const fd = fs.openSync(file, "r");
105
+ try {
106
+ const size = fs.fstatSync(fd).size;
107
+ for (let chunk = 1 << 18; ; chunk *= 4) {
108
+ const start = Math.max(0, size - chunk);
109
+ const buf = Buffer.alloc(size - start);
110
+ fs.readSync(fd, buf, 0, buf.length, start);
111
+ const lines = buf.toString("utf8").split("\n");
112
+ if (start > 0) lines.shift(); // cut in the middle
113
+ let pending = 0;
114
+ for (let i = lines.length - 1; i >= 0; i--) {
115
+ if (isCompaction(lines[i])) return null;
116
+ const n = callSize(lines[i]);
117
+ if (n !== null) return n + Math.round(pending / 4);
118
+ if (OUTPUT.test(lines[i])) pending += Math.min(lines[i].length, PER_ENTRY_CHARS);
119
+ }
120
+ if (start === 0 || chunk > 1 << 25) return null;
121
+ }
122
+ } finally {
123
+ fs.closeSync(fd);
124
+ }
125
+ }
126
+
127
+ const k = (n) => `${Math.round(n / 1000)}k`;
128
+ const pctOf = (tokens, l) => Math.round((tokens / l.window) * 100);
129
+
130
+ function notice(level, pct, tokens, l, worker) {
131
+ const where = `CONTEXT ${pct}% (${k(tokens)} of ${k(l.window)})`;
132
+ if (worker) {
133
+ return level === "handoff"
134
+ ? `${where}: stop adding work. Do not open new files or start new searches. If the ticket is not met, write under ## Comments what is done, what is left and what is unverified, then stop.`
135
+ : `${where}: stop exploring. Read only what the ticket needs, in ranges, and finish.`;
136
+ }
137
+ // Every Claude session in the repo gets this hook, not only the orchestrator, so the text says what to do in either case.
138
+ return level === "handoff"
139
+ ? `${where}: HAND OFF NOW (limit ${l.handoff}%). Finish only the step in hand: no new assignment, no new review, no new work. If you are orchestrating (orchestrate-workers): rewrite progress.md ## Resume, then run \`.agents/skills/orchestrate-workers/context.js handoff .scratch/<feature>\` and give the user what it prints. Otherwise: tell the user the context is at its limit and that they should run /clear (or /compact). Do nothing else until the user has reset the session.`
140
+ : `${where}: nearing the limit (hand-off at ${l.handoff}%). Finish the step in hand and start nothing new. If you are orchestrating: assign nothing, start no review, and hand off at the next point where every result is in a file (a ticket reviewed and recorded, or a wave done). Otherwise: wrap up this task and tell the user a fresh session is better for the next one.`;
141
+ }
142
+
143
+ function emit(event, text) {
144
+ process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: event, additionalContext: text } }) + "\n");
145
+ }
146
+
147
+ function readStdin() {
148
+ try {
149
+ return JSON.parse(fs.readFileSync(0, "utf8") || "{}");
150
+ } catch {
151
+ return {};
152
+ }
153
+ }
154
+
155
+ // Tells once when a level is crossed, and repeats the order to hand off every 6th call, so it is not lost in a long turn.
156
+ function check(input, env = process.env) {
157
+ if (!input.transcript_path || input.agent_id) return; // a subagent's calls carry the main session's transcript, not its own size
158
+ const l = limits(env);
159
+ const tokens = lastContext(input.transcript_path);
160
+ if (tokens === null) return;
161
+ const worker = !!env.CCWF_DONE; // set by pane.sh for every worker
162
+ const own = worker ? { ...l, window: l.workerWindow } : l;
163
+ const pct = pctOf(tokens, own);
164
+ const level = pct >= (worker ? l.workerHandoff : l.handoff) ? "handoff" : pct >= (worker ? l.workerWarn : l.warn) ? "warn" : null;
165
+ const stateFile = path.join(os.tmpdir(), `ccwf-context-${String(input.session_id || "x").replace(/[^A-Za-z0-9_-]/g, "")}.json`);
166
+ let state = { level: null, calls: 0 };
167
+ try {
168
+ state = JSON.parse(fs.readFileSync(stateFile, "utf8"));
169
+ } catch {}
170
+ const calls = state.level === level ? state.calls + 1 : 0;
171
+ try {
172
+ fs.writeFileSync(stateFile, JSON.stringify({ level, calls }), { mode: 0o600 });
173
+ } catch {}
174
+ if (!level) return;
175
+ if (calls === 0 || (level === "handoff" && calls % 6 === 0)) emit(input.hook_event_name || "PostToolUse", notice(level, pct, tokens, own, worker));
176
+ }
177
+
178
+ // The commands that start new work: assign a ticket, ask a reviewer. Everything else (set, check, watch, approve, end, git,
179
+ // editing progress.md) stays open at the limit, because the hand-off itself needs it. This reads the command's words, looking
180
+ // through env prefixes, wrappers, `bash -c '...'`, `eval`, `xargs`, `$(...)`, a variable in the path and a `cd` into the skill's
181
+ // folder. It guards against drifting past the limit; it is not a sandbox: a script that calls assign.sh inside itself is not seen.
182
+ const WORK_SCRIPTS = new Set(["assign.sh", "review.sh"]);
183
+ const SHELLS = new Set(["zsh", "bash", "sh", "eval"]);
184
+ const WRAPPERS = new Set(["env", "command", "time", "nohup", "exec", "node", "xargs", "sudo", "timeout", "nice", "builtin", ...SHELLS]);
185
+ function startsNewWork(command, inSkill = String(command || "").includes("orchestrate-workers"), depth = 0) {
186
+ for (const part of String(command || "").split(/&&|\|\||[;&|\n(){}`]/)) {
187
+ const words = part.trim().split(/\s+/);
188
+ let shell = false;
189
+ while (words.length && (/^[A-Za-z_][A-Za-z0-9_]*=/.test(words[0]) || WRAPPERS.has(words[0]) || /^-/.test(words[0]) || /^\d+$/.test(words[0]))) {
190
+ if (SHELLS.has(words[0])) shell = true;
191
+ words.shift();
192
+ }
193
+ const first = (words[0] || "").replace(/^["']|["']$/g, "");
194
+ if (WORK_SCRIPTS.has(first.split("/").pop()) && (inSkill || first.includes("orchestrate-workers") || first.includes("$"))) return true;
195
+ if (shell && depth < 3 && words.length && startsNewWork(words.join(" ").replace(/["']/g, " "), inSkill, depth + 1)) return true;
196
+ }
197
+ return false;
198
+ }
199
+
200
+ // PreToolUse: at the hand-off limit, refuse the commands that start new work. The reason goes to the agent. Any problem lets the call
201
+ // through (a gate that can break the orchestrator is worse than one that sometimes lets a call by); the call is then still covered by the notice.
202
+ function gate(input, env = process.env) {
203
+ if (env.CCWF_DONE || input.agent_id || input.tool_name !== "Bash" || !input.transcript_path) return;
204
+ if (!startsNewWork(input.tool_input && input.tool_input.command)) return;
205
+ const l = limits(env);
206
+ if (!l.gate) return;
207
+ const tokens = lastContext(input.transcript_path);
208
+ if (tokens === null) return;
209
+ const pct = pctOf(tokens, l);
210
+ if (pct < l.handoff) return;
211
+ process.stdout.write(
212
+ JSON.stringify({
213
+ hookSpecificOutput: {
214
+ hookEventName: "PreToolUse",
215
+ permissionDecision: "deny",
216
+ permissionDecisionReason:
217
+ `CONTEXT ${pct}% (${k(tokens)} of ${k(l.window)}): the hand-off limit (${l.handoff}%) is reached, so no ticket may be assigned and no review started in this session. ` +
218
+ `Finish only the step in hand, rewrite progress.md ## Resume, run \`.agents/skills/orchestrate-workers/context.js handoff .scratch/<feature>\` and give the user what it prints. ` +
219
+ `This opens again after the user's /clear or /compact. Do not change context.conf or any settings to get past it: only the user sets the limits.`,
220
+ },
221
+ }) + "\n",
222
+ );
223
+ }
224
+
225
+ // The newest effort's "## Resume", bounded, so a reset session starts from the saved state and not from a summary of a long one.
226
+ function resume(input, cwd = process.cwd(), env = process.env) {
227
+ if (env.CCWF_DONE || (input.source && !/^(clear|compact)$/.test(input.source))) return;
228
+ const root = input.cwd || cwd;
229
+ const scratch = path.join(root, ".scratch");
230
+ let best = null;
231
+ for (const name of fs.readdirSync(scratch)) {
232
+ const file = path.join(scratch, name, "progress.md");
233
+ let st;
234
+ try {
235
+ st = fs.statSync(file);
236
+ } catch {
237
+ continue;
238
+ }
239
+ if (!best || st.mtimeMs > best.mtime) best = { file, name, mtime: st.mtimeMs };
240
+ }
241
+ if (!best) return;
242
+ const lines = fs.readFileSync(best.file, "utf8").split("\n");
243
+ const from = lines.findIndex((x) => /^##\s+Resume\b/.test(x));
244
+ if (from === -1) return;
245
+ let to = lines.findIndex((x, i) => i > from && /^##\s/.test(x));
246
+ if (to === -1) to = lines.length;
247
+ const body = lines.slice(from, to).join("\n").trim().split("\n").slice(0, 30).join("\n");
248
+ emit(
249
+ "SessionStart",
250
+ `The context was reset (${input.source || "clear"}). The state below is from .scratch/${best.name}/progress.md, written by the session before; it is what that session decided to keep. ` +
251
+ `Run .agents/skills/orchestrate-workers/tickets.sh check .scratch/${best.name} before acting, restart the watcher of every worker that is mid-ticket, then do "Next action". Read nothing else first.\n\n${body}`,
252
+ );
253
+ }
254
+
255
+ function run(cmd, args, opts = {}) {
256
+ return spawnSync(cmd, args, { encoding: "utf8", ...opts });
257
+ }
258
+
259
+ // Hand off only from a true state: what the next session reads must say what is so.
260
+ function handoff(feature) {
261
+ if (!feature || !fs.existsSync(path.join(feature, "progress.md"))) {
262
+ console.error("usage: context.js handoff .scratch/<feature> (the folder with progress.md)");
263
+ return 2;
264
+ }
265
+ const c = run("zsh", [TICKETS, "check", feature]);
266
+ if (c.status !== 0 || !String(c.stdout).includes("is in step with the tickets")) { // silence is not a pass
267
+ process.stdout.write((c.stdout || "") + (c.stderr || ""));
268
+ console.log("NOT READY: fix every line above in progress.md (or, if nothing is listed, the check could not run), then run handoff again. A session that starts from a false Resume does the wrong thing.");
269
+ return 1;
270
+ }
271
+ const counts = run("zsh", [TICKETS, "counts", feature]).stdout || "";
272
+ const running = /\b(in-progress|in-review)\b/.test(counts);
273
+ const text = fs.readFileSync(path.join(feature, "progress.md"), "utf8");
274
+ const line = (key) => (new RegExp(`^[-*]\\s+\\**${key}\\**:?\\**\\s*(.*)$`, "im").exec(text) || [])[1] || "(missing)";
275
+ console.log(`HANDOFF READY: progress.md is in step with the tickets (${counts.trim()}).`);
276
+ console.log(`Next action saved: ${line("Next action")}`);
277
+ console.log(`Waiting on user saved: ${line("Waiting on user")}`);
278
+ console.log("");
279
+ if (running) {
280
+ console.log("Workers are mid-ticket. Ask the user to run exactly:");
281
+ console.log(` /compact Orchestrating ${feature} with orchestrate-workers. Keep: wave tickets and their workers, review findings not yet fixed, pending user questions, the roster decision. State is in progress.md.`);
282
+ console.log("The Resume above comes back by itself after the compact. Then restart each running worker's watcher.");
283
+ } else {
284
+ console.log("No worker is mid-ticket. Ask the user to run /clear, then paste exactly:");
285
+ console.log(` Use the orchestrate-workers skill. Feature: ${feature}. Resume from progress.md.`);
286
+ }
287
+ console.log("Start no ticket and run no check in this session after this.");
288
+ return 0;
289
+ }
290
+
291
+ function newestTranscript(root) {
292
+ const base = path.join(process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), ".claude"), "projects", root.replace(/[^A-Za-z0-9]/g, "-"));
293
+ const files = fs.readdirSync(base).filter((f) => f.endsWith(".jsonl")).map((f) => ({ f: path.join(base, f), t: fs.statSync(path.join(base, f)).mtimeMs }));
294
+ return files.sort((a, b) => b.t - a.t)[0]?.f;
295
+ }
296
+
297
+ function status(file) {
298
+ const l = limits();
299
+ const f = file || newestTranscript(process.cwd());
300
+ if (!f) {
301
+ console.error("no Claude Code transcript found for this folder");
302
+ return 1;
303
+ }
304
+ const tokens = lastContext(f);
305
+ if (tokens === null) {
306
+ console.error(`no model call recorded in ${f}`);
307
+ return 1;
308
+ }
309
+ const pct = pctOf(tokens, l);
310
+ console.log(`context ${pct}% (${k(tokens)} of ${k(l.window)}); orchestrator: warn at ${l.warn}%, hand off at ${l.handoff}%; workers (window ${k(l.workerWindow)}): warn at ${l.workerWarn}%, stop at ${l.workerHandoff}%`);
311
+ return 0;
312
+ }
313
+
314
+ function main(argv) {
315
+ const [cmd, arg] = argv;
316
+ if (cmd === "check" || cmd === "resume" || cmd === "gate") {
317
+ try {
318
+ const input = readStdin();
319
+ if (cmd === "check") check(input);
320
+ else if (cmd === "gate") gate(input);
321
+ else resume(input);
322
+ } catch {} // a hook must never get in the agent's way
323
+ return 0;
324
+ }
325
+ try {
326
+ if (cmd === "handoff") return handoff(arg);
327
+ if (cmd === "status") return status(arg);
328
+ } catch (err) {
329
+ console.error(err.message);
330
+ return 1;
331
+ }
332
+ console.error("usage: context.js check | gate | resume | handoff <feature-dir> | status [transcript]");
333
+ return 2;
334
+ }
335
+
336
+ if (require.main === module) process.exitCode = main(process.argv.slice(2));
337
+ module.exports = { limits, lastContext, check, gate, startsNewWork, resume, handoff, parseConf };