@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.
@@ -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.41.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.
@@ -39,7 +39,7 @@ Branch on `resume_rc` - **only `0` and `4` are meaningful; every other code proc
39
39
 
40
40
  ---
41
41
 
42
- Read `.claude/memory/project.md` before starting any task.
42
+ Before starting any task, Read `.claude/memory/project.md` with `limit: 60` and stop at its `<!-- end current state -->` line: that `## Current State` digest is the bounded summary. For detail, Grep `project.md` with `-n` for the heading its `Active spec:` or `Last checkpoint:` line names, then Read that entry with `offset` and `limit: 60`. If the file has no `## Current State` section, Read it with `limit: 40` instead, then Grep `^## (Spec|Checkpoint)` with `-n` and Read the last match of each with `offset` and `limit: 60`. Never read the whole file: its history is append-only and grows with the project.
43
43
 
44
44
  ## Surgical Plan State Ritual
45
45
 
@@ -0,0 +1,22 @@
1
+ ---
2
+ description: "(Conductor) Report token and time spend from local session logs, with recommendations"
3
+ argument-hint: "[--dir <log directory>]"
4
+ ---
5
+
6
+ Read-only. This command reads Claude Code's local session logs for this project and prints one compact report. It registers no hook and writes no file.
7
+
8
+ ## Step 1 — Run the reader
9
+
10
+ Resolve the reader by presence, the deployed copy first, and run it once:
11
+
12
+ ```bash
13
+ M=.claude/scripts/session-metrics.mjs; [ -f "$M" ] || M=scripts/session-metrics.mjs; node "$M" '$ARGUMENTS'
14
+ ```
15
+
16
+ If neither file exists, output `"cc-metrics: reader not found. Run the installer with --project."` and stop.
17
+
18
+ ## Step 2 — Relay the report
19
+
20
+ Output the reader's stdout verbatim, inside one code block. Do not open, grep or summarize the log files yourself: the report already holds every number, and reading the logs would spend the tokens this command measures.
21
+
22
+ Every recommendation line quotes the number it rests on. Values labelled `est` are estimates (characters / 4). A line starting `cc-metrics: no session logs at` or `cc-metrics: failed:` is the whole report: relay it and stop. From a git worktree, the project's logs live under the main checkout's directory; pass it with `--dir`.
@@ -52,10 +52,10 @@ Skill({ skill: "critical-review" })
52
52
 
53
53
  ---
54
54
 
55
- Require an approved spec before starting. If no spec is in `.claude/memory/project.md` or in the recent conversation, stop and say:
55
+ Require an approved spec before starting. If no spec is in `.claude/memory/project.md` (its `Active spec:` line, or with no `## Current State` section its last `## Spec:` entry) or in the recent conversation, stop and say:
56
56
  "No approved spec found. Run `/cc-spec [name]` first."
57
57
 
58
- Read `.claude/memory/project.md` and this project's `CLAUDE.md` before doing anything else.
58
+ Read this project's `CLAUDE.md` and project memory before doing anything else. Read `.claude/memory/project.md` with `limit: 60` and stop at its `<!-- end current state -->` line: that `## Current State` digest is the bounded summary. For detail, Grep `project.md` with `-n` for the heading its `Active spec:` or `Last checkpoint:` line names, then Read that entry with `offset` and `limit: 60`. If the file has no `## Current State` section, Read it with `limit: 40` instead, then Grep `^## (Spec|Checkpoint)` with `-n` and Read the last match of each with `offset` and `limit: 60`. Never read the whole file: its history is append-only and grows with the project.
59
59
 
60
60
  **Map the codebase structure** before reading any file content:
61
61
  - List directories
@@ -37,14 +37,16 @@ Re-read the updated CLAUDE.md fields after this step so the session resume repor
37
37
 
38
38
  ## Step 3 — Read project memory
39
39
 
40
- Read `.claude/memory/project.md`.
40
+ Read `.claude/memory/project.md` with `limit: 60` and stop at its `<!-- end current state -->` line: that `## Current State` digest is the bounded summary. Never read the whole file: its history is append-only and grows with the project.
41
41
 
42
42
  Extract:
43
- - The content of the most recent `## Checkpoint [...]` block (3 bullets max)
44
- - Any entries under `## Active Conventions`
45
- - Any entries under `## Technical Debt`
43
+ - The `Last checkpoint:` line, then up to 3 bullets of the entry it names: Grep that heading with `-n` and Read the entry with `offset` and `limit: 60`
44
+ - The bullets under `### Conventions` in `## Current State`
45
+ - The bullets under `### Debt` in `## Current State`
46
46
 
