@yeison.restrepo.r/code-conductor 1.41.0 → 1.42.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 +58 -53
- package/bin/code-conductor.mjs +10 -4
- package/global/commands/cc-checkpoint.md +18 -0
- package/package.json +1 -1
- package/project-template/.claude/commands/cc-implement.md +1 -1
- package/project-template/.claude/commands/cc-metrics.md +22 -0
- package/project-template/.claude/commands/cc-plan.md +2 -2
- package/project-template/.claude/commands/cc-resume.md +7 -5
- package/project-template/.claude/commands/cc-spec.md +2 -0
- package/project-template/.claude/hooks/context-guard.ps1 +27 -5
- package/project-template/.claude/hooks/context-guard.sh +32 -10
- package/project-template/.claude/hooks/post-compact.ps1 +2 -1
- package/scripts/conductor-db.mjs +9 -2
- package/scripts/session-metrics.mjs +387 -0
package/README.md
CHANGED
|
@@ -7,9 +7,9 @@
|
|
|
7
7
|
|
|
8
8
|
**Make Claude Code work like a senior engineer, not an enthusiastic intern.**
|
|
9
9
|
|
|
10
|
-
code-conductor is a drop-in governance layer for [Claude Code](https://www.anthropic.com/claude-code): slash commands, hooks, guardrails and a persistent memory system that turn free-form AI coding sessions into a disciplined, repeatable engineering workflow. What an agent may run is checked before it runs, what it decided is written where the next session will read it, and what shipped is asserted against the record by instruments that run in CI. It cuts token usage along the way.
|
|
10
|
+
code-conductor is a drop-in governance layer for [Claude Code](https://www.anthropic.com/claude-code): slash commands, hooks, guardrails, and a persistent memory system that turn free-form AI coding sessions into a disciplined, repeatable engineering workflow. What an agent may run is checked before it runs, what it decided is written where the next session will read it, and what shipped is asserted against the record by instruments that run in CI. It cuts token usage along the way.
|
|
11
11
|
|
|
12
|
-
One command to install. No code changes to your project. Works with any stack. And every claim below is checkable against a commit in this repository.
|
|
12
|
+
One command to install: `npx @yeison.restrepo.r/code-conductor@latest --project`. No code changes to your project. Works with any stack. And every claim below is checkable against a commit in this repository.
|
|
13
13
|
|
|
14
14
|
---
|
|
15
15
|
|
|
@@ -32,7 +32,7 @@ None of these are model problems. They are *process* problems, and process is ex
|
|
|
32
32
|
| Conventions re-explained every session | Project memory and the detected stack loaded at session start |
|
|
33
33
|
| Context fills up until it breaks | A turn counter warns at 80%, and `/cc-compact` snapshots state before you compact |
|
|
34
34
|
| Verbose markdown handoffs eat context | **SNAP**: minified single-line JSON handoffs, schema-validated by `scripts/snap-validate.mjs`, at least 15% smaller than the markdown snapshot they replaced |
|
|
35
|
-
| Hand-tuned CLAUDE.md per project | **Stack auto-detection** fills in your build/test/lint/format commands from `package.json`, `go.mod`, `Cargo.toml
|
|
35
|
+
| Hand-tuned CLAUDE.md per project | **Stack auto-detection** fills in your build/test/lint/format commands from `package.json`, `go.mod`, `Cargo.toml`, and friends |
|
|
36
36
|
|
|
37
37
|
---
|
|
38
38
|
|
|
@@ -40,7 +40,7 @@ None of these are model problems. They are *process* problems, and process is ex
|
|
|
40
40
|
|
|
41
41
|
Three commands, from nothing to a guarded session. The output below is **real**, captured by running exactly these commands in a scratch directory.
|
|
42
42
|
|
|
43
|
-
**Minimum safe version: `1.34.4`.** Older versions can strip or damage an existing `CLAUDE.md`: every release before `1.24` overwrote it with no backup, `1.24` through `1.34.3` silently removed your sections whose headings matched the managed block's, and an older pre-sentinel version left at least one field file with damaged lines. Always install `code-conductor@latest`, as below.
|
|
43
|
+
**Minimum safe version: `1.34.4`.** Older versions can strip or damage an existing `CLAUDE.md`: every release before `1.24` overwrote it with no backup, `1.24` through `1.34.3` silently removed your sections whose headings matched the managed block's, and an older pre-sentinel version left at least one field file (a `CLAUDE.md` whose installer-managed field lines, `- Stack:` and friends, it fills in) with damaged lines. Always install `code-conductor@latest`, as below.
|
|
44
44
|
|
|
45
45
|
```bash
|
|
46
46
|
mkdir demo && cd demo && git init -q && npm init -y >/dev/null
|
|
@@ -49,7 +49,7 @@ npx @yeison.restrepo.r/code-conductor@latest --project
|
|
|
49
49
|
|
|
50
50
|
The installer prints **nothing** and exits 0. That silence is deliberate and is asserted by a test: the stub-detection check runs *before* the seed, so a fresh scaffold cannot warn about the file it was just given (`tests/installer/deploy.test.js`, "says nothing on a fresh scaffold, whose stub it just wrote").
|
|
51
51
|
|
|
52
|
-
You now have `.claude/` with `commands/`, `hooks/`, `memory/`, `scripts
|
|
52
|
+
You now have `.claude/` with `commands/`, `hooks/`, `memory/`, `scripts/`, and `settings.json`, and the guardrails are already live. The third command is any command at all:
|
|
53
53
|
|
|
54
54
|
```bash
|
|
55
55
|
# scene 1: a mass content dump is denied, with a message that says what to do instead
|
|
@@ -72,7 +72,7 @@ grep -n 'export' src/index.ts
|
|
|
72
72
|
|
|
73
73
|
Nothing is printed by the hook. The command runs.
|
|
74
74
|
|
|
75
|
-
Commit `.claude/` to your repository and your whole team gets the same workflow, the same guardrails and the same shared memory.
|
|
75
|
+
Commit `.claude/` to your repository and your whole team gets the same workflow, the same guardrails, and the same shared memory.
|
|
76
76
|
|
|
77
77
|
### Dependencies
|
|
78
78
|
|
|
@@ -81,10 +81,10 @@ code-conductor assumes these are already in place; the installer does not set th
|
|
|
81
81
|
| Dependency | Required for | How to get it |
|
|
82
82
|
|---|---|---|
|
|
83
83
|
| Node.js `>= 20` | Running the `code-conductor` CLI itself | Any current Node LTS |
|
|
84
|
-
| Claude Code | The environment every command, skill and hook here runs inside | See Anthropic's Claude Code docs |
|
|
84
|
+
| Claude Code | The environment every command, skill and hook here runs inside | See [Anthropic's Claude Code docs](https://code.claude.com/docs) |
|
|
85
85
|
| **superpowers plugin** | `/cc-spec` (`brainstorming`), `/cc-plan` (`writing-plans`), and `/cc-debug`, `/cc-refactor`, `/cc-review`, `/cc-test` (all four via `subagent-driven-development`) | Install from Claude Code's `/plugin` marketplace, then run `/reload-plugins`, **before** using these commands; without it, their `Skill(...)` calls fail |
|
|
86
86
|
| GitHub CLI (`gh`), authenticated | Only `/cc-orchestrate --ticket` and `ticket.mjs writeback`. code-conductor holds no credential; `gh` owns authentication | Install GitHub CLI, then run `gh auth login` |
|
|
87
|
-
| ui-ux-pro-max skill | Nothing: retired guidance | No shipped code downloads, installs or activates it. Its replacement is filed as `[FEAT-037]` |
|
|
87
|
+
| ui-ux-pro-max skill | Nothing: retired guidance | No shipped code downloads, installs, or activates it. Its replacement is filed as `[FEAT-037]` |
|
|
88
88
|
|
|
89
89
|
---
|
|
90
90
|
|
|
@@ -104,11 +104,11 @@ A typical session looks like this:
|
|
|
104
104
|
/cc-compact # snapshots phase state to a one-line JSON, then you /compact safely
|
|
105
105
|
```
|
|
106
106
|
|
|
107
|
-
The key idea: **nothing gets built until a human approved what will be built.** The spec gate and the plan gate are cheap, a page of markdown to review, and they eliminate the single most expensive failure mode of AI coding: perfectly executed solutions to the wrong problem.
|
|
107
|
+
The key idea: **nothing gets built until a human approved what will be built.** The spec gate and the plan gate are cheap, each a page of markdown to review, and they eliminate the single most expensive failure mode of AI coding: perfectly executed solutions to the wrong problem.
|
|
108
108
|
|
|
109
109
|
Two things make this cheaper than it sounds:
|
|
110
110
|
|
|
111
|
-
- **Every phase opens with a resume read.** `/cc-spec`, `/cc-plan` and `/cc-implement` restore any context stored for the current git commit, so work survives branch switches, rollbacks and multi-day gaps (see [Local state cache and session persistence](#local-state-cache-and-session-persistence)).
|
|
111
|
+
- **Every phase opens with a resume read.** `/cc-spec`, `/cc-plan` and `/cc-implement` restore any context stored for the current git commit, so work survives branch switches, rollbacks, and multi-day gaps (see [Local state cache and session persistence](#local-state-cache-and-session-persistence)).
|
|
112
112
|
- **Memory does the remembering.** Decisions land in `.claude/memory/project.md` (committed, shared with the team) and preferences in `~/.claude/memory/personal.md` (local). The next session reads them instead of asking you.
|
|
113
113
|
|
|
114
114
|
---
|
|
@@ -142,19 +142,19 @@ Useful variations:
|
|
|
142
142
|
- `--auto` skips the pause between role dispatches. The spec and plan approvals always pause.
|
|
143
143
|
- `--ticket 42` (or an issue URL) binds the run to a GitHub issue. `start` fetches it once through `gh`, halts on a pull request, a closed issue, or an empty or over-65536-byte body, and writes the body into a fenced, hashed snapshot at `.conductor/ticket/<ITEM>.md`, which **only the spec role reads, as untrusted requirement input**. After release, the owner runs `node .claude/scripts/ticket.mjs writeback <ITEM> --version <v> --pr <N|url> [--changelog <file>] [--close]`, which posts one outcome comment to the bound issue, never twice for the same version, and closes it only with `--close`.
|
|
144
144
|
|
|
145
|
-
What it needs: agent definitions named `spec`, `plan`, `code`, `audit
|
|
145
|
+
What it needs: agent definitions named `spec`, `plan`, `code`, `audit`, and `qa` in `.claude/agents/` or `~/.claude/agents/` (they ship from `1.37.0`); a resolvable test command, as above; and plans in the writing-plans format (`### Task N` with a `**Files:**` block). A failed validation halts the run, terminally in this version: recover with `end`, then `start`.
|
|
146
146
|
|
|
147
147
|
While a run is live, hooks enforce the boundaries: the orchestrator itself cannot write tracked files, role agents can only write inside their envelope, and only the orchestrator can dispatch agents. These are process guardrails for cooperative agents, not a security sandbox; see [What this is not](#what-this-is-not) and [Known limits](#known-limits).
|
|
148
148
|
|
|
149
149
|
### Review loop configurations
|
|
150
150
|
|
|
151
|
-
Before each define approval, `/cc-orchestrate` runs a review loop (`[FEAT-041]`): a fresh read-only `define-review` agent checks the spec or plan against a declared checklist, and while rows stay open the orchestrator sends them back to the role that wrote the document, up to three reviewer passes and two revisions. It is advisory: it never gates, never halts the run, and never replaces your approval, which only a message you send
|
|
151
|
+
Before each define approval, `/cc-orchestrate` runs a review loop (`[FEAT-041]`): a fresh read-only `define-review` agent checks the spec or plan against a declared checklist, and while rows stay open the orchestrator sends them back to the role that wrote the document, up to three reviewer passes and two revisions. It is advisory: it never gates, never halts the run, and never replaces your approval, which comes only from a message you send. What a round costs depends on how you launched Claude Code, measured on `claude` 2.1.292:
|
|
152
152
|
|
|
153
153
|
| Configuration | Per round |
|
|
154
154
|
|---|---|
|
|
155
155
|
| Auto mode with the shipped exception: `claude --permission-mode auto --settings .claude/review-loop.settings.json` | 0 owner wakes, 0 prompts |
|
|
156
156
|
| Default (ask) permission mode | 0 wakes; one approval per revision write, plus the orchestrator's `review` calls and report writes |
|
|
157
|
-
| Plain auto mode |
|
|
157
|
+
| Plain auto mode | The auto mode classifier denies the first revision request; the loop closes `skipped:denied`, and you get round 1's findings, unrevised |
|
|
158
158
|
|
|
159
159
|
`.claude/review-loop.settings.json` holds one auto mode allow rule that names this protocol. The installer never writes `autoMode` into `~/.claude/settings.json`, and Claude Code ignores `autoMode` in project settings, so the rule applies only when you pass the file yourself. Read it before you pass it: a cloned repository could ship a different file under the same name.
|
|
160
160
|
|
|
@@ -168,7 +168,7 @@ Most AI debugging goes: paste the error, watch the agent grep around, accept wha
|
|
|
168
168
|
/cc-debug "checkout total is wrong when a coupon is applied twice"
|
|
169
169
|
```
|
|
170
170
|
|
|
171
|
-
1. **Characterize first.** The agent states the symptom, expected behavior, reproduction steps, frequency and context, before touching anything.
|
|
171
|
+
1. **Characterize first.** The agent states the symptom, expected behavior, reproduction steps, frequency, and context, before touching anything.
|
|
172
172
|
2. **Hypothesize.** It lists 2 to 4 root-cause hypotheses **ordered by probability** and asks which to investigate first. You stay in control of where the tokens go.
|
|
173
173
|
3. **Investigate surgically.** Sub-agents do the digging with grep and `git log`; whole files are never read inline, and raw file contents never flood the main context. For visual or UI bugs, it offers to inspect through Playwright MCP.
|
|
174
174
|
4. **Report with evidence.** Root cause at `file:line`, why it happens, what else could be affected, and the exact proposed change.
|
|
@@ -184,9 +184,9 @@ Claude Code is priced in tokens, and unstructured sessions waste them in predict
|
|
|
184
184
|
|
|
185
185
|
| Mechanism | What it does |
|
|
186
186
|
|---|---|
|
|
187
|
-
| **memory-first lookup chain** | Before reading any file, the agent checks project and personal memory, then
|
|
187
|
+
| **memory-first lookup chain** | Before reading any file, the agent checks project and personal memory, then Grep/Glob, and only then does a targeted read, always bounded, max 150 lines. |
|
|
188
188
|
| **Guard 1: large-file reads** | A `Read` of a file over 150 lines with no `limit` is **denied before it runs**, with a redirect to the lookup chain. |
|
|
189
|
-
| **Guard 3: mass content dumps** | Every Bash command is scanned against twelve dump patterns (`cat *.ts`, unbounded `find`, recursive match-all greps, shell read-loops and more) and denied with a targeted alternative. In one measured real-world session it caught **47 denial events across 43 unique commands**. |
|
|
189
|
+
| **Guard 3: mass content dumps** | Every Bash command is scanned against twelve dump patterns (`cat *.ts`, unbounded `find`, recursive match-all greps, shell read-loops, and more) and denied with a targeted alternative. In one measured real-world session it caught **47 denial events across 43 unique commands**. |
|
|
190
190
|
| **Guard 4: node_modules** | Reads into `node_modules` are denied outright. Your context window is not for vendored code. |
|
|
191
191
|
| **Agent delegation** | Exploration runs in sub-agents that return a summary of at most 200 words. Intermediate data never enters the main context. |
|
|
192
192
|
| **SNAP handoffs** | Phase state is serialized as minified single-line JSON, schema-validated, at least 15% smaller than the markdown format it replaced. |
|
|
@@ -207,9 +207,9 @@ The interesting part is what it got wrong, because that is what the record docum
|
|
|
207
207
|
|
|
208
208
|
### The honest numbers
|
|
209
209
|
|
|
210
|
-
Every figure here is cited, and none of them is rounded in the project's
|
|
210
|
+
Every figure here is cited, and none of them is rounded in the project's favor.
|
|
211
211
|
|
|
212
|
-
|
|
|
212
|
+
| Measurement | Value | Source |
|
|
213
213
|
|---|---|---|
|
|
214
214
|
| Guard 3 denials recovered from one real working session | **47 events, 43 unique commands** | `.claude/memory/project.md:991` |
|
|
215
215
|
| ...of which flipped `deny` to `allow` after the `1.31.x` fixes | **36 of 43** | same table |
|
|
@@ -228,8 +228,8 @@ The population in row 1 grew from 41 to 43 *mid-measurement, because two of the
|
|
|
228
228
|
|
|
229
229
|
code-conductor operates at three layers:
|
|
230
230
|
|
|
231
|
-
- **Global core** (`~/.claude/`) applies to every project on your machine: the spec-first workflow, token-efficiency rules, safety checks, simplicity rules and memory conventions. Installed once; always active.
|
|
232
|
-
- **Project template** (`.claude/`) lives in your repository and is shared with your team through git: project slash commands, write-guarding hooks, role agent definitions and the shared memory file for decisions, conventions and technical debt.
|
|
231
|
+
- **Global core** (`~/.claude/`) applies to every project on your machine: the spec-first workflow, token-efficiency rules, safety checks, simplicity rules, and memory conventions. Installed once; always active.
|
|
232
|
+
- **Project template** (`.claude/`) lives in your repository and is shared with your team through git: project slash commands, write-guarding hooks, role agent definitions, and the shared memory file for decisions, conventions, and technical debt.
|
|
233
233
|
- **Dynamic stack discovery and skills.** `/cc-stack` runs the bundled `detect-stack.mjs` scanner and writes your detected build/test/lint/format commands, plus a concise generated ruleset, straight into your project `CLAUDE.md`, so the agent never guesses them. Skills enforce cross-cutting behavior (code simplicity, adversarial self-review, verbosity, memory-first, delegation) in every session.
|
|
234
234
|
|
|
235
235
|
---
|
|
@@ -242,9 +242,9 @@ All commands are tagged `(Conductor)` in the Claude Code command palette, so the
|
|
|
242
242
|
|
|
243
243
|
| Command | What it does |
|
|
244
244
|
|---|---|
|
|
245
|
-
| `/cc-checkpoint` | Read the current session, extract decisions, conventions and debt, and write them to `project.md` and `personal.md` with a timestamp. Run before `/compact`, after completing a feature, and after key architectural decisions. |
|
|
245
|
+
| `/cc-checkpoint` | Read the current session, extract decisions, conventions, and debt, and write them to `project.md` and `personal.md` with a timestamp. Run before `/compact`, after completing a feature, and after key architectural decisions. |
|
|
246
246
|
| `/cc-stack` | Run the dynamic detector and write the detected commands and a generated ruleset into your project `CLAUDE.md` (the `- Stack:` line and the `## Active Stack Profiles` block). On later sessions it asks whether anything changed before re-detecting. |
|
|
247
|
-
| `/cc-lang [code]` | Switch response language for this session (`en` `es` `pt` `fr` `de` `it` `zh` `ja` `ko`). Code identifiers,
|
|
247
|
+
| `/cc-lang [code]` | Switch response language for this session (`en` `es` `pt` `fr` `de` `it` `zh` `ja` `ko`). Code identifiers, file names, and commit messages stay English. |
|
|
248
248
|
| `/cc-compact` | Phase-boundary command. Serializes the current phase's essential state (decisions, pending steps, files touched, constraints) into a single-line SNAP JSON snapshot at `.claude/memory/session-snapshot.json` and, on Node `>= 22.5`, a git-hash-keyed row in the local `.conductor/cache.db`, then prompts you to run `/compact`. Run it at the end of every phase. |
|
|
249
249
|
|
|
250
250
|
### Project (requires `--project` install)
|
|
@@ -252,16 +252,17 @@ All commands are tagged `(Conductor)` in the Claude Code command palette, so the
|
|
|
252
252
|
| Command | What it does |
|
|
253
253
|
|---|---|
|
|
254
254
|
| `/cc-init` | Initialize or re-sync the project environment: detect stack, checkpoint memory, verify hook integrity. Run at the start of every session. |
|
|
255
|
-
| `/cc-resume` | Restore full session context in one command: project identity, memory, latest spec and plan, git state and the detected stack. Scans the active plan for `[>]` (interrupted) and `[!]` (failed) task markers and surfaces them. |
|
|
255
|
+
| `/cc-resume` | Restore full session context in one command: project identity, memory, latest spec and plan, git state, and the detected stack. Scans the active plan for `[>]` (interrupted) and `[!]` (failed) task markers and surfaces them. |
|
|
256
256
|
| `/cc-spec [name]` | Search the codebase first, ask only for missing context, write a full feature spec, and **wait for your approval** before any plan is made. |
|
|
257
|
-
| `/cc-plan` | From an approved spec, map the codebase and write an ordered plan with exact file paths, a test list, a commit order and risks. Every task line carries a unique `[T-NNN]` ID (at least 3 digits, unlimited suffix depth) with plain ASCII checkboxes. |
|
|
257
|
+
| `/cc-plan` | From an approved spec, map the codebase and write an ordered plan with exact file paths, a test list, a commit order, and risks. Every task line carries a unique `[T-NNN]` ID (at least 3 digits, unlimited suffix depth) with plain ASCII checkboxes. |
|
|
258
258
|
| `/cc-implement` | Execute plan tasks with a surgical 5-step ritual: grep-locate pending tasks, single-line Read verify, pre-flip `[ ]` to `[>]`, execute, post-flip to `[X]` or `[!]`. Never reads or rewrites the full plan file. Includes dependency evaluation, drift detection, and a Step 6 hook that records each task's final state to the local SQLite cache. |
|
|
259
259
|
| `/cc-orchestrate <ITEM> [--auto] [--ticket <N\|issue URL>]` | Route one backlog item through Define, Build and Verify with role agents, validated SNAP envelopes, a review loop and human approval gates. See the [walkthrough](#walkthrough-hands-off-delivery-with-cc-orchestrate). |
|
|
260
260
|
| `/cc-review [file\|dir]` | Review in three layers (Critical / Important / Suggestion), deliver a verdict, and offer to auto-fix. |
|
|
261
261
|
| `/cc-debug [problem]` | Hypothesis-driven debugging. See the [walkthrough](#walkthrough-diagnosis-before-surgery-with-cc-debug). |
|
|
262
262
|
| `/cc-refactor [file\|module]` | Diagnose complexity, plan ordered changes, apply one step at a time, and verify tests pass after each step. |
|
|
263
263
|
| `/cc-test [scope]` | Find coverage gaps, write AAA-pattern tests (plus Playwright E2E where applicable), run after confirmation, and report results. |
|
|
264
|
-
| `/cc-docs [scope]` | Audit documentation, write inline docs in your stack's format (JSDoc / docstrings /
|
|
264
|
+
| `/cc-docs [scope]` | Audit documentation, write inline docs in your stack's format (JSDoc / docstrings / Javadoc / GoDoc), and preview before writing. |
|
|
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. |
|
|
265
266
|
|
|
266
267
|
---
|
|
267
268
|
|
|
@@ -270,7 +271,7 @@ All commands are tagged `(Conductor)` in the Claude Code command palette, so the
|
|
|
270
271
|
Skills extend agent behavior for cross-cutting concerns that apply regardless of stack.
|
|
271
272
|
|
|
272
273
|
- **code-simplifier (always active).** Applied to every piece of code written or reviewed: no speculative abstractions; functions of at most 30 lines doing one thing; flat over nested, with guard clauses and early returns; descriptive names (no `Base`, `Abstract`, `Manager`, `Handler`); comments explain why, never what.
|
|
273
|
-
- **critical-review (always active during implementation).** A 4-phase adversarial protocol: (1) **Pre-Flight**, identifying the happy path, failure points and boundary conditions before any code is written; (2) **Adversarial Review** for RESILIENCE (silent failures), EFFICIENCY (code smells) and FRICTION (happy-path friction); (3) **Self-Correction**, each weakness refactored and re-verified in isolation; (4) a required **`[VALIDATION]`** closing section: edge cases covered, justification, residual risks.
|
|
274
|
+
- **critical-review (always active during implementation).** A 4-phase adversarial protocol: (1) **Pre-Flight**, identifying the happy path, failure points, and boundary conditions before any code is written; (2) **Adversarial Review** for RESILIENCE (silent failures), EFFICIENCY (code smells) and FRICTION (happy-path friction); (3) **Self-Correction**, each weakness refactored and re-verified in isolation; (4) a required **`[VALIDATION]`** closing section: edge cases covered, justification, residual risks.
|
|
274
275
|
- **verbosity (always active).** Controls how much Claude writes per turn. The level is set at install time with `--verbosity` and stored in `~/.claude/memory/verbosity.md`; the default is `MIN`.
|
|
275
276
|
|
|
276
277
|
| Level | Behavior |
|
|
@@ -279,7 +280,7 @@ Skills extend agent behavior for cross-cutting concerns that apply regardless of
|
|
|
279
280
|
| `INFO` | Bullet list of what changed and why, at most 5 bullets. `[CHANGES]` + `[REASON]`. |
|
|
280
281
|
| `VERBOSE` | Full explanation, prose allowed. All response tags. |
|
|
281
282
|
|
|
282
|
-
- **memory-first (always active).** Before reading any file, Claude walks a lookup chain and stops at the first step that answers: (1) memory, both `.claude/memory/project.md` and `~/.claude/memory/personal.md`; (2) Grep
|
|
283
|
+
- **memory-first (always active).** Before reading any file, Claude walks a lookup chain and stops at the first step that answers: (1) memory, both `.claude/memory/project.md` and `~/.claude/memory/personal.md`; (2) Grep/Glob; (3) a targeted read, last resort, always with `offset` + `limit`, at most 150 lines.
|
|
283
284
|
- **agent-delegation (always active).** Keeps the main context clean. Sub-agents handle exploration and parallel work and return a summary of at most 200 words; raw file contents and intermediate data never enter the main context.
|
|
284
285
|
- **ui-ux-pro-max (retired guidance, pending `[FEAT-037]`).** Earlier releases described this skill as installed from GitHub and switched on when `/cc-stack` detects a frontend stack. No shipped code does either. The `CLAUDE.md` templates still name it; `[FEAT-037]` replaces it with a frontend design skill stack, and this entry changes when that ships.
|
|
285
286
|
|
|
@@ -287,35 +288,35 @@ Skills extend agent behavior for cross-cutting concerns that apply regardless of
|
|
|
287
288
|
|
|
288
289
|
## Guardrails (hooks)
|
|
289
290
|
|
|
290
|
-
Hooks run automatically at specific points in a Claude Code session and need no manual setup. The pre-tool-use front door is a single zero-dependency Node script (`pre-tool-use.mjs`): it fires before `Read`, `Write`, `Edit`, `create_file`, `write_file
|
|
291
|
+
Hooks run automatically at specific points in a Claude Code session and need no manual setup. The pre-tool-use front door is a single zero-dependency Node script (`pre-tool-use.mjs`): it fires before `Read`, `Write`, `Edit`, `create_file`, `write_file`, and `Bash`, reads the `PreToolUse` payload from stdin, dispatches on `tool_name`, and returns its verdict as `hookSpecificOutput.permissionDecision`. Every path exits 0: a denial is data, never a crash.
|
|
291
292
|
|
|
292
293
|
| Guard | Fires on | What it enforces |
|
|
293
294
|
|---|---|---|
|
|
294
295
|
| **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. |
|
|
295
|
-
| **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. |
|
|
296
|
-
| **3: Bash scan** | `Bash` | Twelve mass content-dump patterns denied before execution. Commands over 8192 characters and unclosed quotes are denied fail-closed. |
|
|
296
|
+
| **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
|
+
| **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. |
|
|
297
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. |
|
|
298
299
|
| **5: Band scope** | role-agent writes | During orchestration, a band role can only write inside its installed envelope's scope. |
|
|
299
300
|
| **6: Orchestrator writes** | live orchestrate runs | The orchestrator session can only write its own run-state surface; nested agent dispatch is denied. |
|
|
300
301
|
| **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. |
|
|
301
302
|
|
|
302
|
-
**Guard 3 in detail.** The twelve patterns are: deep `find` without `-maxdepth 1`, `find -exec` with readers or shells, `xargs` with readers, `cat`
|
|
303
|
+
**Guard 3 in detail.** The twelve patterns are: deep `find` without `-maxdepth 1`, `find -exec` with readers or shells, `xargs` with readers, `cat` followed by an unquoted glob, a pager followed by an unquoted glob, command substitution as a reader's argument, `grep -r` with a match-all pattern, `ls -R`, shell loops, `mapfile` and `readarray`, dynamic execution (`eval`, `source`, and the dot operator, one pattern), and alias remapping to a reader. A separate thirteenth check catches obfuscation sequences.
|
|
303
304
|
|
|
304
305
|
Permanent exceptions live in `.claude/memory/bash-scan-allowlist.txt`, one entry per line, blank lines and `#` comments ignored and whitespace trimmed. An entry ending in `/` covers paths under that prefix, rejecting any suffix that walks up the tree with `..`; any other entry matches a whole command token. **Entries match literally: regex metacharacters carry no special meaning, so `file.ts` matches `file.ts` and nothing else.** The installer ships this file once as a commented template and creates it only when it is absent; it never overwrites an existing one. Every line in it disarms patterns for matching commands, so give each entry a comment saying why it exists; an uncommented entry is a review smell. An agent may *propose* an entry but must never add one to clear its own denial.
|
|
305
306
|
|
|
306
307
|
Hit a block you believe is wrong? Re-run the command with `CC_GUARD3_WARN=1` and the guard asks instead of denying, carrying the same pattern ids. That is a triage aid for reporting a false positive while you keep working, not a configuration mode: the allowlist is the sanctioned permanent exception. The variable affects Guard 3 alone.
|
|
307
308
|
|
|
308
|
-
**Guard 5 in detail.** A `Write`, `Edit`, `create_file` or `write_file` from a
|
|
309
|
+
**Guard 5 in detail.** A `Write`, `Edit`, `create_file` or `write_file` from a sub-agent whose `agent_type` names a band role (`spec`, `plan`, `code`, `audit`, `qa`) is checked against the nearest `.claude/memory/band-envelope.json` above its working directory, a SNAP v3 envelope. A malformed envelope, an agent that is not the envelope's role, a role not holding `RW`, or a path outside the envelope's `scope` globs (anchored at the band root, the directory whose `.claude/` holds the envelope) is denied with a named reason. The main session, any other agent, and any project without an envelope are untouched. It assumes cooperative agents: `agent_type` is a name taken on trust, and `Bash`, `NotebookEdit`, MCP write tools, and symlinked paths are not covered.
|
|
309
310
|
|
|
310
|
-
**Guard 6 in detail.** While a `/cc-orchestrate` run is live, its run file `.claude/memory/orchestrator-run.json` binds it to one session by `session_id`. In that session, a `Write`, `Edit`, `create_file` or `write_file` from anything but a band role (the main session, a payload carrying only `agent_id`, any other agent) is denied with `ORCH_WRITE_DENIED` unless its target lies inside the orchestrator's write surface, anchored at the run root: `.claude/memory/orchestrator-run.json`, `.claude/memory/band-envelope.json`, `.claude/memory/session-snapshot.json` and `.conductor/**`. Band roles stay under Guard 5. A run file from another session is stale and an unreadable one is invalid: both warn (`ORCH_RUN_STALE`, `ORCH_RUN_INVALID`) with the cleanup command and never block. While the run is live, a
|
|
311
|
+
**Guard 6 in detail.** While a `/cc-orchestrate` run is live, its run file `.claude/memory/orchestrator-run.json` binds it to one session by `session_id`. In that session, a `Write`, `Edit`, `create_file` or `write_file` from anything but a band role (the main session, a payload carrying only `agent_id`, any other agent) is denied with `ORCH_WRITE_DENIED` unless its target lies inside the orchestrator's write surface, anchored at the run root: `.claude/memory/orchestrator-run.json`, `.claude/memory/band-envelope.json`, `.claude/memory/session-snapshot.json` and `.conductor/**`. Band roles stay under Guard 5. A run file from another session is stale and an unreadable one is invalid: both warn (`ORCH_RUN_STALE`, `ORCH_RUN_INVALID`) with the cleanup command and never block. While the run is live, a sub-agent's `Agent` or `SendMessage` call is denied with `ORCH_NESTED_DISPATCH`, so only the orchestrator dispatches or messages agents (R7, `[FEAT-011]`'s nested-dispatch requirement; the hook's matcher names both tools). Outside a live run there is no Guard 6. Its limits are listed under [Known limits](#known-limits).
|
|
311
312
|
|
|
312
|
-
**Guard 7 in detail.** A `Bash` call from a
|
|
313
|
+
**Guard 7 in detail.** A `Bash` call from a sub-agent whose `agent_type` names a band role is decided before Guard 3, so Guard 3's `CC_GUARD3_WARN` ask can never outrank it. `spec`, `plan` and `audit` have no shell (`ROLE_SHELL_DENIED`). `code` and `qa` may run exactly one command, byte for byte: the `test_command` that `orchestrate.mjs start` recorded in the run file of a run live in their session. A command carrying `;`, `&`, `|`, a backtick, `$(`, `<`, `>`, or a line break is denied first (`ROLE_SHELL_CHAINING`). No run file, a run of another session, or no recorded command is denied (`ROLE_SHELL_UNRESOLVED`), and any other command is denied naming the allowed one (`ROLE_SHELL_NOT_ALLOWED`). An error inside the guard denies too, and `CC_HOOK_ALLOW` does not reach it. The main session and every other agent are untouched.
|
|
313
314
|
|
|
314
315
|
**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.
|
|
315
316
|
|
|
316
317
|
### The other hooks
|
|
317
318
|
|
|
318
|
-
- **context-guard** (
|
|
319
|
+
- **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.
|
|
319
320
|
- **post-compact.** Fires after `/compact`. Resets the turn counter to 0, reads `project.md`, shows the timestamp of the last `/cc-checkpoint`, and reminds you to checkpoint if this session's context has not been saved. Ships for Unix and Windows.
|
|
320
321
|
- **verbosity-remind** (global + project). Fires on every `UserPromptSubmit` and re-injects the active MIN/INFO/VERBOSE constraint, so the level does not drift as the window fills (BUG-014). The global hook defers to a project-level hook if one exists (upward traversal from `$PWD`), and the level is read from the nearest `.claude/memory/verbosity.md` ancestor file. Set `CC_VERBOSITY_SKIP=1` to disable it in CI/CD.
|
|
321
322
|
|
|
@@ -335,13 +336,13 @@ Hit a block you believe is wrong? Re-run the command with `CC_GUARD3_WARN=1` and
|
|
|
335
336
|
debt, workarounds
|
|
336
337
|
```
|
|
337
338
|
|
|
338
|
-
`/cc-checkpoint` writes to both. Run it before `/compact`, after completing a feature, and after any key architectural decision. The payoff compounds: every decision captured once is a conversation
|
|
339
|
+
`/cc-checkpoint` writes to both. Run it before `/compact`, after completing a feature, and after any key architectural decision. The payoff compounds: every decision captured once is a conversation (and a few thousand tokens) the team never has again.
|
|
339
340
|
|
|
340
341
|
### Local state cache and session persistence
|
|
341
342
|
|
|
342
343
|
On top of the markdown memory, `/cc-implement`'s Step 6 hook records each task's final state to a local SQLite cache at `.conductor/cache.db`, written by the bundled `scripts/conductor-db.mjs` engine, a zero-dependency ES module wrapping Node's built-in `node:sqlite`.
|
|
343
344
|
|
|
344
|
-
- **Schema (v2, ARCH-008):** `task_state(plan_file, task_id, state, updated_at)` keyed by `(plan_file, task_id)`, with `plan_file` normalized to a repo-relative POSIX path so the same plan de-duplicates across working directories; plus `sessions`, `snapshots` (one verbatim SNAP blob per git commit, newest wins) and `raw_history`. Upserts on every write.
|
|
345
|
+
- **Schema (v2, ARCH-008):** `task_state(plan_file, task_id, state, updated_at)` keyed by `(plan_file, task_id)`, with `plan_file` normalized to a repo-relative POSIX path so the same plan de-duplicates across working directories; plus `sessions`, `snapshots` (one verbatim SNAP blob per git commit, newest wins), and `raw_history`. Upserts on every write.
|
|
345
346
|
- **Runtime-gated:** `node:sqlite` needs Node `>= 22.5`, so every caller probes the Node version and self-disables below it. `engines.node` stays `>=20`; the cache is an optimization, never a requirement.
|
|
346
347
|
- **Non-authoritative and fail-safe:** the plan markdown and the `.claude/memory/session-snapshot.json` handoff remain the sources of truth. Every failure path (absent `node:sqlite`, a corrupt or non-regular file at the db path, `SQLITE_BUSY`, a newer schema, CLI misuse) degrades to a single `CONDUCTOR_DB:` stderr line and exit 0. A corrupt db is renamed aside, never deleted, and recreated.
|
|
347
348
|
- **Gitignored:** `.conductor/` is local-only and never committed.
|
|
@@ -352,7 +353,7 @@ On top of the markdown memory, `/cc-implement`'s Step 6 hook records each task's
|
|
|
352
353
|
|
|
353
354
|
## Install
|
|
354
355
|
|
|
355
|
-
**Minimum safe version: `1.34.4`.** Older versions can strip or damage an existing `CLAUDE.md`: every release before `1.24` overwrote it with no backup, `1.24` through `1.34.3` silently removed your sections whose headings matched the managed block's, and an older pre-sentinel version left at least one field file with damaged lines.
|
|
356
|
+
**Minimum safe version: `1.34.4`.** Older versions can strip or damage an existing `CLAUDE.md`: every release before `1.24` overwrote it with no backup, `1.24` through `1.34.3` silently removed your sections whose headings matched the managed block's, and an older pre-sentinel version left at least one field file (a `CLAUDE.md` whose installer-managed field lines, `- Stack:` and friends, it fills in) with damaged lines. Always install `code-conductor@latest`, as below.
|
|
356
357
|
|
|
357
358
|
```bash
|
|
358
359
|
npx @yeison.restrepo.r/code-conductor@latest # one-shot global setup
|
|
@@ -366,13 +367,13 @@ npm install -g @yeison.restrepo.r/code-conductor && code-conductor
|
|
|
366
367
|
npx @yeison.restrepo.r/code-conductor@latest --project # global setup + scaffold ./.claude
|
|
367
368
|
```
|
|
368
369
|
|
|
369
|
-
By default,
|
|
370
|
+
By default, only the global core files are installed. Flags extend that:
|
|
370
371
|
|
|
371
372
|
| Flag | Description |
|
|
372
373
|
|---|---|
|
|
373
|
-
| `--project`
|
|
374
|
-
| `--no-deps` / `-NoDeps` |
|
|
375
|
-
| `--verbosity MIN\|INFO\|VERBOSE`
|
|
374
|
+
| `--project` | Also install the project template into the current directory |
|
|
375
|
+
| `--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. |
|
|
376
377
|
|
|
377
378
|
**Updating:** re-run the same install command. User-configured files are never overwritten; agent-managed files are always updated.
|
|
378
379
|
|
|
@@ -385,7 +386,7 @@ Two cautions:
|
|
|
385
386
|
|
|
386
387
|
`CLAUDE.md` and `.gitignore` are **merged**, never overwritten. Everything else the installer ships (`settings.json`, hooks, commands, `scripts/`) is replaced on every run.
|
|
387
388
|
|
|
388
|
-
- **code-conductor owns one block and nothing else.** Its content lives between `<!-- cc:managed:start -->` and `<!-- cc:managed:end -->`, and those two markers alone decide ownership; a heading's name never does. Every upgrade replaces the block's contents wholesale, so released improvements reach existing installs. Edits inside the block are lost,
|
|
389
|
+
- **code-conductor owns one block and nothing else.** Its content lives between `<!-- cc:managed:start -->` and `<!-- cc:managed:end -->`, and those two markers alone decide ownership; a heading's name never does. Every upgrade replaces the block's contents wholesale, so released improvements reach existing installs. Edits inside the block are lost, but recoverable from the backup.
|
|
389
390
|
- **Everything outside the block is yours, byte for byte.** Nothing outside it is removed, rewritten, reordered or added.
|
|
390
391
|
- **A file without the markers gets the block appended at the end**, after one blank line and in your file's line endings, and nothing else changes. If your file already has sections named like the block's (`## Agent Identity`, `## Hard Constraints` and so on), you will see both: yours above, code-conductor's inside the block. That is deliberate. The installer never decides which of your sections are really its own; reconciling them is planned for `/cc-stack` as `[FEAT-040]`.
|
|
391
392
|
- **Before any change, the installer copies your file to `CLAUDE.md.installer-backup.<UTC timestamp>`**, keeps the five most recent, and prints where it put it:
|
|
@@ -402,7 +403,7 @@ If the markers in your file are damaged (a `start` with no `end`, two blocks, an
|
|
|
402
403
|
|
|
403
404
|
### The .gitignore block
|
|
404
405
|
|
|
405
|
-
When installed with `--project`, the installer keeps its rules in one
|
|
406
|
+
When installed with `--project`, the installer keeps its rules in one labeled block in your project's `.gitignore`:
|
|
406
407
|
|
|
407
408
|
```
|
|
408
409
|
# Code Conductor (added by the installer; safe to keep)
|
|
@@ -423,18 +424,20 @@ The backup and temp rules keep the installer's own backups and crash-stranded te
|
|
|
423
424
|
## What this is not
|
|
424
425
|
|
|
425
426
|
- **Not a sandbox and not a security boundary.** The guards are advisory tooling against context exhaustion and sloppy habits, built for cooperative agents. They do not contain a hostile process and were never built to.
|
|
426
|
-
- **Not a model.** It is configuration, hooks and scripts around Claude Code.
|
|
427
|
+
- **Not a model.** It is configuration, hooks, and scripts around Claude Code.
|
|
427
428
|
- **Not finished.** See the limits below.
|
|
428
429
|
|
|
430
|
+
---
|
|
431
|
+
|
|
429
432
|
## Known limits
|
|
430
433
|
|
|
431
434
|
- **The orchestrator (`1.36.0`) assumes cooperative agents.**
|
|
432
435
|
- Guard 6 does not cover `Bash` writes, `claude -p` children included.
|
|
433
436
|
- Inside a live run, a non-role agent the main session dispatched may write the orchestrator's write surface, the band envelope included.
|
|
434
|
-
- R7 protects live runs only.
|
|
437
|
+
- The nested-dispatch rule (R7) protects live runs only.
|
|
435
438
|
- An agent writing after its hand-back is bounded only by the envelope in force, so a same-role next task inherits it.
|
|
436
439
|
- Under auto permission mode no human stands behind a Bash write or a hook `ask`.
|
|
437
|
-
- A Guard 6 warning reaches you, never the model's tool result, and not in every case. Measured on `claude` 2.1.
|
|
440
|
+
- A Guard 6 warning reaches you, never the model's tool result, and not in every case. Measured on `claude` 2.1.292:
|
|
438
441
|
|
|
439
442
|
| Channel | Permission mode | A prompting decision rides along | You see the warning |
|
|
440
443
|
|---|---|---|---|
|
|
@@ -457,7 +460,7 @@ The backup and temp rules keep the installer's own backups and crash-stranded te
|
|
|
457
460
|
- **`[BUG-057]`, open:** `.claude/memory/project.md` is append-only and the phase commands instruct a full read of it, which collides with Guard 1's 150-line read limit once the file grows; on a long-lived project the read cost rises with project age. Until it is fixed, prune or archive old checkpoint sections by hand when the file gets large.
|
|
458
461
|
- **`[BUG-058]`, open:** the test suite does not pass on a Windows checkout (CRLF checkout of `.mjs` files, `--import` given a bare path, symlink and `chmod` fixtures, `spawnSync('npm')` without a shell), and CI has no Windows leg to show it. Until it is fixed, develop against the suite on Linux/macOS or WSL; the shipped product itself is unaffected.
|
|
459
462
|
- **`[BUG-059]`, open:** the test helper that fakes the `gh` CLI is POSIX-only, so on a Windows machine where the suites load, tests can reach a real, logged-in `gh` and perform live GitHub writes. Until it is fixed, do not run `npm test` on Windows while authenticated to `gh`, or log out (`gh auth logout`) first.
|
|
460
|
-
- **The `P7` false positive** described under [Guard 3, and what it learned](#guard-3-and-what-it-learned)
|
|
463
|
+
- **The `P7` false positive** described under [Guard 3, and what it learned](#guard-3-and-what-it-learned) is still live.
|
|
461
464
|
- **A re-run against an untouched `project.md` prints a recovery hint it cannot prove is needed.** If you install, never write anything into `.claude/memory/project.md`, and install again, you get a line suggesting the file may have been overwritten by a pre-`1.30.0` re-run. It was not; it equals the stub because it was seeded and never edited. The check compares content and **cannot distinguish "seeded and untouched" from "clobbered"**, which is why the wording is hedged to "may have been" rather than "was". This residual is named and accepted in [`BUG-039`'s spec at `:129`](docs/superpowers/specs/2026-09-27-bug039-installer-host-owned-state-design.md), where the alternative (restoring from the host's own git history) was rejected as writing host files out of the host's history with new failure modes. A **fresh** install is silent, which the Quickstart shows.
|
|
462
465
|
- **Three open dossiers**, which are the evidence-collection pipeline working rather than a backlog: a session denial tally, one for interleaved-artifact reports, and an intermittent commit-hook hang in the `snap-build` suite. A dossier holds specimens until a mechanism is characterized by probe; an id is minted only when the written condition is met. `[BUG-047]` is what that pipeline produces when it completes: an out-of-scope note, then a dossier, then four specimens across four sessions, then a mint, then a release.
|
|
463
466
|
|
|
@@ -467,7 +470,7 @@ The backup and temp rules keep the installer's own backups and crash-stranded te
|
|
|
467
470
|
|
|
468
471
|
## Instruments: releases that verify their own record
|
|
469
472
|
|
|
470
|
-
Four checks live in `tools/` as tracked repository infrastructure. Three of them run on every pull request, so a divergence blocks the merge rather than waiting for someone to remember
|
|
473
|
+
Four checks live in `tools/` as tracked repository infrastructure. Three of them run in full on every pull request, so a divergence blocks the merge rather than waiting for someone to remember; the fourth, `id-ceiling.mjs`, runs its duplicate-free half on every pull request too, and its ceiling query by hand before each mint:
|
|
471
474
|
|
|
472
475
|
- **`version-gate.mjs`** takes `VERSION` as the authority and checks four other locations against it, five in all. Agreement reports as agreement, which sounds trivial until you learn that its predecessor reported `FAIL` on five locations that agreed, because it compared against a literal frozen two releases earlier. It runs at the merge gate through `tests/tools/repo-invariants.test.js`, and by hand at closeout.
|
|
473
476
|
- **`record-parity.mjs`** asserts that every item the `CHANGELOG` claims has a closed backlog entry naming the version it shipped in. It exists because `[BUG-044]` shipped, was closed out in memory, and left its backlog entry reading `[ ]` for an entire release with no instrument comparing the two documents. It runs at the merge gate through `tests/tools/repo-invariants.test.js`, and by hand at closeout.
|
|
@@ -491,7 +494,7 @@ Four checks live in `tools/` as tracked repository infrastructure. Three of them
|
|
|
491
494
|
|
|
492
495
|
**Supported codes:** `en` `es` `pt` `fr` `de` `it` `zh` `ja` `ko`
|
|
493
496
|
|
|
494
|
-
Code identifiers, file names and commit messages are always English.
|
|
497
|
+
Code identifiers, file names, and commit messages are always English.
|
|
495
498
|
|
|
496
499
|
---
|
|
497
500
|
|
|
@@ -501,7 +504,7 @@ Code identifiers, file names and commit messages are always English.
|
|
|
501
504
|
code-conductor/
|
|
502
505
|
+-- README.md
|
|
503
506
|
+-- VERSION
|
|
504
|
-
+-- bin/code-conductor.mjs npm CLI entry (npx code-conductor)
|
|
507
|
+
+-- bin/code-conductor.mjs npm CLI entry (npx @yeison.restrepo.r/code-conductor)
|
|
505
508
|
+-- lib/installer/ CLI modules (env, deploy, settings, merges, heal)
|
|
506
509
|
+-- global/
|
|
507
510
|
| +-- CLAUDE.md Global agent behavior (all projects)
|
|
@@ -562,7 +565,7 @@ Claude Code registers personal skills only at `~/.claude/skills/<name>/SKILL.md`
|
|
|
562
565
|
|
|
563
566
|
Hook removal (`rm ~/.claude/hooks/verbosity-remind.sh`) and `settings.json` cleanup work identically in every environment; no git is required.
|
|
564
567
|
|
|
565
|
-
|
|
568
|
+
No uninstall step needs a git working tree. In CI/CD pipelines, Docker containers, or directories that are not git repositories, uninstall the same way as anywhere else: delete `~/.claude/skills/verbosity/SKILL.md` (and any other skill directories you want gone) and remove the `verbosity-remind` entry from `~/.claude/settings.json`.
|
|
566
569
|
|
|
567
570
|
---
|
|
568
571
|
|
|
@@ -570,6 +573,8 @@ Uninstall steps that use `git checkout <tag>` or `git revert <sha>` need a git w
|
|
|
570
573
|
|
|
571
574
|
GitHub Issues are the inbox: an issue or PR is a candidate until the owner mints it an id. Nothing merges without a minted id and owner review, one item per PR. Versions, release branches, tags and GitHub Releases are owner-only. Read [CONTRIBUTING.md](CONTRIBUTING.md) before opening a PR; its hard constraints bind AI agents working on a contributor's behalf as well.
|
|
572
575
|
|
|
576
|
+
---
|
|
577
|
+
|
|
573
578
|
## License
|
|
574
579
|
|
|
575
|
-
See [LICENSE](
|
|
580
|
+
See [LICENSE](LICENSE).
|
package/bin/code-conductor.mjs
CHANGED
|
@@ -8,9 +8,9 @@ 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] [--verbosity MIN|INFO|VERBOSE] [--version] [--help]`;
|
|
11
|
+
const USAGE = `Usage: code-conductor [--project] [--no-deps|-NoDeps] [--verbosity MIN|INFO|VERBOSE] [--version] [--help]`;
|
|
12
12
|
|
|
13
|
-
// Hand-rolled parser (
|
|
13
|
+
// Hand-rolled parser (five flags only). Deliberately NOT node:util's parseArgs —
|
|
14
14
|
// the CLI honors the zero-runtime-dependency rule and node:util adds no value for
|
|
15
15
|
// this tiny surface, so nothing is imported for argument handling.
|
|
16
16
|
// Conflict policy: flags are LAST-WINS. `--verbosity MIN --verbosity VERBOSE`
|
|
@@ -18,10 +18,14 @@ const USAGE = `Usage: code-conductor [--project] [--verbosity MIN|INFO|VERBOSE]
|
|
|
18
18
|
// is idempotent. No "conflicting flags" error is raised — last-wins is the least
|
|
19
19
|
// surprising CLI convention and keeps the parser branchless.
|
|
20
20
|
function parseArgs(argv) {
|
|
21
|
-
const opts = { project: false, verbosity: undefined, verbosityGiven: false, version: false, help: false, unknown: [] };
|
|
21
|
+
const opts = { project: false, noDeps: false, verbosity: undefined, verbosityGiven: false, version: false, help: false, unknown: [] };
|
|
22
22
|
for (let i = 0; i < argv.length; i++) {
|
|
23
23
|
const a = argv[i];
|
|
24
24
|
if (a === '--project') opts.project = true;
|
|
25
|
+
// Accepted no-op: the npm CLI installs no dependencies since FEAT-023 removed the
|
|
26
|
+
// shell installers, so there is nothing to skip. Recognized so callers carried over
|
|
27
|
+
// from install.sh get no misleading "unrecognized" warning.
|
|
28
|
+
else if (a === '--no-deps' || a === '-NoDeps') opts.noDeps = true;
|
|
25
29
|
else if (a === '--verbosity' || a.startsWith('--verbosity=')) {
|
|
26
30
|
opts.verbosityGiven = true;
|
|
27
31
|
if (a.startsWith('--verbosity=')) {
|
|
@@ -34,8 +38,10 @@ function parseArgs(argv) {
|
|
|
34
38
|
// Space-separated form: consume the next token only if it is a real value,
|
|
35
39
|
// not another flag or the end of argv (`--verbosity` passed last). A missing
|
|
36
40
|
// value stays undefined and falls back to MIN + warning in writeVerbosity.
|
|
41
|
+
// Any `-` prefix marks a flag, so single-dash aliases are never eaten as the
|
|
42
|
+
// level; no valid level starts with `-`.
|
|
37
43
|
const next = argv[i + 1];
|
|
38
|
-
if (next !== undefined && !next.startsWith('
|
|
44
|
+
if (next !== undefined && !next.startsWith('-')) { opts.verbosity = next; i++; }
|
|
39
45
|
}
|
|
40
46
|
}
|
|
41
47
|
else if (a === '--version' || a === '-v') opts.version = true;
|
|
@@ -14,6 +14,24 @@ Identify and extract:
|
|
|
14
14
|
- Add a timestamped section: `## Checkpoint [YYYY-MM-DD HH:MM]`
|
|
15
15
|
- List decisions, conventions, and debt from this session
|
|
16
16
|
|
|
17
|
+
**Then update its `## Current State` section**, the bounded digest at the top of `project.md` that phase commands read with a `limit` instead of the whole file:
|
|
18
|
+
- If the section is absent, make the one-time bootstrap insert: add this skeleton directly after the file's `# Project Memory` intro paragraph, in one Edit. It inserts a new section and never rewrites an existing line, so it keeps the BUG-003 invariant.
|
|
19
|
+
|
|
20
|
+
```markdown
|
|
21
|
+
## Current State
|
|
22
|
+
<!-- Bounded digest, max 40 lines, each line max 200 characters. History below is append-only. -->
|
|
23
|
+
- Active spec: none
|
|
24
|
+
- Last checkpoint: none
|
|
25
|
+
### Conventions
|
|
26
|
+
### Debt
|
|
27
|
+
<!-- end current state -->
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
- Replace the single `- Last checkpoint:` line with the heading text of the entry just appended, without its leading `## `.
|
|
31
|
+
- Add each new convention as a bullet under `### Conventions` and each new debt item or workaround as a bullet under `### Debt`, one Edit per bullet.
|
|
32
|
+
- Caps: the section stays within 40 lines, each list within 12 bullets, each line within 200 characters. Before adding to a full list, remove the one bullet that is superseded or resolved, in its own Edit. A removed or shortened bullet loses nothing: the history entry holds the full text.
|
|
33
|
+
- If the `<!-- end current state -->` line is missing, report the malformed section and leave it as it is. Never rewrite it in bulk.
|
|
34
|
+
|
|
17
35
|
**Staging that update, where the workflow commits it:** stage by tracked-ness, with an explicit path. A `project.md` that is already tracked takes `git add -u ".claude/memory/project.md"`; one that is not yet tracked takes plain `git add ".claude/memory/project.md"`, or `git add -f` where the project ignores `.claude/`. **Never an unconditional `-u` here.** This command is global and also runs in freshly scaffolded projects, which do not ignore `.claude/` and whose `project.md` is not yet tracked: there `-u` exits 128 and would halt the checkpoint before its DB tail, trading a defect those projects never had for one they would.
|
|
18
36
|
|
|
19
37
|
**Update `.claude/memory/personal.md`** (local only):
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@yeison.restrepo.r/code-conductor",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.42.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",
|
|
@@ -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`
|
|
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
|
|
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
|
|
44
|
-
-
|
|
45
|
-
-
|
|
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
|
|
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
|
|
@@ -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
|
-
$
|
|
21
|
-
if ($
|
|
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, "$
|
|
51
|
+
[System.IO.File]::WriteAllText($tmp, "$line`n", $enc)
|
|
31
52
|
try {
|
|
32
|
-
|
|
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
|
-
#
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
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
|
-
|
|
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)
|
package/scripts/conductor-db.mjs
CHANGED
|
@@ -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
|
}
|
|
@@ -0,0 +1,387 @@
|
|
|
1
|
+
// scripts/session-metrics.mjs
|
|
2
|
+
// FEAT-046: offline token and time metrics over Claude Code's local session logs.
|
|
3
|
+
// Zero-dep, strictly read-only: it opens files for reading only and prints one report.
|
|
4
|
+
// Every failure degrades to a named note on stdout and exit 0, never a wrong number.
|
|
5
|
+
import { createReadStream, existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
|
|
6
|
+
import { createInterface } from 'node:readline';
|
|
7
|
+
import { execFileSync } from 'node:child_process';
|
|
8
|
+
import { homedir } from 'node:os';
|
|
9
|
+
import { basename, join } from 'node:path';
|
|
10
|
+
import { fileURLToPath } from 'node:url';
|
|
11
|
+
|
|
12
|
+
export const THRESHOLDS = { repeatReads: 5, unboundedReadTokens: 2000, contextPeak: 150000, cacheHitPct: 80 };
|
|
13
|
+
const TOP = 5;
|
|
14
|
+
const NONE = '(none)';
|
|
15
|
+
// Every map keyed by log text has no prototype, so a key like __proto__ is an ordinary row.
|
|
16
|
+
const table = (entries = {}) => Object.assign(Object.create(null), entries);
|
|
17
|
+
const PHASES = table({
|
|
18
|
+
'cc-spec': 'Define', 'cc-plan': 'Define',
|
|
19
|
+
'cc-implement': 'Build', 'cc-refactor': 'Build', 'cc-debug': 'Build',
|
|
20
|
+
'cc-review': 'Verify', 'cc-test': 'Verify',
|
|
21
|
+
});
|
|
22
|
+
const COMMAND_TAG = /<command-name>\/?([^<\s]+)<\/command-name>/;
|
|
23
|
+
const ITEM_IN_BRANCH = /(feat|bug|arch)[-_]?(\d{3})/i;
|
|
24
|
+
|
|
25
|
+
// Claude Code names a project's log directory after its path, with every non-alphanumeric as '-'.
|
|
26
|
+
export function slugOf(path) {
|
|
27
|
+
return path.replace(/[^A-Za-z0-9]/g, '-');
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function resolveLogDir({ dir, env, root, home }) {
|
|
31
|
+
if (dir) return dir;
|
|
32
|
+
const base = env.CLAUDE_CONFIG_DIR || join(home, '.claude');
|
|
33
|
+
return join(base, 'projects', slugOf(root));
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function listLogFiles(dir) {
|
|
37
|
+
const files = [];
|
|
38
|
+
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
39
|
+
if (entry.isFile() && entry.name.endsWith('.jsonl')) files.push(join(dir, entry.name));
|
|
40
|
+
if (!entry.isDirectory()) continue;
|
|
41
|
+
const sub = join(dir, entry.name, 'subagents');
|
|
42
|
+
if (!existsSync(sub)) continue;
|
|
43
|
+
for (const name of readdirSync(sub)) if (name.endsWith('.jsonl')) files.push(join(sub, name));
|
|
44
|
+
}
|
|
45
|
+
return files.sort();
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// A session still being written ends mid-line; that line is skipped, never guessed at.
|
|
49
|
+
export function parseLine(line) {
|
|
50
|
+
if (!line.trim()) return null;
|
|
51
|
+
try {
|
|
52
|
+
const record = JSON.parse(line);
|
|
53
|
+
return record && typeof record === 'object' && !Array.isArray(record) ? record : null;
|
|
54
|
+
} catch {
|
|
55
|
+
return null;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function createTotals() {
|
|
60
|
+
return {
|
|
61
|
+
files: 0, subagentFiles: 0, bytes: 0, requests: 0, unparsable: 0, notMeasured: 0, compactions: 0,
|
|
62
|
+
tokens: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
|
63
|
+
groups: { tool: table(), command: table(), phase: table(), branch: table(), session: table() },
|
|
64
|
+
seen: new Set(), pending: new Map(), command: NONE,
|
|
65
|
+
reads: table(), unboundedReads: [], peaks: table(), sessionCompactions: table(), activeMs: table(),
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function bump(group, key, field, amount) {
|
|
70
|
+
group[key] ??= { tokens: 0, calls: 0, estTokens: 0, wallMs: 0 };
|
|
71
|
+
group[key][field] += amount;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function blocksOf(record) {
|
|
75
|
+
const content = record.message?.content;
|
|
76
|
+
return Array.isArray(content) ? content : [];
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function textOf(record) {
|
|
80
|
+
const content = record.message?.content;
|
|
81
|
+
if (typeof content === 'string') return content;
|
|
82
|
+
return blocksOf(record).filter((b) => b.type === 'text').map((b) => b.text).join('');
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function sessionKey(record) {
|
|
86
|
+
const id = String(record.sessionId ?? '?').slice(0, 8);
|
|
87
|
+
return record.agentId ? `${id}/${record.agentId}` : id;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// Image and document blocks are not text the model reads as tokens at chars/4; they are skipped.
|
|
91
|
+
export function estimateTokens(content) {
|
|
92
|
+
if (typeof content === 'string') return Math.round(content.length / 4);
|
|
93
|
+
if (!Array.isArray(content)) return 0;
|
|
94
|
+
const chars = content.filter((b) => b.type === 'text').reduce((sum, b) => sum + (typeof b.text === 'string' ? b.text.length : 0), 0);
|
|
95
|
+
return Math.round(chars / 4);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export function addRecord(totals, record) {
|
|
99
|
+
if (record.type === 'assistant') return addAssistant(totals, record);
|
|
100
|
+
if (record.type === 'user') return addUser(totals, record);
|
|
101
|
+
if (record.type === 'system') return addSystem(totals, record);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function addAssistant(totals, record) {
|
|
105
|
+
for (const block of blocksOf(record)) if (block.type === 'tool_use') openTool(totals, record, block);
|
|
106
|
+
const usage = record.message?.usage;
|
|
107
|
+
if (!usage || !record.requestId) { totals.notMeasured++; return; }
|
|
108
|
+
// One API response spans several records sharing a requestId, each repeating the same usage.
|
|
109
|
+
if (totals.seen.has(record.requestId)) return;
|
|
110
|
+
totals.seen.add(record.requestId);
|
|
111
|
+
addUsage(totals, record, usage);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function openTool(totals, record, block) {
|
|
115
|
+
totals.pending.set(block.id, { name: block.name, ts: Date.parse(record.timestamp), input: block.input ?? {} });
|
|
116
|
+
if (block.name === 'Skill' && block.input?.skill) totals.command = String(block.input.skill);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function addUsage(totals, record, usage) {
|
|
120
|
+
const n = (k) => Number(usage[k]) || 0;
|
|
121
|
+
const input = n('input_tokens'), output = n('output_tokens');
|
|
122
|
+
const cacheRead = n('cache_read_input_tokens'), cacheWrite = n('cache_creation_input_tokens');
|
|
123
|
+
const all = input + output + cacheRead + cacheWrite;
|
|
124
|
+
const t = totals.tokens;
|
|
125
|
+
t.input += input; t.output += output; t.cacheRead += cacheRead; t.cacheWrite += cacheWrite;
|
|
126
|
+
totals.requests++;
|
|
127
|
+
const session = sessionKey(record);
|
|
128
|
+
totals.peaks[session] = Math.max(totals.peaks[session] ?? 0, input + cacheRead + cacheWrite);
|
|
129
|
+
const g = totals.groups;
|
|
130
|
+
bump(g.command, totals.command, 'tokens', all);
|
|
131
|
+
bump(g.phase, PHASES[totals.command] ?? NONE, 'tokens', all);
|
|
132
|
+
bump(g.branch, record.gitBranch || NONE, 'tokens', all);
|
|
133
|
+
bump(g.session, session, 'tokens', all);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function addUser(totals, record) {
|
|
137
|
+
const command = textOf(record).match(COMMAND_TAG);
|
|
138
|
+
if (command) totals.command = command[1];
|
|
139
|
+
else if (record.promptSource === 'typed') totals.command = NONE;
|
|
140
|
+
for (const block of blocksOf(record)) if (block.type === 'tool_result') closeTool(totals, record, block);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function closeTool(totals, record, block) {
|
|
144
|
+
const call = totals.pending.get(block.tool_use_id);
|
|
145
|
+
if (!call) return;
|
|
146
|
+
totals.pending.delete(block.tool_use_id);
|
|
147
|
+
const tool = totals.groups.tool;
|
|
148
|
+
const est = estimateTokens(block.content);
|
|
149
|
+
const ms = Date.parse(record.timestamp) - call.ts;
|
|
150
|
+
bump(tool, call.name, 'calls', 1);
|
|
151
|
+
bump(tool, call.name, 'estTokens', est);
|
|
152
|
+
// A result stamped before its call is a clock or log fault, so its time is unknown, not negative.
|
|
153
|
+
if (Number.isFinite(ms) && ms >= 0) bump(tool, call.name, 'wallMs', ms);
|
|
154
|
+
else totals.notMeasured++;
|
|
155
|
+
if (call.name === 'Read') trackRead(totals, call.input, est);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function trackRead(totals, input, est) {
|
|
159
|
+
const file = String(input.file_path ?? '?');
|
|
160
|
+
totals.reads[file] ??= { count: 0, estTokens: 0 };
|
|
161
|
+
totals.reads[file].count++;
|
|
162
|
+
totals.reads[file].estTokens += est;
|
|
163
|
+
if (!input.limit && est > THRESHOLDS.unboundedReadTokens) totals.unboundedReads.push({ file, est });
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function addSystem(totals, record) {
|
|
167
|
+
const session = sessionKey(record);
|
|
168
|
+
if (record.subtype === 'compact_boundary') {
|
|
169
|
+
totals.compactions++;
|
|
170
|
+
totals.sessionCompactions[session] = (totals.sessionCompactions[session] ?? 0) + 1;
|
|
171
|
+
}
|
|
172
|
+
if (record.subtype === 'turn_duration' && Number.isFinite(record.durationMs)) {
|
|
173
|
+
totals.activeMs[session] = (totals.activeMs[session] ?? 0) + record.durationMs;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// A tool call cut off by the end of its transcript is still a call; only its time is unknown.
|
|
178
|
+
export function finishFile(totals) {
|
|
179
|
+
for (const call of totals.pending.values()) {
|
|
180
|
+
bump(totals.groups.tool, call.name, 'calls', 1);
|
|
181
|
+
totals.notMeasured++;
|
|
182
|
+
}
|
|
183
|
+
totals.pending.clear();
|
|
184
|
+
totals.command = NONE;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
export async function readLog(totals, file) {
|
|
188
|
+
totals.files++;
|
|
189
|
+
totals.bytes += statSync(file).size;
|
|
190
|
+
if (file.includes('subagents')) totals.subagentFiles++;
|
|
191
|
+
const lines = createInterface({ input: createReadStream(file), crlfDelay: Infinity });
|
|
192
|
+
for await (const line of lines) {
|
|
193
|
+
const record = parseLine(line);
|
|
194
|
+
if (record) addRecord(totals, record);
|
|
195
|
+
else if (line.trim()) totals.unparsable++;
|
|
196
|
+
}
|
|
197
|
+
finishFile(totals);
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
export function itemOf(branch) {
|
|
201
|
+
const m = String(branch).match(ITEM_IN_BRANCH);
|
|
202
|
+
return m ? `${m[1].toUpperCase()}-${m[2]}` : null;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
export function pillarMap(backlogText) {
|
|
206
|
+
const map = table();
|
|
207
|
+
let pillar = null;
|
|
208
|
+
for (const line of backlogText.split(/\r?\n/)) {
|
|
209
|
+
const heading = line.match(/^## PILLAR (\d+)/i);
|
|
210
|
+
if (heading) pillar = `P${heading[1]}`;
|
|
211
|
+
const item = line.match(/^### \[.\] `\[([A-Z]+-\d+)\]`/);
|
|
212
|
+
if (item && pillar) map[item[1]] = pillar;
|
|
213
|
+
}
|
|
214
|
+
return map;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
export function pillarTotals(branchGroup, pillars) {
|
|
218
|
+
const out = table();
|
|
219
|
+
for (const [branch, v] of Object.entries(branchGroup)) {
|
|
220
|
+
const key = pillars[itemOf(branch)] ?? '(unattributed)';
|
|
221
|
+
out[key] = (out[key] ?? 0) + v.tokens;
|
|
222
|
+
}
|
|
223
|
+
return out;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
export function fmt(n) {
|
|
227
|
+
if (n >= 1e6) return `${(n / 1e6).toFixed(1)}M`;
|
|
228
|
+
if (n >= 1e3) return `${(n / 1e3).toFixed(1)}k`;
|
|
229
|
+
return String(n);
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
export function cacheHitPct(tokens) {
|
|
233
|
+
const input = tokens.input + tokens.cacheRead + tokens.cacheWrite;
|
|
234
|
+
return input ? (100 * tokens.cacheRead) / input : null;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
function repeatedReadLine(totals) {
|
|
238
|
+
const hot = Object.entries(totals.reads).filter(([, r]) => r.count >= THRESHOLDS.repeatReads);
|
|
239
|
+
if (!hot.length) return null;
|
|
240
|
+
const [file, r] = hot.sort((a, b) => b[1].count - a[1].count)[0];
|
|
241
|
+
const more = hot.length > 1 ? ` (+${hot.length - 1} more files)` : '';
|
|
242
|
+
return `R1 ${basename(file)} Read ${r.count}x (~${fmt(r.estTokens)} est tok)${more}: grep before reading, or keep the fact in memory`;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
function unboundedReadLine(totals) {
|
|
246
|
+
const reads = totals.unboundedReads;
|
|
247
|
+
if (!reads.length) return null;
|
|
248
|
+
const top = [...reads].sort((a, b) => b.est - a.est)[0];
|
|
249
|
+
return `R2 ${reads.length} Read(s) without limit returned >${fmt(THRESHOLDS.unboundedReadTokens)} est tok (largest ~${fmt(top.est)} in ${basename(top.file)}): pass offset/limit`;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
function contextPeakLine(totals) {
|
|
253
|
+
const high = Object.entries(totals.peaks).filter(([, p]) => p > THRESHOLDS.contextPeak);
|
|
254
|
+
if (!high.length) return null;
|
|
255
|
+
const [session, peak] = high.sort((a, b) => b[1] - a[1])[0];
|
|
256
|
+
const compactions = totals.sessionCompactions[session] ?? 0;
|
|
257
|
+
const more = high.length > 1 ? ` (+${high.length - 1} more sessions)` : '';
|
|
258
|
+
return `R3 session ${session} peaked at ${fmt(peak)} context with ${compactions} compaction(s)${more}: run /cc-compact earlier`;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
function cacheMissLine(totals) {
|
|
262
|
+
const pct = cacheHitPct(totals.tokens);
|
|
263
|
+
if (pct === null || pct >= THRESHOLDS.cacheHitPct) return null;
|
|
264
|
+
const t = totals.tokens;
|
|
265
|
+
return `R4 cache hit ${pct.toFixed(1)}% (cacheR ${fmt(t.cacheRead)} of ${fmt(t.input + t.cacheRead + t.cacheWrite)} input tok): keep the prompt prefix stable`;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
export function recommend(totals) {
|
|
269
|
+
return [repeatedReadLine, unboundedReadLine, contextPeakLine, cacheMissLine]
|
|
270
|
+
.map((rule) => rule(totals))
|
|
271
|
+
.filter(Boolean);
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
function topRows(group, field) {
|
|
275
|
+
return Object.entries(group).sort((a, b) => b[1][field] - a[1][field]).slice(0, TOP);
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
function shareRow(entries, total) {
|
|
279
|
+
return entries.map(([k, v]) => `${k} ${fmt(v)} ${total ? Math.round((100 * v) / total) : 0}%`).join(' | ');
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
function headerLines(totals) {
|
|
283
|
+
const t = totals.tokens;
|
|
284
|
+
const pct = cacheHitPct(t);
|
|
285
|
+
return [
|
|
286
|
+
`cc-metrics: ${totals.files} logs (${totals.subagentFiles} subagent), ${fmt(totals.bytes)}B, ${totals.requests} requests, ` +
|
|
287
|
+
`${totals.unparsable} unparsable lines, ${totals.notMeasured} not measured, ${totals.compactions} compactions`,
|
|
288
|
+
`tokens: in ${fmt(t.input)} out ${fmt(t.output)} cacheR ${fmt(t.cacheRead)} cacheW ${fmt(t.cacheWrite)} | ` +
|
|
289
|
+
`cache hit ${pct === null ? 'n/a' : `${pct.toFixed(1)}%`}`,
|
|
290
|
+
];
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
function toolLines(totals) {
|
|
294
|
+
const rows = topRows(totals.groups.tool, 'calls').map(([name, v]) =>
|
|
295
|
+
` ${name.padEnd(12)} ${String(v.calls).padStart(6)} ${fmt(v.estTokens).padStart(8)} ${String(Math.round(v.wallMs / 1000)).padStart(7)}`);
|
|
296
|
+
return ['by tool (calls, est result tok, wall s):', ...rows];
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
function groupLine(label, group, total) {
|
|
300
|
+
const entries = topRows(group, 'tokens').map(([k, v]) => [k, v.tokens]);
|
|
301
|
+
return `by ${label} (tokens): ${shareRow(entries, total)}`;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
function branchLines(totals, pillars) {
|
|
305
|
+
const rows = topRows(totals.groups.branch, 'tokens').map(([branch, v]) => {
|
|
306
|
+
const item = itemOf(branch);
|
|
307
|
+
const tags = item ? ` ${item} ${pillars?.[item] ?? ''}`.trimEnd() : '';
|
|
308
|
+
return ` ${branch.slice(0, 34).padEnd(34)} ${fmt(v.tokens).padStart(8)}${tags}`;
|
|
309
|
+
});
|
|
310
|
+
return ['by branch (tokens):', ...rows];
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
function sessionLines(totals) {
|
|
314
|
+
const rows = topRows(totals.groups.session, 'tokens').map(([s, v]) => {
|
|
315
|
+
const ms = totals.activeMs[s];
|
|
316
|
+
const active = ms === undefined ? '—' : String(Math.round(ms / 60000));
|
|
317
|
+
return ` ${s.padEnd(20)} ${fmt(v.tokens).padStart(8)} ${active.padStart(6)}`;
|
|
318
|
+
});
|
|
319
|
+
return ['by session (tokens, active min):', ...rows];
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
function pillarLine(totals, pillars, total) {
|
|
323
|
+
if (!pillars) return 'pillar: no AGENT-READABLE BACKLOG.md';
|
|
324
|
+
const entries = Object.entries(pillarTotals(totals.groups.branch, pillars)).sort((a, b) => b[1] - a[1]);
|
|
325
|
+
return `by pillar (tokens): ${shareRow(entries, total)}`;
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
export function formatReport(totals, pillars) {
|
|
329
|
+
const total = Object.values(totals.groups.session).reduce((s, v) => s + v.tokens, 0);
|
|
330
|
+
const recs = recommend(totals);
|
|
331
|
+
const th = THRESHOLDS;
|
|
332
|
+
return [
|
|
333
|
+
...headerLines(totals),
|
|
334
|
+
...toolLines(totals),
|
|
335
|
+
groupLine('command', totals.groups.command, total),
|
|
336
|
+
groupLine('phase', totals.groups.phase, total),
|
|
337
|
+
...branchLines(totals, pillars),
|
|
338
|
+
pillarLine(totals, pillars, total),
|
|
339
|
+
...sessionLines(totals),
|
|
340
|
+
'recommendations:',
|
|
341
|
+
...(recs.length ? recs.map((r) => ` - ${r}`) : [' - none fired']),
|
|
342
|
+
`thresholds: R1>=${th.repeatReads} reads, R2>${fmt(th.unboundedReadTokens)} tok, R3>${fmt(th.contextPeak)} ctx, R4<${th.cacheHitPct}% cache`,
|
|
343
|
+
].join('\n');
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
function readPillars(root) {
|
|
347
|
+
const file = join(root, 'AGENT-READABLE BACKLOG.md');
|
|
348
|
+
return existsSync(file) ? pillarMap(readFileSync(file, 'utf8')) : null;
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
export async function run({ dir, root, env = process.env, home = homedir() }) {
|
|
352
|
+
const logDir = resolveLogDir({ dir, env, root, home });
|
|
353
|
+
if (!existsSync(logDir)) return `cc-metrics: no session logs at ${logDir}`;
|
|
354
|
+
const files = listLogFiles(logDir);
|
|
355
|
+
if (!files.length) return `cc-metrics: no session logs at ${logDir}`;
|
|
356
|
+
const totals = createTotals();
|
|
357
|
+
for (const file of files) await readLog(totals, file);
|
|
358
|
+
return formatReport(totals, readPillars(root));
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
function projectRoot() {
|
|
362
|
+
try {
|
|
363
|
+
const top = execFileSync('git', ['rev-parse', '--show-toplevel'],
|
|
364
|
+
{ encoding: 'utf8', timeout: 2000, stdio: ['ignore', 'pipe', 'ignore'] }).trim();
|
|
365
|
+
if (top) return top;
|
|
366
|
+
} catch { /* not a git checkout: fall back to cwd */ }
|
|
367
|
+
return process.cwd();
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
// The command passes $ARGUMENTS as one quoted word so a path with spaces survives the shell,
|
|
371
|
+
// so everything after --dir is the path, whether it arrives as one argv entry or several.
|
|
372
|
+
export function parseArgs(argv) {
|
|
373
|
+
const m = argv.join(' ').match(/(?:^|\s)--dir\s+(.+)$/);
|
|
374
|
+
if (!m) return { dir: undefined };
|
|
375
|
+
return { dir: m[1].trim().replace(/^(["'])(.*)\1$/, '$2') };
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
async function main() {
|
|
379
|
+
try {
|
|
380
|
+
const { dir } = parseArgs(process.argv.slice(2));
|
|
381
|
+
process.stdout.write(`${await run({ dir, root: projectRoot() })}\n`);
|
|
382
|
+
} catch (e) {
|
|
383
|
+
process.stdout.write(`cc-metrics: failed: ${(e && e.message) || e}\n`);
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) main();
|