@yeison.restrepo.r/code-conductor 1.42.0 → 1.43.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
@@ -263,6 +263,7 @@ All commands are tagged `(Conductor)` in the Claude Code command palette, so the
263
263
  | `/cc-test [scope]` | Find coverage gaps, write AAA-pattern tests (plus Playwright E2E where applicable), run after confirmation, and report results. |
264
264
  | `/cc-docs [scope]` | Audit documentation, write inline docs in your stack's format (JSDoc / docstrings / Javadoc / GoDoc), and preview before writing. |
265
265
  | `/cc-metrics [--dir <path>]` | Read-only report of token and time spend from Claude Code's local session logs, grouped by tool, command, phase, branch, pillar and session, with recommendations that quote the numbers they rest on. Registers no hook and writes no file. |
266
+ | `/cc-flow` | Print the guard lanes with per-guard pass, deny and ask counts, then the newest 20 hook decisions. See [Flow status](#flow-status). |
266
267
 
267
268
  ---
268
269
 
@@ -295,7 +296,7 @@ Hooks run automatically at specific points in a Claude Code session and need no
295
296
  | **1: Large-file read** | `Read` | A file over 150 lines needs an explicit `limit`; otherwise denied with a redirect to memory, grep, then a bounded read. |
296
297
  | **2: Duplicate write** | `Write`, `create_file`, `write_file` | Writing to an existing path asks first, showing the path, line count, and last-modified time: edit in place, confirm the overwrite, or cancel. `Edit` is deliberately not gated, because editing in place is what this guard recommends. |
297
298
  | **3: Bash scan** | `Bash` | Twelve mass content-dump patterns denied before execution. Commands over 8192 characters, and commands with unclosed quotes, are denied fail-closed. |
298
- | **4: node_modules** | `Read` | A path carrying `node_modules` as an exact path component is denied, with backslashes and `..` resolved first. Use Glob for existence checks. |
299
+ | **4: node_modules** | `Read` | A path carrying `node_modules` as an exact path component is denied, with backslashes and `..` resolved first. Use Glob for existence checks. `.claude/.flow-events.jsonl` is denied too: see [Flow status](#flow-status). |
299
300
  | **5: Band scope** | role-agent writes | During orchestration, a band role can only write inside its installed envelope's scope. |
300
301
  | **6: Orchestrator writes** | live orchestrate runs | The orchestrator session can only write its own run-state surface; nested agent dispatch is denied. |
301
302
  | **7: Role shell** | role-agent `Bash` | `spec`, `plan` and `audit` get no shell; `code` and `qa` may run exactly one command, the recorded test command, byte for byte, no chaining. |
@@ -314,6 +315,16 @@ Hit a block you believe is wrong? Re-run the command with `CC_GUARD3_WARN=1` and
314
315
 
315
316
  **Unparseable input fails closed.** It is denied with one stderr line naming `CC_HOOK_ALLOW=1`, which overrides that denial alone and leaves every guard fully active on every payload the hook can read. Set `CC_HOOK_DEBUG=1` to see the diagnostic lines it otherwise swallows.
316
317
 
318
+ ### Flow status
319
+
320
+ After each decision is written, the pre-tool-use hook appends one JSON line to `.claude/.flow-events.jsonl`: the tool, the verdict, the deciding guard and its reason code, the guards that passed before it, and a short target (a path relative to the project, an agent type, or the first word of a Bash command after any `VAR=value` words, never the full command; quotes are honored when finding that word, and an unclosed quote or a `$( )`, backtick or `${ }` substitution among those words records an empty target instead of a guess). The file is capped at about 160 KiB and rotated to its last 250 lines, it is git-ignored by the managed `.gitignore` block, and Guard 4 keeps the agent from reading it into context. Writing it can never block or change a tool call: any error is swallowed.
321
+
322
+ - **Status line.** `--project` sets `"statusLine": {"type": "command", "command": "node .claude/flow-status.mjs"}` in `.claude/settings.json`. It shows one line below the prompt for the current session, for example `⛔ G3 P9 · 12 calls · 3 deny` after a denial or `✓ 12 calls · 3 deny` after an allow. Claude Code refreshes it when a new assistant message arrives, not on every tool call.
323
+ - **`/cc-flow`.** Prints one lane per tool family with each guard's pass, deny and ask counts, then the newest 20 events.
324
+ - **What Guard 4 covers.** It denies the `Read` tool on `.claude/.flow-events.jsonl` and on rotation's `.flow-events.jsonl.tmp`. A plain `cat .claude/.flow-events.jsonl` through Bash is not caught: Guard 3 looks for mass-dump shapes, not this file's name.
325
+ - **`CC_FLOW_OFF=1`** stops the hook from writing events; the status line goes blank and `/cc-flow` says the log is off.
326
+ - **An existing status line wins.** If your project or user `settings.json` already has a `statusLine`, the installer leaves both files untouched and prints a line saying the flow status line was skipped; `/cc-flow` still works, and you can set the entry above by hand. An entry whose command names `flow-status.mjs` is treated as the installer's own and kept current.
327
+
317
328
  ### The other hooks
318
329
 
319
330
  - **context-guard** (project). Fires on every `UserPromptSubmit` and atomically increments a turn counter in `.claude/memory/turn-count.txt`. At 80% of the threshold it emits a CONTEXT WARNING; at or above the threshold, CONTEXT CRITICAL. The threshold is read from `.claude/memory/context-threshold.txt` (default 25). Ships for Unix (`context-guard.sh`) and Windows (`context-guard.ps1`). `CC_GUARD_DEBUG=1` prints debug info to stderr; `CC_PROJECT_ROOT` overrides the project root used for the memory directory.
@@ -371,9 +382,9 @@ By default, only the global core files are installed. Flags extend that:
371
382
 
372
383
  | Flag | Description |
373
384
  |---|---|
374
- | `--project` | Also install the project template into the current directory |
385
+ | `--project` / `-Project` | Also install the project template into the current directory |
375
386
  | `--no-deps` / `-NoDeps` | Accepted for compatibility with the retired shell installers; a no-op, since the npm CLI installs no dependencies and copies agent files only |
376
- | `--verbosity MIN\|INFO\|VERBOSE` | Default response verbosity (default `MIN`). `MIN` = one sentence per response, `INFO` = bullet list, `VERBOSE` = full explanation. Re-run the installer to change it. |
387
+ | `--verbosity MIN\|INFO\|VERBOSE` / `-Verbosity LEVEL` | Default response verbosity (default `MIN`). `MIN` = one sentence per response, `INFO` = bullet list, `VERBOSE` = full explanation. Re-run the installer to change it. PowerShell's `-Verbosity:INFO` form is not supported; it warns and the level stays `MIN`. |
377
388
 
378
389
  **Updating:** re-run the same install command. User-configured files are never overwritten; agent-managed files are always updated.
379
390
 
@@ -8,7 +8,12 @@ import { verbosityHookCommand, mergeVerbosityHook } from '../lib/installer/setti
8
8
  import { healGraphifyHook } from '../lib/installer/heal.mjs';
9
9
  import { writeVerbosity, writeVersionFile } from '../lib/installer/config.mjs';
10
10
 
11
- const USAGE = `Usage: code-conductor [--project] [--no-deps|-NoDeps] [--verbosity MIN|INFO|VERBOSE] [--version] [--help]`;
11
+ const USAGE = `Usage: code-conductor [--project|-Project] [--no-deps|-NoDeps] [--verbosity|-Verbosity MIN|INFO|VERBOSE] [--version] [--help]`;
12
+
13
+ // -Verbosity is the spelling the retired install.ps1 documented. Both spellings share
14
+ // every form (space-separated, inline `=`, missing value) and last-wins across them.
15
+ const VERBOSITY_FLAGS = ['--verbosity', '-Verbosity'];
16
+ const isVerbosityFlag = (a) => VERBOSITY_FLAGS.some((f) => a === f || a.startsWith(`${f}=`));
12
17
 
13
18
  // Hand-rolled parser (five flags only). Deliberately NOT node:util's parseArgs —
14
19
  // the CLI honors the zero-runtime-dependency rule and node:util adds no value for
@@ -21,19 +26,21 @@ function parseArgs(argv) {
21
26
  const opts = { project: false, noDeps: false, verbosity: undefined, verbosityGiven: false, version: false, help: false, unknown: [] };
22
27
  for (let i = 0; i < argv.length; i++) {
23
28
  const a = argv[i];
24
- if (a === '--project') opts.project = true;
29
+ // -Project is the spelling the retired install.ps1 documented; matched exact-case
30
+ // like every other flag here.
31
+ if (a === '--project' || a === '-Project') opts.project = true;
25
32
  // Accepted no-op: the npm CLI installs no dependencies since FEAT-023 removed the
26
33
  // shell installers, so there is nothing to skip. Recognized so callers carried over
27
34
  // from install.sh get no misleading "unrecognized" warning.
28
35
  else if (a === '--no-deps' || a === '-NoDeps') opts.noDeps = true;
29
- else if (a === '--verbosity' || a.startsWith('--verbosity=')) {
36
+ else if (isVerbosityFlag(a)) {
30
37
  opts.verbosityGiven = true;
31
- if (a.startsWith('--verbosity=')) {
38
+ if (a.includes('=')) {
32
39
  // Inline form: --verbosity=INFO. Empty (`--verbosity=`) leaves value ''.
33
40
  // Surrounding whitespace (e.g. a quoted `--verbosity= VERBOSE `) is NOT
34
41
  // stripped here — normalizeVerbosity() trims before matching, so whitespace
35
42
  // is tolerated and a whitespace-only/`=`-only value normalizes to null → MIN+warn.
36
- opts.verbosity = a.slice('--verbosity='.length);
43
+ opts.verbosity = a.slice(a.indexOf('=') + 1);
37
44
  } else {
38
45
  // Space-separated form: consume the next token only if it is a real value,
39
46
  // not another flag or the end of argv (`--verbosity` passed last). A missing
@@ -110,7 +117,7 @@ export function run(argv, env = process.env, { cwd = process.cwd(), log, nodeVer
110
117
  if (heal.status === 'removed') emit('stdout', 'code-conductor: removed the retired graphify-ast-refresh hook from settings.json (backup written beside it)');
111
118
  for (const line of heal.lines) emit('stderr', `code-conductor: ${line}`);
112
119
  writeVersionFile(home, pkgVersion(assetRoot));
113
- if (opts.project) deployProject(assetRoot, cwd, { warn: (m) => emit('stderr', m), report: (m) => emit('stdout', m) });
120
+ if (opts.project) deployProject(assetRoot, cwd, { warn: (m) => emit('stderr', m), report: (m) => emit('stdout', m), home });
114
121
  return 0;
115
122
  } catch (err) {
116
123
  // Pre-flight failures (nothing written yet) → exit 1.
@@ -1,9 +1,11 @@
1
1
  import { cpSync, mkdirSync, chmodSync, existsSync, lstatSync, readdirSync, readFileSync, statSync, rmSync, unlinkSync } from 'node:fs';
2
2
  import { join, relative, isAbsolute, sep } from 'node:path';
3
+ import { createHash } from 'node:crypto';
3
4
  import { mergeFileInto, resolveRealTarget } from './file-merge.mjs';
4
5
  import { mergeClaudeMdText, mergeGitignoreText } from './merge-md.mjs';
5
6
  import { GLOBAL_HOST_OWNED, PROJECT_HOST_OWNED, GLOBAL_SETTINGS_FINGERPRINTS, PROJECT_SETTINGS_FINGERPRINTS, hostOwnedFilter, seedHostOwned } from './host-owned.mjs';
6
7
  import { mergeSettingsFile } from './settings-merge.mjs';
8
+ import { mergeFlowStatusLine, FLOW_STATUS_COMMAND } from './settings.mjs';
7
9
 
8
10
  // Host-authored data, not managed assets: these are merged, never force-copied —
9
11
  // everything else in the template keeps its overwrite. Keyed by the name the file
@@ -154,14 +156,24 @@ function sweepStaleRootScripts(assetRoot, cwd) {
154
156
  // host's own history, with new failure modes (detached HEAD, shallow clone,
155
157
  // submodule, dirty index, no git at all) for a path that fires in one narrow
156
158
  // case. Print the two commands and write nothing.
159
+ // (#94) Those releases wrote the stub as it stood at b018793, which carried
160
+ // code-conductor's own history. The neutral stub replaced it, so the old bytes are
161
+ // recognized by digest rather than re-shipped.
162
+ export const LEGACY_PROJECT_MEMORY_STUB_SHA256 = '01e65fdecfd0a842dc1269cb0a5ff59718978830c94d5815b09c3a0454f261f9';
163
+
157
164
  function warnIfProjectMemoryIsStub(templateClaude, target, emit) {
158
165
  const rel = '.claude/memory/project.md';
159
166
  const stub = join(templateClaude, 'memory', 'project.md');
160
167
  const host = join(target, 'memory', 'project.md');
161
- if (!existsSync(stub) || !existsSync(host)) return false;
162
- if (readFileSync(host, 'utf8') !== readFileSync(stub, 'utf8')) return false;
168
+ if (!existsSync(host)) return false;
169
+ const text = readFileSync(host, 'utf8');
170
+ const isCurrentStub = existsSync(stub) && text === readFileSync(stub, 'utf8');
171
+ // The digest is of the LF bytes; an autocrlf=true clone wrote the stub as CRLF.
172
+ const lf = text.replace(/\r\n/g, '\n');
173
+ const isLegacyStub = createHash('sha256').update(lf).digest('hex') === LEGACY_PROJECT_MEMORY_STUB_SHA256;
174
+ if (!isCurrentStub && !isLegacyStub) return false;
163
175
  emit([
164
- `code-conductor: ${rel} matches the bundled stub; it may have been overwritten by an installer re-run before 1.30.0.`,
176
+ `code-conductor: ${rel} matches a bundled stub; it may have been overwritten by an installer re-run before 1.30.0.`,
165
177
  ` Find a committed copy: git log --oneline -- ${rel}`,
166
178
  ` Restore it: git checkout <commit> -- ${rel}`,
167
179
  ].join('\n'));
@@ -195,7 +207,35 @@ function packageName(path) {
195
207
  try { return JSON.parse(text).name ?? null; } catch { return null; }
196
208
  }
197
209
 
198
- export function deployProject(assetRoot, cwd, { warn = toStderr, report = toStdout } = {}) {
210
+ // One line per outcome of the flow status line merge. 'unchanged' has none, so a re-run of
211
+ // an unchanged release stays as quiet as every other managed file.
212
+ // The replaced line names the entry it overwrote, so a host who hand-tuned it can restore it.
213
+ const FLOW_STATUS_REPORT = {
214
+ added: () => `code-conductor: added the flow status line to .claude/settings.json (${FLOW_STATUS_COMMAND})`,
215
+ replaced: (previous) =>
216
+ `code-conductor: updated the flow status line in .claude/settings.json to ${FLOW_STATUS_COMMAND} ` +
217
+ `(replaced ${JSON.stringify(previous)})`,
218
+ 'host-skipped': () =>
219
+ 'code-conductor: kept your existing statusLine, so the flow status line was skipped (/cc-flow still works). ' +
220
+ `To use it, set "statusLine": {"type": "command", "command": "${FLOW_STATUS_COMMAND}"} in .claude/settings.json`,
221
+ 'malformed-skipped': () =>
222
+ 'code-conductor: .claude/settings.json is not valid JSON; it was backed up and left as is, so the flow status line was not added',
223
+ 'unreadable-skipped': () => 'code-conductor: .claude/settings.json could not be read, so the flow status line was not added',
224
+ };
225
+
226
+ // Only when the template ships the script the entry points at: a statusLine naming a
227
+ // missing file would blank the host's line for nothing. Runs after mergeSettingsFile, so
228
+ // it sees the settings.json that merge leaves behind.
229
+ function mergeFlowStatus(templateClaude, target, home, report) {
230
+ if (!existsSync(join(templateClaude, 'flow-status.mjs'))) return;
231
+ const userPath = home ? join(home, '.claude', 'settings.json') : null;
232
+ const { status, previous } = mergeFlowStatusLine(join(target, 'settings.json'), userPath);
233
+ if (FLOW_STATUS_REPORT[status]) report(FLOW_STATUS_REPORT[status](previous));
234
+ }
235
+
236
+ // `home` is where the user-level settings.json lives, consulted only by the flow status
237
+ // line rule. A caller that passes none gets the project-level check alone.
238
+ export function deployProject(assetRoot, cwd, { warn = toStderr, report = toStdout, home = null } = {}) {
199
239
  const emit = warn;
200
240
  // Also run by the CLI's pre-flight; kept here for direct callers.
201
241
  assertNotSelfInstall(assetRoot, cwd);
@@ -233,6 +273,7 @@ export function deployProject(assetRoot, cwd, { warn = toStderr, report = toStdo
233
273
  mkdirSync(join(target, 'memory'), { recursive: true });
234
274
  seedHostOwned(templateClaude, target, PROJECT_HOST_OWNED);
235
275
  mergeSettingsFile(join(templateClaude, 'settings.json'), join(target, 'settings.json'), PROJECT_SETTINGS_FINGERPRINTS);
276
+ mergeFlowStatus(templateClaude, target, home, report);
236
277
  // scripts/ is a sibling of project-template/ under assetRoot (source layout),
237
278
  // but is deployed as a CHILD of .claude/ (target) - it must stay inside the
238
279
  // project's self-contained .claude footprint, not spill into the host's own
@@ -111,8 +111,10 @@ export function mergeSettingsFile(templatePath, settingsPath, fingerprints, { no
111
111
 
112
112
  const text = `${JSON.stringify(merged, null, 2)}\n`;
113
113
  // Skipping an identical write is what makes a re-run of an unchanged release
114
- // byte-identical AND leaves the file's mtime alone.
115
- if (text === raw) return 'unchanged';
114
+ // byte-identical AND leaves the file's mtime alone. The host's line endings
115
+ // are not content: a CRLF file (a Windows autocrlf checkout, or an editor's
116
+ // choice) that matches after normalizing is left as it is.
117
+ if (text === raw.replace(/\r\n/g, '\n')) return 'unchanged';
116
118
  writeAtomic(target.realPath, text);
117
119
  return 'merged';
118
120
  }
@@ -95,3 +95,63 @@ function mergeHook(settingsPath, hookCmd, fingerprint, now) {
95
95
  export function mergeVerbosityHook(settingsPath, hookCmd, now = new Date()) {
96
96
  return mergeHook(settingsPath, hookCmd, FINGERPRINT, now);
97
97
  }
98
+
99
+ // FEAT-044: the flow status line. The fingerprint names the entry this repo OWNS, exactly
100
+ // as FINGERPRINT does for the verbosity hook.
101
+ export const FLOW_STATUS_FINGERPRINT = 'flow-status.mjs';
102
+ export const FLOW_STATUS_COMMAND = 'node .claude/flow-status.mjs';
103
+
104
+ // { obj } when the file parses to an object, { missing } when absent, { malformed } when
105
+ // it holds something else, { unreadable } when it cannot be read at all.
106
+ function readSettingsObject(path) {
107
+ let raw;
108
+ try { raw = readFileSync(path, 'utf8'); }
109
+ catch (e) { return e.code === 'ENOENT' ? { missing: true } : { unreadable: true }; }
110
+ if (raw.trim() === '') return { obj: {} };
111
+ try {
112
+ const obj = JSON.parse(raw);
113
+ return obj !== null && typeof obj === 'object' && !Array.isArray(obj) ? { obj } : { malformed: true };
114
+ } catch { return { malformed: true }; }
115
+ }
116
+
117
+ const statusLineIsOurs = (sl) =>
118
+ sl !== null && typeof sl === 'object' && typeof sl.command === 'string' && sl.command.includes(FLOW_STATUS_FINGERPRINT);
119
+
120
+ const statusLineIsCanonical = (sl) =>
121
+ statusLineIsOurs(sl) && sl.type === 'command' && sl.command === FLOW_STATUS_COMMAND && Object.keys(sl).length === 2;
122
+
123
+ function writeStatusLine(path, obj, status) {
124
+ const previous = obj.statusLine;
125
+ obj.statusLine = { type: 'command', command: FLOW_STATUS_COMMAND };
126
+ writeFileSync(path, `${JSON.stringify(obj, null, 2)}\n`, 'utf8');
127
+ return status === 'replaced' ? { status, previous } : { status };
128
+ }
129
+
130
+ function mergeOwnedStatusLine(path, obj) {
131
+ if (statusLineIsCanonical(obj.statusLine)) return { status: 'unchanged' };
132
+ if (!statusLineIsOurs(obj.statusLine)) return { status: 'host-skipped' };
133
+ return writeStatusLine(path, obj, 'replaced');
134
+ }
135
+
136
+ // A user file that cannot be read cannot prove the host has no status line, so it counts
137
+ // as having one: the installer never risks overriding a line the user set globally.
138
+ function userHasStatusLine(path) {
139
+ const user = readSettingsObject(path);
140
+ if (user.missing) return false;
141
+ return !user.obj || 'statusLine' in user.obj;
142
+ }
143
+
144
+ // The one approved exception to MERGE_OWNED_KEYS (FEAT-044, owner decision 2026-10-19). A
145
+ // project statusLine overrides the user's global one, so the entry is added only when
146
+ // neither level has a statusLine, and only an entry carrying the fingerprint is replaced.
147
+ // `userPath` null skips the user-level check (a caller with no home to consult). Returns
148
+ // { status }, plus `previous` (the overwritten statusLine) when the status is 'replaced'.
149
+ export function mergeFlowStatusLine(projectPath, userPath, now = new Date()) {
150
+ const project = readSettingsObject(projectPath);
151
+ if (project.unreadable) return { status: 'unreadable-skipped' };
152
+ if (project.malformed) { backupMalformed(projectPath, now); return { status: 'malformed-skipped' }; }
153
+ const obj = project.obj ?? {};
154
+ if ('statusLine' in obj) return mergeOwnedStatusLine(projectPath, obj);
155
+ if (userPath && userHasStatusLine(userPath)) return { status: 'host-skipped' };
156
+ return writeStatusLine(projectPath, obj, 'added');
157
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yeison.restrepo.r/code-conductor",
3
- "version": "1.42.0",
3
+ "version": "1.43.0",
4
4
  "description": "A governance layer for Claude Code sessions: hooks that check an agent's commands before they run, a spec-first workflow, and project memory the next session reads.",
5
5
  "keywords": [
6
6
  "agentic-development",
@@ -0,0 +1,15 @@
1
+ ---
2
+ description: "(Conductor) Show the guard lanes and the latest hook decisions"
3
+ ---
4
+
5
+ Run this one command from the project root and nothing else:
6
+
7
+ ```bash
8
+ node .claude/flow-status.mjs --detail
9
+ ```
10
+
11
+ Echo its output verbatim inside a code block. Add nothing before or after it: no summary, no interpretation, no advice.
12
+
13
+ The output lists one lane per tool family with each guard's pass, deny and ask counts, then the newest 20 events from `.claude/.flow-events.jsonl`. Do not open that file with the Read tool; Guard 4 denies it, and this command is the way to see it.
14
+
15
+ If the command fails, print its error output verbatim and stop.
@@ -0,0 +1,146 @@
1
+ #!/usr/bin/env node
2
+ // Flow status line (FEAT-044). Claude Code runs this as its statusLine command and shows
3
+ // what it prints; /cc-flow runs it with --detail. It reads only the tail of the event file
4
+ // the PreToolUse hook appends to, and every path exits 0: a failing status line must never
5
+ // put a stack trace under the prompt. Event fields are printed as data, never evaluated.
6
+ // Zero dependencies by design; node: builtins only.
7
+ import { closeSync, fstatSync, openSync, readFileSync, readSync } from 'node:fs';
8
+ import { join, resolve } from 'node:path';
9
+ import { fileURLToPath } from 'node:url';
10
+
11
+ export const TAIL_BYTES = 32 * 1024;
12
+ const EVENTS_REL = ['.claude', '.flow-events.jsonl'];
13
+ const NEWEST = 20;
14
+
15
+ // One lane per tool family, guards in the hook's dispatch order (spec D3). The hook's
16
+ // GUARD_NUMBER table is the other half; tests/installer/flow-status.test.js fails on drift.
17
+ export const LANES = [
18
+ { name: 'Read', tools: ['Read'], guards: [4, 1] },
19
+ { name: 'Write', tools: ['Write', 'create_file', 'write_file'], guards: [5, 6, 2] },
20
+ { name: 'Edit', tools: ['Edit'], guards: [5, 6] },
21
+ { name: 'Bash', tools: ['Bash'], guards: [7, 3] },
22
+ { name: 'Agent', tools: ['Agent', 'SendMessage'], guards: [6] },
23
+ ];
24
+
25
+ // Null when there is no event file yet. A read that starts mid-file starts mid-line, so
26
+ // that first fragment is dropped rather than reported as a broken event.
27
+ export function readTail(path) {
28
+ let fd;
29
+ try { fd = openSync(path, 'r'); } catch (e) { if (e.code === 'ENOENT') return null; throw e; }
30
+ try {
31
+ const stat = fstatSync(fd);
32
+ // Windows opens a directory for reading and reports size 0, which would pass for "empty".
33
+ if (!stat.isFile()) throw new Error(`${path} is not a file`);
34
+ const size = stat.size;
35
+ const length = Math.min(size, TAIL_BYTES);
36
+ const buf = Buffer.alloc(length);
37
+ readSync(fd, buf, 0, length, size - length);
38
+ const text = buf.toString('utf8');
39
+ return size > length ? text.slice(text.indexOf('\n') + 1) : text;
40
+ } finally { closeSync(fd); }
41
+ }
42
+
43
+ const isEvent = (ev) => ev !== null && typeof ev === 'object' && typeof ev.verdict === 'string';
44
+
45
+ // Unparseable lines are skipped; only a broken LAST line is reported, because that is the
46
+ // one the next append repairs (spec D7) and the one the status line would otherwise hide.
47
+ export function parseEvents(text) {
48
+ const events = [];
49
+ let lastBroken = false;
50
+ for (const line of text.split('\n')) {
51
+ if (line.trim() === '') continue;
52
+ let ev;
53
+ try { ev = JSON.parse(line); } catch { ev = null; }
54
+ lastBroken = !isEvent(ev);
55
+ if (!lastBroken) events.push(ev);
56
+ }
57
+ return { events, lastBroken };
58
+ }
59
+
60
+ // Control characters would break the one-line display; replace them, never interpret them.
61
+ const clean = (s) => String(s ?? '').replace(/[\u0000-\u001f\u007f]/g, ' ');
62
+ const decidedBy = (ev) => `G${clean(ev.guard)}${ev.code ? ` ${clean(ev.code)}` : ''}`;
63
+ const callWord = (n) => (n === 1 ? 'call' : 'calls');
64
+
65
+ // The spec D2 state table, one line.
66
+ export function statusLine(events, lastBroken) {
67
+ if (lastBroken) return 'flow: unreadable, retrying';
68
+ if (events.length === 0) return '';
69
+ const count = (verdict) => events.filter((e) => e.verdict === verdict).length;
70
+ const calls = `${events.length} ${callWord(events.length)}`;
71
+ const last = events.at(-1);
72
+ if (last.verdict === 'deny') return `⛔ ${decidedBy(last)} · ${calls} · ${count('deny')} deny`;
73
+ if (last.verdict === 'ask') return `? ${decidedBy(last)} · ${calls} · ${count('ask')} ask`;
74
+ return `✓ ${calls} · ${count('deny')} deny`;
75
+ }
76
+
77
+ // The status line counts the current session only. Events carry no session id, so the
78
+ // session's start is taken from the elapsed wall-clock time Claude Code passes on stdin;
79
+ // without it (no stdin, or an older release) every event in the tail counts.
80
+ export function sessionStart(session, now = Date.now()) {
81
+ const ms = session?.cost?.total_duration_ms;
82
+ return typeof ms === 'number' && ms >= 0 ? now - ms : 0;
83
+ }
84
+
85
+ function laneRow(lane, events) {
86
+ const mine = events.filter((e) => lane.tools.includes(e.tool));
87
+ const cells = lane.guards.map((g) => {
88
+ const pass = mine.filter((e) => Array.isArray(e.passed) && e.passed.includes(g)).length;
89
+ const deny = mine.filter((e) => e.guard === g && e.verdict === 'deny').length;
90
+ const ask = mine.filter((e) => e.guard === g && e.verdict === 'ask').length;
91
+ return `G${g} ${pass} pass ${deny} deny${ask ? ` ${ask} ask` : ''}`;
92
+ });
93
+ return `${lane.name.padEnd(6)} ${String(mine.length).padStart(4)} ${callWord(mine.length).padEnd(5)} ${cells.join(' · ')}`;
94
+ }
95
+
96
+ function eventRow(ev) {
97
+ const time = Number.isFinite(ev.ts) ? new Date(ev.ts).toTimeString().slice(0, 8) : '--:--:--';
98
+ const decided = ev.guard == null ? '' : ` ${decidedBy(ev)}`;
99
+ const agent = ev.agent ? ` [${clean(ev.agent)}]` : '';
100
+ // JSON.stringify escapes a quote or a newline in the target, so one event stays one row.
101
+ return `${time} ${clean(ev.tool).padEnd(6)} ${clean(ev.verdict)}${decided} ${JSON.stringify(String(ev.target ?? ''))}${agent}`;
102
+ }
103
+
104
+ // The /cc-flow report: every lane, then the newest events, oldest first.
105
+ export function detailReport(events) {
106
+ const newest = events.slice(-NEWEST).map(eventRow);
107
+ return [
108
+ 'Flow lanes (guards in dispatch order):',
109
+ ...LANES.map((lane) => laneRow(lane, events)),
110
+ '',
111
+ newest.length ? `Newest ${newest.length} events:` : 'no events yet',
112
+ ...newest,
113
+ ].join('\n');
114
+ }
115
+
116
+ function readSession() {
117
+ if (process.stdin.isTTY) return {};
118
+ try {
119
+ const raw = readFileSync(0, 'utf8');
120
+ return raw.trim() ? JSON.parse(raw) : {};
121
+ } catch { return {}; }
122
+ }
123
+
124
+ function workingDir(session) {
125
+ const dir = session?.workspace?.current_dir ?? session?.cwd;
126
+ return typeof dir === 'string' && dir ? dir : process.cwd();
127
+ }
128
+
129
+ // --detail never reads stdin: run from a shell tool, stdin may be a pipe nobody closes.
130
+ export function render(argv, env = process.env) {
131
+ const detail = argv.includes('--detail');
132
+ // Exactly '1', as the README documents and the hook checks: CC_FLOW_OFF=0 leaves it on.
133
+ if (env.CC_FLOW_OFF === '1') return detail ? 'flow log is off (CC_FLOW_OFF=1)' : '';
134
+ const session = detail ? {} : readSession();
135
+ const text = readTail(join(workingDir(session), ...EVENTS_REL));
136
+ const { events, lastBroken } = parseEvents(text ?? '');
137
+ if (detail) return detailReport(events);
138
+ const start = sessionStart(session);
139
+ return statusLine(events.filter((e) => !(e.ts < start)), lastBroken);
140
+ }
141
+
142
+ const invoked = process.argv[1] && resolve(process.argv[1]).toLowerCase() === fileURLToPath(import.meta.url).toLowerCase();
143
+ if (invoked) {
144
+ try { process.stdout.write(`${render(process.argv.slice(2))}\n`); } catch { /* print nothing, never a trace */ }
145
+ process.exitCode = 0;
146
+ }
@@ -4,10 +4,11 @@
4
4
  // hookSpecificOutput.permissionDecision and EVERY path exits 0. Nothing here exits 2:
5
5
  // a deliberate denial must never be indistinguishable from a crashed script.
6
6
  // Zero dependencies by design; node: builtins only.
7
- import { existsSync, readFileSync, statSync } from 'node:fs';
7
+ import { appendFileSync, closeSync, existsSync, openSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
8
8
  import { posix, join, resolve, dirname, relative, isAbsolute, sep } from 'node:path';
9
9
 
10
10
  const LINE_LIMIT = 150;
11
+ const BINARY_SNIFF_BYTES = 8000;
11
12
  const BLOCKED_COMPONENTS = new Set(['node_modules']);
12
13
 
13
14
  let emitted = false;
@@ -16,8 +17,14 @@ function debug(msg) {
16
17
  if (process.env.CC_HOOK_DEBUG) process.stderr.write(`PRE_TOOL_USE: ${msg}\n`);
17
18
  }
18
19
 
19
- const deny = (reason) => ({ permissionDecision: 'deny', permissionDecisionReason: reason });
20
- const ask = (reason) => ({ permissionDecision: 'ask', permissionDecisionReason: reason });
20
+ // `code` is the guard's own short reason token for the flow log (FEAT-044 D5), so the
21
+ // readers never parse the human-readable reason. It is non-enumerable on purpose: a
22
+ // decision's shape, and the hookSpecificOutput emit() spreads it into, stay exactly
23
+ // { permissionDecision, permissionDecisionReason }, and only the emitter reads it.
24
+ const makeDecision = (permissionDecision, reason, code) =>
25
+ Object.defineProperty({ permissionDecision, permissionDecisionReason: reason }, 'code', { value: code });
26
+ const deny = (reason, code = null) => makeDecision('deny', reason, code);
27
+ const ask = (reason, code = null) => makeDecision('ask', reason, code);
21
28
 
22
29
  let warning = '';
23
30
 
@@ -71,27 +78,57 @@ function guard4BlockedRead(input) {
71
78
  if (!path) return null; // Case A: nothing to verify
72
79
  const normalized = posix.normalize(path.replace(/\\/g, '/'));
73
80
  const parts = normalized.split('/').filter(p => p && p !== '.');
81
+ if (isFlowEventsPath(parts)) return deny(FLOW_EVENTS_DENIAL, 'FLOW_EVENTS_READ');
74
82
  if (!parts.some(p => BLOCKED_COMPONENTS.has(p.toLowerCase()))) return null;
75
83
  return deny(
76
- 'Guard 4: direct reads of node_modules/ are forbidden. Use Glob for existence checks.'
84
+ 'Guard 4: direct reads of node_modules/ are forbidden. Use Glob for existence checks.',
85
+ 'NODE_MODULES'
77
86
  );
78
87
  }
79
88
 
89
+ // FEAT-044 D8: the agent must not pull its own audit log into context. The status line and
90
+ // /cc-flow read it from Node, never through the Read tool, so they are unaffected.
91
+ const FLOW_EVENTS_DENIAL =
92
+ 'Guard 4: .claude/.flow-events.jsonl is the hook\'s own flow log and is not read into context. Run /cc-flow for a summary.';
93
+
94
+ function isFlowEventsPath(parts) {
95
+ const [dir, file] = parts.slice(-2).map(p => p.toLowerCase());
96
+ // The .tmp is rotation's snapshot of the same lines, alive for one write and rename.
97
+ return dir === '.claude' && (file === '.flow-events.jsonl' || file === '.flow-events.jsonl.tmp');
98
+ }
99
+
100
+ // git's binary heuristic (buffer_is_binary): a NUL in the first 8,000 bytes. A binary has
101
+ // no lines, and Claude Code renders an image Read rather than reading it as text (#93).
102
+ // UTF-16 text is full of NULs but is read as text, so a UTF-16 BOM rules binary out. Its
103
+ // newline is still a single 0x0A byte, so the UTF-8 line count stays right.
104
+ function isBinary(buffer) {
105
+ if (hasUtf16Bom(buffer)) return false;
106
+ return buffer.subarray(0, BINARY_SNIFF_BYTES).indexOf(0) !== -1;
107
+ }
108
+
109
+ function hasUtf16Bom(buffer) {
110
+ const [a, b] = buffer;
111
+ return (a === 0xff && b === 0xfe) || (a === 0xfe && b === 0xff);
112
+ }
113
+
80
114
  // Guard 1: a large-file Read with no limit. A path that cannot be stat'd has no size to
81
115
  // exceed the threshold, so it allows.
82
116
  function guard1LargeRead(input) {
83
117
  if (input.limit !== undefined) return null;
84
118
  const path = targetPath(input);
85
119
  if (!path || !isRegularFile(path)) return null;
86
- let lines;
87
- try { lines = countLines(readFileSync(path, 'utf8')); }
120
+ let buffer;
121
+ try { buffer = readFileSync(path); }
88
122
  catch (e) { debug(`guard 1 could not read ${path}: ${e.message}`); return null; }
123
+ if (isBinary(buffer)) return null;
124
+ const lines = countLines(buffer.toString('utf8'));
89
125
  if (lines <= LINE_LIMIT) return null;
90
126
  return deny(
91
127
  `Guard 1: LARGE FILE READ BLOCKED. File: ${path}. Lines: ${lines} ` +
92
128
  `(>${LINE_LIMIT}, no limit specified). Follow the orchestrator lookup chain: ` +
93
129
  '1. Check .claude/memory/project.md 2. Use Grep/Glob for pattern searches ' +
94
- '3. Read with explicit offset + limit.'
130
+ '3. Read with explicit offset + limit.',
131
+ 'LARGE_FILE_READ'
95
132
  );
96
133
  }
97
134
 
@@ -114,7 +151,8 @@ function guard2DuplicateWrite(input) {
114
151
  ' Choose an action:\n' +
115
152
  ' 1. Edit the existing file instead of overwriting\n' +
116
153
  ' 2. Confirm you want to overwrite (re-issue the command)\n' +
117
- ' 3. Cancel'
154
+ ' 3. Cancel',
155
+ 'FILE_EXISTS'
118
156
  );
119
157
  }
120
158
 
@@ -180,14 +218,14 @@ function guard5BandScope(input, payload) {
180
218
  if (!root) return null;
181
219
  const file = join(root, ...BAND_ENVELOPE_REL);
182
220
  const env = readEnvelope(file);
183
- if (!env) return deny(`Guard 5: BAND_ENVELOPE_INVALID: ${file} is unreadable or not a valid v3 band envelope.`);
184
- if (env.sys.role !== role) return deny(`Guard 5: BAND_ROLE_MISMATCH: agent ${role} is not the envelope's role ${env.sys.role}.`);
185
- if (env.sys.tk !== 'RW') return deny(`Guard 5: BAND_READ_ONLY: role ${role} holds tk ${env.sys.tk}, not RW.`);
221
+ if (!env) return deny(`Guard 5: BAND_ENVELOPE_INVALID: ${file} is unreadable or not a valid v3 band envelope.`, 'BAND_ENVELOPE_INVALID');
222
+ if (env.sys.role !== role) return deny(`Guard 5: BAND_ROLE_MISMATCH: agent ${role} is not the envelope's role ${env.sys.role}.`, 'BAND_ROLE_MISMATCH');
223
+ if (env.sys.tk !== 'RW') return deny(`Guard 5: BAND_READ_ONLY: role ${role} holds tk ${env.sys.tk}, not RW.`, 'BAND_READ_ONLY');
186
224
  const target = targetPath(input);
187
225
  const rel = relative(root, resolve(cwd, target)).split(sep).join('/');
188
226
  const inside = target !== '' && rel !== '' && rel !== '..' && !rel.startsWith('../') && !isAbsolute(rel);
189
227
  if (inside && env.ops.scope.some((g) => globToRegExp(g).test(rel))) return null;
190
- return deny(`Guard 5: BAND_SCOPE_VIOLATION: ${target || '<no path>'} is outside the declared scope [${env.ops.scope.join(', ')}]`);
228
+ return deny(`Guard 5: BAND_SCOPE_VIOLATION: ${target || '<no path>'} is outside the declared scope [${env.ops.scope.join(', ')}]`, 'BAND_SCOPE_VIOLATION');
191
229
  }
192
230
 
193
231
  // ── Guard 6 constants ─────────────────────────────────────────────────────────
@@ -218,7 +256,7 @@ function guard6NestedDispatch(payload) {
218
256
  if (!root) return null;
219
257
  const run = readRunFile(join(root, ...ORCH_RUN_REL));
220
258
  if (!run || payload.session_id !== run.session_id) return null;
221
- return deny(`Guard 6: ORCH_NESTED_DISPATCH: ${payload.tool_name} from agent ${payload.agent_type} is denied while run ${run.item} is live; only the orchestrator dispatches or messages agents during a run.`);
259
+ return deny(`Guard 6: ORCH_NESTED_DISPATCH: ${payload.tool_name} from agent ${payload.agent_type} is denied while run ${run.item} is live; only the orchestrator dispatches or messages agents during a run.`, 'ORCH_NESTED_DISPATCH');
222
260
  }
223
261
 
224
262
  // Guard 6: while a run is live in this session, nothing but a band role writes outside the
@@ -241,7 +279,7 @@ function guard6OrchestratorRun(input, payload) {
241
279
  const target = targetPath(input);
242
280
  const rel = relative(root, resolve(cwd, target)).split(sep).join('/');
243
281
  if (target !== '' && ORCH_WRITE_SURFACE.some((g) => globToRegExp(g).test(rel))) return null;
244
- return deny(`Guard 6: ORCH_WRITE_DENIED: ${target || '<no path>'} is outside the orchestrator's write surface while run ${run.item} is live; repository writes during a run go through a band role (Guard 5).`);
282
+ return deny(`Guard 6: ORCH_WRITE_DENIED: ${target || '<no path>'} is outside the orchestrator's write surface while run ${run.item} is live; repository writes during a run go through a band role (Guard 5).`, 'ORCH_WRITE_DENIED');
245
283
  }
246
284
 
247
285
  // ── Guard 7 constants ─────────────────────────────────────────────────────────
@@ -263,13 +301,13 @@ function liveTestCommand(payload) {
263
301
  // R1-R5, the first match decides. The match is exact: a prefix allowlist is walked around by
264
302
  // chaining, which is the T-003 vector.
265
303
  function roleShellDecision(role, input, payload) {
266
- if (!ROLE_SHELL_ROLES.includes(role)) return deny(`Guard 7: ROLE_SHELL_DENIED: ${role} has no shell.`);
304
+ if (!ROLE_SHELL_ROLES.includes(role)) return deny(`Guard 7: ROLE_SHELL_DENIED: ${role} has no shell.`, 'ROLE_SHELL_DENIED');
267
305
  const command = typeof input.command === 'string' ? input.command : '';
268
306
  const found = ROLE_SHELL_METACHARACTERS.find((m) => command.includes(m));
269
- if (found !== undefined) return deny(`Guard 7: ROLE_SHELL_CHAINING: the command contains ${JSON.stringify(found)}; a role runs one command, never a chain.`);
307
+ if (found !== undefined) return deny(`Guard 7: ROLE_SHELL_CHAINING: the command contains ${JSON.stringify(found)}; a role runs one command, never a chain.`, 'ROLE_SHELL_CHAINING');
270
308
  const allowed = liveTestCommand(payload);
271
- if (allowed === null) return deny(`Guard 7: ROLE_SHELL_UNRESOLVED: no live run in this session records a test command, so ${role} has no shell.`);
272
- if (command !== allowed) return deny(`Guard 7: ROLE_SHELL_NOT_ALLOWED: allowed command is ${allowed}`);
309
+ if (allowed === null) return deny(`Guard 7: ROLE_SHELL_UNRESOLVED: no live run in this session records a test command, so ${role} has no shell.`, 'ROLE_SHELL_UNRESOLVED');
310
+ if (command !== allowed) return deny(`Guard 7: ROLE_SHELL_NOT_ALLOWED: allowed command is ${allowed}`, 'ROLE_SHELL_NOT_ALLOWED');
273
311
  return null;
274
312
  }
275
313
 
@@ -280,7 +318,7 @@ function guard7RoleShell(input, payload) {
280
318
  const role = payload.agent_type;
281
319
  if (!BAND_ROLES.includes(role)) return null;
282
320
  try { return roleShellDecision(role, input, payload); }
283
- catch (e) { return deny(`Guard 7: ROLE_SHELL_UNRESOLVED: the guard could not decide (${e && e.message}), so the call is denied.`); }
321
+ catch (e) { return deny(`Guard 7: ROLE_SHELL_UNRESOLVED: the guard could not decide (${e && e.message}), so the call is denied.`, 'ROLE_SHELL_UNRESOLVED'); }
284
322
  }
285
323
 
286
324
  // ── Guard 3 constants ─────────────────────────────────────────────────────────
@@ -708,10 +746,10 @@ const G3_OPERATOR_POLICY =
708
746
  '.claude/memory/bash-scan-allowlist.txt, are reviewed in git, and an agent may propose ' +
709
747
  'one but must not add it to clear its own denial.';
710
748
 
711
- function g3Blocked(detail, { allowlistApplies = false } = {}) {
749
+ function g3Blocked(detail, code, { allowlistApplies = false } = {}) {
712
750
  const decide = process.env.CC_GUARD3_WARN ? ask : deny;
713
751
  const policy = allowlistApplies ? ` ${G3_OPERATOR_POLICY}` : '';
714
- return decide(`BASH SCAN BLOCKED. ${detail} ${G3_ALTERNATIVES}${policy}`);
752
+ return decide(`BASH SCAN BLOCKED. ${detail} ${G3_ALTERNATIVES}${policy}`, code);
715
753
  }
716
754
 
717
755
  // Guard 3: the bash command scanner, ported from tests/fixtures/guard3-reference.sh.
@@ -720,11 +758,11 @@ function guard3BashScan(input) {
720
758
  const command = typeof input.command === 'string' ? input.command : '';
721
759
  if (command === '') return null;
722
760
  if (command.length > G3_MAX_LEN) {
723
- return g3Blocked(`The command string exceeds the maximum scan length (${G3_MAX_LEN} chars).`);
761
+ return g3Blocked(`The command string exceeds the maximum scan length (${G3_MAX_LEN} chars).`, 'MAX_LENGTH');
724
762
  }
725
763
  const scan = g3Scan('strip', g3Chomp(g3JoinContinuations(command)));
726
764
  if (scan.malformed) {
727
- return g3Blocked('Malformed shell syntax (unclosed quote), blocked as a precaution.');
765
+ return g3Blocked('Malformed shell syntax (unclosed quote), blocked as a precaution.', 'MALFORMED');
728
766
  }
729
767
  // Real newlines become semicolons so a multi-line script reads as a command
730
768
  // sequence to every position-anchored pattern above.
@@ -742,7 +780,7 @@ function guard3BashScan(input) {
742
780
  for (const { id, check } of G3_CHECKS) if (check(UNMASKED_CHECKS.has(id) ? pre : masked)) ids.push(id);
743
781
  if (ids.length === 0) return null;
744
782
  if (g3AllowlistCovers(pre, g3ReadAllowlist())) return null;
745
- return g3Blocked(`The command triggered a mass content-dump pattern. Pattern ids: ${ids.join(' ')}.`, { allowlistApplies: true });
783
+ return g3Blocked(`The command triggered a mass content-dump pattern. Pattern ids: ${ids.join(' ')}.`, ids.join(' '), { allowlistApplies: true });
746
784
  }
747
785
 
748
786
  const DISPATCH = {
@@ -762,6 +800,119 @@ for (const tool of ORCH_DISPATCH_TOOLS) DISPATCH[tool] = [guard6OrchestratorRun]
762
800
  // and an ask must never outrank a role's shell deny.
763
801
  DISPATCH.Bash.unshift(guard7RoleShell);
764
802
 
803
+ // ── Flow events (FEAT-044) ────────────────────────────────────────────────────
804
+ // The guard numbers the flow log records. flow-status.mjs carries the same numbers in its
805
+ // lane table, and tests/installer/flow-status.test.js fails when the two drift.
806
+ const GUARD_NUMBER = new Map([
807
+ [guard1LargeRead, 1], [guard2DuplicateWrite, 2], [guard3BashScan, 3], [guard4BlockedRead, 4],
808
+ [guard5BandScope, 5], [guard6OrchestratorRun, 6], [guard7RoleShell, 7],
809
+ ]);
810
+ // About 500 events at the capped line length (D7). Size rather than a line count, because
811
+ // counting lines would read the whole file on every tool call.
812
+ const FLOW_MAX_BYTES = 160 * 1024;
813
+ const FLOW_KEEP_LINES = 250;
814
+ // A lock older than this belongs to a hook that died mid-rotation; without the cutoff the
815
+ // file would grow forever.
816
+ const FLOW_LOCK_STALE_MS = 10000;
817
+ const SHELL_ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/;
818
+ const SHELL_SUBSTITUTION = /\$\(|\$\{|`/;
819
+
820
+ // Full command text is never written: commands carry inline tokens often enough. Leading
821
+ // VAR=value words are skipped so `TOKEN=sk-... curl` records `curl`, never the token (D5).
822
+ // Words are found on Guard 3's mask, where quoted text is all 'x', so `P='a b' psql` is two
823
+ // words, not three. An unclosed quote or a substitution makes the word boundary a guess, and
824
+ // a wrong guess records a secret fragment, so either one records nothing. So does an array
825
+ // assignment: `K=(a b)` spans words, and the word after `K=(a` is a value, not the command.
826
+ function flowCommandWord(command) {
827
+ const { result, malformed } = g3Scan('mask', command);
828
+ if (malformed) return '';
829
+ // The mask keeps an unquoted escape as written; folding it in keeps `a\ b` one word.
830
+ // [^] is any character, newline included, without the shorthands this block forbids.
831
+ const mask = result.replace(/\\[^]/g, 'xx');
832
+ for (const m of mask.matchAll(/[^ \t\n]+/g)) {
833
+ const word = command.slice(m.index, m.index + m[0].length);
834
+ // Tested on the original, because the mask turns a quoted `"$(…)"` into x's, and quotes
835
+ // nested inside it shift the word boundaries (review round 2 of PR #89).
836
+ if (SHELL_SUBSTITUTION.test(word)) return '';
837
+ if (m[0].includes('=(')) return '';
838
+ if (!SHELL_ASSIGNMENT.test(m[0])) return word;
839
+ }
840
+ return '';
841
+ }
842
+
843
+ function flowTarget(name, input, cwd) {
844
+ if (name === 'Bash') return flowCommandWord(typeof input.command === 'string' ? input.command : '');
845
+ if (ORCH_DISPATCH_TOOLS.includes(name)) return String(input.subagent_type ?? input.to ?? '');
846
+ const path = targetPath(input);
847
+ return (isAbsolute(path) ? relative(cwd, path) : path).split(sep).join('/');
848
+ }
849
+
850
+ function flowEvent(payload, input, decision, passed, guard) {
851
+ return {
852
+ ts: Date.now(),
853
+ tool: payload.tool_name,
854
+ verdict: decision ? decision.permissionDecision : 'allow',
855
+ guard: decision ? guard : null,
856
+ code: decision && decision.code ? String(decision.code).slice(0, 80) : null,
857
+ target: flowTarget(payload.tool_name, input, payload.cwd).slice(0, 200),
858
+ agent: BAND_ROLES.includes(payload.agent_type) ? payload.agent_type : null,
859
+ passed,
860
+ };
861
+ }
862
+
863
+ function takeFlowLock(lock) {
864
+ try { return openSync(lock, 'wx'); } catch { /* held or stale: decided below */ }
865
+ try {
866
+ if (Date.now() - statSync(lock).mtimeMs < FLOW_LOCK_STALE_MS) return null;
867
+ unlinkSync(lock);
868
+ return openSync(lock, 'wx');
869
+ } catch { return null; }
870
+ }
871
+
872
+ function isJsonLine(line) {
873
+ try { JSON.parse(line); return true; } catch { return false; }
874
+ }
875
+
876
+ // Also the repair path: unparseable lines are dropped, so one torn write cannot blind the
877
+ // readers for good. The lock exists because an unlocked rename fails with EPERM on Windows
878
+ // under parallel hooks (spec M8). No trailing newline: the next append brings its own.
879
+ function rotateFlowEvents(path) {
880
+ const lock = join(dirname(path), '.flow-events.lock');
881
+ const fd = takeFlowLock(lock);
882
+ if (fd === null) return;
883
+ const tmp = `${path}.tmp`;
884
+ try {
885
+ const keep = readFileSync(path, 'utf8').split('\n').filter((l) => l && isJsonLine(l)).slice(-FLOW_KEEP_LINES);
886
+ writeFileSync(tmp, keep.join('\n'));
887
+ renameSync(tmp, path);
888
+ } catch (e) {
889
+ try { unlinkSync(tmp); } catch { /* never written */ }
890
+ debug(`flow rotate: ${e.message}`);
891
+ } finally {
892
+ closeSync(fd);
893
+ try { unlinkSync(lock); } catch { /* already gone */ }
894
+ }
895
+ }
896
+
897
+
898
+ // Runs after emit(), so it can never delay, change or suppress a decision, and its own
899
+ // catch keeps a full disk from reaching the fail-closed catch around main() (spec, Error
900
+ // cases). It never creates a directory: with no .claude/ the append throws ENOENT, which the
901
+ // catch swallows, so a missing directory costs no separate existence check per call.
902
+ function recordFlowEvent(payload, input, decision, passed, guard) {
903
+ try {
904
+ if (process.env.CC_FLOW_OFF === '1' || typeof payload.cwd !== 'string' || !payload.cwd) return;
905
+ const path = join(payload.cwd, '.claude', '.flow-events.jsonl');
906
+ const size = statSync(path, { throwIfNoEntry: false })?.size ?? 0;
907
+ if (size > FLOW_MAX_BYTES) rotateFlowEvents(path);
908
+ // The newline LEADS the line: one O_APPEND write per event (spec M7: no torn line under
909
+ // parallel appends) can only ever end a line, so a tail torn by a crash or a hand edit is
910
+ // fenced off by the next event instead of fused with it, and no per-call read of the last
911
+ // byte is needed. Readers skip blank lines; rotation drops the torn one.
912
+ appendFileSync(path, `\n${JSON.stringify(flowEvent(payload, input, decision, passed, guard))}`);
913
+ } catch (e) { debug(`flow event: ${e.message}`); }
914
+ }
915
+
765
916
  // Case B. Unparseable input is not "nothing to verify", it is "the verifier could not
766
917
  // run", which is the condition that fails closed. CC_HOOK_ALLOW bypasses THIS denial only;
767
918
  // it does not suppress, alter or bypass any guard's decision on input that parses.
@@ -797,11 +948,18 @@ function main() {
797
948
  const input = (rawInput && typeof rawInput === 'object' && !Array.isArray(rawInput)) ? rawInput : {};
798
949
  const guards = DISPATCH[name];
799
950
  if (!guards) { debug(`no guard registered for tool_name "${name}"; allowing`); return; }
951
+ const passed = [];
800
952
  for (const guard of guards) {
801
953
  const decision = guard(input, payload);
802
- if (decision) { emit(decision); return; }
954
+ if (decision) {
955
+ emit(decision);
956
+ recordFlowEvent(payload, input, decision, passed, GUARD_NUMBER.get(guard));
957
+ return;
958
+ }
959
+ passed.push(GUARD_NUMBER.get(guard));
803
960
  }
804
961
  if (warning) emit(null);
962
+ recordFlowEvent(payload, input, null, passed, null);
805
963
  }
806
964
 
807
965
  try { main(); } catch (e) { unreadable(`the hook threw (${e && e.message})`); }
@@ -1,48 +1,18 @@
1
1
  # Project Memory
2
2
 
3
- Shared team memory. Committed to git. Updated automatically by /checkpoint.
3
+ Shared team memory. Committed to git. Updated automatically by /cc-checkpoint.
4
4
 
5
5
  ## Stack
6
- <!-- Set by /stack -->
6
+ <!-- Set by /cc-stack -->
7
7
 
8
8
  ## Architecture Decisions
9
- <!-- Append by /checkpoint. Never delete entries. -->
10
-
11
- ### Checkpoint 2026-06-09 17:45
12
-
13
- **BUG-001: Phase Boundary Compaction (/cc-compact) — v1.7.0**
14
-
15
- - **Decided:** phase context clearing uses a dedicated `/cc-compact` command (not baked into phase commands, not an extension of `/cc-checkpoint`). One command, one invariant: serialize then prompt for `/compact`.
16
- - **Decided:** snapshot schema is fixed and token-bounded (≤300 tokens): Phase, Commit (full SHA-1 via `git rev-parse HEAD`), Decisions (max 10), Pending, Files Touched, Constraints (max 5), Spec Reference. No freeform prose.
17
- - **Decided:** snapshot file is `.claude/memory/session-snapshot.md`, gitignored, single instance (always overwritten).
18
- - **Decided:** Destructive Read Invariant — every phase command that reads the snapshot must delete it immediately after reading. Deletion failure halts the command.
19
- - **Decided:** Phase Handoff Enforcement uses decoupled conditions — turn count > 5 is the only blocking halt; absent snapshot is a read-if-present fallback, not a blocker (prevents infinite standby on fresh sessions).
20
- - **Decided:** `/compact` is user-invoked, not agent-invoked. `/cc-compact` outputs a prompt; it does not call `/compact` itself.
21
- - **Rejected:** extending `/cc-checkpoint` with phase-boundary semantics (blurs its purpose as a general decision-saver).
22
- - **Rejected:** baking compaction logic directly into phase commands (harder to evolve independently).
23
-
24
- **Files added/modified:**
25
- - `global/commands/cc-compact.md` — new
26
- - `project-template/.claude/commands/cc-implement.md` — new
27
- - `project-template/.claude/commands/cc-spec.md` — DRI + exit prompt
28
- - `project-template/.claude/commands/cc-plan.md` — enforcement + DRI + exit prompt
29
- - `project-template/.claude/commands/cc-review.md` — enforcement + DRI
9
+ <!-- Append by /cc-checkpoint. Never delete entries. -->
30
10
 
31
11
  ## Active Conventions
32
12
  <!-- Project-specific conventions established in this codebase -->
33
13
 
34
- - No em-dashes (—) anywhere in command files or docs — use hyphens (-) or colons (:).
35
- - All phase command files use `## Phase entry - <Name>` and `## Phase exit` section headers (second-level).
36
- - Spec files live in `docs/superpowers/specs/YYYY-MM-DD-<slug>-design.md` (force-added since `docs/` is gitignored).
37
- - Plan files live in `docs/superpowers/plans/YYYY-MM-DD-<slug>.md` (force-added).
38
- - VERSION file contains a single semver string. Minor bump for new behavioral features.
39
-
40
14
  ## Technical Debt
41
15
  <!-- Known shortcuts, limitations, and deferred work -->
42
16
 
43
- - `docs/` is in `.gitignore` but spec/plan files need to be tracked — currently force-added individually. Should add `!docs/superpowers/` exception to `.gitignore` to fix this properly (deferred).
44
- - BUG-001 enforcement check relies on the agent counting turns correctly — no programmatic turn counter exists yet. FEAT-007 (token threshold auto-compaction) would make this structural.
45
- - `/cc-compact` depends on the agent accurately recalling phase state from conversation context — no structured state extraction mechanism exists yet (FEAT-005 SQLite layer would fix this).
46
-
47
17
  ## Workarounds
48
18
  <!-- Non-obvious solutions and why they exist -->
@@ -5,3 +5,4 @@
5
5
  .claude/memory/band-envelope.json
6
6
  .claude/memory/orchestrator-run.json
7
7
  .conductor/
8
+ .claude/.flow-events.*