@yeison.restrepo.r/code-conductor 1.42.0 → 1.44.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -263,6 +263,7 @@ All commands are tagged `(Conductor)` in the Claude Code command palette, so the
263
263
  | `/cc-test [scope]` | Find coverage gaps, write AAA-pattern tests (plus Playwright E2E where applicable), run after confirmation, and report results. |
264
264
  | `/cc-docs [scope]` | Audit documentation, write inline docs in your stack's format (JSDoc / docstrings / Javadoc / GoDoc), and preview before writing. |
265
265
  | `/cc-metrics [--dir <path>]` | Read-only report of token and time spend from Claude Code's local session logs, grouped by tool, command, phase, branch, pillar and session, with recommendations that quote the numbers they rest on. Registers no hook and writes no file. |
266
+ | `/cc-flow` | Print the guard lanes with per-guard pass, deny and ask counts, then the newest 20 hook decisions. See [Flow status](#flow-status). |
266
267
 
267
268
  ---
268
269
 
@@ -295,7 +296,7 @@ Hooks run automatically at specific points in a Claude Code session and need no
295
296
  | **1: Large-file read** | `Read` | A file over 150 lines needs an explicit `limit`; otherwise denied with a redirect to memory, grep, then a bounded read. |
296
297
  | **2: Duplicate write** | `Write`, `create_file`, `write_file` | Writing to an existing path asks first, showing the path, line count, and last-modified time: edit in place, confirm the overwrite, or cancel. `Edit` is deliberately not gated, because editing in place is what this guard recommends. |
297
298
  | **3: Bash scan** | `Bash` | Twelve mass content-dump patterns denied before execution. Commands over 8192 characters, and commands with unclosed quotes, are denied fail-closed. |
298
- | **4: node_modules** | `Read` | A path carrying `node_modules` as an exact path component is denied, with backslashes and `..` resolved first. Use Glob for existence checks. |
299
+ | **4: node_modules** | `Read` | A path carrying `node_modules` as an exact path component is denied, with backslashes and `..` resolved first. Use Glob for existence checks. `.claude/.flow-events.jsonl` is denied too: see [Flow status](#flow-status). |
299
300
  | **5: Band scope** | role-agent writes | During orchestration, a band role can only write inside its installed envelope's scope. |
300
301
  | **6: Orchestrator writes** | live orchestrate runs | The orchestrator session can only write its own run-state surface; nested agent dispatch is denied. |
301
302
  | **7: Role shell** | role-agent `Bash` | `spec`, `plan` and `audit` get no shell; `code` and `qa` may run exactly one command, the recorded test command, byte for byte, no chaining. |
@@ -314,6 +315,16 @@ Hit a block you believe is wrong? Re-run the command with `CC_GUARD3_WARN=1` and
314
315
 
315
316
  **Unparseable input fails closed.** It is denied with one stderr line naming `CC_HOOK_ALLOW=1`, which overrides that denial alone and leaves every guard fully active on every payload the hook can read. Set `CC_HOOK_DEBUG=1` to see the diagnostic lines it otherwise swallows.
316
317
 
318
+ ### Flow status
319
+
320
+ After each decision is written, the pre-tool-use hook appends one JSON line to `.claude/.flow-events.jsonl`: the tool, the verdict, the deciding guard and its reason code, the guards that passed before it, and a short target (a path relative to the project, an agent type, or the first word of a Bash command after any `VAR=value` words, never the full command; quotes are honored when finding that word, and an unclosed quote or a `$( )`, backtick or `${ }` substitution among those words records an empty target instead of a guess). The file is capped at about 160 KiB and rotated to its last 250 lines, it is git-ignored by the managed `.gitignore` block, and Guard 4 keeps the agent from reading it into context. Writing it can never block or change a tool call: any error is swallowed.
321
+
322
+ - **Status line.** `--project` sets `"statusLine": {"type": "command", "command": "node .claude/flow-status.mjs"}` in `.claude/settings.json`. It shows one line below the prompt for the current session, for example `⛔ G3 P9 · 12 calls · 3 deny` after a denial or `✓ 12 calls · 3 deny` after an allow. Claude Code refreshes it when a new assistant message arrives, not on every tool call.
323
+ - **`/cc-flow`.** Prints one lane per tool family with each guard's pass, deny and ask counts, then the newest 20 events.
324
+ - **What Guard 4 covers.** It denies the `Read` tool on `.claude/.flow-events.jsonl` and on rotation's `.flow-events.jsonl.tmp`. A plain `cat .claude/.flow-events.jsonl` through Bash is not caught: Guard 3 looks for mass-dump shapes, not this file's name.
325
+ - **`CC_FLOW_OFF=1`** stops the hook from writing events; the status line goes blank and `/cc-flow` says the log is off.
326
+ - **An existing status line wins.** If your project or user `settings.json` already has a `statusLine`, the installer leaves both files untouched and prints a line saying the flow status line was skipped; `/cc-flow` still works, and you can set the entry above by hand. An entry whose command names `flow-status.mjs` is treated as the installer's own and kept current.
327
+
317
328
  ### The other hooks
318
329
 
319
330
  - **context-guard** (project). Fires on every `UserPromptSubmit` and atomically increments a turn counter in `.claude/memory/turn-count.txt`. At 80% of the threshold it emits a CONTEXT WARNING; at or above the threshold, CONTEXT CRITICAL. The threshold is read from `.claude/memory/context-threshold.txt` (default 25). Ships for Unix (`context-guard.sh`) and Windows (`context-guard.ps1`). `CC_GUARD_DEBUG=1` prints debug info to stderr; `CC_PROJECT_ROOT` overrides the project root used for the memory directory.
@@ -371,9 +382,10 @@ By default, only the global core files are installed. Flags extend that:
371
382
 
372
383
  | Flag | Description |
373
384
  |---|---|
374
- | `--project` | Also install the project template into the current directory |
385
+ | `--project` / `-Project` | Also install the project template into the current directory |
375
386
  | `--no-deps` / `-NoDeps` | Accepted for compatibility with the retired shell installers; a no-op, since the npm CLI installs no dependencies and copies agent files only |
376
- | `--verbosity MIN\|INFO\|VERBOSE` | Default response verbosity (default `MIN`). `MIN` = one sentence per response, `INFO` = bullet list, `VERBOSE` = full explanation. Re-run the installer to change it. |
387
+ | `--verbosity MIN\|INFO\|VERBOSE` / `-Verbosity LEVEL` | Default response verbosity (default `MIN`). `MIN` = one sentence per response, `INFO` = bullet list, `VERBOSE` = full explanation. Re-run the installer to change it. PowerShell's `-Verbosity:INFO` form is not supported; it warns and the level stays `MIN`. |
388
+ | `--opencode` | With `--project`, also install the OpenCode guard plugin at `.opencode/plugin/conductor-guard.js` (see [OpenCode](#opencode)). Without `--project` it warns and writes nothing for OpenCode |
377
389
 
378
390
  **Updating:** re-run the same install command. User-configured files are never overwritten; agent-managed files are always updated.
379
391
 
@@ -382,13 +394,36 @@ Two cautions:
382
394
  - Do **not** clone this repository under a directory named `node_modules`. Guard 4 checks path components and will block agent `Read` calls on its source files.
383
395
  - `--project` refuses to run in a directory whose `package.json` names this package, such as a clone of this repository (`[BUG-052]`, fixed in `1.39.1`): the installer exits 1 before writing anything, global half included, because its project half would land on its own source tree.
384
396
 
397
+ ### OpenCode
398
+
399
+ `--project --opencode` adds one file, `.opencode/plugin/conductor-guard.js`, an [OpenCode](https://opencode.ai) plugin. It does not copy the guard: before each `bash`, `read`, `write`, `edit`, `multiedit` or patch call it sends the call to the project's own `.claude/hooks/pre-tool-use.mjs`, in the payload Claude Code sends, and blocks the call when the guard denies it. Read-only tools pass, and every other tool is blocked, because the guard cannot inspect it. A Claude Code install without the flag is unchanged.
400
+
401
+ This is the first slice of `[FEAT-048]` (issue #97), and it covers enforcement only:
402
+
403
+ | On OpenCode | Status |
404
+ |---|---|
405
+ | Guards 1, 2, 3 and 4 | Enforced. Guard 2's "file already exists" question blocks the write, because a plugin cannot ask you; the model is told to edit instead |
406
+ | Guards 5, 6 and 7 (band roles, orchestrator run) | Not enforced for subagents: OpenCode does not tell the plugin which subagent made the call |
407
+ | Guard warnings | Not shown |
408
+ | `patch`/`apply_patch`, `multiedit` | Sent to the guard; a patch is checked file by file, confined to the project, under a strict marker grammar |
409
+ | `task`, `batch`, MCP and any other tool | Blocked: the guard cannot inspect them |
410
+ | `glob`, `grep`, `list`, `webfetch`, `websearch`, `codesearch` and other read-only tools | Allowed, as on Claude Code |
411
+ | `cc-*` commands, band agents, verbosity and context hooks | Not installed for OpenCode yet. OpenCode reads `CLAUDE.md` when there is no `AGENTS.md`, and loads `.claude/skills` |
412
+
413
+ The plugin needs `node` on `PATH`. If the guard cannot run, the call is blocked and the reason names the guard's path. Checked against OpenCode 1.18.33 during the proof of concept; Codex CLI and Antigravity are not supported yet.
414
+
385
415
  ### How the installer treats your CLAUDE.md
386
416
 
387
417
  `CLAUDE.md` and `.gitignore` are **merged**, never overwritten. Everything else the installer ships (`settings.json`, hooks, commands, `scripts/`) is replaced on every run.
388
418
 
389
419
  - **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.
390
420
  - **Everything outside the block is yours, byte for byte.** Nothing outside it is removed, rewritten, reordered or added.
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]`.
421
+ - **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.
422
+ - 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; `/cc-stack` offers to reconcile them (FEAT-040).
423
+ - The model only classifies each of your sections into a slot (identity, commands, architecture, conventions, out-of-scope, or keep), a script renders the whole resulting file, and you see it in full. Nothing is written unless you approve that exact render: the script writes only when handed the sha256 token of the render you were shown, so any other result is refused.
424
+ - Your file is first copied to `CLAUDE.md.installer-backup.<UTC timestamp>` and the path is printed.
425
+ - The managed block is never rewritten, unmapped sections stay byte for byte, and declining changes nothing.
426
+ - The offer is repeated on every run for any file that still holds content other than conductor's own scaffold, including one you already adopted; only a scaffold-only file is excluded. Say no, or keep every section, and nothing changes.
392
427
  - **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:
393
428
 
394
429
  ```
@@ -455,7 +490,6 @@ The backup and temp rules keep the installer's own backups and crash-stranded te
455
490
  - Installing or updating copies `.claude/agents/{spec,plan,code,audit,qa,define-review}.md` over the host project's files of the same names, as it does every shipped `.claude/` asset.
456
491
  - A gate certifies protocol position and the claim its role states, never the truth of the work beyond that claim.
457
492
  - **The review loop (`1.39.0`) is process discipline.** The spec or plan envelope stays installed after its hand-back, so the role can revise. Outside a round, its writes are bounded by its tool mask, Guard 5's scope, the re-hash before `approve`, and your review. Gating Guard 5 on an open round is a follow-up candidate.
458
- - **`[BUG-055]`, open:** detect-stack exits 0 with `{}` when a truthy non-string `package.json` `description`, or a truthy non-string script with no detector matched, crashes it; when a detector matches, a non-string script or `name` passes through raw. Until it is fixed, keep `name`, `description` and the `build`/`test`/`lint`/`format` scripts as strings, or `/cc-stack` reports no stack.
459
493
  - **`[BUG-056]`, open:** the context-guard turn counter persists across sessions — only `/compact`'s PostCompact hook resets `.claude/memory/turn-count.txt` — so a fresh session inherits the previous session's count and can show the CONTEXT WARNING or CRITICAL banner on its first prompt. Until it is fixed, delete that file when starting a fresh session, or disregard a banner that appears before the session has done any work.
460
494
  - **`[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.
461
495
  - **`[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.
@@ -470,11 +504,12 @@ The backup and temp rules keep the installer's own backups and crash-stranded te
470
504
 
471
505
  ## Instruments: releases that verify their own record
472
506
 
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:
507
+ Five checks live in `tools/` as tracked repository infrastructure. Three of them run in full on every pull request, and a fourth, `records-guard.mjs`, on every pull request not opened by the owner, so a divergence blocks the merge rather than waiting for someone to remember; the fifth, `id-ceiling.mjs`, runs its duplicate-free half on every pull request too, and its ceiling query by hand before each mint:
474
508
 
475
509
  - **`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.
476
510
  - **`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.
477
511
  - **`skip-baseline.mjs`** asserts each CI leg's exact skipped-test set against `tools/skip-baseline.json`, where every set is copied from that leg's own run rather than typed. It runs directly in `.github/workflows/test.yml` on the Node 20 and Node 24 legs, after the suite. It exists because CI was green with 96 tests skipped on Node 20 against 12 locally, and nothing asserted either number.
512
+ - **`records-guard.mjs`** compares the owner-side records between a pull request's base and head by parsed value, not by line: the `VERSION` content, the `package.json` and `package-lock.json` root versions, the set of `CHANGELOG.md` release headings, and the backlog's heading states and DONE lines. A dependency bump, an `[Unreleased]` entry or a new open item passes. It runs in `.github/workflows/records-guard.yml` on every pull request not opened by the repository owner. It exists because PR #59 shipped release records from a contributor branch and only a human reviewer caught it.
478
513
  - **`id-ceiling.mjs`** reports the highest filed id over the working tree **union** `origin/main`, counting only filed headings. Its predecessor counted id-shaped tokens anywhere, so it once read a plan file's prediction of its own output back as evidence. It is local-only by ruling: a person or agent runs it, over both legs, before minting an id. Its remote leg needs history the CI checkout does not fetch, so CI asserts only its duplicate-free half.
479
514
 
480
515
  **The example worth checking.** `[BUG-046]`'s own release ran those instruments against itself, then proved the green rather than trusting it: with the item's backlog heading deliberately flipped to `[ ]`, `record-parity` reported `FAIL [A] 1.32.2 claims BUG-046 but its heading reads [ ]` once per claim bullet and exited 1; flipped back, `RECORD_PARITY_OK`. The first release whose record cannot silently diverge is the release that made divergence detectable.
@@ -518,6 +553,7 @@ code-conductor/
518
553
  +-- project-template/
519
554
  | +-- CLAUDE.md
520
555
  | +-- gitignore Merged into the host project's .gitignore
556
+ | +-- .opencode/plugin/conductor-guard.js OpenCode guard plugin, only with --opencode (FEAT-048)
521
557
  | +-- .claude/
522
558
  | +-- settings.json Hooks wiring
523
559
  | +-- review-loop.settings.json Auto mode exception for the review loop (FEAT-041)
@@ -8,7 +8,12 @@ import { verbosityHookCommand, mergeVerbosityHook } from '../lib/installer/setti
8
8
  import { healGraphifyHook } from '../lib/installer/heal.mjs';
9
9
  import { writeVerbosity, writeVersionFile } from '../lib/installer/config.mjs';
10
10
 
11
- const USAGE = `Usage: code-conductor [--project] [--no-deps|-NoDeps] [--verbosity MIN|INFO|VERBOSE] [--version] [--help]`;
11
+ const USAGE = `Usage: code-conductor [--project|-Project] [--no-deps|-NoDeps] [--verbosity|-Verbosity MIN|INFO|VERBOSE] [--opencode] [--version] [--help]`;
12
+
13
+ // -Verbosity is the spelling the retired install.ps1 documented. Both spellings share
14
+ // every form (space-separated, inline `=`, missing value) and last-wins across them.
15
+ const VERBOSITY_FLAGS = ['--verbosity', '-Verbosity'];
16
+ const isVerbosityFlag = (a) => VERBOSITY_FLAGS.some((f) => a === f || a.startsWith(`${f}=`));
12
17
 
13
18
  // Hand-rolled parser (five flags only). Deliberately NOT node:util's parseArgs —
14
19
  // the CLI honors the zero-runtime-dependency rule and node:util adds no value for
@@ -18,22 +23,26 @@ const USAGE = `Usage: code-conductor [--project] [--no-deps|-NoDeps] [--verbosit
18
23
  // is idempotent. No "conflicting flags" error is raised — last-wins is the least
19
24
  // surprising CLI convention and keeps the parser branchless.
20
25
  function parseArgs(argv) {
21
- const opts = { project: false, noDeps: false, verbosity: undefined, verbosityGiven: false, version: false, help: false, unknown: [] };
26
+ const opts = { project: false, opencode: false, noDeps: false, verbosity: undefined, verbosityGiven: false, version: false, help: false, unknown: [] };
22
27
  for (let i = 0; i < argv.length; i++) {
23
28
  const a = argv[i];
24
- if (a === '--project') opts.project = true;
29
+ // -Project is the spelling the retired install.ps1 documented; matched exact-case
30
+ // like every other flag here.
31
+ if (a === '--project' || a === '-Project') opts.project = true;
25
32
  // Accepted no-op: the npm CLI installs no dependencies since FEAT-023 removed the
26
33
  // shell installers, so there is nothing to skip. Recognized so callers carried over
27
34
  // from install.sh get no misleading "unrecognized" warning.
28
35
  else if (a === '--no-deps' || a === '-NoDeps') opts.noDeps = true;
29
- else if (a === '--verbosity' || a.startsWith('--verbosity=')) {
36
+ // FEAT-048: also install the OpenCode guard plugin; meaningful only with --project.
37
+ else if (a === '--opencode') opts.opencode = true;
38
+ else if (isVerbosityFlag(a)) {
30
39
  opts.verbosityGiven = true;
31
- if (a.startsWith('--verbosity=')) {
40
+ if (a.includes('=')) {
32
41
  // Inline form: --verbosity=INFO. Empty (`--verbosity=`) leaves value ''.
33
42
  // Surrounding whitespace (e.g. a quoted `--verbosity= VERBOSE `) is NOT
34
43
  // stripped here — normalizeVerbosity() trims before matching, so whitespace
35
44
  // is tolerated and a whitespace-only/`=`-only value normalizes to null → MIN+warn.
36
- opts.verbosity = a.slice('--verbosity='.length);
45
+ opts.verbosity = a.slice(a.indexOf('=') + 1);
37
46
  } else {
38
47
  // Space-separated form: consume the next token only if it is a real value,
39
48
  // not another flag or the end of argv (`--verbosity` passed last). A missing
@@ -74,6 +83,7 @@ export function run(argv, env = process.env, { cwd = process.cwd(), log, nodeVer
74
83
  const opts = parseArgs(argv);
75
84
 
76
85
  if (opts.unknown.length) emit('stderr', `code-conductor: ignoring unrecognized argument(s): ${opts.unknown.join(' ')}`);
86
+ if (opts.opencode && !opts.project) emit('stderr', 'code-conductor: --opencode needs --project; no OpenCode files were written');
77
87
 
78
88
  // --help and --version are explicit informational OUTPUT (not diagnostics), so they
79
89
  // go to STDOUT and exit 0 — this lets `code-conductor --version` be captured in a
@@ -110,7 +120,7 @@ export function run(argv, env = process.env, { cwd = process.cwd(), log, nodeVer
110
120
  if (heal.status === 'removed') emit('stdout', 'code-conductor: removed the retired graphify-ast-refresh hook from settings.json (backup written beside it)');
111
121
  for (const line of heal.lines) emit('stderr', `code-conductor: ${line}`);
112
122
  writeVersionFile(home, pkgVersion(assetRoot));
113
- if (opts.project) deployProject(assetRoot, cwd, { warn: (m) => emit('stderr', m), report: (m) => emit('stdout', m) });
123
+ if (opts.project) deployProject(assetRoot, cwd, { warn: (m) => emit('stderr', m), report: (m) => emit('stdout', m), home, opencode: opts.opencode });
114
124
  return 0;
115
125
  } catch (err) {
116
126
  // Pre-flight failures (nothing written yet) → exit 1.
@@ -13,7 +13,7 @@ Collect from the current conversation context:
13
13
  - **Files Touched** (`ops.f`): each entry `<relpath>:C|M|D` (uppercase only); replace any backslash in the path with `/`; if the path contains a literal `:`, percent-encode it as `%3A` before appending the suffix; max 20 elements, each ≤300 chars
14
14
  - **Constraints** (`mem.x`): hard constraints next phase must respect, max 5 elements, each ≤200 chars
15
15
 
16
- For all four array fields: filter out empty/whitespace-only strings, deduplicate by exact case-sensitive string equality (first occurrence wins), then truncate each surviving element to its per-element cap (Unicode-safe: `Array.from(str).slice(0, cap).join('')`), then if the array still exceeds its cap, drop from the **head** (oldest first) until it fits. Empty arrays are valid and must still be serialized (never omitted).
16
+ For all four array fields: filter out empty/whitespace-only strings, deduplicate by exact case-sensitive string equality (first occurrence wins), then truncate each surviving element to its per-element cap (`snap-build` does the cut, to the cap measured as JSON-escaped length, never splitting a character; an over-cap `ops.f` entry keeps its `:C`/`:M`/`:D` suffix and loses path, and one with no such suffix is refused with `SNAP_FILE_NO_ACTION`), then if the array still exceeds its cap, drop from the **head** (oldest first) until it fits. Empty arrays are valid and must still be serialized (never omitted).
17
17
 
18
18
  Serialize by piping a flat JSON object `{ph, c, s, n, f, d, x}` (no `pr`) on **stdin** to `node .claude/scripts/snap-build.mjs`; its stdout is the canonical single-line **v1** SNAP JSON. `snap-build` performs all array normalization (filter/dedup/per-element cap/head-drop) and the 4096-char size trim internally — do not pre-serialize. If `snap-build` exits non-zero (malformed field object), report the error and stop; do not write the handoff file, do not run the DB tail, do not print the compact prompt.
19
19
 
@@ -34,10 +34,23 @@ If the root `CLAUDE.md` does not exist, do not create it: instruct the user to r
34
34
 
35
35
  Otherwise read `CLAUDE.md` and look for the `- Stack:` line under `## Project Identity`:
36
36
  - **Stack line present and non-empty** -> ask: `I see you're using [stack]. Has anything changed?` This is a blocking yes/no prompt with no timeout.
37
- - `no` -> acknowledge in one line and stop; make no edits.
37
+ - `no` -> acknowledge in one line, run sub-step 5a′ (additive: the only edit this path may make, Ruling 1), and stop.
38
38
  - `yes`, or free text describing a change -> re-run the detector (step 3) and rewrite the managed sections from the fresh output. Free text is an additive hint only: fold user-named tools the detector missed into the ruleset, but detected facts always win on conflict.
39
39
  - **`## Project Identity` missing, or present without a `- Stack:` line** -> treat as "no recorded stack" (not an error). Proceed to the write path; append the `## Project Identity` header if absent, or surgically insert the `- Stack:` line if only that line is missing. Note in one line that a fresh stack identity was recorded.
40
40
 
41
+ ### 4b. Adopt a host-authored CLAUDE.md (FEAT-040)
42
+
43
+ Run once, before step 5, and only when the file holds content conductor did not write. Resolve the helper by presence, the deployed copy first: `A=.claude/scripts/adopt-claude-md.mjs; [ -f "$A" ] || A=scripts/adopt-claude-md.mjs`. If neither exists, skip 4b silently.
44
+
45
+ 1. Run `node "$A" sections CLAUDE.md`. If it prints `"trigger": false`, or exits non-zero (unbalanced sentinels, unclosed fence), skip 4b. A scaffold-only file never triggers.
46
+ 2. Classify each listed section into exactly one slot: `identity`, `commands`, `architecture`, `conventions`, `out-of-scope` or `keep`. When unsure, use `keep`. Write a plan file `{"<section id>": "<slot>"}`. You classify only; you never edit text.
47
+ 3. Run `node "$A" render CLAUDE.md <plan>`. Show the owner the **full resulting file** (stdout) and the approval token (stderr), naming any duplicate headings it reconciles.
48
+ 4. Ask: `Adopt this result? (yes/no)`. This is a blocking prompt with no timeout. Only an explicit `yes` to that exact render counts; if the owner wants a change, redo steps 2-3 and show the new render.
49
+ 5. On `yes`, run `node "$A" apply CLAUDE.md <plan> <token>` and announce the backup path it prints. The helper refuses a token that does not match the render, so nothing unshown is written.
50
+ 6. On `no`, or anything else, write nothing: the file stays exactly as the installer left it. Continue with step 5 either way.
51
+
52
+ The managed block is copied verbatim and unmapped content is kept byte for byte; adoption only moves host sections.
53
+
41
54
  ## 5. Write path
42
55
 
43
56
  Detect and preserve `CLAUDE.md`'s dominant EOL style (LF or CRLF); never convert wholesale. If the OS denies the write or the file is locked, abort that write with a single-line error naming the path and cause (e.g. `ERROR: cannot write CLAUDE.md: permission denied - no changes applied`), leave the file byte-for-byte untouched, and still report the detection result.
@@ -46,6 +59,23 @@ Detect and preserve `CLAUDE.md`'s dominant EOL style (LF or CRLF); never convert
46
59
 
47
60
  For each of `Build`, `Test`, `Lint`, `Format`, `Setup`, if the detector JSON has a non-empty string for the matching key (`build`, `test`, `lint`, `format`, `setup`), replace that single line under `## Development Commands` with `- <Label>: <value>`. Edit one field line at a time (BUG-003). If a key is absent, leave the existing placeholder (e.g. `<command>` or `N/A`) unchanged - never fabricate a command. Also set the `- Stack:` line under `## Project Identity` from the `stack` key (or record the stack name derived from detection). If `## Development Commands` is absent, append the header and its five fields at the end of the file.
48
61
 
62
+ ### 5a′. Spec and plan folders (FEAT-047)
63
+
64
+ Act only when both `- Specs:` and `- Plans:` are absent under `## Development Commands`. Existing lines are never rewritten.
65
+
66
+ 1. **Neither line present.** Resolve the location resolver by presence, the deployed copy first, and run `node "$L"` from the repo root:
67
+
68
+ ```bash
69
+ L=.claude/scripts/doc-locations.mjs; [ -f "$L" ] || L=scripts/doc-locations.mjs
70
+ ```
71
+
72
+ 2. **Success.** Accept the output only when the exit code is 0 and stdout parses as a JSON object whose `specs` and `plans` are non-empty strings. Insert `- Specs: <specs>` and then `- Plans: <plans>` after the last field line under `## Development Commands`, one surgical edit per line (BUG-003). If the header is absent, append both lines together with the five fields. Announce the recorded pair and its `source`.
73
+ 3. **Failure.** If `L` is missing at both paths, the run exits non-zero, or stdout is empty, not JSON, or lacks either string, write nothing and announce `Spec/plan folders not recorded: <cause>; start will discover them per run`. 5b and 6 continue.
74
+ 4. **Exactly one line present.** Write nothing and do not run the CLI; this step never fills the missing half from discovery. Announce: `CLAUDE.md records - Specs: but not - Plans: (or the reverse); add the missing line by hand, or remove both and re-run /cc-stack. /cc-orchestrate start halts ORCH_DOC_LOCATION_INVALID until then.`
75
+ 5. **Both lines present.** Do nothing, whatever the values; an invalid recorded value is the owner's to fix, and `start` names it.
76
+
77
+ The EOL rule of step 5 applies to every edit here.
78
+
49
79
  ### 5b. Active Stack Profiles (whole-block regeneration)
50
80
 
51
81
  Regenerate the entire body between the `## Active Stack Profiles` header and the next `##` (or end of file). If the header is absent, append it at the end of the file - never insert mid-document. The block is bounded and its prior content is fully replaced, not merged; all content outside it is preserved verbatim.
@@ -1,9 +1,11 @@
1
1
  import { cpSync, mkdirSync, chmodSync, existsSync, lstatSync, readdirSync, readFileSync, statSync, rmSync, unlinkSync } from 'node:fs';
2
2
  import { join, relative, isAbsolute, sep } from 'node:path';
3
+ import { createHash } from 'node:crypto';
3
4
  import { mergeFileInto, resolveRealTarget } from './file-merge.mjs';
4
5
  import { mergeClaudeMdText, mergeGitignoreText } from './merge-md.mjs';
5
6
  import { GLOBAL_HOST_OWNED, PROJECT_HOST_OWNED, GLOBAL_SETTINGS_FINGERPRINTS, PROJECT_SETTINGS_FINGERPRINTS, hostOwnedFilter, seedHostOwned } from './host-owned.mjs';
6
7
  import { mergeSettingsFile } from './settings-merge.mjs';
8
+ import { mergeFlowStatusLine, FLOW_STATUS_COMMAND } from './settings.mjs';
7
9
 
8
10
  // Host-authored data, not managed assets: these are merged, never force-copied —
9
11
  // everything else in the template keeps its overwrite. Keyed by the name the file
@@ -23,6 +25,7 @@ const MERGED_ROOT_FILES = new Map([
23
25
  // path here; the option is set only to guarantee that a symlink accidentally added
24
26
  // later is copied as a link (never followed into user content), not resolved.
25
27
  const CP_OPTS = { recursive: true, force: true, dereference: false };
28
+ const OPENCODE_DIR = '.opencode';
26
29
 
27
30
  // One stdout line per backup, because the backup is git-ignored by the managed
28
31
  // block and would otherwise be invisible (BUG-049). A backup outside `root` (a
@@ -154,14 +157,24 @@ function sweepStaleRootScripts(assetRoot, cwd) {
154
157
  // host's own history, with new failure modes (detached HEAD, shallow clone,
155
158
  // submodule, dirty index, no git at all) for a path that fires in one narrow
156
159
  // case. Print the two commands and write nothing.
160
+ // (#94) Those releases wrote the stub as it stood at b018793, which carried
161
+ // code-conductor's own history. The neutral stub replaced it, so the old bytes are
162
+ // recognized by digest rather than re-shipped.
163
+ export const LEGACY_PROJECT_MEMORY_STUB_SHA256 = '01e65fdecfd0a842dc1269cb0a5ff59718978830c94d5815b09c3a0454f261f9';
164
+
157
165
  function warnIfProjectMemoryIsStub(templateClaude, target, emit) {
158
166
  const rel = '.claude/memory/project.md';
159
167
  const stub = join(templateClaude, 'memory', 'project.md');
160
168
  const host = join(target, 'memory', 'project.md');
161
- if (!existsSync(stub) || !existsSync(host)) return false;
162
- if (readFileSync(host, 'utf8') !== readFileSync(stub, 'utf8')) return false;
169
+ if (!existsSync(host)) return false;
170
+ const text = readFileSync(host, 'utf8');
171
+ const isCurrentStub = existsSync(stub) && text === readFileSync(stub, 'utf8');
172
+ // The digest is of the LF bytes; an autocrlf=true clone wrote the stub as CRLF.
173
+ const lf = text.replace(/\r\n/g, '\n');
174
+ const isLegacyStub = createHash('sha256').update(lf).digest('hex') === LEGACY_PROJECT_MEMORY_STUB_SHA256;
175
+ if (!isCurrentStub && !isLegacyStub) return false;
163
176
  emit([
164
- `code-conductor: ${rel} matches the bundled stub; it may have been overwritten by an installer re-run before 1.30.0.`,
177
+ `code-conductor: ${rel} matches a bundled stub; it may have been overwritten by an installer re-run before 1.30.0.`,
165
178
  ` Find a committed copy: git log --oneline -- ${rel}`,
166
179
  ` Restore it: git checkout <commit> -- ${rel}`,
167
180
  ].join('\n'));
@@ -195,7 +208,37 @@ function packageName(path) {
195
208
  try { return JSON.parse(text).name ?? null; } catch { return null; }
196
209
  }
197
210
 
198
- export function deployProject(assetRoot, cwd, { warn = toStderr, report = toStdout } = {}) {
211
+ // One line per outcome of the flow status line merge. 'unchanged' has none, so a re-run of
212
+ // an unchanged release stays as quiet as every other managed file.
213
+ // The replaced line names the entry it overwrote, so a host who hand-tuned it can restore it.
214
+ const FLOW_STATUS_REPORT = {
215
+ added: () => `code-conductor: added the flow status line to .claude/settings.json (${FLOW_STATUS_COMMAND})`,
216
+ replaced: (previous) =>
217
+ `code-conductor: updated the flow status line in .claude/settings.json to ${FLOW_STATUS_COMMAND} ` +
218
+ `(replaced ${JSON.stringify(previous)})`,
219
+ 'host-skipped': () =>
220
+ 'code-conductor: kept your existing statusLine, so the flow status line was skipped (/cc-flow still works). ' +
221
+ `To use it, set "statusLine": {"type": "command", "command": "${FLOW_STATUS_COMMAND}"} in .claude/settings.json`,
222
+ 'malformed-skipped': () =>
223
+ 'code-conductor: .claude/settings.json is not valid JSON; it was backed up and left as is, so the flow status line was not added',
224
+ 'unreadable-skipped': () => 'code-conductor: .claude/settings.json could not be read, so the flow status line was not added',
225
+ };
226
+
227
+ // Only when the template ships the script the entry points at: a statusLine naming a
228
+ // missing file would blank the host's line for nothing. Runs after mergeSettingsFile, so
229
+ // it sees the settings.json that merge leaves behind.
230
+ function mergeFlowStatus(templateClaude, target, home, report) {
231
+ if (!existsSync(join(templateClaude, 'flow-status.mjs'))) return;
232
+ const userPath = home ? join(home, '.claude', 'settings.json') : null;
233
+ const { status, previous } = mergeFlowStatusLine(join(target, 'settings.json'), userPath);
234
+ if (FLOW_STATUS_REPORT[status]) report(FLOW_STATUS_REPORT[status](previous));
235
+ }
236
+
237
+ // `home` is where the user-level settings.json lives, consulted only by the flow status
238
+ // line rule. A caller that passes none gets the project-level check alone.
239
+ // `opencode` opts into the OpenCode guard plugin (FEAT-048); without it the template's
240
+ // .opencode/ entry is skipped, so a Claude Code install is unchanged byte for byte.
241
+ export function deployProject(assetRoot, cwd, { warn = toStderr, report = toStdout, home = null, opencode = false } = {}) {
199
242
  const emit = warn;
200
243
  // Also run by the CLI's pre-flight; kept here for direct callers.
201
244
  assertNotSelfInstall(assetRoot, cwd);
@@ -217,7 +260,9 @@ export function deployProject(assetRoot, cwd, { warn = toStderr, report = toStdo
217
260
  cpSync(templateClaude, target, { ...CP_OPTS, filter: hostOwnedFilter(templateClaude, PROJECT_HOST_OWNED) });
218
261
  for (const name of readdirSync(templateRoot)) {
219
262
  if (name === '.claude' || MERGED_ROOT_FILES.has(name)) continue;
263
+ if (name === OPENCODE_DIR && !opencode) continue;
220
264
  cpSync(join(templateRoot, name), join(cwd, name), CP_OPTS);
265
+ if (name === OPENCODE_DIR) report(`code-conductor: installed the OpenCode guard plugin at ${OPENCODE_DIR}/plugin/conductor-guard.js`);
221
266
  }
222
267
  for (const [source, { target: dest, merge }] of MERGED_ROOT_FILES) {
223
268
  mergeFileInto(join(templateRoot, source), join(cwd, dest), merge, {
@@ -233,12 +278,20 @@ export function deployProject(assetRoot, cwd, { warn = toStderr, report = toStdo
233
278
  mkdirSync(join(target, 'memory'), { recursive: true });
234
279
  seedHostOwned(templateClaude, target, PROJECT_HOST_OWNED);
235
280
  mergeSettingsFile(join(templateClaude, 'settings.json'), join(target, 'settings.json'), PROJECT_SETTINGS_FINGERPRINTS);
281
+ mergeFlowStatus(templateClaude, target, home, report);
236
282
  // scripts/ is a sibling of project-template/ under assetRoot (source layout),
237
283
  // but is deployed as a CHILD of .claude/ (target) - it must stay inside the
238
284
  // project's self-contained .claude footprint, not spill into the host's own
239
285
  // project root where it could collide with a scripts/ dir the host already owns.
240
286
  sweepStaleRootScripts(assetRoot, cwd);
241
287
  cpSync(join(assetRoot, 'scripts'), join(target, 'scripts'), CP_OPTS);
288
+ // adopt-claude-md.mjs imports ../lib/installer/merge-md.mjs; from .claude/scripts that
289
+ // resolves here. A pure string engine, so a copy cannot drift in behavior (FEAT-040).
290
+ const engine = join(assetRoot, 'lib', 'installer', 'merge-md.mjs');
291
+ if (existsSync(engine)) {
292
+ mkdirSync(join(target, 'lib', 'installer'), { recursive: true });
293
+ cpSync(engine, join(target, 'lib', 'installer', 'merge-md.mjs'), CP_OPTS);
294
+ }
242
295
  return target;
243
296
  }
244
297
 
@@ -111,8 +111,10 @@ export function mergeSettingsFile(templatePath, settingsPath, fingerprints, { no
111
111
 
112
112
  const text = `${JSON.stringify(merged, null, 2)}\n`;
113
113
  // Skipping an identical write is what makes a re-run of an unchanged release
114
- // byte-identical AND leaves the file's mtime alone.
115
- if (text === raw) return 'unchanged';
114
+ // byte-identical AND leaves the file's mtime alone. The host's line endings
115
+ // are not content: a CRLF file (a Windows autocrlf checkout, or an editor's
116
+ // choice) that matches after normalizing is left as it is.
117
+ if (text === raw.replace(/\r\n/g, '\n')) return 'unchanged';
116
118
  writeAtomic(target.realPath, text);
117
119
  return 'merged';
118
120
  }
@@ -95,3 +95,63 @@ function mergeHook(settingsPath, hookCmd, fingerprint, now) {
95
95
  export function mergeVerbosityHook(settingsPath, hookCmd, now = new Date()) {
96
96
  return mergeHook(settingsPath, hookCmd, FINGERPRINT, now);
97
97
  }
98
+
99
+ // FEAT-044: the flow status line. The fingerprint names the entry this repo OWNS, exactly
100
+ // as FINGERPRINT does for the verbosity hook.
101
+ export const FLOW_STATUS_FINGERPRINT = 'flow-status.mjs';
102
+ export const FLOW_STATUS_COMMAND = 'node .claude/flow-status.mjs';
103
+
104
+ // { obj } when the file parses to an object, { missing } when absent, { malformed } when
105
+ // it holds something else, { unreadable } when it cannot be read at all.
106
+ function readSettingsObject(path) {
107
+ let raw;
108
+ try { raw = readFileSync(path, 'utf8'); }
109
+ catch (e) { return e.code === 'ENOENT' ? { missing: true } : { unreadable: true }; }
110
+ if (raw.trim() === '') return { obj: {} };
111
+ try {
112
+ const obj = JSON.parse(raw);
113
+ return obj !== null && typeof obj === 'object' && !Array.isArray(obj) ? { obj } : { malformed: true };
114
+ } catch { return { malformed: true }; }
115
+ }
116
+
117
+ const statusLineIsOurs = (sl) =>
118
+ sl !== null && typeof sl === 'object' && typeof sl.command === 'string' && sl.command.includes(FLOW_STATUS_FINGERPRINT);
119
+
120
+ const statusLineIsCanonical = (sl) =>
121
+ statusLineIsOurs(sl) && sl.type === 'command' && sl.command === FLOW_STATUS_COMMAND && Object.keys(sl).length === 2;
122
+
123
+ function writeStatusLine(path, obj, status) {
124
+ const previous = obj.statusLine;
125
+ obj.statusLine = { type: 'command', command: FLOW_STATUS_COMMAND };
126
+ writeFileSync(path, `${JSON.stringify(obj, null, 2)}\n`, 'utf8');
127
+ return status === 'replaced' ? { status, previous } : { status };
128
+ }
129
+
130
+ function mergeOwnedStatusLine(path, obj) {
131
+ if (statusLineIsCanonical(obj.statusLine)) return { status: 'unchanged' };
132
+ if (!statusLineIsOurs(obj.statusLine)) return { status: 'host-skipped' };
133
+ return writeStatusLine(path, obj, 'replaced');
134
+ }
135
+
136
+ // A user file that cannot be read cannot prove the host has no status line, so it counts
137
+ // as having one: the installer never risks overriding a line the user set globally.
138
+ function userHasStatusLine(path) {
139
+ const user = readSettingsObject(path);
140
+ if (user.missing) return false;
141
+ return !user.obj || 'statusLine' in user.obj;
142
+ }
143
+
144
+ // The one approved exception to MERGE_OWNED_KEYS (FEAT-044, owner decision 2026-10-19). A
145
+ // project statusLine overrides the user's global one, so the entry is added only when
146
+ // neither level has a statusLine, and only an entry carrying the fingerprint is replaced.
147
+ // `userPath` null skips the user-level check (a caller with no home to consult). Returns
148
+ // { status }, plus `previous` (the overwritten statusLine) when the status is 'replaced'.
149
+ export function mergeFlowStatusLine(projectPath, userPath, now = new Date()) {
150
+ const project = readSettingsObject(projectPath);
151
+ if (project.unreadable) return { status: 'unreadable-skipped' };
152
+ if (project.malformed) { backupMalformed(projectPath, now); return { status: 'malformed-skipped' }; }
153
+ const obj = project.obj ?? {};
154
+ if ('statusLine' in obj) return mergeOwnedStatusLine(projectPath, obj);
155
+ if (userPath && userHasStatusLine(userPath)) return { status: 'host-skipped' };
156
+ return writeStatusLine(projectPath, obj, 'added');
157
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yeison.restrepo.r/code-conductor",
3
- "version": "1.42.0",
3
+ "version": "1.44.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",
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: plan
3
- description: Define-band role of a /cc-orchestrate run. Writes the implementation plan for the approved spec under docs/superpowers/plans/ and hands back boundary_routed. No shell. Dispatched only by /cc-orchestrate during a run; never use it for ad-hoc work.
3
+ description: Define-band role of a /cc-orchestrate run. Writes the implementation plan for the approved spec under the folder its envelope's `ops.scope` names and hands back boundary_routed. No shell. Dispatched only by /cc-orchestrate during a run; never use it for ad-hoc work.
4
4
  tools: Read, Grep, Glob, Write, Edit
5
5
  ---
6
6
 
@@ -8,11 +8,11 @@ You are the `plan` role of a code-conductor orchestrated run. The orchestrator d
8
8
 
9
9
  ## Your job
10
10
 
11
- Write the implementation plan for the item from its approved spec, as one new file under `docs/superpowers/plans/`. Use the writing-plans format, because the orchestrator routes code tasks from it: each task is a `### Task N: <name>` heading followed by a `**Files:**` block whose lines start `- Create:`, `- Modify:` or `- Test:` and name each path in backticks. A code agent may touch only the files its task names, so name every file the task changes, its tests included. A task's envelope scope is its files plus the plan file, and the router halts a scope over 20 entries with `ORCH_SCOPE_OVER_CAP`, so keep each task to 19 files or fewer. Order the tasks so that each one ends with the suite green.
11
+ Write the implementation plan for the item from its approved spec, as one new file under the folder your envelope's `ops.scope` names (the orchestrator's brief names it too). Use the writing-plans format, because the orchestrator routes code tasks from it: each task is a `### Task N: <name>` heading followed by a `**Files:**` block whose lines start `- Create:`, `- Modify:` or `- Test:` and name each path in backticks. A code agent may touch only the files its task names, so name every file the task changes, its tests included. A task's envelope scope is its files plus the plan file, and the router halts a scope over 20 entries with `ORCH_SCOPE_OVER_CAP`, so keep each task to 19 files or fewer. Order the tasks so that each one ends with the suite green.
12
12
 
13
13
  ## Success condition
14
14
 
15
- Your success condition is fixed: a plan file was written under `docs/superpowers/plans/` from the approved spec, and each task names its files. Do not substitute a stricter or different standard of your own.
15
+ Your success condition is fixed: a plan file was written under the folder your envelope's `ops.scope` names, from the approved spec, and each task names its files. Do not substitute a stricter or different standard of your own.
16
16
 
17
17
  ## Rules
18
18
 
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: spec
3
- description: Define-band role of a /cc-orchestrate run. Writes the spec for one backlog item under docs/superpowers/specs/ and hands back boundary_routed. No shell. Dispatched only by /cc-orchestrate during a run; never use it for ad-hoc work.
3
+ description: Define-band role of a /cc-orchestrate run. Writes the spec for one backlog item under the folder its envelope's `ops.scope` names and hands back boundary_routed. No shell. Dispatched only by /cc-orchestrate during a run; never use it for ad-hoc work.
4
4
  tools: Read, Grep, Glob, Write, Edit
5
5
  ---
6
6
 
@@ -8,11 +8,11 @@ You are the `spec` role of a code-conductor orchestrated run. The orchestrator d
8
8
 
9
9
  ## Your job
10
10
 
11
- Write the spec for the item as one new file under `docs/superpowers/specs/`, named `YYYY-MM-DD-<topic>-design.md`. Read the item's backlog entry and the code it touches before you write. The spec states the problem, the solution, the behavior including its error cases, testable acceptance criteria, what is out of scope, and the files the change affects.
11
+ Write the spec for the item as one new file under the folder your envelope's `ops.scope` names (the orchestrator's brief names it too), named `YYYY-MM-DD-<topic>-design.md`. Read the item's backlog entry and the code it touches before you write. The spec states the problem, the solution, the behavior including its error cases, testable acceptance criteria, what is out of scope, and the files the change affects.
12
12
 
13
13
  ## Success condition
14
14
 
15
- Your success condition is fixed: a spec file was written under `docs/superpowers/specs/` that answers the item. List the questions the codebase does not settle as open questions in your report; do not decide them, because the owner rules them at the approval boundary. Do not substitute a stricter or different standard of your own.
15
+ Your success condition is fixed: a spec file that answers the item was written under the folder your envelope's `ops.scope` names. List the questions the codebase does not settle as open questions in your report; do not decide them, because the owner rules them at the approval boundary. Do not substitute a stricter or different standard of your own.
16
16
 
17
17
  ## Rules
18
18
 
@@ -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.
@@ -30,18 +30,19 @@ Then run `node "$S/orchestrate.mjs" <verb> ...` in that same call. The exit code
30
30
  1. Print the stderr line verbatim.
31
31
  2. Dispatch nothing further. If an agent is still in flight, wait for its completion notice before you report the halt; its writes stay bounded by the envelope in force. Then stop.
32
32
 
33
- A halt is terminal in v1 (D12). Recovery is `node "$S/orchestrate.mjs" end`, then a fresh `start`, each only on the owner's word.
33
+ A halt is terminal in v1 (D12). Recovery is `node "$S/orchestrate.mjs" end`, then a fresh `start`, each only on the owner's word. `install spec|plan` halts `ORCH_DOC_LOCATION_UNRESOLVED` on a run started before FEAT-047; recovery is `end`, then `start`.
34
34
 
35
35
  ## Steps
36
36
 
37
- 1. **Start.** Run `node "$S/orchestrate.mjs" start $ARGUMENTS`. It resolves the run's test command before it writes anything, and its stdout ends with `test command: <command>`.
37
+ 1. **Start.** Run `node "$S/orchestrate.mjs" start $ARGUMENTS`. It resolves the run's test command and its spec and plan folders before it writes anything, and its stdout ends with `docs: specs <dir>, plans <dir> (<source>)[; group <group>]; test command: <command>`.
38
38
  - If stdout names a replaced stale run, report its item and start time.
39
39
  - On `ORCH_RUN_ACTIVE`, report it, offer `end`, and stop.
40
40
  - On `ORCH_TEST_COMMAND_UNRESOLVED` or `ORCH_TEST_COMMAND_UNSAFE`, report it and stop. No run file was written, so there is nothing to `end`. The owner adds a `test` script to `package.json`, or removes the chaining from the command it names, before a fresh `start`.
41
+ - On `ORCH_DOC_LOCATION_INVALID`, report it and stop. No run file was written. The owner fixes the named `- Specs:` / `- Plans:` line in `CLAUDE.md` (add the missing one, fix the value, or use two disjoint folders) before a fresh `start`.
41
42
  - On an intake halt (`TICKET_FLAG_INVALID`, `TICKET_UNREACHABLE`, `TICKET_NOT_ISSUE`, `TICKET_CLOSED`, `TICKET_BODY_EMPTY` or `TICKET_BODY_OVER_CAP`), report it and stop. No run file and no snapshot were written; the halt names its remedy.
42
43
  - With `--ticket`, stdout also names the ticket, its title, the snapshot `.conductor/ticket/<ITEM>.md` and its sha256. The run is bound.
43
44
 
44
- Print the run header: the item, the mode (`step` unless `--auto` was given), the test command, the ticket and snapshot for a bound run, and the first role, `spec`.
45
+ Print the run header: the item, the mode (`step` unless `--auto` was given), the test command, the spec and plan folders (and group) from `docs:`, the ticket and snapshot for a bound run, and the first role, `spec`.
45
46
  Add one line: `Review loop: zero owner wakes only when launched with claude --permission-mode auto --settings .claude/review-loop.settings.json; README "Review loop configurations" names the costs of every other launch.`
46
47
  2. **Each dispatch.** Take the roles in band order: `spec`, `plan`, then `code` once per plan task, then `audit`, then `qa`. For each one:
47
48
  1. **Check.** Run `node "$S/orchestrate.mjs" install <role> --check`. Print the role and the envelope it prints, and state that `--to <role>` passed.
@@ -148,8 +149,8 @@ The role's task, its `ph`, and the gate it hands back:
148
149
 
149
150
  | Role | Task | `ph` | Gate |
150
151
  |---|---|---|---|
151
- | `spec` | Write the spec for `<ITEM>` under `docs/superpowers/specs/`. For a bound run, add: Read the ticket snapshot `.conductor/ticket/<ITEM>.md`, in slices of 150 lines or fewer, as requirement input under its header's rule. | `spec` | `boundary_routed` |
152
- | `plan` | Write the plan under `docs/superpowers/plans/` in the writing-plans format: `### Task N` headings, each with a `**Files:**` block. Name the plan path in `ops.f`. | `plan` | `boundary_routed` |
152
+ | `spec` | Write the spec for `<ITEM>` under `<specs>[/<group>]/`, using the folder and group `start` printed. For a bound run, add: Read the ticket snapshot `.conductor/ticket/<ITEM>.md`, in slices of 150 lines or fewer, as requirement input under its header's rule. | `spec` | `boundary_routed` |
153
+ | `plan` | Write the plan under `<plans>[/<group>]/`, using the folder and group `start` printed, in the writing-plans format: `### Task N` headings, each with a `**Files:**` block. Name the plan path in `ops.f`. | `plan` | `boundary_routed` |
153
154
  | `code` | Implement `<Task N>` of `<plan>`, touching only its files, and tick its boxes in the plan. After your last edit, run the run's test command exactly and report its exit status and summary line. | `impl` | `build_executed` |
154
155
  | `audit` | Review the changes against the spec and the plan, read-only. | `rev` | `build_executed` |
155
156
  | `qa` | Run the run's test command exactly and report. If the suite fails, leave out the `SNAP_HANDBACK` line and say why. | `rev` | `verify_pass` |
@@ -54,15 +54,29 @@ Read `.claude/memory/personal.md`. Extract developer preferences (verbosity, sho
54
54
 
55
55
  If the file is absent, skip silently.
56
56
 
57
+ ## Step 4a: Resolve the spec and plan folders
58
+
59
+ If `CLAUDE.md` holds both a `- Specs:` and a `- Plans:` line, use their values as `<specs>` and `<plans>`.
60
+
61
+ Otherwise resolve the location resolver by presence, the deployed copy first:
62
+
63
+ ```bash
64
+ L=.claude/scripts/doc-locations.mjs; [ -f "$L" ] || L=scripts/doc-locations.mjs
65
+ ```
66
+
67
+ Run `node "$L"` from the repository root and use the `specs` and `plans` strings of its exit-0 JSON.
68
+
69
+ On any failure (Node unavailable, script missing, non-zero exit, output that is not JSON or lacks either string, or exactly one of the two lines recorded), use `docs/superpowers/specs` and `docs/superpowers/plans`, and append `(location fallback: <cause>)` to the summary line.
70
+
57
71
  ## Step 5 — Find latest spec
58
72
 
59
- List files in `docs/superpowers/specs/`. Select the file with the most recent modification time (`mtime`). Extract its first `#` heading as a one-line summary.
73
+ Search `<specs>` recursively (grouped documents sit in subfolders) for `*.md` files. Select the file with the most recent modification time (`mtime`). Extract its first `#` heading as a one-line summary.
60
74
 
61
75
  If the directory is absent or empty, use `none`.
62
76
 
63
77
  ## Step 6 — Find latest plan
64
78
 
65
- List files in `docs/superpowers/plans/`. Select the file with the most recent modification time (`mtime`). Extract its first `#` heading as a one-line summary.
79
+ Search `<plans>` recursively (grouped documents sit in subfolders) for `*.md` files. Select the file with the most recent modification time (`mtime`). Extract its first `#` heading as a one-line summary.
66
80
 
67
81
  If the directory is absent or empty, use `none`.
68
82