47
- If the file is absent or has no `## Checkpoint` block, note `"No checkpoints yet"`.
47
+ If the file has no `## Current State` section, Read it with `limit: 40` instead, then Grep `^## (Spec|Checkpoint)` with `-n`, Read the last `## Checkpoint` match with `offset` and `limit: 60` for its 3 bullets, and note `"No Current State yet: run /cc-checkpoint"` for conventions and debt.
48
+
49
+ If the file is absent or has no `## Checkpoint` entry, note `"No checkpoints yet"`.
48
50
 
49
51
  ## Step 4 — Read personal preferences
50
52
 
@@ -127,6 +127,8 @@ Wait for explicit approval before proceeding to `/cc-plan`.
127
127
  Once approved, append a summary to `.claude/memory/project.md` under:
128
128
  `## Spec: [name] [YYYY-MM-DD]`
129
129
 
130
+ Then, in its `## Current State` section, replace the single `- Active spec:` line with that heading text, without its leading `## `, in one Edit. If the section is absent, skip this step: the next `/cc-checkpoint` inserts it.
131
+
130
132
  ---
131
133
 
132
134
  ## Phase exit
@@ -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
+ }
@@ -13,23 +13,45 @@ try {
13
13
  if ($val -match '^[1-9][0-9]*$') { $critical = [int]$val }
14
14
  } catch { }
15
15
 
16
+ # The key must follow { or , so an escaped "session_id" inside the prompt text never matches.
17
+ $sessionId = ''
18
+ try {
19
+ if ([Console]::IsInputRedirected) {
20
+ $reader = New-Object System.IO.StreamReader([Console]::OpenStandardInput(), [System.Text.UTF8Encoding]::new($false))
21
+ $in = $reader.ReadToEnd()
22
+ if ($in -match '[{,]\s*"session_id"\s*:\s*"([A-Za-z0-9_-]+)"') { $sessionId = $Matches[1] }
23
+ }
24
+ } catch { }
25
+
26
+ # Accepts "<id> <count>" or a legacy bare "<count>".
27
+ $storedId = ''
16
28
  $count = 0
17
29
  $countFile = Join-Path $mem 'turn-count.txt'
18
30
  try {
19
31
  $raw = [System.IO.File]::ReadAllText($countFile, [System.Text.Encoding]::UTF8)
20
- $val = $raw.Split("`n")[0].TrimEnd("`r").Trim()
21
- if ($val -match '^[0-9]+$') { $count = [int]$val }
32
+ $fields = @($raw.Split("`n")[0].TrimEnd("`r").Trim() -split '\s+')
33
+ if ($fields.Count -eq 1 -and $fields[0] -match '^[0-9]+$') { $count = [int]$fields[0] }
34
+ if ($fields.Count -ge 2 -and $fields[0] -match '^[A-Za-z0-9_-]+$' -and $fields[1] -match '^[0-9]+$') {
35
+ $storedId = $fields[0]
36
+ $count = [int]$fields[1]
37
+ }
22
38
  } catch { }
23
39
 
40
+ # A count left by another session says nothing about this session's context (BUG-056).
41
+ if ($sessionId -and $sessionId -cne $storedId) { $count = 0 }
42
+ if (-not $sessionId) { $sessionId = $storedId }
43
+
24
44
  $warning = [Math]::Truncate($critical * 80 / 100)
25
45
  $newCount = [Math]::Min($count + 1, 99999)
46
+ $line = if ($sessionId) { "$sessionId $newCount" } else { "$newCount" }
26
47
 
27
48
  $target = Join-Path $mem 'turn-count.txt'
28
49
  $tmp = Join-Path $mem 'turn-count.txt.tmp'
29
50
  $enc = [System.Text.UTF8Encoding]::new($false)
