@mayurdluffy/ccwf 0.7.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.
package/README.md CHANGED
@@ -26,7 +26,7 @@ npx @mayurdluffy/ccwf@latest init # tools + user-level skills + project files
26
26
  | `tracking` | `docs/ROADMAP.md` (session entry point: product, order of work, efforts with their `progress.md`), empty `docs/GLOSSARY.md`, `DECISIONS.md`, `FEATURES.md`, `BACKLOG.md`, `adr/`, `learnings/` + `save-learning` skill + rules; `docs/agents/{domain,issue-tracker,triage-labels}.md` |
27
27
  | `browser` | `agent-browser` + `verify-ui` skills, `chrome-devtools` MCP, `.cursor/cli.json`, Claude MCP approval and allowed sites |
28
28
  | `guardrails` (only when asked for: `ccwf add guardrails`) | `.agents/guardrails/check.sh` runs your project's checks from `checks.conf` and looks for new secrets. The same script serves workers (a finished one is sent back once if it fails), git commits (`--install-hook`) and CI (`--all`) |
29
- | `workers` | `orchestrate-workers` skill (a `workers` tab of four panes in the orchestrator's own herdr space, `hc` reference, `workers.conf`). A `reviewer` row in `workers.conf` turns on an independent review of every ticket. `isolation worktree` gives each worker a folder of its own, which is deleted once its work is merged |
29
+ | `workers` | `orchestrate-workers` skill (a `workers` tab of four panes in the orchestrator's own herdr space, `hc` reference, `workers.conf`). A `reviewer` row in `workers.conf` turns on an independent review of every ticket. `isolation worktree` gives each worker a folder of its own, which is deleted once its work is merged. `context.conf` sets the orchestrator's context limits: in Claude Code, and in Codex once you approve its hooks with `/hooks`, a hook warns at 50% of the window and orders a hand-off at 65%, a second hook then refuses `assign.sh` and `review.sh` until the session is reset (`GATE=off` in `context.conf` turns that off), and a third puts `progress.md`'s Resume back after `/clear` or `/compact` |
30
30
 
31
31
  Skills live in `.agents/skills/` (Codex, Cursor); Claude Code gets symlinks in `.claude/skills/`. Files are written only for the agents you select.
32
32
 
@@ -45,7 +45,7 @@ A skill that needs project settings asks you the first time it runs and saves th
45
45
  | `ccwf update` | the only command that re-renders templates from this ccwf version; files you edited are merged, not overwritten (see below) |
46
46
  | `ccwf sync` | push skill settings into agent configs and add navigation rules; does not re-render templates |
47
47
  | `ccwf doctor` | check tools, skills and files; offer to install what is missing and to run `update` (`--yes` does both). `--check` changes nothing and exits 1 on problems |
48
- | `ccwf stats` | worker runs in this repo per model and folder mode: done, first try, time, fix rounds, failed checks (`--json`). Recorded in `.git/ccwf/runs.jsonl` on your computer only, without prompts or code |
48
+ | `ccwf stats` | worker runs in this repo per model and folder mode: done, first try, time, fix rounds, failed checks, and from the Claude Code and Codex session files the context each session started with and reached, the tokens it read and its codebase-memory calls, plus every orchestrator session against its limit (`--json`). Runs are recorded in `.git/ccwf/runs.jsonl`; numbers only, no prompts or code, and nothing leaves your computer |
49
49
  | `ccwf eject <skill>` | stop managing a skill you changed |
50
50
  | `ccwf status` | installed modules; files, managed blocks, settings and links that differ. `--check` exits 1 when something is missing or broken; your edits do not count |
51
51
 
@@ -108,6 +108,8 @@ Then follow `docs/agents/workflow.md` in your repo. Commit `.ccwf.json` and the
108
108
 
109
109
  `node scripts/harvest.js <repo> --terms yourproduct` diffs a working repo's skills against `templates/skills/`, flags project-specific lines, and with `--apply` copies the clean ones. Not published to npm.
110
110
 
111
+ Why the context limits exist and how they were found, measured and tested: [docs/context-engineering.md](docs/context-engineering.md) (the model and the story), [docs/context-engineering-methods.md](docs/context-engineering-methods.md) (how to reproduce it), [docs/audit-context.md](docs/audit-context.md) (the findings). The analysis scripts are in `scripts/context/`.
112
+
111
113
  Before and after changing a skill, run its tasks in [evals/](evals/README.md). They use paid agent sessions and never run in CI.
112
114
 
113
115
  ## Releasing
package/lib/index.js CHANGED
@@ -27,7 +27,7 @@ Usage: ccwf <command> [options]
27
27
  chrome-mcp serve the project’s Chrome DevTools MCP (--print shows its command)
28
28
  doctor check tools, skills and files; offer to fix what is missing
29
29
  eject <skill> stop managing a skill you changed
30
- stats worker runs per model: done, time, fix rounds, failed checks (--json)
30
+ stats worker runs per model: done, time, fix rounds, failed checks; context per session (--json)
31
31
  status show installed modules and drifted files
32
32
 
33
33
  Modules: ${ORDER.join(", ")}
@@ -270,6 +270,9 @@ async function install(cmd, opts, root) {
270
270
  if (cmd === "update" && prev.ccwf !== pkg.version) console.log(`update: ccwf ${prev.ccwf} -> ${pkg.version}`);
271
271
  report(r.ins, opts["dry-run"]);
272
272
  if (!opts["dry-run"]) saveManifest(root, { agents, modules, ejected, ...tracked(r.ins) });
273
+ if (r.ins.log.some((l) => l.rel === ".codex/hooks.json" && /created|updated/.test(l.state))) {
274
+ console.log(" next: Codex runs project hooks only after you approve them. Open Codex in this repo and review them with /hooks (they are the context limits: orchestrate-workers/context.js). Until then Codex has no context limit here.");
275
+ }
273
276
  if (modules.includes("guardrails") && !prev?.modules?.includes("guardrails")) {
274
277
  console.log(" next: check the commands in .agents/guardrails/checks.conf and commit the folder. To run the quick ones before each commit: .agents/guardrails/check.sh --install-hook. In CI: .agents/guardrails/check.sh --all");
275
278
  }
package/lib/installer.js CHANGED
@@ -324,9 +324,9 @@ class Installer {
324
324
  }
325
325
 
326
326
  // Deep-merge keys into a JSON file; invalid JSON aborts without touching the file.
327
- json(rel, patch, union = []) {
327
+ json(rel, patch, union = [], owns = null) {
328
328
  const cur = this.read(rel) ?? "";
329
- const next = mergeJson(cur, patch, rel, union);
329
+ const next = mergeJson(cur, patch, rel, union, owns);
330
330
  if (next === cur) return this.note(rel, "unchanged", "json");
331
331
  const existed = cur !== "";
332
332
  this.write(rel, next);
package/lib/merge.js CHANGED
@@ -119,7 +119,9 @@ function setPath(obj, dotted, value) {
119
119
 
120
120
  // Merge `patch` into JSON text, keeping every other key. Throws on invalid JSON (never overwrite).
121
121
  // `union`: dotted paths whose arrays are merged as a set (existing entries first) instead of replaced.
122
- function mergeJson(text, patch, label = "JSON file", union = []) {
122
+ // `owns`: tells an entry this tool wrote earlier. When the patch brings entries of its own, the old ones are replaced, not kept
123
+ // beside them, so a changed hook (a new timeout, a new command) never runs twice.
124
+ function mergeJson(text, patch, label = "JSON file", union = [], owns = null) {
123
125
  let data = {};
124
126
  if (text.trim() !== "") {
125
127
  try {
@@ -134,7 +136,10 @@ function mergeJson(text, patch, label = "JSON file", union = []) {
134
136
  const add = getPath(p, path);
135
137
  if (!Array.isArray(add)) continue;
136
138
  const have = getPath(data, path);
137
- setPath(p, path, [...new Set([...(Array.isArray(have) ? have : []), ...add])]);
139
+ // Equal values once, by content: hook entries are objects, which a Set would keep twice.
140
+ const kept = (Array.isArray(have) ? have : []).filter((v) => !(owns && owns(v) && add.some(owns)));
141
+ const all = [...kept, ...add];
142
+ setPath(p, path, [...new Map(all.map((v) => [JSON.stringify(v), v])).values()]);
138
143
  }
139
144
  const before = JSON.parse(JSON.stringify(data));
140
145
  deepMerge(data, p);
package/lib/modules.js CHANGED
@@ -31,7 +31,7 @@ function skillFiles(name, params) {
31
31
  rel,
32
32
  content: render(fs.readFileSync(path.join(dir, rel), "utf8"), params),
33
33
  mode: st.mode & 0o111 ? 0o755 : undefined,
34
- seed: rel === "workers.conf", // the user's roster: written once, never merged
34
+ seed: rel === "workers.conf" || rel === "context.conf", // the user's roster and context limits: written once, never merged
35
35
  };
36
36
  });
37
37
  }
@@ -119,6 +119,27 @@ function checksConf(ins) {
119
119
  ].join("\n") + "\n";
120
120
  }
121
121
 
122
+ // The context guard (orchestrate-workers/context.js): it measures the session after each tool call and each prompt, refuses
123
+ // new work (assign.sh, review.sh) at the hand-off limit, and puts progress.md's "## Resume" back after /clear or /compact.
124
+ // Claude Code reads .claude/settings.json and Codex reads .codex/hooks.json; both take this shape. Cursor has no equivalent, so
125
+ // the skill's wave rule is the only limit it gets.
126
+ // Shell form with the path quoted, which Claude Code's docs allow beside "exec form" (command + args). Exec form needs a Claude
127
+ // Code version this cannot check, and an older one would run bare `node` and do nothing.
128
+ // timeout: the default is 600 seconds and a stalled hook delays every tool call; these only read a file's tail.
129
+ const GUARD = "orchestrate-workers/context.js";
130
+ const guardHooks = (root) => {
131
+ const hook = (arg) => ({ type: "command", command: `node "${root}/.agents/skills/${GUARD}" ${arg}`, timeout: 10 });
132
+ return {
133
+ PostToolUse: [{ hooks: [hook("check")] }],
134
+ UserPromptSubmit: [{ hooks: [hook("check")] }],
135
+ PreToolUse: [{ matcher: "Bash", hooks: [hook("gate")] }],
136
+ SessionStart: [{ matcher: "clear|compact", hooks: [hook("resume")] }],
137
+ };
138
+ };
139
+ const CONTEXT_HOOKS = guardHooks("$CLAUDE_PROJECT_DIR");
140
+ const CODEX_HOOKS = guardHooks("$(git rev-parse --show-toplevel)"); // Codex sets no project variable; the worktree of an isolated worker is its own top level
141
+ const ownsGuard = (entry) => JSON.stringify(entry).includes(GUARD); // an earlier version of these entries: replaced, not kept beside
142
+
122
143
  const MODULES = {
123
144
  core: {
124
145
  desc: "engineering discipline rules, commit skill, workflow + setup guides",
@@ -176,9 +197,12 @@ const MODULES = {
176
197
  },
177
198
  },
178
199
  workers: {
179
- desc: "orchestrate-workers skill (needs herdr + hc)",
200
+ desc: "orchestrate-workers skill (needs herdr + hc) and its context limits",
180
201
  run(ctx) {
181
202
  installSkill(ctx, "orchestrate-workers");
203
+ const events = Object.keys(CONTEXT_HOOKS).map((e) => `hooks.${e}`);
204
+ if (ctx.agents.includes("claude")) ctx.ins.json(".claude/settings.json", { hooks: CONTEXT_HOOKS }, events, ownsGuard);
205
+ if (ctx.agents.includes("codex")) ctx.ins.json(".codex/hooks.json", { hooks: CODEX_HOOKS }, events, ownsGuard);
182
206
  // ccwf 0.1 named the fourth worker theta; the panes now look up delta.
183
207
  ctx.ins.rewrite(
184
208
  ".agents/skills/orchestrate-workers/workers.conf",
package/lib/stats.js CHANGED
@@ -3,6 +3,15 @@
3
3
  const fs = require("fs");
4
4
  const path = require("path");
5
5
  const { spawnSync } = require("child_process");
6
+ const transcripts = require("./transcripts");
7
+
8
+ // The main folder of the repo: worker folders and linked worktrees count as the repo they belong to.
9
+ function mainRoot(root) {
10
+ const r = spawnSync("git", ["rev-parse", "--git-common-dir"], { cwd: root, encoding: "utf8" });
11
+ if (r.status !== 0) return root;
12
+ const common = path.resolve(root, r.stdout.trim());
13
+ return path.basename(common) === ".git" ? fs.realpathSync(path.dirname(common)) : root;
14
+ }
6
15
 
7
16
  function readEvents(root) {
8
17
  const r = spawnSync("git", ["rev-parse", "--git-common-dir"], { cwd: root, encoding: "utf8" });
@@ -23,13 +32,20 @@ function readEvents(root) {
23
32
  });
24
33
  }
25
34
 
35
+ // Context numbers of the sessions found for a group of runs. Medians, since one long ticket should not set the picture.
36
+ function contextOf(found) {
37
+ if (!found.length) return null;
38
+ const m = (f) => median(found.map(f));
39
+ return { sessions: found.length, startCtx: m((x) => x.startCtx), peakCtx: m((x) => x.peakCtx), turns: m((x) => x.turns), read: m((x) => x.read), graph: found.reduce((n, x) => n + x.graph, 0) };
40
+ }
41
+
26
42
  function median(values) {
27
43
  if (!values.length) return null;
28
44
  const s = [...values].sort((a, b) => a - b);
29
45
  return (s[(s.length - 1) >> 1] + s[s.length >> 1]) / 2;
30
46
  }
31
47
 
32
- function summarise(events) {
48
+ function summarise(events, sessions = []) {
33
49
  const runs = new Map();
34
50
  const lastRun = new Map(); // ticket -> the run that worked on it last
35
51
  const doneBy = new Map(); // ticket -> the run that had it when it was set to done
@@ -58,6 +74,7 @@ function summarise(events) {
58
74
  }
59
75
  }
60
76
  const done = new Set(doneBy.values());
77
+ const matched = transcripts.matchRuns(events, sessions);
61
78
  const groups = new Map();
62
79
  for (const r of runs.values()) {
63
80
  const folder = r.tree === "worktree" ? "own" : "shared";
@@ -83,9 +100,11 @@ function summarise(events) {
83
100
  gates: sum((r) => r.gates),
84
101
  conflicts: sum((r) => r.conflicts),
85
102
  failedStarts: all.length - ran.length,
103
+ context: contextOf(ran.map((r) => matched.get(r.run)).filter(Boolean)),
86
104
  };
87
105
  });
88
- return { workers: workers.sort((a, b) => b.runs - a.runs), reviews: [...reviewers.values()] };
106
+ const orchestrators = sessions.filter((x) => x.kind === "orchestrator").sort((a, b) => a.start - b.start);
107
+ return { workers: workers.sort((a, b) => b.runs - a.runs), reviews: [...reviewers.values()], orchestrators };
89
108
  }
90
109
 
91
110
  function table(rows) {
@@ -93,10 +112,35 @@ function table(rows) {
93
112
  return rows.map((r) => " " + r.map((c, i) => (i < 4 ? String(c).padEnd(width[i]) : String(c).padStart(width[i]))).join(" ").trimEnd()).join("\n");
94
113
  }
95
114
 
115
+ const kTokens = (n) => (n === null || n === undefined ? "-" : n >= 1e6 ? `${(n / 1e6).toFixed(1)}M` : `${Math.round(n / 1000)}k`);
116
+
117
+ // Sessions changed within 30 days, or since the first recorded run if that is older.
118
+ function sessionsFor(root, events) {
119
+ const first = events.length ? Math.min(...events.map((e) => e.t)) * 1000 - 86400000 : Infinity;
120
+ return transcripts.readSessions(mainRoot(root), Math.min(Date.now() - 30 * 86400000, first));
121
+ }
122
+
123
+ function printContext(s, window) {
124
+ const rows = s.workers.filter((w) => w.context);
125
+ if (rows.length) {
126
+ const head = ["agent", "model", "effort", "folder", "sessions", "start ctx", "peak ctx", "turns", "tokens read", "graph calls"];
127
+ const row = (w) => [w.agent, w.model, w.effort, w.folder, w.context.sessions, kTokens(w.context.startCtx), kTokens(w.context.peakCtx), Math.round(w.context.turns), kTokens(w.context.read), w.context.graph];
128
+ console.log("\nContext per worker session (medians; tokens read = what the model re-read over the whole session; graph calls = codebase-memory tools, total)");
129
+ console.log(table([head, ...rows.map(row)]));
130
+ }
131
+ if (s.orchestrators.length) {
132
+ console.log(`\nOrchestrator sessions (the limit is ${kTokens(window)}; see context.conf)`);
133
+ const head = ["started", "agent", "turns", "start ctx", "peak ctx", "peak % of limit", "tokens read", "graph calls"];
134
+ const row = (o) => [new Date(o.start).toISOString().slice(0, 16).replace("T", " "), o.agent, o.turns, kTokens(o.startCtx), kTokens(o.peakCtx), `${Math.round((100 * o.peakCtx) / window)}%`, kTokens(o.read), o.graph];
135
+ console.log(table([head, ...s.orchestrators.map(row)]));
136
+ }
137
+ }
138
+
96
139
  function print(root, asJson) {
97
- const s = summarise(readEvents(root));
140
+ const events = readEvents(root);
141
+ const s = summarise(events, sessionsFor(root, events));
98
142
  if (asJson) return console.log(JSON.stringify(s, null, 2));
99
- if (!s.workers.length && !s.reviews.length) return console.log("no worker runs recorded yet (orchestrate-workers writes them to .git/ccwf/runs.jsonl)");
143
+ if (!s.workers.length && !s.reviews.length && !s.orchestrators.length) return console.log("no worker runs recorded yet (orchestrate-workers writes them to .git/ccwf/runs.jsonl)");
100
144
  if (s.workers.length) {
101
145
  const head = ["agent", "model", "effort", "folder", "runs", "done", "first try", "min to finish", "fix rounds", "checks failed", "prompts", "conflicts", "failed starts"];
102
146
  const row = (w) => [w.agent, w.model, w.effort, w.folder, w.runs, w.done, w.firstTry, w.minutesToFinish === null ? "-" : w.minutesToFinish.toFixed(1), w.fixRounds, w.checksFailed, w.gates, w.conflicts, w.failedStarts];
@@ -104,6 +148,7 @@ function print(root, asJson) {
104
148
  console.log("\nfirst try: done with no fix round and no failed check. min to finish: median, from the start to the end of the first turn");
105
149
  console.log("that passed or gave up, waiting for you included. Tickets differ in size: compare models only over many runs.");
106
150
  }
151
+ printContext(s, transcripts.windowOf(mainRoot(root)));
107
152
  for (const r of s.reviews) console.log(`\nreviewer ${r.agent} ${r.model}: ${r.reviews} reviews, ${r.withFindings} with findings${r.noVerdict ? `, ${r.noVerdict} without a verdict` : ""}`);
108
153
  }
109
154
 
@@ -0,0 +1,192 @@
1
+ "use strict";
2
+ // What the agents' own session files say about context: how big a session started, how big it got, and
3
+ // how many tokens it read. Claude Code keeps them in ~/.claude/projects/<folder>/*.jsonl, Codex in
4
+ // ~/.codex/sessions/<y>/<m>/<d>/*.jsonl. Cursor keeps none that can be read. Only numbers leave this
5
+ // file: no prompt, code or output is kept.
6
+ const fs = require("fs");
7
+ const os = require("os");
8
+ const path = require("path");
9
+
10
+ // A call, not a search for the tool: Codex writes `tools.mcp__codebase_memory__search_graph(`.
11
+ const GRAPH_CALL = /mcp__codebase[-_]memory__[a-z_]+\s*\(/g;
12
+ const slug = (p) => p.replace(/[^A-Za-z0-9]/g, "-");
13
+ const WORKER_PROMPT = /You are worker ([a-z]+)\./;
14
+ const workerOf = (text) => WORKER_PROMPT.exec(String(text).slice(0, 80));
15
+ const when = (iso) => (Number.isFinite(Date.parse(iso)) ? Date.parse(iso) : null);
16
+
17
+ function lines(file) {
18
+ try {
19
+ return fs.readFileSync(file, "utf8").split("\n");
20
+ } catch {
21
+ return [];
22
+ }
23
+ }
24
+
25
+ function tryParse(line) {
26
+ try {
27
+ return JSON.parse(line);
28
+ } catch {
29
+ return null;
30
+ }
31
+ }
32
+
33
+ function claudeText(content) {
34
+ if (typeof content === "string") return content;
35
+ return Array.isArray(content) ? (content.find((c) => c.type === "text") || {}).text || "" : "";
36
+ }
37
+
38
+ // Claude Code: one assistant message is written once per content block, all with the same usage.
39
+ function parseClaude(file) {
40
+ const calls = new Map(); // message id -> usage
41
+ let prompt = null;
42
+ let start = null;
43
+ let orchestrator = false;
44
+ let graph = 0;
45
+ for (const line of lines(file)) {
46
+ if (!line) continue;
47
+ const isAssistant = line.includes('"type":"assistant"');
48
+ if (!isAssistant && (prompt !== null || !line.includes('"type":"user"'))) continue;
49
+ const e = tryParse(line);
50
+ if (!e) continue;
51
+ start = start ?? when(e.timestamp);
52
+ if (e.type === "user") {
53
+ prompt = claudeText(e.message && e.message.content);
54
+ continue;
55
+ }
56
+ const m = e.message || {};
57
+ if (m.usage && m.model !== "<synthetic>") calls.set(m.id || e.uuid, m.usage);
58
+ for (const c of m.content || []) {
59
+ if (c.type !== "tool_use") continue;
60
+ if (c.name === "Bash" && String((c.input || {}).command || "").includes("orchestrate-workers/")) orchestrator = true;
61
+ if (/^mcp__codebase[-_]memory/.test(c.name)) graph++;
62
+ }
63
+ }
64
+ const usage = [...calls.values()];
65
+ const ctx = usage.map((u) => (u.input_tokens || 0) + (u.cache_read_input_tokens || 0) + (u.cache_creation_input_tokens || 0));
66
+ return finish({ agent: "claude", file, start, prompt: prompt || "", orchestrator, graph, ctx, output: usage.reduce((n, u) => n + (u.output_tokens || 0), 0) });
67
+ }
68
+
69
+ // Codex: one token_count event per model call; the same totals are sometimes written twice.
70
+ function parseCodex(file, root) {
71
+ let meta = null;
72
+ let prompt = null;
73
+ let orchestrator = false;
74
+ let graph = 0;
75
+ let lastTotal = -1;
76
+ let output = 0;
77
+ const ctx = [];
78
+ for (const line of lines(file)) {
79
+ if (!line) continue;
80
+ if (meta === null) {
81
+ const e = tryParse(line);
82
+ if (!e || e.type !== "session_meta") return null;
83
+ meta = e.payload || {};
84
+ if (!inRepo(meta.cwd || "", root)) return null;
85
+ continue;
86
+ }
87
+ if (line.includes('"token_count"')) {
88
+ const p = (tryParse(line) || {}).payload || {};
89
+ const info = p.info;
90
+ if (!info || !info.last_token_usage || info.total_token_usage.total_tokens === lastTotal) continue;
91
+ lastTotal = info.total_token_usage.total_tokens;
92
+ ctx.push(info.last_token_usage.input_tokens || 0);
93
+ output = info.total_token_usage.output_tokens || 0;
94
+ } else if (/"type":"(function_call|custom_tool_call)"/.test(line)) {
95
+ if (line.includes("orchestrate-workers/")) orchestrator = true;
96
+ graph += (line.match(GRAPH_CALL) || []).length;
97
+ } else if (prompt === null && line.includes('"role":"user"')) {
98
+ const p = (tryParse(line) || {}).payload || {};
99
+ const text = (p.content || []).map((c) => c.text || "").join("");
100
+ if (workerOf(text)) prompt = text;
101
+ }
102
+ }
103
+ return finish({ agent: "codex", file, start: when(meta && meta.timestamp), prompt: prompt || "", orchestrator, graph, ctx, output });
104
+ }
105
+
106
+ function finish(s) {
107
+ if (!s.ctx.length) return null;
108
+ const worker = workerOf(s.prompt);
109
+ return {
110
+ agent: s.agent,
111
+ start: s.start,
112
+ kind: worker ? "worker" : s.orchestrator ? "orchestrator" : "other",
113
+ worker: worker ? worker[1] : null,
114
+ prompt: worker ? s.prompt : "",
115
+ turns: s.ctx.length,
116
+ startCtx: s.ctx[0],
117
+ peakCtx: Math.max(...s.ctx),
118
+ read: s.ctx.reduce((a, b) => a + b, 0),
119
+ output: s.output,
120
+ graph: s.graph,
121
+ };
122
+ }
123
+
124
+ function inRepo(cwd, root) {
125
+ return cwd === root || cwd.startsWith(root + path.sep) || cwd.startsWith(root + "-workers" + path.sep);
126
+ }
127
+
128
+ // Every Claude and Codex session of this repo (and of its worker folders) changed since `sinceMs`.
129
+ function readSessions(root, sinceMs, env = process.env) {
130
+ const out = [];
131
+ const recent = (f) => {
132
+ try {
133
+ return fs.statSync(f).mtimeMs >= sinceMs;
134
+ } catch {
135
+ return false;
136
+ }
137
+ };
138
+ const claudeProjects = path.join(env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), ".claude"), "projects");
139
+ let dirs = [];
140
+ try {
141
+ dirs = fs.readdirSync(claudeProjects).filter((d) => d === slug(root) || d.startsWith(slug(root) + "-workers-"));
142
+ } catch {}
143
+ for (const d of dirs) {
144
+ for (const f of fs.readdirSync(path.join(claudeProjects, d)).filter((f) => f.endsWith(".jsonl"))) {
145
+ const file = path.join(claudeProjects, d, f);
146
+ if (recent(file)) out.push(parseClaude(file));
147
+ }
148
+ }
149
+ const codexRoot = path.join(env.CODEX_HOME || path.join(os.homedir(), ".codex"), "sessions");
150
+ const walk = (dir) => {
151
+ let entries = [];
152
+ try {
153
+ entries = fs.readdirSync(dir, { withFileTypes: true });
154
+ } catch {}
155
+ for (const e of entries) {
156
+ const p = path.join(dir, e.name);
157
+ if (e.isDirectory()) walk(p);
158
+ else if (e.name.endsWith(".jsonl") && recent(p)) out.push(parseCodex(p, root));
159
+ }
160
+ };
161
+ walk(codexRoot);
162
+ return out.filter(Boolean);
163
+ }
164
+
165
+ // Gives each recorded run (runlog.sh "start" event) the session that did it: the same agent, started
166
+ // within a few minutes of the run, with that ticket in its prompt. Nothing is guessed: no match, no numbers.
167
+ function matchRuns(events, sessions) {
168
+ const free = sessions.filter((s) => s.kind === "worker");
169
+ const bySession = new Map();
170
+ for (const e of events.filter((x) => x.e === "start" && (x.agent === "claude" || x.agent === "codex"))) {
171
+ let best = null;
172
+ for (const s of free) {
173
+ if (s.agent !== e.agent || s.worker !== e.worker || !s.start || [...bySession.values()].includes(s)) continue;
174
+ if (e.ticket && !s.prompt.includes(e.ticket)) continue;
175
+ const gap = s.start - e.t * 1000;
176
+ if (gap < -30000 || gap > 300000) continue;
177
+ if (!best || Math.abs(gap) < Math.abs(best.start - e.t * 1000)) best = s;
178
+ }
179
+ if (best) bySession.set(e.run, best);
180
+ }
181
+ return bySession;
182
+ }
183
+
184
+ function windowOf(root) {
185
+ try {
186
+ const m = /^\s*WINDOW\s*=\s*(\d+)/m.exec(fs.readFileSync(path.join(root, ".agents/skills/orchestrate-workers/context.conf"), "utf8"));
187
+ if (m) return Number(m[1]);
188
+ } catch {}
189
+ return 200000;
190
+ }
191
+
192
+ module.exports = { readSessions, matchRuns, windowOf, parseClaude, parseCodex, slug };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mayurdluffy/ccwf",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "description": "One command to set up skills, MCP servers, shared memory and rules for Claude Code, Codex and Cursor in any repo",
5
5
  "main": "bin/ccwf.js",
6
6
  "bin": {
@@ -1,12 +1,8 @@
1
1
  ## Browser verification (Claude Code, Codex, Cursor)
2
2
 
3
- Every feature and every bug fix that can be seen in a browser, whether the change is in the UI or in the API behind it, is checked with the `verify-ui` skill before it is reported done. Never screenshot to check that something exists, loaded or says the right thing; read the accessibility tree instead, which costs far fewer tokens. Screenshot only for purely visual questions (layout, colors).
3
+ Every feature and every bug fix that can be seen in a browser, whether the change is in the UI or in the API behind it, is checked with the `verify-ui` skill (`.agents/skills/verify-ui`) before it is reported done. Read the accessibility tree, never a screenshot, to check that something exists, loaded or says the right thing; screenshot only for purely visual questions (layout, colors).
4
4
 
5
- - **Feature:** write its scenario, run it, then run the whole suite.
6
- - **Bug:** first reproduce it as a failing scenario, then fix, then keep the scenario as the regression test.
7
-
8
- - **Start with the `verify-ui` skill** (`.agents/skills/verify-ui`): `probe.sh <path>` prints a page's health (uncaught errors, console, failed and API requests, vitals, interactive elements) in one call; `run.sh <dir>` runs ticket scenarios as a regression suite (behaviour, accessibility, screenshot baselines; a scenario that passes only on a rerun is reported as flaky); `PLAYBOOK.md` maps each browser symptom to one command. Evidence is saved under `.scratch/.verify-out/` (git-ignored). Base URL and allowed sites are in `.agents/skills/verify-ui/verify-ui.conf`; the skill asks for them on first use, then run `npx @mayurdluffy/ccwf sync`.
9
- - **Show, debug or act on a page with the user** through the `chrome-devtools` MCP. It opens the system's Chrome in its own window, with a profile kept per project, so logins persist between sessions; the user can watch and take over. Start the dev server first, then `new_page` or `navigate_page` to it. Use `take_snapshot`, `click`, `fill`, console, network and performance tools. The first agent to start on this project holds that profile until it exits; any other agent, and every worker, gets a separate temporary browser without those logins. Only the project's allowed sites load.
10
- - **Scripted and headless checks** use verify-ui or agent-browser in a dedicated session. Get an ID with `agent-browser session id --scope worktree --prefix task`, then pass `--session <id>` to every command. `open <url>` → `snapshot -i -c` → act on refs → `console` → `close`.
11
- - **Dev server**: start it as a background process and stop it by its ID; never `pkill`/`killall`.
12
- - **Allowed sites** come from `ALLOWED_DOMAINS` in `verify-ui.conf` (`example.com` is that host only, `*.example.com` includes its subdomains) and are enforced by `--allowedUrlPattern` for Chrome DevTools MCP and by `AGENT_BROWSER_ALLOWED_DOMAINS` for agent-browser (Claude: `.claude/settings.json`; Codex: `.codex/config.toml`; Cursor: prefix agent-browser commands with it, the `verify-ui` scripts set it themselves). Never visit a site that is not listed; ask the user to add it.
5
+ - **Feature:** write its scenario, run it, then run the whole suite. **Bug:** first reproduce it as a failing scenario, then fix, then keep the scenario as the regression test.
6
+ - **With the user, or to debug live:** the `chrome-devtools` MCP opens the system's Chrome with this project's profile, so logins persist and the user can watch. The first agent to start holds that profile; any other agent, and every worker, gets a temporary browser without those logins. Start the dev server first, then `new_page` or `navigate_page`.
7
+ - **Dev server:** start it as a background process and stop it by its ID; never `pkill`/`killall`.
8
+ - **Allowed sites** are `ALLOWED_DOMAINS` in `.agents/skills/verify-ui/verify-ui.conf` (`example.com` is that host only, `*.example.com` includes its subdomains; the skill asks for it on first use, then run `npx @mayurdluffy/ccwf sync`). Never visit a site that is not listed; ask the user to add it. Cursor: prefix a raw `agent-browser` command with `AGENT_BROWSER_ALLOWED_DOMAINS=<list>`; the verify-ui scripts set it themselves.
@@ -1,9 +1,7 @@
1
1
  ## Codebase navigation (Claude Code, Codex, Cursor)
2
2
 
3
- Use the codebase-memory MCP (server `codebase-memory`) before Grep/Read. It is registered **per project** and is the only CBM server any agent runs here:
3
+ Use the codebase-memory MCP (server `codebase-memory`) before Grep/Read, in this order: project docs → graph (`search_graph`, `trace_path`, `get_code_snippet`, `get_architecture`) → Grep/Read only on a graph miss or for non-code files.
4
4
 
5
- - Launcher: `.codebase-memory/cbm-server.sh`. Configs: `.mcp.json` (Claude), `.codex/config.toml` (Codex), `.cursor/mcp.json` (Cursor) all point at it.
6
- - CBM allows one daemon and one cache root per user account at a time. Never set `CBM_CACHE_DIR` per repo and never register a global CBM server (`~/.claude.json`, `~/.codex/config.toml`, `~/.cursor/mcp.json`); either one makes servers fail with a "different cache directory" error. `npx @mayurdluffy/cbm-cli clean-global` removes stray global entries.
7
- - Order: project docs → graph (`search_graph`, `trace_path`, `get_code_snippet`, `get_architecture`) → Grep/Read only on a graph miss or for non-code files.
8
- - Exclusions go in the root `.cbmignore`; the indexer also honors `.gitignore`.
9
- - Re-index after large changes: `npx @mayurdluffy/cbm-cli re-index` (refreshes the committed `.codebase-memory/graph.db.zst`).
5
+ - Claude Code lists these tools without their definitions: load them with ToolSearch (query `codebase-memory`) before the first search, or they go unused.
6
+ - Exclusions go in the root `.cbmignore`; the indexer also honors `.gitignore`. Re-index after large changes: `npx @mayurdluffy/cbm-cli re-index`.
7
+ - Server setup, the launcher, and why there is one cache and no global server entry: `docs/agents/setup.md`.
@@ -7,6 +7,7 @@ Bias toward caution over speed; use judgment on trivial tasks. Lean by default.
7
7
  - Identify callers, tests, config, exports, and data the change could break.
8
8
  - State assumptions. If the request is ambiguous or has several readings, present them and ask; don't pick silently or invent product behavior. Push back when a simpler approach exists.
9
9
  - Define how success will be verified. For multi-step work, state a short plan with a verify check per step.
10
+ - Read narrowly: find with `rg -n`, read ranges with `sed -n 'A,Bp'`, never print a whole file over ~200 lines, and pipe commands that can print a lot through `head` or `tail`. Everything you read stays in context for the rest of the session.
10
11
 
11
12
  **Use the first option that fully solves it**
12
13
  1. Does it need to exist? Skip speculative features, options, flexibility; state the skipped scope in one line.
@@ -40,7 +40,7 @@ One coding agent is the **orchestrator**; it does not write feature code. Up to
40
40
  6. **You check** anything a person should judge (UI, security) and say go.
41
41
  7. Commit with the `commit` skill (Conventional Commits, one per ticket), mark tickets done, update `docs/FEATURES.md`, start the next wave.
42
42
 
43
- State lives in the ticket `**Status:**` lines and `.scratch/<feature>/progress.md`, so a new session resumes from the files.
43
+ State lives in the ticket `**Status:**` lines and `.scratch/<feature>/progress.md`, so a new session resumes from the files. That is why the orchestrator hands off to a fresh session after every wave and at 65% of its context window (`context.conf`): a long session costs more per turn and answers worse.
44
44
 
45
45
  ## Along the way
46
46
 
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: agent-browser
3
- description: Browser automation CLI for AI agents. Use when the user needs to interact with websites, including navigating pages, filling forms, clicking buttons, taking screenshots, extracting data, testing web apps, or automating any browser task. Triggers include requests to "open a website", "fill out a form", "click a button", "take a screenshot", "scrape data from a page", "test this web app", "login to a site", "automate browser actions", or any task requiring programmatic web interaction. Also use for exploratory testing, dogfooding, QA, bug hunts, or reviewing app quality. Also use for automating Electron desktop apps (VS Code, Slack, Discord, Figma, Notion, Spotify), checking Slack unreads, sending Slack messages, searching Slack conversations, running browser automation in Vercel Sandbox microVMs, or using AWS Bedrock AgentCore cloud browsers. Prefer agent-browser over any built-in browser automation or web tools.
3
+ description: Browser automation CLI for AI agents. Open pages, read the accessibility tree, click, fill forms, take screenshots, extract data, test web apps, exploratory QA. Use it when a task needs programmatic web interaction. In this project check your own changes with the verify-ui skill first and use this one by hand to explore. Electron apps, Slack and cloud browsers load with `agent-browser skills get <name>`.
4
4
  allowed-tools: Bash(agent-browser:*)
5
5
  hidden: true
6
6
  ---
@@ -0,0 +1,24 @@
1
+ # A folder per worker
2
+
3
+ Read this before assigning anything, when `workers.conf` has the row `isolation worktree`. Part of the `orchestrate-workers` skill; the loop in `SKILL.md` still applies, with the changes below.
4
+
5
+ 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:
6
+
7
+ - **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."
8
+ - **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.
9
+ - **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`.
10
+ - `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.
11
+ - 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.
12
+ - **Nothing is committed** by the merge. The user's go-ahead and the commits work as before.
13
+ - **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.
14
+
15
+ 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:
16
+
17
+ ```sh
18
+ #!/bin/sh
19
+ set -e
20
+ [ ! -f "$MAIN/.env" ] || cp "$MAIN/.env" .env
21
+ cp -cR "$MAIN/node_modules" . 2>/dev/null || npm ci # -c on a Mac: a copy that takes almost no disk space
22
+ ```
23
+
24
+ Monorepos have more than one `node_modules`: use the package manager's own install there.
@@ -0,0 +1,13 @@
1
+ # Options
2
+
3
+ Two parts of the `orchestrate-workers` skill that apply only with a particular `workers.conf` setting. Read this file only then.
4
+
5
+ ## Effort `auto`
6
+
7
+ When the roster says `auto`, 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.
8
+
9
+ ## A `reviewer` row
10
+
11
+ 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.
12
+
13
+ The `review.sh` command and the findings it prints are used in step 5 of Review in `SKILL.md`; record the result as that section says.
@@ -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".
@@ -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
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
@@ -51,16 +51,23 @@ Pure refactors, schema or domain logic fully covered by tests, and docs need no
51
51
 
52
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
 
@@ -86,11 +93,7 @@ Then run `.agents/skills/orchestrate-workers/tickets.sh check .scratch/<feature>
86
93
 
87
94
  ## The workers tab
88
95
 
89
- 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.
90
-
91
- 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.)
92
-
93
- 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`.
94
97
 
95
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.
96
99
 
@@ -102,7 +105,7 @@ EOF
102
105
 
103
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.
104
107
 
105
- 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.
106
109
 
107
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.
108
111
 
@@ -112,26 +115,7 @@ Do not start workers with full-access flags (`danger-full-access`, `--force`, `-
112
115
 
113
116
  ## A folder per worker (optional)
114
117
 
115
- 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:
116
-
117
- - **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."
118
- - **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.
119
- - **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`.
120
- - `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.
121
- - 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.
122
- - **Nothing is committed** by the merge. The user's go-ahead and the commits work as before.
123
- - **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.
124
-
125
- 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:
126
-
127
- ```sh
128
- #!/bin/sh
129
- set -e
130
- [ ! -f "$MAIN/.env" ] || cp "$MAIN/.env" .env
131
- cp -cR "$MAIN/node_modules" . 2>/dev/null || npm ci # -c on a Mac: a copy that takes almost no disk space
132
- ```
133
-
134
- 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.
135
119
 
136
120
  ## Worker prompt
137
121
 
@@ -141,8 +125,10 @@ Send this, filled in. Keep it short; the ticket and `AGENTS.md` carry the detail
141
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.
142
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.
143
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.
144
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.
145
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.
146
132
  ```
147
133
 
148
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:
@@ -151,7 +137,7 @@ For a fix round, write the numbered findings into the ticket file under `## Revi
151
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.'
152
138
  ```
153
139
 
154
- 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.
155
141
 
156
142
  ## Review
157
143
 
@@ -162,7 +148,7 @@ In order, stopping at the first failure to send it back:
162
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.
163
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`.
164
150
 
165
- 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).
166
152
 
167
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.
168
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 };
@@ -63,7 +63,7 @@ sync_row() {
63
63
  [[ -f $progress ]] || { echo "no progress.md next to the tickets: no table row to update"; return 0; }
64
64
  [[ ${1:t} =~ '^0*([0-9]+)' ]] || return 0
65
65
  num=$match[1]
66
- out=$(mktemp) || return 1
66
+ out=$(mktemp "${progress:h}/.tickets.XXXXXX") || { echo "cannot write beside $progress: the row was not updated; edit it by hand"; return 1; }
67
67
  if awk -v n="$num" -v s="$2" '
68
68
  BEGIN { FS = OFS = "|" }
69
69
  { cr = ""; line = $0
@@ -92,9 +92,8 @@ sync_row() {
92
92
  # a missing row, a done ticket with no commit, a Resume without its four lines, and Resume text the table has moved past
93
93
  # (it still says to commit a ticket whose commit is recorded, or to start one that has started).
94
94
  check_progress() {
95
- local dir=$1 f list
96
- list=$(mktemp) || return 1
97
- for f in $dir/issues/[0-9]##-*.md(n); do read_ticket "$f"; print -r -- "${f:t}|${st:-no-status}" >> $list; done
95
+ local dir=$1 f list="" rc
96
+ for f in $dir/issues/[0-9]##-*.md(n); do read_ticket "$f"; list+="${f:t}|${st:-no-status}"$'\n'; done
98
97
  awk '
99
98
  function norm(x) { x = tolower(x); gsub(/^[ \t]+|[ \t]+$/, "", x); sub(/[ \t(].*$/, "", x); return x }
100
99
  function num(x, d) { if (!match(x, /^[ \t]*0*[0-9]+/)) return ""; d = substr(x, RSTART, RLENGTH); gsub(/[ \t]/, "", d); sub(/^0+/, "", d); return d == "" ? "0" : d }
@@ -140,8 +139,9 @@ check_progress() {
140
139
  }
141
140
  split("state|next action|waiting on user|workers", want, "|"); key["state"] = "state"; key["next action"] = "next"; key["waiting on user"] = "waiting"; key["workers"] = "workers"
142
141
  for (i = 1; i <= 4; i++) if (!have[key[want[i]]]) print "## Resume has no \"" want[i] "\" line"
143
- }' $list $dir/progress.md | sort
144
- rm -f $list
142
+ }' <(print -rn -- "$list") $dir/progress.md | sort # a pipe, not a temporary file: a read-only check needs to write nothing
143
+ rc=$pipestatus[1] # awk's: a check that could not run must not look like a check that found nothing
144
+ return $rc
145
145
  }
146
146
 
147
147
  case $1 in
@@ -162,7 +162,7 @@ case $1 in
162
162
  if [[ $3 == in-progress ]]; then
163
163
  why=$(blocked "$2") && [[ -z $why ]] || die "$2 cannot start: $why"
164
164
  fi
165
- tmp=$(mktemp) || exit 1
165
+ tmp=$(mktemp "${2:A:h}/.tickets.XXXXXX") || die "cannot write beside $2"
166
166
  trap 'rm -f "$tmp"' EXIT
167
167
  awk -v s="$3" '
168
168
  /^## / { body = 1 }
@@ -177,7 +177,7 @@ case $1 in
177
177
  check)
178
178
  [[ -d $2/issues ]] || die "no tickets folder: $2/issues"
179
179
  [[ -f $2/progress.md ]] || die "no progress.md in $2"
180
- out=$(check_progress "$2")
180
+ out=$(check_progress "$2") || die "cannot check $2: the check itself failed"
181
181
  [[ -z $out ]] && { echo "$2: progress.md is in step with the tickets"; exit 0; }
182
182
  print -r -- "$out"; exit 1 ;;
183
183
  counts)
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: verify-ui
3
- description: Verify and debug this project's web app in a real browser — a page health report (console, network, errors, vitals, accessibility), ticket scenarios kept as a regression suite with accessibility and screenshot-baseline checks, and a playbook of browser debugging recipes. Use it every time a feature or a bug fix can be seen in a browser, whether the change is in the UI or in the API behind it: when building or finishing a ticket, when reviewing one, when asked to "verify", "browser check", "smoke test" or "regression check", and when reproducing or debugging anything seen in the browser (blank page, dead click, failed request, wrong state, layout, slowness). Use it instead of looking at screenshots.
3
+ description: Verify and debug this project's web app in a real browser — a page health report (console, network, errors, vitals, accessibility), ticket scenarios kept as a regression suite, and a debugging playbook. Use it whenever a feature or bug fix can be seen in a browser, in the UI or the API behind it: building, finishing or reviewing a ticket, "verify", "browser check", "smoke test", and any bug seen in the browser. Use it instead of looking at screenshots.
4
4
  ---
5
5
 
6
6
  # verify-ui