@warren-dean/code-kit 0.30.0 → 0.30.2

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.
@@ -9,7 +9,7 @@
9
9
  "name": "code-kit",
10
10
  "source": "./",
11
11
  "description": "Keeps AI coding agents inside your project's rules, from idea to merged code: spec design, lanes, layer rules, protected paths with an approval log, spec-check and design gates, proof-before-finish checks, dispatch, review, build status and CI verification, configured per project from its docs",
12
- "version": "0.30.0",
12
+ "version": "0.30.2",
13
13
  "category": "development",
14
14
  "tags": ["guardrails", "architecture", "lanes", "layers", "spec-driven", "ci", "multi-agent"],
15
15
  "license": "MIT"
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "code-kit",
3
- "version": "0.30.0",
3
+ "version": "0.30.2",
4
4
  "description": "Keeps AI coding agents inside your project's rules, from idea to merged code: spec design, lanes, layer rules, protected paths with an approval log, spec-check and design gates, proof-before-finish checks, dispatch, review, build status and CI verification, configured per project from its docs",
5
5
  "author": {
6
6
  "name": "Warren Langeveldt"
package/CHANGELOG.md CHANGED
@@ -2,6 +2,31 @@
2
2
 
3
3
  What changed in each release of code-kit, newest first. Versions follow the plugin manifest and the npm package `@warren-dean/code-kit`. Each release is also on [GitHub Releases](https://github.com/warrendeanlangeveldt/code-kit/releases).
4
4
 
5
+ ## 0.30.2 (2026-11-04)
6
+
7
+ Fixes from how code-kit is used: fewer commits refused after commands that write nothing, the setup commit takes the person's approval of the setup, and the fix check and the merge queue see more of a project.
8
+
9
+ - **A commit after a tool records its notes.** With Context Graph on, a commit in the same command after `ctx record` or `ctx card` is no longer refused as possibly writing files: they write only Context Graph's own records, which any actor may write. An adapter names such commands in its `shell.records`.
10
+ - **Committing the setup.** Until code-kit's config has first been committed, the lead's protected files (the specs, the standards, the design register) need no approval of their own: the person approved them with the setup init showed. The commit that switches code-kit on no longer asks for an approval for each, and the stop check no longer asks the lead to revert the new specs; the approval log records each file as part of the setup. Once any commit has held the config, protected files need their approvals as before, even if a later commit takes the config away.
11
+ - **A screen state with commas in brackets.** A spec's `**States:**` line such as `default, error (timed out, offline)` is read as two states, not three, so the design register's entry for it matches.
12
+ - **A commit after code-kit's own reads.** A commit in the same command after `code-kit designs`, `status`, `check`, `next`, `who`, `trace` and its other commands that only read and print is no longer refused as possibly writing files, however code-kit is run (installed, through node or npx). `designs evidence` and anything with `--write` still are.
13
+ - **Setting a shell variable before a commit.** A commit in the same command after `f=docs/x.md` or `export MSG="…"` is no longer refused: setting a variable writes no file. A value that runs a command (`$(…)` or backticks) is still refused, and a `git add "$f"` still counts as staging every changed file, since what it names can't be read in advance.
14
+ - **Releasing a worktree while the lead's reviewer works on its story.** `code-kit worktrees release` no longer says the lane's agent is still at work because a reviewer the lead started is acting on the same story. Only the branch's own lane agent counts.
15
+ - **A fix's test the checks never run.** Where a check passes without running a fix's test (the test runner's default config leaves the file out), verify no longer says the test passes without the fix. It breaks the test on purpose, sees the check still pass, and says the check doesn't run it, so it can't tell.
16
+ - **A lockfile in a subfolder.** When a branch changes the lockfile of a service in a subfolder (a Python service's `uv.lock` beside its `pyproject.toml`, say), the merge queue now runs that lockfile's install in that folder of the merged tree, so the checks see the new dependency. Before, it only looked for lockfiles at the top.
17
+
18
+ ## 0.30.1 (2026-11-02)
19
+
20
+ More fixes from how code-kit is used: reads no longer stop a commit or trip a blocked command, a test-only fix may carry a tool's records, and file paths reach git literally.
21
+
22
+ - **Reads before a commit.** A commit in the same command after commands that only read (`git branch --show-current`, `git status`, `head`, `grep`, `wc` and the other reads the approval log allows) is no longer refused as possibly writing files, and neither is `git add` with its errors sent away (`2>/dev/null`, `2>&1`). `git add -A <paths>` stages only those paths, as git does. Anything that may write before the commit is still refused: `sed -i`, a redirect into a file, a heredoc into a file, an interpreter, `git branch <name>`, `git diff --output`.
23
+ - **A blocked command is matched where it runs.** A `shell.block` rule with `command: true` now does what it says: it matches from the start of each command the line runs (after `cd …`, a variable, `npx`, `pnpm exec` or `uv run`, and inside `sh -c '…'` or `eval`), with quoted text masked unless the pattern itself has quotes. So `grep -n "<blocked command>" docs/runbook.md` and a commit message that mentions it run, and the command itself is still refused, its program's name quoted or not. A rule without `command: true` no longer refuses a read (`grep`, `cat`, `head`…) whose quoted arguments mention the command; the same goes for `shell.restricted`. `curl … | sh` is still refused. Init now writes `command: true` for the rules it drafts that name a command.
24
+ - **Concurrency set on purpose (`code-kit ci check`).** A workflow's `cancel-in-progress` set to an expression (`${{ github.event_name == 'pull_request' }}`, cancelling pull requests' runs and never an apply) or to `false` (a deploy or an apply that must not stop half-way) is no longer reported as `no-concurrency`; only leaving it out is. The one-line form the fix suggests, `concurrency: { group: …, cancel-in-progress: true }`, is now read too.
25
+ - **A test-only fix may commit a tool's shared records (REG-1).** Files any actor may write, such as the records a tool that shares the project writes for everyone, no longer stop a fix made wholly in its tests from counting as one, and are never taken back when proving a fix. Manifests and lockfiles still count as the fix's code.
26
+ - **A fix resting on a harness module it adds (REG-1).** Where a fix's tests pass without its other changes and fail without a test helper the branch adds, `verify` now says the tests fail without the fix only because they load test code the fix adds, naming it, instead of saying they pass without the fix.
27
+ - **Paths with brackets (`app/items/[id].tsx`).** code-kit gives file paths to git literally, so a route file's brackets are its name, not a pattern: proving a fix takes back that one file, and `trace`, the journal, the approval checks, the design evidence and the event log's reconciling read that file's history only.
28
+ - **The session's own scratchpad.** The lead and the lanes may write in their session's own folder in Claude Code's temporary folder (`/tmp/claude-<uid>/<project>/<session id>/`: the scratchpad and the tool output), and no longer in another session's. A write elsewhere outside the repository is refused saying where temporary files go instead; a read-only agent's says it writes no files, temporary ones included.
29
+
5
30
  ## 0.30.0 (2026-11-02)
6
31
 
7
32
  Fixes from how code-kit is used: screens are built from their exported designs and compared in review, the merge queue lands what it verified and only holds a branch to its own changes, and the lead can hold stories and the queue on purpose. code-kit's part of CLAUDE.md is now version 12, so `next` asks to bring it up to date first.
package/README.md CHANGED
@@ -539,15 +539,15 @@ code-kit approve <name>... --reason "…" [--lane name] [--delegated [--story ST
539
539
  | `docs.decisions` | no | Where agreed intents are recorded as numbered decision records (`code-kit intend record`); default `docs/decisions` |
540
540
  | `docs.standards` | no | The project's standards (spec 22), default `docs/standards.md`: each a `### <id> <title>` heading with `level` (required or recommended), `applied` (enforced, checked or advice), `layers`, `why`, `source` and, when enforced, `enforced by` naming the layer rule, protected path, check or shell rule that refuses a breach. The id's prefix is its category: `PRI-` principles, `PAT-` patterns, `ARC-` architecture, `CON-` conventions, `POL-` policies. Each lane agent is given the ones for its layers; a refusal from an enforcing rule names the standard; reviews check the checked ones. Protect the file with the `standards` approval: removing a standard, or weakening a required one, always needs the person's, whatever is delegated |
541
541
  | `lead.paths` | yes | What the main session writes. `.claude/**` and `.mcp.json` are always added. |
542
- | `lead.outside` | no | Paths outside the repository the lead may write, e.g. `../shared-lib/**`. Claude's memory and scratchpad are always included. |
542
+ | `lead.outside` | no | Paths outside the repository the lead may write, e.g. `../shared-lib/**`. Claude's memory is always included, and the session's own folder in Claude Code's temporary folder (`/tmp/claude-<uid>/<project>/<session id>/`: its scratchpad and tool output), which the lanes may write too; another session's isn't. |
543
543
  | `anyActor` | no | Paths every writer may change (e.g. the lockfile), read-only agents included. `.claude/state/**` is always included. An entry may be `{ "glob", "reviewer" }` to name the lane (or `"lead"`) that reviews changes to it; otherwise the lead reviews them, and `who` and `trace` say so. |
544
544
  | `lanes.<name>` | yes (may be `{}`) | `{ agent, paths, exclude?, owners?, label? }`: the agent name maps a subagent to its lane; `label` names what the lane delivers ("Screens", "API contract"; one line, at most 60 characters), for a team provider's report, and is otherwise taken from the lane's name; `owners` (GitHub handles) are the people whose sessions work it, in a team (needs `team`). A worktree with a `.lane` file holding the lane name makes the main session that lane. |
545
545
  | `protected[]` | no | `{ glob, approval, why }`: logged on every commit. Anyone but the lead needs an approval: the lead's where `approvals.delegate.protected` names it, otherwise a person's (see [Approvals](#approvals)). `.claude/**` is always protected as `kit`. |
546
546
  | `designGate` | no | `{ register, screens: [{ glob, not? }], howTo }`: screen files wait until the register (`{ "screens": [{ "file": … }] }`) holds their exported designs; an entry naming only a design tool's artboard doesn't open the gate. Init sets it for every lane that owns screens; `/code-kit:design` adds approved designs |
547
547
  | `layers[]` | no | `{ name, paths, mayImport, denyPackages?, label? }`: the first layer whose paths match a file owns it. A layer may always import itself. `label` names what the layer delivers ("Data", "Service"; one line, at most 60 characters), for a team provider's report, and is otherwise taken from the layer's name. |
548
548
  | `importAliases` | no | `{ "@app/domain": "packages/domain/src" }`: resolves non-relative imports to repository paths |
549
- | `shell.block[]` | no | `{ pattern, why, person?, command? }`: never run. `person: true` marks a person's act, which the lead may do for them with `approvals.lead` on. `command: true` matches the pattern from the start of each command the line runs, so a heredoc or quoted text that mentions it isn't refused |
550
- | `shell.restricted[]` | no | `{ pattern, lanes, why }`: only the lead and these lanes |
549
+ | `shell.block[]` | no | `{ pattern, why, person?, command? }`: never run. `person: true` marks a person's act, which the lead may do for them with `approvals.lead` on. `command: true` matches the pattern from the start of each command the line runs (after a package runner such as `npx` or `pnpm exec`, and inside `sh -c` or `eval`), with quoted text masked unless the pattern has quotes, so a grep, a heredoc or a message that mentions it isn't refused. Without it the pattern reads the whole line, except a read's quoted arguments: `grep "<command>" docs` doesn't run it |
550
+ | `shell.restricted[]` | no | `{ pattern, lanes, why }`: only the lead and these lanes. A read's quoted arguments don't count, as for `shell.block` |
551
551
  | `postEdit[]` | no | `{ files, exclude?, run }`: after each edit of a matching file. `{file}` is the file. Exit 127 (tool not installed) is skipped. |
552
552
  | `tests[]` | no | Globs naming the test files, in place of the conventions, for every rule that asks what a test is: weakened tests, a fix's tests, the tests that name a requirement, the code map and the security review. Default: a file named as a test (`*.test.*`, `*.spec.*`, `*.smoke.*`, `test_*.py`, `*_test.go`, `*_test.py`) or in a test folder (`test/`, `tests/`, `__tests__/`, `e2e/`, `smoke/`). Proving a fix keeps the files named as tests and takes the rest back, test-folder helpers included; with `tests` set, the files it names are the ones kept. |
553
553
  | `regression.prepare` | no | A command run in a fresh checkout before a fix's tests run there without the fix, such as `npm ci`. The checkout's `node_modules` and virtualenvs are copied in first (a copy-on-write clone where the disk has one), so it can't change the checkout's own. The merge queue runs it too, in the merged tree's checkout, when its manifests or lockfiles differ from the installs copied in; without it, the queue runs the install the lockfile calls for. |
@@ -14,7 +14,16 @@ import {
14
14
  ecosystemOf,
15
15
  isDependencyFile,
16
16
  } from './lib/dependencies.mjs';
17
- import { CODE_KIT, GIT, codeOf, commandsOf, readsOnly, runs } from './lib/shell.mjs';
17
+ import {
18
+ CODE_KIT,
19
+ GIT,
20
+ codeOf,
21
+ commandsOf,
22
+ readsOnly,
23
+ ruleMatches,
24
+ runs,
25
+ withoutHarmlessRedirects,
26
+ } from './lib/shell.mjs';
18
27
  import { block, start } from './lib/hook.mjs';
19
28
  import { CONFIG_FILE, committedConfig } from './lib/config.mjs';
20
29
  import { laneOfBranch, storyOfBranch, teamOf, teamProvider, whoami } from './lib/team.mjs';
@@ -48,6 +57,7 @@ import {
48
57
  owns,
49
58
  protectedEntry,
50
59
  leadNeedsApproval,
60
+ beforeSetup,
51
61
  approvalEnded,
52
62
  recordRequest,
53
63
  sessionRoot,
@@ -194,8 +204,9 @@ const forPerson = actor.kind === 'lead' && config.approvals.lead;
194
204
 
195
205
  for (const { pattern, why, person, command } of config.shell.block) {
196
206
  // `command: true`: the pattern names a command, matched from the start of each one the line runs, so a
197
- // heredoc or a quoted message that mentions it isn't refused. Otherwise it reads the whole text.
198
- const matched = command ? runs(cmd, new RegExp(pattern)) : new RegExp(pattern).test(cmd);
207
+ // heredoc, an argument or a quoted message that mentions it isn't refused. Otherwise it reads the whole
208
+ // text, except a read's quoted arguments (lib/shell.mjs ruleMatches).
209
+ const matched = ruleMatches({ pattern, command }, cmd);
199
210
  if (!matched || (person && forPerson)) continue;
200
211
  const hint =
201
212
  person && actor.kind === 'lead'
@@ -356,7 +367,7 @@ if (packages.length) {
356
367
  }
357
368
  for (const { pattern, lanes, why } of config.shell.restricted) {
358
369
  const allowed = actor.kind === 'lead' || (actor.kind === 'lane' && lanes.includes(actor.lane));
359
- if (!allowed && new RegExp(pattern).test(cmd))
370
+ if (!allowed && ruleMatches({ pattern }, cmd))
360
371
  block(`Blocked: the ${actor.label} may not run this. ${why}\nCommand: ${cmd}`);
361
372
  }
362
373
 
@@ -504,7 +515,7 @@ function committedFiles() {
504
515
  l.slice(3),
505
516
  );
506
517
  // Each git command of the chain, however it's run (`git -C <worktree> add`).
507
- const pieces = commandsOf(cmd).map((c) => c.text);
518
+ const pieces = commandsOf(withoutHarmlessRedirects(cmd)).map((c) => c.text);
508
519
  const gitRun = (sub) =>
509
520
  pieces.map((p) => p.match(new RegExp(String.raw`^${GIT}${sub}`))).filter(Boolean);
510
521
  const commitAll = gitRun(String.raw`commit(?![\w-])(.*)`).some((m) =>
@@ -517,7 +528,14 @@ function committedFiles() {
517
528
  .filter((a) => a && !a.startsWith('-'))
518
529
  .map((a) => a.replace(/^(['"])(.*)\1$/, '$2'));
519
530
  const addRuns = gitRun(String.raw`add\b(.*)`);
520
- const addAll = addRuns.some((m) => /\s(-A|--all|\.)(\s|$)/.test(` ${m[1]}`));
531
+ // `-A` stages everything only without paths: `git add -A <paths>` stages those paths. A pathspec with
532
+ // magic (`:/`, `:(top)…`) could name any file, so it counts as everything.
533
+ const addAll = addRuns.some(
534
+ (m) =>
535
+ /\s\.(\s|$)/.test(` ${m[1]}`) ||
536
+ argsOf(m).some((a) => a.startsWith(':')) ||
537
+ (/\s(-A|--all)(\s|$)/.test(` ${m[1]}`) && argsOf(m).length === 0),
538
+ );
521
539
  // `git rm` and `git mv` stage as they run: their files count though nothing has changed them yet, and
522
540
  // what they take away is gone from the commit though it's still on disk now.
523
541
  const rmArgs = gitRun(String.raw`rm\b(.*)`).flatMap(argsOf);
@@ -617,6 +635,8 @@ function recordApprovals() {
617
635
  );
618
636
  }
619
637
  }
638
+ // The commit that switches code-kit on: the person approved the setup it holds as init showed it.
639
+ const setup = settingUp && files.includes(CONFIG_FILE) && beforeSetup(root);
620
640
  for (const file of files) {
621
641
  // Concluding a merge: what arrives as the other branch has it was logged there, with its approvals.
622
642
  if (arrivesWithMerge(root, file, { staged: true })) continue;
@@ -629,6 +649,14 @@ function recordApprovals() {
629
649
  const granted = entry && approval(root, entry.approval, actor);
630
650
  const byDependency = actor.kind === 'lane' && dependencyChange(actor, file, root, config);
631
651
  const leadFree = actor.kind === 'lead' && !leadNeedsApproval(entry?.approval, config);
652
+ if (entry && !granted && setup) {
653
+ record(file, {
654
+ approval: entry.approval,
655
+ reason: 'The setup that switches code-kit on, as the person approved it in init.',
656
+ setup: true,
657
+ });
658
+ continue;
659
+ }
632
660
  if (entry && !granted && !leadFree && !byDependency) {
633
661
  recordRequest(root, actor, entry.approval, file, entry.why);
634
662
  block(
@@ -745,16 +773,32 @@ ${approvalHowTo(TESTS_APPROVAL, actor, root, 'weakening tests in one commit', pe
745
773
 
746
774
  // The commit hook judges what the commit holds before the command runs, so a file a command earlier in
747
775
  // the chain writes (a formatter, a script, a heredoc) can't be seen, and would go in unjudged and
748
- // unlogged. Before the commit, a chain may only move into the checkout and stage.
776
+ // unlogged. Before the commit, a chain may only move into the checkout, stage, and run commands that
777
+ // only read (lib/shell.mjs readsOnly: git's status, diff, log and show among them, with no output
778
+ // file). Errors sent into the output or /dev/null write no file.
749
779
  const BEFORE_COMMIT = new RegExp(
750
- String.raw`^(?:cd\s|${GIT}(?:add|rm|mv|status|diff|log|show|restore\s+--staged|reset\s+--soft)(?![\w-]))`,
780
+ String.raw`^(?:cd\s|${GIT}(?:add|rm|mv|restore\s+--staged|reset\s+--soft)(?![\w-]))`,
751
781
  );
782
+ // Setting shell variables (`f=docs/x.md`, `export MSG="…"`) writes no file, unless a value runs a
783
+ // command. What a later `git add "$f"` stages can't be read, so it counts as every changed file.
784
+ const ASSIGNS_ONLY = /^(?:export\s+)?[A-Za-z_]\w*=\S*(?:\s+[A-Za-z_]\w*=\S*)*$/;
785
+ const assignsOnly = (c) => ASSIGNS_ONLY.test(c.code) && !/`|\$\(|<\(/.test(c.text);
786
+ // A tool's command that writes only the tool's own records (an adapter's `shell.records`), which any
787
+ // actor may write and no check covers, with no redirect of its own.
788
+ const recordsOnly = (c) =>
789
+ !/[<>]/.test(c.code) && (config.shell.records ?? []).some((re) => new RegExp(re).test(c.text));
752
790
  function writesBeforeCommit() {
753
- const pieces = commandsOf(cmd);
791
+ const pieces = commandsOf(withoutHarmlessRedirects(cmd));
754
792
  const at = pieces.findIndex((c) => new RegExp(String.raw`^${GIT}commit(?![\w-])`).test(c.text));
755
793
  return pieces
756
794
  .slice(0, Math.max(at, 0))
757
- .find((c) => !BEFORE_COMMIT.test(c.text) || /[<>]/.test(c.code));
795
+ .find(
796
+ (c) =>
797
+ (!BEFORE_COMMIT.test(c.text) || /[<>]/.test(c.code)) &&
798
+ !readsOnly(c.whole) &&
799
+ !assignsOnly(c) &&
800
+ !recordsOnly(c),
801
+ );
758
802
  }
759
803
 
760
804
  if (commits) {
@@ -68,6 +68,9 @@ export default {
68
68
  why: "Ratifying a Context Graph proposal with --commit, dropping one, and changing Context Graph's harness settings are the person's own acts: they run them themselves, with a `!` command, or from the Context Graph pane.",
69
69
  },
70
70
  ],
71
+ // Recording a decision or writing a card writes only ctx's own records (anyActor above), so a commit
72
+ // may follow it in the same command.
73
+ records: [String.raw`^${CTX}\s+(?:record|card)\b`],
71
74
  restricted: [
72
75
  {
73
76
  pattern: 'Ctx-Ratified-By\\s*[:=][^\\n"\']*\\(delegated\\)',
@@ -99,6 +99,7 @@ export function applyAdapters(config, raw, root) {
99
99
  merged.protected.push(...(c.protected ?? []));
100
100
  merged.shell.block.push(...(a.shell?.block ?? []));
101
101
  merged.shell.restricted.push(...(a.shell?.restricted ?? []));
102
+ (merged.shell.records ??= []).push(...(a.shell?.records ?? []));
102
103
  }
103
104
  merged.adapters = active.map((a) => a.name);
104
105
  return merged;
@@ -140,6 +140,7 @@ const JS = [
140
140
  'npm-shrinkwrap.json',
141
141
  'yarn.lock',
142
142
  ];
143
+ const shellQuote = (s) => `'${s.replace(/'/g, `'\\''`)}'`;
143
144
  const INSTALLERS = [
144
145
  ['pnpm-lock.yaml', 'pnpm install --frozen-lockfile --prefer-offline', JS],
145
146
  ['package-lock.json', 'npm ci --prefer-offline --no-audit --no-fund', JS],
@@ -163,10 +164,25 @@ const INSTALLERS = [
163
164
  export function matchInstalls(dir, from, { prepare = null, timeout = 900000 } = {}) {
164
165
  const differ = dependencyDifferences(from, dir);
165
166
  const copied = installsOf(dir).length > 0;
166
- const present = INSTALLERS.filter(([lock]) => existsSync(join(dir, lock)));
167
- const known = present.find(([, , files]) => differ.some((f) => files.includes(basename(f))));
168
- const command = differ.length ? (prepare ?? known?.[1] ?? null) : null;
169
- const facts = { differ, copied, lockfile: present.length > 0 };
167
+ // Each file that differs is installed by the nearest lockfile of its ecosystem at or above its folder
168
+ // (a service in a subfolder with its own lockfile, a workspace package under the top one's), run there.
169
+ const installs = [];
170
+ for (const f of differ) {
171
+ for (let folder = dirname(f); ; folder = dirname(folder)) {
172
+ const found = INSTALLERS.find(
173
+ ([lock, , files]) => files.includes(basename(f)) && existsSync(join(dir, folder, lock)),
174
+ );
175
+ if (found) {
176
+ const run = folder === '.' ? found[1] : `(cd ${shellQuote(folder)} && ${found[1]})`;
177
+ if (!installs.includes(run)) installs.push(run);
178
+ break;
179
+ }
180
+ if (folder === '.') break;
181
+ }
182
+ }
183
+ const present = INSTALLERS.some(([lock]) => existsSync(join(dir, lock))) || installs.length > 0;
184
+ const command = differ.length ? (prepare ?? (installs.join(' && ') || null)) : null;
185
+ const facts = { differ, copied, lockfile: present };
170
186
  if (!command) return { ...facts, command: null, failed: null };
171
187
  const res = spawnSync(command, { cwd: dir, shell: true, encoding: 'utf8', timeout });
172
188
  if (res.status === 0) return { ...facts, command, failed: null };
package/hooks/lib/ci.mjs CHANGED
@@ -31,6 +31,32 @@ const stripComment = (line) => {
31
31
  }
32
32
  return line;
33
33
  };
34
+ /** A one-line map's entries (`group: x, cancel-in-progress: true`), split at commas outside quotes and `${{ }}`. */
35
+ function flowMap(body) {
36
+ const parts = [];
37
+ let quote = null;
38
+ let depth = 0;
39
+ let start = 0;
40
+ for (let i = 0; i < body.length; i++) {
41
+ const c = body[i];
42
+ if (quote) {
43
+ if (c === quote) quote = null;
44
+ } else if (c === '"' || c === "'") quote = c;
45
+ else if (c === '{' || c === '[') depth += 1;
46
+ else if (c === '}' || c === ']') depth -= 1;
47
+ else if (c === ',' && depth === 0) {
48
+ parts.push(body.slice(start, i));
49
+ start = i + 1;
50
+ }
51
+ }
52
+ parts.push(body.slice(start));
53
+ const out = {};
54
+ for (const part of parts) {
55
+ const m = /^\s*("[^"]*"|'[^']*'|[^:]+?):(?:\s+|$)(.*)$/s.exec(part);
56
+ if (m) out[unquote(m[1])] = scalar(m[2]);
57
+ }
58
+ return out;
59
+ }
34
60
  const scalar = (v) => {
35
61
  const t = v.trim();
36
62
  if (t === '') return null;
@@ -40,7 +66,7 @@ const scalar = (v) => {
40
66
  .split(',')
41
67
  .map((x) => unquote(x))
42
68
  .filter(Boolean);
43
- if (t.startsWith('{') && t.endsWith('}')) return {};
69
+ if (t.startsWith('{') && t.endsWith('}')) return flowMap(t.slice(1, -1));
44
70
  if (t === 'true') return true;
45
71
  if (t === 'false') return false;
46
72
  if (/^-?\d+(\.\d+)?$/.test(t)) return Number(t);
@@ -206,7 +232,14 @@ export function workflowFindings(file, text, base) {
206
232
  `${untimed.length === 1 ? 'job' : 'jobs'} ${untimed.join(', ')} ${untimed.length === 1 ? 'has' : 'have'} no timeout-minutes, so a hung step runs up to GitHub's ${GITHUB_LIMIT_MINUTES / 60} hours`,
207
233
  'give each job a timeout-minutes a little over its usual run',
208
234
  );
209
- const cancels = (c) => c && typeof c === 'object' && c['cancel-in-progress'] === true;
235
+ // Concurrency is decided when cancel-in-progress is set: true, an expression (`${{ … }}`, such as
236
+ // cancelling pull requests' runs but never an apply), or false on purpose, for a workflow that must
237
+ // never be stopped half-way (a deploy, an infrastructure apply). Left out, every push runs to the end.
238
+ const cancels = (c) =>
239
+ c &&
240
+ typeof c === 'object' &&
241
+ (typeof c['cancel-in-progress'] === 'boolean' ||
242
+ /^\s*\$\{\{[\s\S]*\}\}\s*$/.test(String(c['cancel-in-progress'] ?? '')));
210
243
  if (
211
244
  onPr &&
212
245
  !cancels(doc.concurrency) &&
@@ -9,11 +9,8 @@ import { ADAPTERS, applyAdapters } from './adapters/index.mjs';
9
9
 
10
10
  export const CONFIG_FILE = '.claude/code-kit.json';
11
11
  // Claude's own memory and session scratchpad, which the lead always writes.
12
- export const CLAUDE_OWN = [
13
- '~/.claude/projects/*/memory/**',
14
- '/private/tmp/claude-*/**',
15
- '/tmp/claude-*/**',
16
- ];
12
+ // Claude's memory. The session's own temporary folder is the lead's and the lanes' too (rules.mjs).
13
+ export const CLAUDE_OWN = ['~/.claude/projects/*/memory/**'];
17
14
  const KIT = { glob: '.claude/**', approval: 'kit', why: 'the rules that constrain agents' };
18
15
 
19
16
  /** `{ config }` when the project has a valid config, `{ error }` when it is invalid, `{}` when it has none. */
@@ -15,10 +15,10 @@ import {
15
15
  import { spawnSync } from 'node:child_process';
16
16
  import { randomUUID } from 'node:crypto';
17
17
  import { join } from 'node:path';
18
- import { CODE_KIT, GIT, commandsOf } from './shell.mjs';
18
+ import { CODE_KIT, GIT, commandsOf, ruleMatches } from './shell.mjs';
19
19
  import { addedPackages } from './dependencies.mjs';
20
20
  import { storyOfBranch } from './teamfacts.mjs';
21
- import { globToRegExp } from './glob.mjs';
21
+ import { globToRegExp, literalPath } from './glob.mjs';
22
22
  import { projectWorktrees } from './rules.mjs';
23
23
  import { readQueue, settle, waiting } from './queue.mjs';
24
24
  import { sessions } from './sessions.mjs';
@@ -65,20 +65,21 @@ const TEST =
65
65
  * approval protects), one the project blocks or restricts, or one in `execution.unrepeatable`.
66
66
  */
67
67
  export function unrepeatable(command, config) {
68
- const patterns = [
69
- ...(config.shell?.block ?? []).map((b) => b.pattern),
70
- ...(config.shell?.restricted ?? []).map((r) => r.pattern),
71
- ...(config.execution?.unrepeatable ?? []),
68
+ // The project's blocked and restricted commands are matched as the shell hook matches them.
69
+ const rules = [
70
+ ...(config.shell?.block ?? []),
71
+ ...(config.shell?.restricted ?? []),
72
+ ...(config.execution?.unrepeatable ?? []).map((pattern) => ({ pattern })),
72
73
  ];
73
- if (patterns.some((p) => safeTest(p, command))) return true;
74
+ if (rules.some((r) => safeTest(r, command))) return true;
74
75
  const migrations = (config.protected ?? []).filter((p) => p.approval === 'migration');
75
76
  return command
76
77
  .split(/\s+/)
77
78
  .some((w) => migrations.some((p) => globToRegExp(p.glob).test(w.replace(/^\.\//, ''))));
78
79
  }
79
- function safeTest(pattern, text) {
80
+ function safeTest(rule, text) {
80
81
  try {
81
- return new RegExp(pattern).test(text);
82
+ return ruleMatches(rule, text);
82
83
  } catch {
83
84
  return false;
84
85
  }
@@ -525,7 +526,7 @@ export function checkAct(root, act, base) {
525
526
  }
526
527
  if (act.kind === 'edit' && tree) {
527
528
  const rel = act.target?.startsWith(tree) ? act.target.slice(tree.length + 1) : act.target;
528
- const changed = out(git(tree, 'status', '--porcelain', '--', rel));
529
+ const changed = out(git(tree, 'status', '--porcelain', '--', literalPath(rel)));
529
530
  return {
530
531
  found: changed ? 'done' : 'not done',
531
532
  how: changed ? `${rel} holds uncommitted changes` : `${rel} is as committed`,
@@ -40,3 +40,10 @@ export function globToRegExp(glob) {
40
40
  }
41
41
 
42
42
  export const matchesAny = (path, globs = []) => globs.some((g) => globToRegExp(g).test(path));
43
+
44
+ /**
45
+ * A file's path as a git pathspec that names exactly that file: git reads `*`, `?` and `[…]` in a
46
+ * pathspec as a pattern, so a route file such as `app/[id].tsx` would otherwise match `app/i.tsx`
47
+ * and miss itself.
48
+ */
49
+ export const literalPath = (path) => `:(literal)${path}`;
@@ -7,6 +7,7 @@ import { execFileSync } from 'node:child_process';
7
7
  import { existsSync, readFileSync } from 'node:fs';
8
8
  import { join } from 'node:path';
9
9
  import { dispatches } from './dispatches.mjs';
10
+ import { literalPath } from './glob.mjs';
10
11
  import { APPROVAL_LOG } from './rules.mjs';
11
12
  import { sendBacks } from './reviews.mjs';
12
13
  import { storyTimes } from './timeline.mjs';
@@ -27,7 +28,7 @@ const gitIn =
27
28
 
28
29
  /** When a file was first committed, in ms, or null. */
29
30
  const addedAt = (git, file) => {
30
- const t = git('log', '--diff-filter=A', '--format=%ct', '--', file)
31
+ const t = git('log', '--diff-filter=A', '--format=%ct', '--', literalPath(file))
31
32
  .split('\n')
32
33
  .filter(Boolean)
33
34
  .at(-1);
@@ -93,12 +93,18 @@ export const screenKey = (name) =>
93
93
  .toLowerCase();
94
94
 
95
95
  /** The states a `**States:**` line or a States cell lists, in lower case. */
96
- const statesOf = (text) =>
97
- String(text)
98
- .replace(/<br\s*\/?>/gi, ',')
99
- .split(/[,;/]/)
100
- .map((s) => screenKey(s).replace(/\.$/, ''))
101
- .filter(Boolean);
96
+ // A state's own brackets keep their commas: `error (timed out, offline)` is one state.
97
+ const statesOf = (text) => {
98
+ const states = [''];
99
+ let depth = 0;
100
+ for (const ch of String(text).replace(/<br\s*\/?>/gi, ',')) {
101
+ if ('([{'.includes(ch)) depth++;
102
+ else if (')]}'.includes(ch)) depth = Math.max(0, depth - 1);
103
+ if (depth === 0 && ',;/'.includes(ch)) states.push('');
104
+ else states[states.length - 1] += ch;
105
+ }
106
+ return states.map((s) => screenKey(s).replace(/\.$/, '')).filter(Boolean);
107
+ };
102
108
 
103
109
  /** A `- **Name** …` bullet that lists a screen: { indent, title }, or null (a field such as `**States:**`). */
104
110
  function screenBullet(line) {
@@ -4,11 +4,12 @@
4
4
  // WHO-2), the person's otherwise and always on the lead's own. The commit hook
5
5
  // refuses a weakening commit; verify finds what a branch weakened, from git.
6
6
  import { execFileSync, spawnSync } from 'node:child_process';
7
- import { existsSync, readFileSync, rmSync } from 'node:fs';
7
+ import { existsSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
8
8
  import { join } from 'node:path';
9
9
  import { freshCheckout } from './checkout.mjs';
10
10
  import { runChecks } from './checks.mjs';
11
- import { matchesAny } from './glob.mjs';
11
+ import { isDependencyFile } from './dependencies.mjs';
12
+ import { literalPath, matchesAny } from './glob.mjs';
12
13
  import { readStories } from './plan.mjs';
13
14
  import { isNamedTest, isTestFile } from './testfiles.mjs';
14
15
 
@@ -226,6 +227,9 @@ const UNREACHABLE =
226
227
  const ASSERTED =
227
228
  /AssertionError|AssertionFailedError|Expected:|Received:|expected .+ to |toBe|toEqual|assert\w* failed|^\s*--- FAIL|Error: expect\(/m;
228
229
 
230
+ // What a test file holds to break it: unbalanced, so no language's parser takes it.
231
+ const UNPARSEABLE = 'broken on purpose by code-kit, to see whether a check runs this test (\n';
232
+
229
233
  /** The names a failure says can't be reached: quoted ones on its unreachable lines. */
230
234
  function missingNames(output) {
231
235
  const names = new Set();
@@ -257,6 +261,11 @@ export function proveFix({ root, from, base, changed, config, fix }) {
257
261
  return [
258
262
  `${what}, but it adds or changes no test. Add a test that fails without the fix: it's what stops the bug coming back.`,
259
263
  ];
264
+ // Records a tool writes for everyone (files any actor may write, such as an adapter's, but not the
265
+ // manifests and lockfiles, which can be a fix) are neither the fix's code nor its tests: they don't
266
+ // make a fix more than its tests, and they don't go back.
267
+ const shared = (f) => matchesAny(f, config.anyActor) && !isDependencyFile(f);
268
+ changed = changed.filter((f) => !shared(f));
260
269
  // A fix made wholly in the tests (a flaky test, a broken helper) has no code to take back: its tests
261
270
  // are the fix. REG-2 still holds them, so it can't be made by weakening one.
262
271
  if (changed.every((f) => isTestFile(f, config) || SNAPSHOT.test(f))) return [];
@@ -298,10 +307,38 @@ export function proveFix({ root, from, base, changed, config, fix }) {
298
307
  `${what}, but its tests don't pass in a fresh checkout of the branch (${withFix.title.replace(/ Fix it:$/, '')}), so code-kit can't tell whether they fail without it. If they need an install or a build first, set regression.prepare.${withFix.output ? `\n${String(withFix.output).trim().split('\n').slice(-20).join('\n')}` : ''}`,
299
308
  ];
300
309
  for (const f of revert) {
301
- if (showAt(root, from, f) !== null) git(dir, 'checkout', from, '--', f);
310
+ if (showAt(root, from, f) !== null) git(dir, 'checkout', from, '--', literalPath(f));
302
311
  else rmSync(join(dir, f), { force: true });
303
312
  }
304
313
  const { failure: without } = runChecks(strict, tests, dir, actor);
314
+ // Test code the branch adds was kept for the tests to load. Where they pass without the rest of
315
+ // the fix, and fail without that code, the fix is the new test code itself: the base's code never
316
+ // had it, so the tests can't show the bug there, like tests that call only what a fix adds.
317
+ const added = changed.filter(
318
+ (f) =>
319
+ !tests.includes(f) &&
320
+ !SNAPSHOT.test(f) &&
321
+ isTestFile(f, config) &&
322
+ showAt(root, from, f) === null,
323
+ );
324
+ if (!without && added.length) {
325
+ for (const f of added) rmSync(join(dir, f), { force: true });
326
+ const { failure: unloaded } = runChecks(strict, tests, dir, actor);
327
+ if (unloaded)
328
+ return [
329
+ `${what}, but its tests (${tests.join(', ')}) pass without the fix's other changes, and fail without it only because they load test code the fix adds (${added.join(', ')}), which the base never had. A test that goes through the code the fix changed fails on an assertion when the bug is there: write that one. If the fix is only in the tests and their helpers, keep the branch to test files.`,
330
+ ];
331
+ }
332
+ if (!without) {
333
+ // A check can pass without running a test at all (its runner's config leaves the file out). Broken
334
+ // on purpose, a test it runs fails: one that still passes was never run, so it shows nothing.
335
+ for (const f of tests) writeFileSync(join(dir, f), UNPARSEABLE);
336
+ const { failure: broken } = runChecks(strict, tests, dir, actor);
337
+ if (!broken)
338
+ return [
339
+ `${what}, but the checks covering its tests (${covering.map((c) => c.name).join(', ')}) pass even with them broken, so they don't run them (${tests.join(', ')}), and code-kit can't tell whether they fail without the fix. Give the tests a check that runs them: where the test runner's default config leaves them out, a check that runs them with the config that includes them.`,
340
+ ];
341
+ }
305
342
  if (!without)
306
343
  return [
307
344
  `${what}, but its tests (${tests.join(', ')}) also pass without the fix, so they don't prove the bug and it can come back. Write a test that fails on ${base} and passes here.`,
@@ -30,7 +30,8 @@ import { homedir } from 'node:os';
30
30
  import { basename, dirname, join, relative, resolve } from 'node:path';
31
31
  import { fileURLToPath } from 'node:url';
32
32
  import { DEPENDENCY_APPROVAL, isDependencyFile } from './dependencies.mjs';
33
- import { globToRegExp, matchesAny } from './glob.mjs';
33
+ import { globToRegExp, literalPath, matchesAny } from './glob.mjs';
34
+ import { CONFIG_FILE } from './config.mjs';
34
35
  import { noteFor } from './standards.mjs';
35
36
 
36
37
  export const APPROVAL_LOG = '.claude/approval-log.jsonl';
@@ -105,6 +106,29 @@ export const leadNeedsApproval = (name, config) =>
105
106
  Boolean(config?.approvals?.delegate?.merge) &&
106
107
  !leadDecides(name, config, { kind: 'lead' });
107
108
 
109
+ /**
110
+ * Whether code-kit is being set up in `root`: its config is in the checkout, not ignored, and no commit
111
+ * the repository has ever held it. The person approves the setup as init shows it, the specs, standards
112
+ * and design register it protects included, so until the commit that switches code-kit on the lead
113
+ * writes and commits them with no approval of their own. Once any commit has held the config it never
114
+ * is again, even after a commit takes the config away.
115
+ */
116
+ export function beforeSetup(root) {
117
+ const git = (...args) => {
118
+ try {
119
+ return execFileSync('git', ['-C', root, ...args], {
120
+ encoding: 'utf8',
121
+ stdio: ['ignore', 'pipe', 'ignore'],
122
+ });
123
+ } catch {
124
+ return null;
125
+ }
126
+ };
127
+ if (!existsSync(join(root, CONFIG_FILE))) return false;
128
+ if (git('check-ignore', '-q', CONFIG_FILE) !== null) return false;
129
+ return git('log', '--all', '--format=%H', '-1', '--', CONFIG_FILE) === '';
130
+ }
131
+
108
132
  /** HELM-2: whose decision approvals `names` are: the lead's when it may grant every one, else the person's. */
109
133
  export const decidedBy = (names, config, actor) =>
110
134
  [names].flat().every((n) => leadDecides(n, config, actor)) ? 'lead' : 'person';
@@ -572,7 +596,7 @@ function commitsFrom(root, path, at) {
572
596
  [
573
597
  ...['-C', root, 'log', '--all', '--format=%H'],
574
598
  `--since=@${Math.floor(Date.parse(at) / 1000)}`,
575
- ...['--', path],
599
+ ...['--', literalPath(path)],
576
600
  ],
577
601
  { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] },
578
602
  )
@@ -795,7 +819,7 @@ export function writeProblem(actor, rel, root, config) {
795
819
  if (target === approvals || target.startsWith(`${approvals}/`))
796
820
  return `${rel} is an approval. Only a person creates approvals, with a \`!\` shell command.`;
797
821
  if (rel.startsWith('..'))
798
- return outsideAllowed(actor, rel, root, config) ? null : `${rel} is outside the repository.`;
822
+ return outsideAllowed(actor, rel, root, config) ? null : outsideProblem(actor, rel);
799
823
  if (SECRETS(rel))
800
824
  return `${rel} may hold secrets. Secrets never go in files an agent writes; use the secret store.`;
801
825
  if (rel === APPROVAL_LOG)
@@ -810,7 +834,9 @@ export function writeProblem(actor, rel, root, config) {
810
834
  // The lead writes protected files without an approval where the person merges: they review them in
811
835
  // the pull request, and every committed change is in the audit log. Where the lead merges, what the
812
836
  // person keeps needs their approval (WHO-1). Anyone else needs an approval as well.
813
- const leadFree = actor.kind === 'lead' && !leadNeedsApproval(guarded?.approval, config);
837
+ const leadFree =
838
+ actor.kind === 'lead' &&
839
+ (!leadNeedsApproval(guarded?.approval, config) || (guarded && beforeSetup(root)));
814
840
  if (guarded && !leadFree && !approval(root, guarded.approval, actor)) {
815
841
  recordRequest(root, actor, guarded.approval, rel, guarded.why);
816
842
  const who =
@@ -830,13 +856,42 @@ export function writeProblem(actor, rel, root, config) {
830
856
  const readonlyProblem = (actor, rel) =>
831
857
  `${actor.label} is read-only; it may not write ${rel}. If a command you ran changed it (a build, a formatter or a code generator), put it back with git restore -- ${rel} (or delete it if it's new), and run such commands only in a throwaway worktree of the branch.`;
832
858
 
833
- // Claude Code's own temporary folders (a session's scratchpad, its tool output): no repository's files.
834
- const CLAUDE_TEMP = ['/private/tmp/claude-*/**', '/tmp/claude-*/**'];
859
+ /**
860
+ * Whether `rel` is in the folder Claude Code gives this session for its own temporary files
861
+ * (`/tmp/claude-<uid>/<project>/<session id>/`: its scratchpad and its tool output), outside every
862
+ * repository. A session's id is its own, so the folder is no other session's or project's.
863
+ */
864
+ function inSessionTemp(actor, rel, root) {
865
+ if (!actor.session || !/^[\w.-]+$/.test(actor.session)) return false;
866
+ // `rel` is from the root's real path: /tmp is /private/tmp on macOS.
867
+ const parts = resolve(realPath(root), rel)
868
+ .replace(/^\/private(?=\/tmp\/)/, '')
869
+ .split('/');
870
+ return (
871
+ parts[1] === 'tmp' &&
872
+ /^claude-[^/]+$/.test(parts[2] ?? '') &&
873
+ Boolean(parts[3]) &&
874
+ parts[4] === actor.session &&
875
+ parts.length > 5
876
+ );
877
+ }
878
+
879
+ /** Why a write outside the repository is refused, and where the actor's temporary files go instead. */
880
+ function outsideProblem(actor, rel) {
881
+ if (actor.kind === 'readonly')
882
+ return `${rel} is outside the repository, and ${actor.label} is read-only: it writes no files, temporary ones included.`;
883
+ const own = actor.session
884
+ ? `this session's own scratchpad, the folder Claude Code gives it under /tmp/claude-<uid>/<project>/${actor.session}/scratchpad/`
885
+ : "this session's own scratchpad, the folder Claude Code gives it under /tmp/claude-<uid>/<project>/<session id>/scratchpad/";
886
+ return `${rel} is outside the repository. Temporary files (a probe, a throwaway harness) go in ${own}; another session's is not this one's to write.${actor.kind === 'lead' ? ' Anywhere else outside the repository is the config\'s "lead.outside".' : ''}`;
887
+ }
835
888
 
836
889
  function outsideAllowed(actor, rel, root, config) {
837
890
  const target = resolve(root, rel);
838
- // A lane's scratch files go where Claude Code's own do, outside every repository.
839
- if (actor.kind === 'lane') return CLAUDE_TEMP.some((g) => globToRegExp(g).test(target));
891
+ // The session's scratch files go where Claude Code's own do, outside every repository.
892
+ if (actor.kind === 'lane' || actor.kind === 'lead') {
893
+ if (inSessionTemp(actor, rel, root)) return true;
894
+ }
840
895
  if (actor.kind !== 'lead') return false;
841
896
  return config.lead.outside.some((g) =>
842
897
  globToRegExp(resolve(root, g.replace(/^~(?=\/)/, homedir()))).test(target),
@@ -52,7 +52,8 @@ const LEADING =
52
52
  /**
53
53
  * The simple commands `cmd` runs, in order: split at `;`, `&`, `|`, newlines, parentheses and
54
54
  * backticks outside quotes, heredoc bodies left out, each without leading `VAR=value` assignments.
55
- * Each is `{ text, code }`: `text` as written, `code` with its quoted text masked.
55
+ * Each is `{ text, code, whole }`: `text` as written, `code` with its quoted text masked, and `whole`
56
+ * as written with its leading assignments and wrappers kept.
56
57
  */
57
58
  export function commandsOf(cmd) {
58
59
  const text = withoutHeredocs(cmd);
@@ -66,7 +67,8 @@ export function commandsOf(cmd) {
66
67
  const skip = body.match(LEADING)?.[0].length ?? 0;
67
68
  const from = start + lead + skip;
68
69
  const piece = text.slice(from, start + lead + body.length);
69
- if (piece) found.push({ text: piece, code: mask.slice(from, from + piece.length) });
70
+ if (piece)
71
+ found.push({ text: piece, code: mask.slice(from, from + piece.length), whole: body });
70
72
  };
71
73
  for (let i = 0; i < mask.length; i++)
72
74
  if (SEPARATOR.test(mask[i])) {
@@ -95,6 +97,9 @@ export const CODE_KIT = String.raw`(?:code-kit|node\s+(?:"[^"]*code-kit(?:\.mjs)
95
97
 
96
98
  // What a read may redirect: its errors into its output (2>&1, >&2), or anything into /dev/null.
97
99
  const HARMLESS_REDIRECT = /(?:\d+|&)?>>?\s*(?:&\d+|\/dev\/null(?![\w/.-]))/g;
100
+
101
+ /** `cmd` with its harmless redirects (`2>&1`, `>&2`, anything into /dev/null) taken out: they write no file. */
102
+ export const withoutHarmlessRedirects = (cmd) => String(cmd).replace(HARMLESS_REDIRECT, ' ');
98
103
  // An assignment before a command (GIT_PAGER=…, GIT_EXTERNAL_DIFF=…, LESSOPEN=…) can make a reader run a
99
104
  // program, so a read that sets one isn't only a read.
100
105
  const ASSIGNS = /^\s*(?:(?:sudo|exec|time|command|nohup|env)\s+|!\s+)*[A-Za-z_]\w*=/;
@@ -107,11 +112,20 @@ const READERS = [
107
112
  // less with no log file of what it shows.
108
113
  /^(?!.*\s(?:-[a-zA-Z]*[oO]|--log-file\b|--LOG-FILE\b))less(?:\s|$)/,
109
114
  /^(?!.*\s(?:--output\b|-O|--open-files-in-pager\b))git(?:\s+(?:-C\s+\S+|--no-pager|-P))*\s+(?:diff|log|show|blame|grep|status|cat-file|ls-files|shortlog|rev-parse)(?:\s|$)/,
115
+ // git branch only listing branches or naming the current one: no name to create, move or delete.
116
+ /^git(?:\s+(?:-C\s+\S+|--no-pager|-P))*\s+branch(?:\s+(?:--show-current|--list|-l|-a|--all|-r|--remotes|-vv?|--verbose|--no-color|--color|--merged|--no-merged))*\s*$/,
110
117
  // rg with no preprocessor; sort with no output file or compressor.
111
118
  /^(?!.*\s--pre\b)rg(?:\s|$)/,
112
119
  /^(?!.*\s(?:-[a-zA-Z]*o|--output\b|--compress-program\b))sort(?:\s|$)/,
113
120
  ];
114
121
 
122
+ // code-kit's own commands that only read and print: what the config says, who owns a path, the
123
+ // imports, a requirement's trail, the build's state, the next step and the approved designs (not their
124
+ // `evidence`, which records a screenshot), with nothing written but code-kit's own state.
125
+ const CODE_KIT_READS = new RegExp(
126
+ String.raw`^(?!.*\s--write\b)${CODE_KIT}\s+(?:check|who|unowned|diff|graph|trace|adapters|status|next|designs(?!\s+evidence\b))(?:\s|$)`,
127
+ );
128
+
115
129
  /** A command's words, quotes taken off. */
116
130
  const wordsOf = (text) =>
117
131
  (text.match(/'[^']*'|"(?:\\.|[^"\\])*"|\S+/g) ?? []).map((w) =>
@@ -173,7 +187,7 @@ const uniqPrints = (text) =>
173
187
  */
174
188
  export function readsOnly(cmd) {
175
189
  // Taken out first: `&` in `2>&1` would otherwise split the command there.
176
- const read = String(cmd).replace(HARMLESS_REDIRECT, ' ');
190
+ const read = withoutHarmlessRedirects(cmd);
177
191
  const code = codeOf(read);
178
192
  if (/[>`]|\$\(|<\(|<>/.test(code)) return false;
179
193
  if (code.split(/[;&|\n()]/).some((piece) => ASSIGNS.test(piece))) return false;
@@ -182,6 +196,7 @@ export function readsOnly(cmd) {
182
196
  parts.length > 0 &&
183
197
  parts.every(({ text, code: c }) => {
184
198
  if (READERS.some((re) => re.test(c))) return true;
199
+ if (CODE_KIT_READS.test(text)) return true;
185
200
  if (/^sed(?:\s|$)/.test(c)) return sedPrints(text);
186
201
  if (/^awk(?:\s|$)/.test(c)) return awkPrints(text);
187
202
  if (/^uniq(?:\s|$)/.test(c)) return uniqPrints(text);
@@ -189,3 +204,50 @@ export function readsOnly(cmd) {
189
204
  })
190
205
  );
191
206
  }
207
+
208
+ // What may come before a command it runs: a package runner (`npx`, `pnpm exec`, `uv run`…) or a wrapper
209
+ // (`xargs`, `nice`, `timeout 60`), so a rule naming the command finds it there too.
210
+ const WRAPPER = String.raw`(?:(?:npx|bunx|pnpx)(?:\s+-\S+)*\s+|(?:pnpm|yarn|bun)\s+(?:(?:exec|dlx|x|run)\s+)?(?:-\S+\s+)*|npm\s+(?:exec|x|run)\s+(?:--\s+)?|(?:uv|poetry|pipenv)\s+run\s+|(?:xargs|nice|nohup|time|command|exec)(?:\s+-\S+)*\s+|timeout\s+(?:-\S+\s+)*\S+\s+)`;
211
+ // A shell handed a script (`sh -c '…'`, `bash -lc "…"`): the script's commands run too, as do eval's.
212
+ const SHELL_SCRIPT = /^(?:ba|z|da|k)?sh\s+(?:-[a-zA-Z]+\s+)*-[a-zA-Z]*c[a-zA-Z]*\s/;
213
+ const SCRIPT_FLAG = /^-[a-zA-Z]*c[a-zA-Z]*$/;
214
+
215
+ /** The script a command hands a shell it starts (`sh -c '…'`) or `eval`, or null. */
216
+ function scriptOf({ text, code }) {
217
+ const words = wordsOf(text);
218
+ if (/^eval\s/.test(code)) return words.slice(1).join(' ');
219
+ if (!SHELL_SCRIPT.test(code)) return null;
220
+ const at = words.findIndex((w, i) => i > 0 && SCRIPT_FLAG.test(w));
221
+ return at > 0 ? (words[at + 1] ?? null) : null;
222
+ }
223
+
224
+ /**
225
+ * Whether `cmd` runs a command `pattern` names: matched from the start of each command the line runs
226
+ * (after a package runner or wrapper, and inside `sh -c` or `eval`), with quoted text masked unless the
227
+ * pattern itself has quotes, so an argument, a heredoc or a message that mentions the command isn't it.
228
+ */
229
+ export function runsNamed(cmd, pattern, depth = 0) {
230
+ const source = String(pattern).replace(/^\^/, '');
231
+ const quoted = /["']/.test(source);
232
+ const re = new RegExp(String.raw`^${WRAPPER}*(?:${source})`);
233
+ return commandsOf(cmd).some((c) => {
234
+ // The program's own name counts however it's quoted: `"tool" deploy` runs tool.
235
+ const first = c.text.match(/^(?:'[^']*'|"(?:\\.|[^"\\])*"|\S+)/)?.[0] ?? '';
236
+ const subject = quoted ? c.text : wordsOf(first).join('') + c.code.slice(first.length);
237
+ if (re.test(subject)) return true;
238
+ const script = depth < 3 ? scriptOf(c) : null;
239
+ return script !== null && runsNamed(script, pattern, depth + 1);
240
+ });
241
+ }
242
+
243
+ /**
244
+ * Whether a project's rule for a command (`shell.block`, `shell.restricted`: `{ pattern, command? }`)
245
+ * matches `cmd`. `command: true` matches the commands the line runs (runsNamed). Otherwise the pattern
246
+ * reads the whole line, except that in a line that only reads (readsOnly) quoted text is data: a grep
247
+ * for a blocked command doesn't run it.
248
+ */
249
+ export function ruleMatches({ pattern, command }, cmd) {
250
+ if (command) return runsNamed(cmd, pattern);
251
+ const quoted = /["']/.test(pattern);
252
+ return new RegExp(pattern).test(!quoted && readsOnly(cmd) ? codeOf(cmd) : cmd);
253
+ }
@@ -3,7 +3,7 @@
3
3
  // other tools read (`code-kit trace <path> --json`); Context Graph's adapter uses it to anchor a file's
4
4
  // card in the spec and to show the layer rule before an agent drafts an edit.
5
5
  import { execFileSync } from 'node:child_process';
6
- import { matchesAny } from './glob.mjs';
6
+ import { literalPath, matchesAny } from './glob.mjs';
7
7
  import { layerOf } from './layers.mjs';
8
8
  import { readRequirements, readStories } from './plan.mjs';
9
9
  import { ownerOf, reviewerOf } from './rules.mjs';
@@ -23,7 +23,8 @@ const git = (root, ...args) => {
23
23
  /** Story ids named by the commits that changed `rel`, and by the current branch if it is a story branch. */
24
24
  export function storiesOf(root, rel) {
25
25
  const ids = new Set();
26
- for (const m of git(root, 'log', '--format=%B', '--', rel).matchAll(/\bST-\d+\b/g)) ids.add(m[0]);
26
+ for (const m of git(root, 'log', '--format=%B', '--', literalPath(rel)).matchAll(/\bST-\d+\b/g))
27
+ ids.add(m[0]);
27
28
  const branch = git(root, 'rev-parse', '--abbrev-ref', 'HEAD').trim();
28
29
  const onBranch = /^[\w-]+\/(st-\d+)$/i.exec(branch)?.[1];
29
30
  if (onBranch) ids.add(onBranch.toUpperCase());
@@ -11,7 +11,7 @@ import { isDependencyFile } from './dependencies.mjs';
11
11
  import { entryProblems, freshEntries, readRegister, statesWithoutEvidence } from './designs.mjs';
12
12
  import { evidenceRecords } from './reviews.mjs';
13
13
  import { storyOfBranch } from './teamfacts.mjs';
14
- import { matchesAny } from './glob.mjs';
14
+ import { literalPath, matchesAny } from './glob.mjs';
15
15
  import { layerProblems } from './layers.mjs';
16
16
  import { STANDARDS_APPROVAL, standardsFile, standardsWeakenings } from './standards.mjs';
17
17
  import { TESTS_APPROVAL, branchWeakenings, fixOf, proveFix } from './regression.mjs';
@@ -138,7 +138,7 @@ function logEntries(root, base) {
138
138
  */
139
139
  function signedByPerson(root, from, file, signedBy) {
140
140
  if (!signedBy) return false;
141
- const out = git(root, 'log', '--format=%B%x1e', `${from}..HEAD`, '--', file);
141
+ const out = git(root, 'log', '--format=%B%x1e', `${from}..HEAD`, '--', literalPath(file));
142
142
  const messages = out
143
143
  .split('\x1e')
144
144
  .map((m) => m.trim())
@@ -340,8 +340,16 @@ export function verifyBranch({
340
340
  Boolean(r.sha) &&
341
341
  spawnSync('git', ['-C', root, 'merge-base', '--is-ancestor', r.sha, 'HEAD']).status ===
342
342
  0 &&
343
- spawnSync('git', ['-C', root, 'diff', '--quiet', r.sha, 'HEAD', '--', r.file]).status ===
344
- 0;
343
+ spawnSync('git', [
344
+ '-C',
345
+ root,
346
+ 'diff',
347
+ '--quiet',
348
+ r.sha,
349
+ 'HEAD',
350
+ '--',
351
+ literalPath(r.file),
352
+ ]).status === 0;
345
353
  const story = storyOfBranch(name) ?? name;
346
354
  for (const { entry, state } of statesWithoutEvidence(entries, present, records, current))
347
355
  found.evidence.push(
@@ -161,12 +161,14 @@ export const BUSY_MS = 3 * 60_000;
161
161
  /**
162
162
  * LEAN-6: whether a lane agent is still at work on a worktree's story, by the story's event log (spec
163
163
  * 26): its lane's last act is still open, or came within BUSY_MS, with no hand-back or stop after it. Releasing
164
- * a worktree under a running agent takes its git away mid-step.
164
+ * a worktree under a running agent takes its git away mid-step. Only the branch's own lane counts: the
165
+ * lead's helpers (a reviewer, a security reviewer) act on the story too, but never commit on its branch.
165
166
  */
166
167
  export function agentBusy(root, w, now = Date.now()) {
167
- if (!w.story) return false;
168
+ if (!w.story || !w.branch?.includes('/')) return false;
169
+ const lane = w.branch.split('/')[0];
168
170
  const last = readEvents(root, w.story)
169
- .filter((e) => e.actor && e.actor !== 'lead' && e.agent)
171
+ .filter((e) => e.actor === lane && e.agent)
170
172
  .at(-1);
171
173
  if (!last || ['handback', 'stopped'].includes(last.kind)) return false;
172
174
  return last.phase === 'start' || now - Date.parse(last.at) < BUSY_MS;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@warren-dean/code-kit",
3
- "version": "0.30.0",
3
+ "version": "0.30.2",
4
4
  "description": "Keeps AI coding agents inside your project's rules: lanes, layer rules, protected paths and proof before finish, enforced by Claude Code hooks and in CI",
5
5
  "license": "MIT",
6
6
  "author": "Warren Langeveldt",
@@ -71,7 +71,7 @@ Write `.claude/code-kit.draft.json`. Follow `${CLAUDE_PLUGIN_ROOT}/README.md`
71
71
  - `screens`: a glob for each such lane's screen files (routes, pages, views), from the architecture's folders, with `not` for tests and stories;
72
72
  - `howTo`: "Design it first: run /code-kit:design for this area's design story, and a person approves it.";
73
73
  - a `protected` entry for the register (approval `design`, why "only approved designs are built"). Never put `design` in `approvals.delegate`: approving a design is the person's.
74
- - **`shell.block`:** deploy, release and production commands reserved for CI or a person.
74
+ - **`shell.block`:** deploy, release and production commands reserved for CI or a person. Each rule that names a command (`cdk deploy`, `supabase db push`, `terraform apply`) gets `"command": true`, with a pattern for the command and its arguments (`"cdk\\s+deploy\\b"`), so a grep, a heredoc or a commit message that mentions the command isn't refused, while running it, after `cd …`, through `npx` or `pnpm exec`, or in `sh -c`, still is. Leave `command` out only for a rule about the whole line, such as a download piped into a shell.
75
75
  - **`shell.restricted`:** commands that affect a shared local service, limited to the lanes that own it.
76
76
  - **`postEdit`:** the project's existing per-file linters and formatters, with `{file}`.
77
77
  - **`checks`:** the typecheck, test, architecture and database commands, each scoped by `files`. Only include commands that pass on the current code, or ones the person chose to keep.
@@ -162,7 +162,7 @@ Once they approve (with any changes):
162
162
  - tell the person to make the `code-kit` check required on the protected branches;
163
163
  - run `code-kit ci check` on the project's own workflows. Each story is its own branch, pull request and merge, so a workflow that runs its full suite on every push to the base or every pull request runs once per story, after the merge queue has already run the checks. Show the person what it found and the changes you propose: the full suite on `release/**` instead (`code-kit release <version>` cuts one when they release), a `timeout-minutes` on each job, and `concurrency` with `cancel-in-progress` on pull requests. Changing CI is theirs to approve (approval `ci`); make only the changes they approve.
164
164
  7. Run `check` and `unowned` again, without `--config`.
165
- 8. Commit the setup straight onto the base branch (usually `main`), not a branch: while the base has no `.claude/code-kit.json` committed, the hooks let the lead make that one commit, so the rules the person just approved are in force on `main` and the lead can merge reviewed work from the start, with no first merge for anyone to make. The kit records the protected files in `.claude/approval-log.jsonl`. If the base already has rules (an update, section 4), commit on a branch as usual.
165
+ 8. Commit the setup straight onto the base branch (usually `main`), not a branch: while the base has no `.claude/code-kit.json` committed, the hooks let the lead make that one commit, so the rules the person just approved are in force on `main` and the lead can merge reviewed work from the start, with no first merge for anyone to make. The person's approval of the setup covers the protected files in it (the specs, the standards, the design register): they need no approvals of their own in that commit, and the kit records each in `.claude/approval-log.jsonl` as part of the setup. Don't ask the person for them. If the base already has rules (an update, section 4), commit on a branch as usual.
166
166
  9. **A team, only if there is one.** Not every developer works in a team. Ask once: "Do other developers work in this repository with their own Claude Code sessions?" If yes, run `/code-kit:team-init` now (it asks who the tech lead is and who owns which lanes, and writes the `team` section). If no, or not yet, leave it out and say `/code-kit:team-init` sets it up any time.
167
167
  10. Set up each companion the config now wants (`"adapters": { "<name>": true }`) by running its init skill, for example `/context-graph:init`, which asks nothing. Do it before reporting, so it's in place before the coding loop starts; `code-kit next` also gives `setup` until it is.
168
168