30
- [System.IO.File]::WriteAllText($tmp, "$newCount`n", $enc)
51
+ [System.IO.File]::WriteAllText($tmp, "$line`n", $enc)
31
52
  try {
32
- [System.IO.File]::Replace($tmp, $target, $null)
53
+ # PowerShell turns a bare $null into "" for a string argument, which Replace rejects.
54
+ [System.IO.File]::Replace($tmp, $target, [NullString]::Value)
33
55
  } catch [System.IO.FileNotFoundException] {
34
56
  try {
35
57
  [System.IO.File]::Move($tmp, $target)
@@ -40,7 +62,7 @@ try {
40
62
  }
41
63
 
42
64
  if ($env:CC_GUARD_DEBUG) {
43
- Write-Host "[context-guard] root=$root count=$newCount critical=$critical warning=$warning"
65
+ Write-Host "[context-guard] root=$root session=$sessionId count=$newCount critical=$critical warning=$warning"
44
66
  }
45
67
 
46
68
  if ($newCount -ge 99999) {
@@ -1,5 +1,29 @@
1
1
  #!/usr/bin/env bash
2
2
  set +e
3
+
4
+ # Prints the session_id from the UserPromptSubmit stdin JSON, or nothing.
5
+ # The key must follow { or , so an escaped "session_id" inside the prompt text never matches.
6
+ read_session_id() {
7
+ [ -t 0 ] && return 0
8
+ local _in _re
9
+ _in=$(cat 2>/dev/null)
10
+ _re='[{,][[:space:]]*"session_id"[[:space:]]*:[[:space:]]*"([A-Za-z0-9_-]+)"'
11
+ [[ "$_in" =~ $_re ]] && printf '%s' "${BASH_REMATCH[1]}"
12
+ }
13
+
14
+ # Sets stored_id and count from "<id> <count>" or a legacy bare "<count>".
15
+ read_state() {
16
+ local _f1="" _f2=""
17
+ IFS=' ' read -r _f1 _f2 _ < "$1" 2>/dev/null
18
+ _f1="${_f1%$'\r'}"; _f1="${_f1#$'\xef\xbb\xbf'}"; _f2="${_f2%$'\r'}"
19
+ stored_id=""; count=0
20
+ if [ -z "$_f2" ]; then
21
+ [[ "$_f1" =~ ^[0-9]+$ ]] && count=$_f1
22
+ return 0
23
+ fi
24
+ [[ "$_f1" =~ ^[A-Za-z0-9_-]+$ ]] && [[ "$_f2" =~ ^[0-9]+$ ]] && { stored_id=$_f1; count=$_f2; }
25
+ }
26
+
3
27
  main() {
4
28
  _mem="${CC_PROJECT_ROOT:-.}/.claude/memory"
5
29
  if [ -e "$_mem" ] && [ ! -d "$_mem" ]; then exit 0; fi
@@ -14,23 +38,21 @@ main() {
14
38
  critical=$_thresh
15
39
  warning=$(( (critical * 80) / 100 ))
16
40
 
17
- # Read count
18
- _c=""
19
- IFS= read -r _c < "${_mem}/turn-count.txt" 2>/dev/null || _c=""
20
- _c="${_c%$'\r'}"
21
- _c="${_c#$'\xef\xbb\xbf'}"
22
- [[ "$_c" =~ ^[0-9]+$ ]] || _c=0
23
- count=$_c
41
+ # A count left by another session says nothing about this session's context (BUG-056).
42
+ session_id=$(read_session_id)
43
+ read_state "${_mem}/turn-count.txt"
44
+ if [ -n "$session_id" ] && [ "$session_id" != "$stored_id" ]; then count=0; fi
45
+ [ -n "$session_id" ] || session_id=$stored_id
24
46
 
25
47
  new_count=$(( count < 99999 ? count + 1 : 99999 ))
26
48
 
27
49
  _target="${_mem}/turn-count.txt"
28
50
  _tmp="${_mem}/turn-count.txt.tmp"
29
- printf '%d\n' "$new_count" > "$_tmp" && mv -f "$_tmp" "$_target" \
51
+ printf '%s%d\n' "${session_id:+$session_id }" "$new_count" > "$_tmp" && mv -f "$_tmp" "$_target" \
30
52
  || { rm -f "$_tmp" 2>/dev/null; exit 0; }
31
53
 
32
- [ -n "${CC_GUARD_DEBUG:-}" ] && printf '[context-guard] root=%s count=%d critical=%d warning=%d\n' \
33
- "${CC_PROJECT_ROOT:-.}" "$new_count" "$critical" "$warning" >&2
54
+ [ -n "${CC_GUARD_DEBUG:-}" ] && printf '[context-guard] root=%s session=%s count=%d critical=%d warning=%d\n' \
55
+ "${CC_PROJECT_ROOT:-.}" "$session_id" "$new_count" "$critical" "$warning" >&2
34
56
 
35
57
  if [ "$new_count" -ge 99999 ]; then
36
58
  printf '🚨 CONTEXT CRITICAL: Turn 99999/%d (counter saturated) — run /cc-compact NOW.\n' "$critical"
@@ -10,7 +10,8 @@ try {
10
10
  $enc = [System.Text.UTF8Encoding]::new($false)
11
11
  [System.IO.File]::WriteAllText($tmp, "0`n", $enc)
12
12
  try {
13
- [System.IO.File]::Replace($tmp, $target, $null)
13
+ # PowerShell turns a bare $null into "" for a string argument, which Replace rejects.
14
+ [System.IO.File]::Replace($tmp, $target, [NullString]::Value)
14
15
  } catch [System.IO.FileNotFoundException] {
15
16
  try {
16
17
  [System.IO.File]::Move($tmp, $target)