@yeison.restrepo.r/code-conductor 1.43.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 +28 -3
- package/bin/code-conductor.mjs +6 -3
- package/global/commands/cc-compact.md +1 -1
- package/global/commands/cc-stack.md +31 -1
- package/lib/installer/deploy.mjs +13 -1
- package/package.json +1 -1
- package/project-template/.claude/agents/plan.md +3 -3
- package/project-template/.claude/agents/spec.md +3 -3
- package/project-template/.claude/commands/cc-orchestrate.md +6 -5
- package/project-template/.claude/commands/cc-resume.md +16 -2
- package/project-template/.claude/hooks/pre-tool-use.mjs +21 -2
- package/project-template/.claude/review-loop.settings.json +1 -1
- package/project-template/.opencode/plugin/conductor-guard.js +157 -0
- package/scripts/adopt-claude-md.mjs +229 -0
- package/scripts/detect-stack.mjs +38 -17
- package/scripts/doc-locations.mjs +193 -0
- package/scripts/orchestrate.mjs +45 -9
- package/scripts/snap-build.mjs +42 -6
- package/scripts/snap-contract.mjs +3 -0
- package/scripts/snap-validate.mjs +2 -2
package/README.md
CHANGED
|
@@ -385,6 +385,7 @@ By default, only the global core files are installed. Flags extend that:
|
|
|
385
385
|
| `--project` / `-Project` | Also install the project template into the current directory |
|
|
386
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 |
|
|
387
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 |
|
|
388
389
|
|
|
389
390
|
**Updating:** re-run the same install command. User-configured files are never overwritten; agent-managed files are always updated.
|
|
390
391
|
|
|
@@ -393,13 +394,36 @@ Two cautions:
|
|
|
393
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.
|
|
394
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.
|
|
395
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
|
+
|
|
396
415
|
### How the installer treats your CLAUDE.md
|
|
397
416
|
|
|
398
417
|
`CLAUDE.md` and `.gitignore` are **merged**, never overwritten. Everything else the installer ships (`settings.json`, hooks, commands, `scripts/`) is replaced on every run.
|
|
399
418
|
|
|
400
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.
|
|
401
420
|
- **Everything outside the block is yours, byte for byte.** Nothing outside it is removed, rewritten, reordered or added.
|
|
402
|
-
- **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.
|
|
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.
|
|
403
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:
|
|
404
428
|
|
|
405
429
|
```
|
|
@@ -466,7 +490,6 @@ The backup and temp rules keep the installer's own backups and crash-stranded te
|
|
|
466
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.
|
|
467
491
|
- A gate certifies protocol position and the claim its role states, never the truth of the work beyond that claim.
|
|
468
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.
|
|
469
|
-
- **`[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.
|
|
470
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.
|
|
471
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.
|
|
472
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.
|
|
@@ -481,11 +504,12 @@ The backup and temp rules keep the installer's own backups and crash-stranded te
|
|
|
481
504
|
|
|
482
505
|
## Instruments: releases that verify their own record
|
|
483
506
|
|
|
484
|
-
|
|
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:
|
|
485
508
|
|
|
486
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.
|
|
487
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.
|
|
488
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.
|
|
489
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.
|
|
490
514
|
|
|
491
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.
|
|
@@ -529,6 +553,7 @@ code-conductor/
|
|
|
529
553
|
+-- project-template/
|
|
530
554
|
| +-- CLAUDE.md
|
|
531
555
|
| +-- gitignore Merged into the host project's .gitignore
|
|
556
|
+
| +-- .opencode/plugin/conductor-guard.js OpenCode guard plugin, only with --opencode (FEAT-048)
|
|
532
557
|
| +-- .claude/
|
|
533
558
|
| +-- settings.json Hooks wiring
|
|
534
559
|
| +-- review-loop.settings.json Auto mode exception for the review loop (FEAT-041)
|
package/bin/code-conductor.mjs
CHANGED
|
@@ -8,7 +8,7 @@ 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|-Project] [--no-deps|-NoDeps] [--verbosity|-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
12
|
|
|
13
13
|
// -Verbosity is the spelling the retired install.ps1 documented. Both spellings share
|
|
14
14
|
// every form (space-separated, inline `=`, missing value) and last-wins across them.
|
|
@@ -23,7 +23,7 @@ const isVerbosityFlag = (a) => VERBOSITY_FLAGS.some((f) => a === f || a.startsWi
|
|
|
23
23
|
// is idempotent. No "conflicting flags" error is raised — last-wins is the least
|
|
24
24
|
// surprising CLI convention and keeps the parser branchless.
|
|
25
25
|
function parseArgs(argv) {
|
|
26
|
-
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: [] };
|
|
27
27
|
for (let i = 0; i < argv.length; i++) {
|
|
28
28
|
const a = argv[i];
|
|
29
29
|
// -Project is the spelling the retired install.ps1 documented; matched exact-case
|
|
@@ -33,6 +33,8 @@ function parseArgs(argv) {
|
|
|
33
33
|
// shell installers, so there is nothing to skip. Recognized so callers carried over
|
|
34
34
|
// from install.sh get no misleading "unrecognized" warning.
|
|
35
35
|
else if (a === '--no-deps' || a === '-NoDeps') opts.noDeps = true;
|
|
36
|
+
// FEAT-048: also install the OpenCode guard plugin; meaningful only with --project.
|
|
37
|
+
else if (a === '--opencode') opts.opencode = true;
|
|
36
38
|
else if (isVerbosityFlag(a)) {
|
|
37
39
|
opts.verbosityGiven = true;
|
|
38
40
|
if (a.includes('=')) {
|
|
@@ -81,6 +83,7 @@ export function run(argv, env = process.env, { cwd = process.cwd(), log, nodeVer
|
|
|
81
83
|
const opts = parseArgs(argv);
|
|
82
84
|
|
|
83
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');
|
|
84
87
|
|
|
85
88
|
// --help and --version are explicit informational OUTPUT (not diagnostics), so they
|
|
86
89
|
// go to STDOUT and exit 0 — this lets `code-conductor --version` be captured in a
|
|
@@ -117,7 +120,7 @@ export function run(argv, env = process.env, { cwd = process.cwd(), log, nodeVer
|
|
|
117
120
|
if (heal.status === 'removed') emit('stdout', 'code-conductor: removed the retired graphify-ast-refresh hook from settings.json (backup written beside it)');
|
|
118
121
|
for (const line of heal.lines) emit('stderr', `code-conductor: ${line}`);
|
|
119
122
|
writeVersionFile(home, pkgVersion(assetRoot));
|
|
120
|
-
if (opts.project) deployProject(assetRoot, cwd, { warn: (m) => emit('stderr', m), report: (m) => emit('stdout', m), home });
|
|
123
|
+
if (opts.project) deployProject(assetRoot, cwd, { warn: (m) => emit('stderr', m), report: (m) => emit('stdout', m), home, opencode: opts.opencode });
|
|
121
124
|
return 0;
|
|
122
125
|
} catch (err) {
|
|
123
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 (
|
|
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
|
|
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.
|
package/lib/installer/deploy.mjs
CHANGED
|
@@ -25,6 +25,7 @@ const MERGED_ROOT_FILES = new Map([
|
|
|
25
25
|
// path here; the option is set only to guarantee that a symlink accidentally added
|
|
26
26
|
// later is copied as a link (never followed into user content), not resolved.
|
|
27
27
|
const CP_OPTS = { recursive: true, force: true, dereference: false };
|
|
28
|
+
const OPENCODE_DIR = '.opencode';
|
|
28
29
|
|
|
29
30
|
// One stdout line per backup, because the backup is git-ignored by the managed
|
|
30
31
|
// block and would otherwise be invisible (BUG-049). A backup outside `root` (a
|
|
@@ -235,7 +236,9 @@ function mergeFlowStatus(templateClaude, target, home, report) {
|
|
|
235
236
|
|
|
236
237
|
// `home` is where the user-level settings.json lives, consulted only by the flow status
|
|
237
238
|
// line rule. A caller that passes none gets the project-level check alone.
|
|
238
|
-
|
|
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 } = {}) {
|
|
239
242
|
const emit = warn;
|
|
240
243
|
// Also run by the CLI's pre-flight; kept here for direct callers.
|
|
241
244
|
assertNotSelfInstall(assetRoot, cwd);
|
|
@@ -257,7 +260,9 @@ export function deployProject(assetRoot, cwd, { warn = toStderr, report = toStdo
|
|
|
257
260
|
cpSync(templateClaude, target, { ...CP_OPTS, filter: hostOwnedFilter(templateClaude, PROJECT_HOST_OWNED) });
|
|
258
261
|
for (const name of readdirSync(templateRoot)) {
|
|
259
262
|
if (name === '.claude' || MERGED_ROOT_FILES.has(name)) continue;
|
|
263
|
+
if (name === OPENCODE_DIR && !opencode) continue;
|
|
260
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`);
|
|
261
266
|
}
|
|
262
267
|
for (const [source, { target: dest, merge }] of MERGED_ROOT_FILES) {
|
|
263
268
|
mergeFileInto(join(templateRoot, source), join(cwd, dest), merge, {
|
|
@@ -280,6 +285,13 @@ export function deployProject(assetRoot, cwd, { warn = toStderr, report = toStdo
|
|
|
280
285
|
// project root where it could collide with a scripts/ dir the host already owns.
|
|
281
286
|
sweepStaleRootScripts(assetRoot, cwd);
|
|
282
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
|
+
}
|
|
283
295
|
return target;
|
|
284
296
|
}
|
|
285
297
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@yeison.restrepo.r/code-conductor",
|
|
3
|
-
"version": "1.
|
|
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
|
|
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 `
|
|
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 `
|
|
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
|
|
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 `
|
|
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
|
|
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
|
|
|
@@ -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
|
|
152
|
-
| `plan` | Write the plan under
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
// hookSpecificOutput.permissionDecision and EVERY path exits 0. Nothing here exits 2:
|
|
5
5
|
// a deliberate denial must never be indistinguishable from a crashed script.
|
|
6
6
|
// Zero dependencies by design; node: builtins only.
|
|
7
|
-
import {
|
|
7
|
+
import { closeSync, existsSync, openSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync, writeSync } from 'node:fs';
|
|
8
8
|
import { posix, join, resolve, dirname, relative, isAbsolute, sep } from 'node:path';
|
|
9
9
|
|
|
10
10
|
const LINE_LIMIT = 150;
|
|
@@ -894,6 +894,25 @@ function rotateFlowEvents(path) {
|
|
|
894
894
|
}
|
|
895
895
|
}
|
|
896
896
|
|
|
897
|
+
// A rotation's rename that lands while another hook opens the file can fail that open with
|
|
898
|
+
// EPERM on Windows (#130): measured at 1 open in about 75,000 against a renaming process,
|
|
899
|
+
// with no lock involved. The window is that one instant, so the open is tried again. Only
|
|
900
|
+
// the open: a write that failed is never repeated, so no event can land twice.
|
|
901
|
+
const FLOW_OPEN_TRIES = 3;
|
|
902
|
+
|
|
903
|
+
function openFlowEvents(path) {
|
|
904
|
+
for (let tries = 1; ; tries++) {
|
|
905
|
+
try { return openSync(path, 'a'); } catch (e) {
|
|
906
|
+
if (e.code !== 'EPERM' || tries >= FLOW_OPEN_TRIES) throw e;
|
|
907
|
+
}
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
|
|
911
|
+
function appendFlowLine(path, text) {
|
|
912
|
+
const fd = openFlowEvents(path);
|
|
913
|
+
try { writeSync(fd, text); } finally { closeSync(fd); }
|
|
914
|
+
}
|
|
915
|
+
|
|
897
916
|
|
|
898
917
|
// Runs after emit(), so it can never delay, change or suppress a decision, and its own
|
|
899
918
|
// catch keeps a full disk from reaching the fail-closed catch around main() (spec, Error
|
|
@@ -909,7 +928,7 @@ function recordFlowEvent(payload, input, decision, passed, guard) {
|
|
|
909
928
|
// parallel appends) can only ever end a line, so a tail torn by a crash or a hand edit is
|
|
910
929
|
// fenced off by the next event instead of fused with it, and no per-call read of the last
|
|
911
930
|
// byte is needed. Readers skip blank lines; rotation drops the torn one.
|
|
912
|
-
|
|
931
|
+
appendFlowLine(path, `\n${JSON.stringify(flowEvent(payload, input, decision, passed, guard))}`);
|
|
913
932
|
} catch (e) { debug(`flow event: ${e.message}`); }
|
|
914
933
|
}
|
|
915
934
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"autoMode":{"allow":["$defaults","Orchestrator revision rounds (code-conductor FEAT-041): during a live /cc-orchestrate run, the main session may use SendMessage to a spec or plan band agent that has already handed back, asking it to revise its own document under
|
|
1
|
+
{"autoMode":{"allow":["$defaults","Orchestrator revision rounds (code-conductor FEAT-041): during a live /cc-orchestrate run, the main session may use SendMessage to a spec or plan band agent that has already handed back, asking it to revise its own document under the project's resolved specs or plans folder and to report the revision as prose without a SNAP_HANDBACK line. This is the project's reviewer-in-loop protocol, not an evasion of oversight: the agent's edits remain subject to the project's PreToolUse guards, and the owner's boundary approval still follows."]}}
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
// code-conductor guard for OpenCode (FEAT-048, issue #97; fails closed since the pre-1.44.0
|
|
2
|
+
// hardening). An adapter, not a copy: every mapped tool call is turned into the payload(s)
|
|
3
|
+
// Claude Code sends, handed to the project's own .claude/hooks/pre-tool-use.mjs, and a deny
|
|
4
|
+
// or ask decision is thrown back, which is how OpenCode blocks a call.
|
|
5
|
+
// Every tool is one of three kinds: mapped (sent to the guard), read-only (passes, as its
|
|
6
|
+
// Claude Code twin passes the hook matcher), or blocked. Anything not named is blocked:
|
|
7
|
+
// OpenCode's tool set is not versioned with this guard, so an unknown tool is never trusted.
|
|
8
|
+
// Zero dependencies by design; node: builtins only.
|
|
9
|
+
import { spawnSync } from 'node:child_process';
|
|
10
|
+
import { join, resolve, sep } from 'node:path';
|
|
11
|
+
|
|
12
|
+
const GUARD_REL = join('.claude', 'hooks', 'pre-tool-use.mjs');
|
|
13
|
+
// Claude Code's default hook timeout; a hung guard must not hang the session.
|
|
14
|
+
const GUARD_TIMEOUT_MS = 60000;
|
|
15
|
+
|
|
16
|
+
// None of these writes the working tree; todowrite writes OpenCode's own todo list.
|
|
17
|
+
const READ_ONLY = new Set([
|
|
18
|
+
'glob', 'grep', 'list', 'lsp', 'todoread', 'todowrite',
|
|
19
|
+
'webfetch', 'websearch', 'codesearch', 'question', 'skill', 'invalid',
|
|
20
|
+
]);
|
|
21
|
+
|
|
22
|
+
// Whether tool.execute.before fires inside a subagent is unverified, so no subagent starts.
|
|
23
|
+
const TASK_REASON = 'code-conductor guard cannot inspect OpenCode subagents; "task" is blocked';
|
|
24
|
+
const uncovered = (tool) => `code-conductor guard does not cover the OpenCode tool "${tool}"; it is blocked until the guard maps it`;
|
|
25
|
+
const blocked = (tool, why) => ({ block: `code-conductor guard blocked "${tool}": ${why}` });
|
|
26
|
+
const badArg = (tool, arg, want) => blocked(tool, `argument "${arg}" is missing or not ${want}`);
|
|
27
|
+
|
|
28
|
+
const isText = (v) => typeof v === 'string' && v.length > 0;
|
|
29
|
+
const one = (tool_name, tool_input) => ({ payloads: [{ tool_name, tool_input }] });
|
|
30
|
+
|
|
31
|
+
// A patch path must stay inside the project. No `\`, no absolute form, and the resolved
|
|
32
|
+
// path must sit strictly below the project directory (the directory itself is refused).
|
|
33
|
+
function confine(p, directory) {
|
|
34
|
+
if (p.includes('\\')) return { why: 'contains "\\"' };
|
|
35
|
+
if (p.startsWith('/') || /^[A-Za-z]:/.test(p)) return { why: 'is absolute' };
|
|
36
|
+
const root = resolve(directory);
|
|
37
|
+
const abs = resolve(root, p);
|
|
38
|
+
if (!abs.startsWith(root + sep)) return { why: 'resolves outside the project' };
|
|
39
|
+
return { path: abs };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// Exact, column-0 markers only. The path group admits no leading or trailing whitespace
|
|
43
|
+
// and cannot be empty, so every malformed marker fails the match and blocks the patch.
|
|
44
|
+
const MARKER = /^\*\*\* (?:(Begin Patch|End Patch|End of File)|(Add File|Update File|Delete File|Move to): (\S(?:.*\S)?))$/;
|
|
45
|
+
|
|
46
|
+
function parsePatch(tool, text, directory) {
|
|
47
|
+
const files = [];
|
|
48
|
+
let cur = null;
|
|
49
|
+
for (const raw of text.split('\n')) {
|
|
50
|
+
const line = raw.replace(/\r$/, '');
|
|
51
|
+
if (line.trim().startsWith('***')) {
|
|
52
|
+
const m = MARKER.exec(line);
|
|
53
|
+
if (!m) return blocked(tool, `the patch has a \`***\` line that is not an exact marker: ${JSON.stringify(line)}`);
|
|
54
|
+
if (m[1]) continue;
|
|
55
|
+
const where = confine(m[3], directory);
|
|
56
|
+
if (where.why) return blocked(tool, `the patch path ${JSON.stringify(m[3])} ${where.why}`);
|
|
57
|
+
if (m[2] === 'Move to') {
|
|
58
|
+
if (!cur || cur.kind !== 'Update File' || cur.moveTo) return blocked(tool, 'a "*** Move to:" must directly follow an "*** Update File:" section');
|
|
59
|
+
cur.moveTo = where.path;
|
|
60
|
+
continue;
|
|
61
|
+
}
|
|
62
|
+
cur = { kind: m[2], path: where.path, added: [], removed: [] };
|
|
63
|
+
files.push(cur);
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
if (!cur) continue;
|
|
67
|
+
if (line.startsWith('+')) cur.added.push(line.slice(1));
|
|
68
|
+
else if (line.startsWith('-')) cur.removed.push(line.slice(1));
|
|
69
|
+
}
|
|
70
|
+
if (!files.length) return blocked(tool, 'the patch names no file');
|
|
71
|
+
const payloads = [];
|
|
72
|
+
for (const f of files) {
|
|
73
|
+
const added = f.added.join('\n');
|
|
74
|
+
if (f.kind === 'Add File') payloads.push({ tool_name: 'Write', tool_input: { file_path: f.path, content: added } });
|
|
75
|
+
else if (f.kind === 'Delete File') payloads.push({ tool_name: 'Edit', tool_input: { file_path: f.path, old_string: '', new_string: '' } });
|
|
76
|
+
else payloads.push({ tool_name: 'Edit', tool_input: { file_path: f.path, old_string: f.removed.join('\n'), new_string: added } });
|
|
77
|
+
// A move writes the target, so Guard 2 sees an existing target as an overwrite.
|
|
78
|
+
if (f.moveTo) payloads.push({ tool_name: 'Write', tool_input: { file_path: f.moveTo, content: added } });
|
|
79
|
+
}
|
|
80
|
+
return { payloads };
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function patchTool(a, directory, tool) {
|
|
84
|
+
if (!isText(a.patchText)) return badArg(tool, 'patchText', 'a non-empty string');
|
|
85
|
+
return parsePatch(tool, a.patchText, directory);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// OpenCode tool name -> { payloads } for the guard, or { block } before any guard runs.
|
|
89
|
+
const MAPPED = {
|
|
90
|
+
// An empty command is the guard's to judge (it allows it), so only the type is checked.
|
|
91
|
+
bash: (a, _d, t) => (typeof a.command === 'string' ? one('Bash', { command: a.command }) : badArg(t, 'command', 'a string')),
|
|
92
|
+
read: (a, _d, t) => (isText(a.filePath) ? one('Read', { file_path: a.filePath, offset: a.offset, limit: a.limit }) : badArg(t, 'filePath', 'a non-empty string')),
|
|
93
|
+
write: (a, _d, t) => (isText(a.filePath) ? one('Write', { file_path: a.filePath, content: a.content }) : badArg(t, 'filePath', 'a non-empty string')),
|
|
94
|
+
edit: (a, _d, t) => (isText(a.filePath) ? one('Edit', { file_path: a.filePath, old_string: a.oldString, new_string: a.newString }) : badArg(t, 'filePath', 'a non-empty string')),
|
|
95
|
+
multiedit: (a, _d, t) => {
|
|
96
|
+
if (!isText(a.filePath)) return badArg(t, 'filePath', 'a non-empty string');
|
|
97
|
+
if (!Array.isArray(a.edits) || a.edits.length === 0) return badArg(t, 'edits', 'a non-empty array');
|
|
98
|
+
const payloads = [];
|
|
99
|
+
for (const [i, e] of a.edits.entries()) {
|
|
100
|
+
for (const k of ['oldString', 'newString']) {
|
|
101
|
+
if (!e || typeof e[k] !== 'string') return badArg(t, `edits[${i}].${k}`, 'a string');
|
|
102
|
+
}
|
|
103
|
+
payloads.push({ tool_name: 'Edit', tool_input: { file_path: a.filePath, old_string: e.oldString, new_string: e.newString } });
|
|
104
|
+
}
|
|
105
|
+
return { payloads };
|
|
106
|
+
},
|
|
107
|
+
patch: patchTool,
|
|
108
|
+
apply_patch: patchTool,
|
|
109
|
+
};
|
|
110
|
+
|
|
111
|
+
// The guard emits nothing to allow and one JSON line to decide. Anything else means it
|
|
112
|
+
// did not run, and a call no guard inspected fails closed, as in the guard itself.
|
|
113
|
+
function readDecision(res, guardPath) {
|
|
114
|
+
const failed = `code-conductor guard could not run (${guardPath})`;
|
|
115
|
+
if (res.error) return `${failed}: ${res.error.message}`;
|
|
116
|
+
if (res.status !== 0) return `${failed}: exit ${res.status}. ${(res.stderr || '').trim()}`.trim();
|
|
117
|
+
const out = (res.stdout || '').trim();
|
|
118
|
+
if (!out) return null;
|
|
119
|
+
let decision;
|
|
120
|
+
try { decision = JSON.parse(out).hookSpecificOutput; } catch { return `${failed}: output was not JSON`; }
|
|
121
|
+
if (!decision) return null;
|
|
122
|
+
// A plugin cannot ask the user, so an ask blocks with the guard's own reason.
|
|
123
|
+
if (decision.permissionDecision !== 'deny' && decision.permissionDecision !== 'ask') return null;
|
|
124
|
+
return decision.permissionDecisionReason || 'denied by the code-conductor guard';
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// `node` from PATH, not process.execPath: inside OpenCode that is the OpenCode binary.
|
|
128
|
+
function runGuard(guardPath, payload, directory) {
|
|
129
|
+
return spawnSync('node', [guardPath], {
|
|
130
|
+
cwd: directory,
|
|
131
|
+
input: JSON.stringify(payload),
|
|
132
|
+
encoding: 'utf8',
|
|
133
|
+
timeout: GUARD_TIMEOUT_MS,
|
|
134
|
+
windowsHide: true,
|
|
135
|
+
env: { ...process.env, CLAUDE_PROJECT_DIR: directory },
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
export const ConductorGuard = async ({ directory }) => {
|
|
140
|
+
const guardPath = join(directory, GUARD_REL);
|
|
141
|
+
return {
|
|
142
|
+
'tool.execute.before': async (input, output) => {
|
|
143
|
+
const tool = String(input && input.tool);
|
|
144
|
+
if (READ_ONLY.has(tool)) return;
|
|
145
|
+
if (tool === 'task') throw new Error(TASK_REASON);
|
|
146
|
+
if (!Object.hasOwn(MAPPED, tool)) throw new Error(uncovered(tool));
|
|
147
|
+
const mapped = MAPPED[tool]((output && output.args) || {}, directory, tool);
|
|
148
|
+
if (mapped.block) throw new Error(mapped.block);
|
|
149
|
+
// One guard run per payload; the first deny or ask blocks the whole call.
|
|
150
|
+
for (const p of mapped.payloads) {
|
|
151
|
+
const payload = { session_id: input.sessionID, cwd: directory, hook_event_name: 'PreToolUse', ...p };
|
|
152
|
+
const reason = readDecision(runGuard(guardPath, payload, directory), guardPath);
|
|
153
|
+
if (reason) throw new Error(reason);
|
|
154
|
+
}
|
|
155
|
+
},
|
|
156
|
+
};
|
|
157
|
+
};
|