@yeison.restrepo.r/code-conductor 1.41.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.
@@ -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.*
@@ -12,7 +12,7 @@
12
12
  // The plan markdown remains the authoritative task-state record.
13
13
 
14
14
  import { execFileSync } from 'node:child_process';
15
- import { mkdirSync, existsSync, renameSync, unlinkSync, statSync, readSync } from 'node:fs';
15
+ import { mkdirSync, existsSync, renameSync, unlinkSync, statSync, readSync, realpathSync } from 'node:fs';
16
16
  import { dirname, basename, join, resolve, relative, sep } from 'node:path';
17
17
  import { fileURLToPath } from 'node:url';
18
18
  import { PRE_PARSE_MAX_BYTES as MAX_SNAP_BYTES } from './snap-contract.mjs';
@@ -81,12 +81,19 @@ function resolveRoot() {
81
81
  return basename(parent) === '.claude' ? resolve(parent, '..') : parent;
82
82
  }
83
83
 
84
+ // git prints the root's long spelling while cwd may carry an 8.3 (`RUNNER~1`) or
85
+ // symlinked spelling of the same directory; relative() across two spellings climbs
86
+ // out of the root [BUG-058]. The native realpath expands 8.3 names; the JS one does not.
87
+ function canonical(path) {
88
+ try { return realpathSync.native(path); } catch { return path; }
89
+ }
90
+
84
91
  function normalizePlanFile(planFile, root) {
85
92
  // Repo-relative, then force POSIX separators so a Windows `\` key never
86
93
  // duplicates the same plan's POSIX `/` key. `sep` is `\` on Windows, `/` on POSIX.
87
94
  // `resolve`/`relative` already collapse redundant separators (`a//b` -> `a/b`);
88
95
  // the trailing replace is a defensive guarantee that no `//` ever persists.
89
- return relative(root, resolve(process.cwd(), planFile))
96
+ return relative(canonical(root), resolve(canonical(process.cwd()), planFile))
90
97
  .split(sep).join('/')
91
98
  .replace(/\/{2,}/g, '/');
92
99
  }