@warren-dean/code-kit 0.26.1 → 0.27.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.
@@ -18,6 +18,7 @@ import { CODE_KIT, GIT, codeOf, commandsOf, runs } from './lib/shell.mjs';
18
18
  import { block, start } from './lib/hook.mjs';
19
19
  import { CONFIG_FILE, committedConfig } from './lib/config.mjs';
20
20
  import { laneOfBranch, storyOfBranch, teamOf, teamProvider, whoami } from './lib/team.mjs';
21
+ import { entryProblems, readRegister } from './lib/designs.mjs';
21
22
  import { globToRegExp, matchesAny } from './lib/glob.mjs';
22
23
  import { noteBefore } from './lane-audit.mjs';
23
24
  import { storyMerges } from './lib/queue.mjs';
@@ -44,6 +45,8 @@ import {
44
45
  useApproval,
45
46
  owns,
46
47
  protectedEntry,
48
+ leadNeedsApproval,
49
+ approvalEnded,
47
50
  recordRequest,
48
51
  sessionRoot,
49
52
  } from './lib/rules.mjs';
@@ -115,7 +118,7 @@ const queues = runs(cmd, new RegExp(String.raw`^${CODE_KIT}\s+queue\s+(?:add|dro
115
118
  const rulesOntoBase = runs(cmd, new RegExp(String.raw`^${CODE_KIT}\s+queue\s+rules\b`));
116
119
  const asks = runs(cmd, new RegExp(String.raw`^${CODE_KIT}\s+ask\b\s+(?!--json\b)\S`));
117
120
  const dropsRequests = runs(cmd, new RegExp(String.raw`^${CODE_KIT}\s+requests\s+drop\b`));
118
- const commits = runs(cmd, new RegExp(String.raw`^${GIT}commit\b`));
121
+ const commits = runs(cmd, new RegExp(String.raw`^${GIT}commit(?![\w-])`));
119
122
  if (error) {
120
123
  if (commits) block(`Blocked: ${error}\nFix the config before committing.`);
121
124
  if (approves) block(`Blocked: ${error}\nApprovals wait until the config is valid.`);
@@ -141,7 +144,7 @@ function committedOnHead(root, file) {
141
144
 
142
145
  const writesHistory = runs(
143
146
  cmd,
144
- new RegExp(String.raw`^${GIT}(commit|merge|cherry-pick|rebase|revert|am)\b`),
147
+ new RegExp(String.raw`^${GIT}(commit|merge|cherry-pick|rebase|revert|am)(?![\w-])`),
145
148
  );
146
149
  const switchesToProtected = runs(
147
150
  cmd,
@@ -393,8 +396,8 @@ try {
393
396
  // that commit on, the branch is protected by the rules it now holds.
394
397
  const settingUp =
395
398
  actor.kind === 'lead' &&
396
- runs(cmd, new RegExp(String.raw`^${GIT}commit\b`)) &&
397
- !runs(cmd, new RegExp(String.raw`^${GIT}(merge|cherry-pick|rebase|revert|am)\b`)) &&
399
+ runs(cmd, new RegExp(String.raw`^${GIT}commit(?![\w-])`)) &&
400
+ !runs(cmd, new RegExp(String.raw`^${GIT}(merge|cherry-pick|rebase|revert|am)(?![\w-])`)) &&
398
401
  !committedOnHead(root, CONFIG_FILE);
399
402
  if (writesHistory && config.branches.protected.includes(branch) && !settingUp) {
400
403
  block(
@@ -513,12 +516,27 @@ function committedFiles() {
513
516
  const changed = names(git('status', '--porcelain', '-uall', '--no-renames')).map((l) =>
514
517
  l.slice(3),
515
518
  );
516
- const commitAll = /\bgit\s+commit\b[^;&|]*\s(-a|--all|-[b-zB-Z]*a[a-zA-Z]*)(\s|$)/.test(cmd);
517
- const addAll = /\bgit\s+add\b[^;&|]*\s(-A|--all|\.)(\s|$)/.test(cmd);
518
- const addArgs = [...cmd.matchAll(/\bgit\s+add\s+([^;&|]+)/g)]
519
- .flatMap((m) => m[1].trim().split(/\s+/))
520
- .filter((a) => a && !a.startsWith('-'))
521
- .map((a) => a.replace(/^(['"])(.*)\1$/, '$2'));
519
+ // Each git command of the chain, however it's run (`git -C <worktree> add`).
520
+ const pieces = commandsOf(cmd).map((c) => c.text);
521
+ const gitRun = (sub) =>
522
+ pieces.map((p) => p.match(new RegExp(String.raw`^${GIT}${sub}`))).filter(Boolean);
523
+ const commitAll = gitRun(String.raw`commit(?![\w-])(.*)`).some((m) =>
524
+ /\s(-a|--all|-[b-zB-Z]*a[a-zA-Z]*)(\s|$)/.test(` ${m[1]}`),
525
+ );
526
+ const argsOf = (m) =>
527
+ m[1]
528
+ .trim()
529
+ .split(/\s+/)
530
+ .filter((a) => a && !a.startsWith('-'))
531
+ .map((a) => a.replace(/^(['"])(.*)\1$/, '$2'));
532
+ const addRuns = gitRun(String.raw`add\b(.*)`);
533
+ const addAll = addRuns.some((m) => /\s(-A|--all|\.)(\s|$)/.test(` ${m[1]}`));
534
+ // `git rm` and `git mv` stage as they run: their files count though nothing has changed them yet, and
535
+ // what they take away is gone from the commit though it's still on disk now.
536
+ const rmArgs = gitRun(String.raw`rm\b(.*)`).flatMap(argsOf);
537
+ const mvArgs = gitRun(String.raw`mv\b(.*)`).map(argsOf);
538
+ const moved = [...rmArgs, ...mvArgs.flat()];
539
+ const addArgs = [...addRuns.flatMap(argsOf), ...moved];
522
540
  // What the shell expands before git sees it (#76): an argument it can't be read from, such as a
523
541
  // variable or a command's output, could be any file, so every changed file counts.
524
542
  const unknowable = addArgs.some((a) => /[$`]/.test(a));
@@ -532,12 +550,16 @@ function committedFiles() {
532
550
  const added = changed.filter(
533
551
  (f) => commitAll || addAll || unknowable || addArgs.some((a) => matches(f, a)),
534
552
  );
553
+ const tracked = moved.length ? names(git('ls-files')) : [];
554
+ const removed = tracked.filter((f) => moved.some((a) => matches(f, a)));
555
+ const takenAway = [...rmArgs, ...mvArgs.flatMap((args) => args.slice(0, -1))];
556
+ const gone = new Set(tracked.filter((f) => takenAway.some((a) => matches(f, a))));
535
557
  // `git reset --soft <ref> && git commit` commits everything since <ref>, staged by the reset (#76).
536
- const resetTo = [...cmd.matchAll(/\bgit\s+reset\s+--soft\s+([^\s;&|]+)/g)].map((m) => m[1]);
558
+ const resetTo = gitRun(String.raw`reset\s+--soft\s+(\S+)`).map((m) => m[1]);
537
559
  const reset = resetTo.flatMap((ref) =>
538
560
  names(git('diff', '--name-only', '--no-renames', ref, 'HEAD')),
539
561
  );
540
- return { files: [...new Set([...staged, ...added, ...reset])], git };
562
+ return { files: [...new Set([...staged, ...added, ...removed, ...reset])], gone, git };
541
563
  }
542
564
 
543
565
  // Every committed protected file is recorded in the audit log, with the person's reason when an
@@ -545,7 +567,7 @@ function committedFiles() {
545
567
  // dependency approval: that entry is how `code-kit verify` accepts it. The log is staged into the same
546
568
  // commit, so record and change land together.
547
569
  function recordApprovals() {
548
- const { files, git } = committedFiles();
570
+ const { files, gone, git } = committedFiles();
549
571
  const lines = [];
550
572
  const record = (file, fields) =>
551
573
  lines.push(
@@ -595,10 +617,11 @@ function recordApprovals() {
595
617
  : null);
596
618
  const granted = entry && approval(root, entry.approval, actor);
597
619
  const byDependency = actor.kind === 'lane' && dependencyChange(actor, file, root, config);
598
- if (entry && !granted && actor.kind !== 'lead' && !byDependency) {
620
+ const leadFree = actor.kind === 'lead' && !leadNeedsApproval(entry?.approval, config);
621
+ if (entry && !granted && !leadFree && !byDependency) {
599
622
  recordRequest(root, actor, entry.approval, file, entry.why);
600
623
  block(
601
- `Blocked: ${file} is ${entry.why}; committing it needs ${decidedBy(entry.approval, config, actor) === 'lead' ? "the lead's" : "a person's"} approval in force.${noteFor(root, config, { kind: 'protected', name: entry.approval, glob: entry.glob })} ${askHowTo(entry.approval, actor, root, config)}`,
624
+ `Blocked: ${file} is ${entry.why}; committing it needs ${decidedBy(entry.approval, config, actor) === 'lead' ? "the lead's" : "a person's"} approval in force.${approvalEnded(root, entry.approval, actor)}${noteFor(root, config, { kind: 'protected', name: entry.approval, glob: entry.glob })} ${askHowTo(entry.approval, actor, root, config)}`,
602
625
  );
603
626
  }
604
627
  if (granted)
@@ -630,6 +653,8 @@ function recordApprovals() {
630
653
  root,
631
654
  files.filter((f) => !arrivesWithMerge(root, f, { staged: true })),
632
655
  config,
656
+ gone,
657
+ config.branches.protected[0],
633
658
  );
634
659
  if (weakened.length) {
635
660
  const granted = approval(root, TESTS_APPROVAL, actor);
@@ -646,7 +671,7 @@ function recordApprovals() {
646
671
  ? `Also weakened: ${more.map((x) => `${x.file} (${said(x)})`).join('; ')}.
647
672
  `
648
673
  : '') +
649
- `A weakened test can hide a regression. Fix the code so the test passes as it was. ` +
674
+ `A weakened test can hide a regression.${approvalEnded(root, TESTS_APPROVAL, actor)} Fix the code so the test passes as it was. ` +
650
675
  (leads
651
676
  ? `If the test itself is wrong, the lead decides after reviewing it: ${askHowTo(TESTS_APPROVAL, actor, root, config, { allows: 'weakening tests in one commit', need: 'the test, what you weakened and why the test was wrong, and the story' })}`
652
677
  : `If the test itself is wrong, ask the person: ${actor.kind === 'lead' ? "on your own branch nobody else reviews it, so you can't approve it." : "the lead can't approve it here."} They run
@@ -686,8 +711,41 @@ ${approvalHowTo(TESTS_APPROVAL, actor, root, 'weakening tests in one commit', pe
686
711
  git('add', APPROVAL_LOG);
687
712
  }
688
713
 
714
+ // The commit hook judges what the commit holds before the command runs, so a file a command earlier in
715
+ // the chain writes (a formatter, a script, a heredoc) can't be seen, and would go in unjudged and
716
+ // unlogged. Before the commit, a chain may only move into the checkout and stage.
717
+ const BEFORE_COMMIT = new RegExp(
718
+ String.raw`^(?:cd\s|${GIT}(?:add|rm|mv|status|diff|log|show|restore\s+--staged|reset\s+--soft)(?![\w-]))`,
719
+ );
720
+ function writesBeforeCommit() {
721
+ const pieces = commandsOf(cmd);
722
+ const at = pieces.findIndex((c) => new RegExp(String.raw`^${GIT}commit(?![\w-])`).test(c.text));
723
+ return pieces
724
+ .slice(0, Math.max(at, 0))
725
+ .find((c) => !BEFORE_COMMIT.test(c.text) || /[<>]/.test(c.code));
726
+ }
727
+
689
728
  if (commits) {
690
- recordApprovals();
729
+ const writer = writesBeforeCommit();
730
+ if (writer)
731
+ block(
732
+ `Blocked: this commit runs after \`${writer.text.slice(0, 80)}\` in the same command, which may write files code-kit can't see before the commit, so they would go in without their checks or their entry in the approval log. Run that first, on its own; then commit in a command of its own (\`git add … && git commit …\` is fine).\nCommand: ${cmd}`,
733
+ );
734
+ // HAND-2: a register entry this commit adds or changes names the approved design's files, as approved.
735
+ const register = config.designGate?.register;
736
+ if (register && committedFiles().files.includes(register)) {
737
+ const before = spawnSync('git', ['-C', root, 'show', `HEAD:${register}`], { encoding: 'utf8' });
738
+ const old = before.status === 0 ? readRegister(root, config, before.stdout).entries : [];
739
+ const same = (e) => old.some((o) => JSON.stringify(o) === JSON.stringify(e));
740
+ const problems = readRegister(root, config)
741
+ .entries.filter((e) => !same(e))
742
+ .flatMap((e) => entryProblems(root, e, config.docs?.specs));
743
+ if (problems.length)
744
+ block(
745
+ `Blocked: ${register} names approved designs a lane can't build from as approved:\n ${problems.join('\n ')}\nEach screen's design is files in the repository, every state, with its hash (docs/specs/24-designs-handed-over.md).\nCommand: ${cmd}`,
746
+ );
747
+ }
748
+ // Every refusal comes before approvals are spent and logged, so a refused commit spends none.
691
749
  const scan = spawnSync('gitleaks', ['protect', '--staged', '--redact', '--no-banner'], {
692
750
  cwd: root,
693
751
  encoding: 'utf8',
@@ -697,5 +755,6 @@ if (commits) {
697
755
  `Blocked: gitleaks found possible secrets in staged changes.\n${scan.stdout}${scan.stderr}`,
698
756
  );
699
757
  }
758
+ recordApprovals();
700
759
  }
701
760
  process.exit(0);
@@ -0,0 +1,105 @@
1
+ // A fresh checkout of the project, for checks that mustn't run in anyone's worktree: the merge queue's
2
+ // verify of a branch merged with the base as it is now (MQ-1), and the fix check's tree with the fix
3
+ // taken out (REG-1). It's a temporary worktree with its own copy of the installs (node_modules and
4
+ // the like): a link back to a worktree's installs resolves outside the checkout, which path-sensitive
5
+ // tools refuse, and an install run in it would rewrite the worktree's own.
6
+ import { execFileSync, spawnSync } from 'node:child_process';
7
+ import { existsSync, mkdtempSync, rmSync } from 'node:fs';
8
+ import { platform, tmpdir } from 'node:os';
9
+ import { basename, dirname, join } from 'node:path';
10
+
11
+ // The folders an install puts beside the code, which a fresh checkout lacks.
12
+ const INSTALLS = new Set(['node_modules', '.venv', 'venv']);
13
+
14
+ const git = (cwd, ...args) =>
15
+ execFileSync('git', ['-C', cwd, ...args], {
16
+ encoding: 'utf8',
17
+ stdio: ['ignore', 'pipe', 'pipe'],
18
+ maxBuffer: 64 * 1024 * 1024,
19
+ });
20
+
21
+ /** The installs git ignores in `root`, repo-relative, outermost only. */
22
+ export function installsOf(root) {
23
+ try {
24
+ return git(root, 'ls-files', '--others', '--ignored', '--exclude-standard', '--directory')
25
+ .split('\n')
26
+ .map((l) => l.replace(/\/$/, ''))
27
+ .filter((l) => l && INSTALLS.has(basename(l)));
28
+ } catch {
29
+ return [];
30
+ }
31
+ }
32
+
33
+ /**
34
+ * Copies `root`'s installs into `dir`, each where it sits in `root`, keeping the symlinks inside them
35
+ * as they are. A copy-on-write clone where the filesystem has one (APFS, btrfs, XFS), so it's quick
36
+ * and takes no room; a plain copy elsewhere. What can't be copied is left out, and the check that
37
+ * needs it says what it couldn't run.
38
+ */
39
+ export function copyInstalls(root, dir) {
40
+ const clone = platform() === 'darwin' ? ['-c', '-R'] : ['-R', '--reflink=auto'];
41
+ for (const rel of installsOf(root)) {
42
+ const to = join(dir, rel);
43
+ if (!existsSync(dirname(to)) || existsSync(to)) continue;
44
+ const from = join(root, rel);
45
+ const cloned = spawnSync('cp', [...clone, from, to], { stdio: 'ignore' });
46
+ if (cloned.status !== 0) {
47
+ rmSync(to, { recursive: true, force: true, maxRetries: 3 });
48
+ spawnSync('cp', ['-R', from, to], { stdio: 'ignore' });
49
+ }
50
+ }
51
+ }
52
+
53
+ /**
54
+ * A temporary worktree of `ref` (detached), with `merge` merged into it when given, and the installs
55
+ * of `installsFrom` copied in. `{ dir, remove }`; a merge that conflicts throws a `conflict` error
56
+ * after removing what it made. `remove` never throws: a folder that won't go is left to the OS.
57
+ */
58
+ export function freshCheckout(
59
+ root,
60
+ ref,
61
+ { merge = null, installsFrom = root, prefix = 'code-kit-' } = {},
62
+ ) {
63
+ const dir = mkdtempSync(join(tmpdir(), prefix));
64
+ rmSync(dir, { recursive: true });
65
+ git(root, 'worktree', 'add', '--quiet', '--detach', dir, ref);
66
+ const remove = () => {
67
+ try {
68
+ git(root, 'worktree', 'remove', '--force', dir);
69
+ } catch {
70
+ // git leaves it when a process still writes there; the folder goes, and git prunes its record
71
+ }
72
+ try {
73
+ rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 });
74
+ git(root, 'worktree', 'prune');
75
+ } catch {
76
+ // the OS clears its temporary folder
77
+ }
78
+ };
79
+ if (merge) {
80
+ const merged = spawnSync(
81
+ 'git',
82
+ [
83
+ '-C',
84
+ dir,
85
+ '-c',
86
+ 'user.name=code-kit',
87
+ '-c',
88
+ 'user.email=code-kit@localhost',
89
+ 'merge',
90
+ '--no-ff',
91
+ '--no-edit',
92
+ '--quiet',
93
+ merge,
94
+ ],
95
+ { encoding: 'utf8' },
96
+ );
97
+ if (merged.status !== 0) {
98
+ const why = `${merged.stdout ?? ''}${merged.stderr ?? ''}`.trim();
99
+ remove();
100
+ throw Object.assign(new Error(why || 'the merge conflicts'), { conflict: true });
101
+ }
102
+ }
103
+ copyInstalls(installsFrom, dir);
104
+ return { dir, remove };
105
+ }
@@ -1,10 +1,41 @@
1
1
  // The project's checks (config.checks): each runs when files matching it changed. Shared by the stop
2
2
  // hook (before an agent finishes) and `code-kit verify` (in CI, for a branch's changes).
3
3
  import { spawnSync } from 'node:child_process';
4
- import { existsSync } from 'node:fs';
4
+ import { closeSync, existsSync, fstatSync, mkdtempSync, openSync, readSync, rmSync } from 'node:fs';
5
+ import { tmpdir } from 'node:os';
5
6
  import { join } from 'node:path';
6
7
  import { globToRegExp, matchesAny } from './glob.mjs';
7
8
 
9
+ /** How much of a check's output is kept to show: its end, where test runners put the failures. */
10
+ const OUTPUT_KEPT = 256 * 1024;
11
+
12
+ /**
13
+ * Runs a check's command with its output going to a file rather than a buffer, so a long run's output
14
+ * (a thousand tests' worth) never stops it: the exit code decides. `{ status, signal, error, output }`,
15
+ * the output's last OUTPUT_KEPT bytes.
16
+ */
17
+ function runCommand(command, cwd, timeout) {
18
+ const dir = mkdtempSync(join(tmpdir(), 'code-kit-check-'));
19
+ const file = join(dir, 'output');
20
+ const fd = openSync(file, 'w+');
21
+ try {
22
+ const res = spawnSync(command, { cwd, shell: true, timeout, stdio: ['ignore', fd, fd] });
23
+ const size = fstatSync(fd).size;
24
+ const length = Math.min(size, OUTPUT_KEPT);
25
+ const tail = Buffer.alloc(length);
26
+ readSync(fd, tail, 0, length, size - length);
27
+ return {
28
+ status: res.status,
29
+ signal: res.signal,
30
+ error: res.error,
31
+ output: `${size > length ? '…\n' : ''}${tail.toString('utf8')}`,
32
+ };
33
+ } finally {
34
+ closeSync(fd);
35
+ rmSync(dir, { recursive: true, force: true });
36
+ }
37
+ }
38
+
8
39
  /** The directories a check runs in: each changed one matching `each` that still exists, or the worktree. */
9
40
  function directories(check, files, root) {
10
41
  if (!check.each) return [root];
@@ -30,12 +61,7 @@ function runCheck(check, files, root, actor, skipped) {
30
61
  }
31
62
  for (const cwd of directories(check, files, root)) {
32
63
  for (const command of check.run) {
33
- const res = spawnSync(command, {
34
- cwd,
35
- shell: true,
36
- encoding: 'utf8',
37
- timeout: (check.timeoutSeconds ?? 240) * 1000,
38
- });
64
+ const res = runCommand(command, cwd, (check.timeoutSeconds ?? 240) * 1000);
39
65
  const where = cwd === root ? '' : ` in ${cwd.slice(root.length + 1)}`;
40
66
  if (res.status === 127) {
41
67
  if (check.ifMissing === 'fail')
@@ -57,7 +83,7 @@ function runCheck(check, files, root, actor, skipped) {
57
83
  return {
58
84
  check: check.name,
59
85
  title: `${check.name}: \`${command}\` fails${where}. Fix it:`,
60
- output: res.stdout + res.stderr,
86
+ output: res.output,
61
87
  };
62
88
  }
63
89
  }
@@ -74,12 +74,15 @@ export const effectiveConfig = (raw, root) => applyAdapters(withDefaults(raw), r
74
74
  /** An anyActor entry's glob: entries are globs, or { glob, reviewer } naming who reviews changes to it. */
75
75
  export const anyActorGlob = (e) => (typeof e === 'string' ? e : e?.glob);
76
76
 
77
- /** The engine's fixed rules, merged into the project's: the kit and Claude's own files belong to the lead. */
77
+ /**
78
+ * The engine's fixed rules, merged into the project's: the kit and Claude's own files belong to the
79
+ * lead, the project's MCP servers (`.mcp.json`, which a team provider's connect writes) among them.
80
+ */
78
81
  export function withDefaults(c) {
79
82
  return {
80
83
  ...c,
81
84
  lead: {
82
- paths: [...c.lead.paths, '.claude/**'],
85
+ paths: [...c.lead.paths, '.claude/**', '.mcp.json'],
83
86
  outside: [...(c.lead.outside ?? []), ...CLAUDE_OWN],
84
87
  },
85
88
  anyActor: [...(c.anyActor ?? []).map(anyActorGlob), '.claude/state/**'],
@@ -118,6 +118,9 @@ function packagesWithManagers(cmd) {
118
118
  quoted: /^["']/.test(m[0]),
119
119
  word: text.slice(m.index, m.index + m[0].length).replace(/^["']|["']$/g, ''),
120
120
  }));
121
+ // What a container installs is the container's: the project's manifests don't change, and a
122
+ // mounted project whose manifests do is still held to its dependency approvals when committed.
123
+ if (CONTAINERS.has(basename(words[0]?.word ?? ''))) continue;
121
124
  words.forEach(({ word, quoted }, i) => {
122
125
  if (quoted) return;
123
126
  if (SHELLS.has(basename(word)) && words[i + 1]?.word === '-c' && words[i + 2])
@@ -136,6 +139,7 @@ function packagesWithManagers(cmd) {
136
139
  }
137
140
 
138
141
  const SHELLS = new Set(['sh', 'bash', 'zsh']);
142
+ const CONTAINERS = new Set(['docker', 'podman', 'nerdctl']);
139
143
 
140
144
  // The words after a package manager's name: its subcommand must be one that adds packages, and the
141
145
  // words after that, other than flags and their values, are the packages.
@@ -0,0 +1,137 @@
1
+ // Designs handed over (docs/specs/24-designs-handed-over.md). An approved design is files in the
2
+ // repository, each state's code where the tool gives it and a PNG, named in the design register with a
3
+ // hash of each, so a lane builds from what the person approved and the review compares with it. The
4
+ // design gate (ONB-2) refuses a screen until the register lists it; this checks what the register holds.
5
+ import { createHash } from 'node:crypto';
6
+ import { readFileSync } from 'node:fs';
7
+ import { join } from 'node:path';
8
+ import { markdownFiles } from './plan.mjs';
9
+
10
+ /** The states a screen has when its spec names none: the ones every screen is asked for. */
11
+ export const STATE_WORDS = ['default', 'empty', 'loading', 'error'];
12
+
13
+ /** A file's sha256, or null when it isn't there. */
14
+ export function sha256Of(root, rel) {
15
+ try {
16
+ return createHash('sha256')
17
+ .update(readFileSync(join(root, rel)))
18
+ .digest('hex');
19
+ } catch {
20
+ return null;
21
+ }
22
+ }
23
+
24
+ /** The register's entries: `{ entries }`, or `{ entries: [], error }` when it can't be read. */
25
+ export function readRegister(root, config, text = null) {
26
+ const register = config.designGate?.register;
27
+ if (!register) return { entries: [] };
28
+ try {
29
+ const raw = JSON.parse(text ?? readFileSync(join(root, register), 'utf8'));
30
+ return { entries: Array.isArray(raw.screens) ? raw.screens : [] };
31
+ } catch (e) {
32
+ return { entries: [], error: `${register} is missing or invalid (${e.message}).` };
33
+ }
34
+ }
35
+
36
+ /** HAND-2: whether an entry's design is files in the repository rather than only in a design tool. */
37
+ export const handedOver = (entry) => Array.isArray(entry?.states) && entry.states.length > 0;
38
+
39
+ /** The tool an entry's design lives in, for an entry not handed over yet: "paper" from "paper:…". */
40
+ export const toolOf = (entry) =>
41
+ entry?.source?.tool ??
42
+ String(entry?.design ?? '').match(/^([a-z][\w-]*):/i)?.[1] ??
43
+ 'the design tool';
44
+
45
+ /**
46
+ * HAND-2: the states the specs' `## Screens` sections give `screen`: its `**States:**` line, or else the
47
+ * usual state words its text mentions (default always). Null when no spec lists the screen.
48
+ */
49
+ export function screenStates(root, specs, screen) {
50
+ if (!specs || !screen) return null;
51
+ const name = String(screen).toLowerCase();
52
+ for (const file of markdownFiles(root, specs)) {
53
+ let text;
54
+ try {
55
+ text = readFileSync(join(root, file), 'utf8');
56
+ } catch {
57
+ continue;
58
+ }
59
+ const section = text.split(/^## /m).find((s) => /^Screens\b/i.test(s));
60
+ if (!section) continue;
61
+ const lines = section.split('\n');
62
+ const at = lines.findIndex(
63
+ (l, i) => i > 0 && /^(#{3,4}\s|\s*[-*]\s)/.test(l) && l.toLowerCase().includes(name),
64
+ );
65
+ if (at < 0) continue;
66
+ const ownIndent = lines[at].match(/^\s*/)[0].length;
67
+ const isHeading = /^#{3,4}\s/.test(lines[at]);
68
+ const block = [lines[at]];
69
+ for (const l of lines.slice(at + 1)) {
70
+ if (/^#{1,4}\s/.test(l)) break;
71
+ if (!isHeading && /^\s*[-*]\s/.test(l) && l.match(/^\s*/)[0].length <= ownIndent) break;
72
+ block.push(l);
73
+ }
74
+ const body = block.join('\n');
75
+ const listed = body.match(/\*\*States:\*\*\s*(.+)/i)?.[1];
76
+ if (listed)
77
+ return listed
78
+ .split(/[,;]/)
79
+ .map((s) => s.trim().toLowerCase().replace(/\.$/, ''))
80
+ .filter(Boolean);
81
+ return STATE_WORDS.filter((w) => w === 'default' || new RegExp(`\\b${w}\\b`, 'i').test(body));
82
+ }
83
+ return null;
84
+ }
85
+
86
+ /**
87
+ * HAND-2: what's wrong with a register entry, in sentences naming the screen, the state and the file:
88
+ * a design only in a tool, a field missing, a file not there, a hash that isn't the approved one, or a
89
+ * state the spec lists with none. `specs` is the specs' folder, for the states each screen should have.
90
+ */
91
+ export function entryProblems(root, entry, specs = null) {
92
+ const screen = entry.screen ?? entry.file;
93
+ const fix = 'Export it from the design tool with /code-kit:design, as the person approved it.';
94
+ if (!handedOver(entry))
95
+ return [
96
+ `${entry.file}: its approved design (${screen}) is only in ${toolOf(entry)}, not as files a lane can read. Hand it over: /code-kit:design --hand-over.`,
97
+ ];
98
+ const problems = [];
99
+ for (const field of ['screen', 'story', 'approved', 'source'])
100
+ if (!entry[field]) problems.push(`${entry.file}: its register entry has no "${field}".`);
101
+ for (const state of entry.states) {
102
+ const name = state?.name ?? '(unnamed)';
103
+ const where = `${screen}'s ${name} state`;
104
+ if (!state?.image) problems.push(`${where} has no image. ${fix}`);
105
+ if (!state?.code && !state?.why)
106
+ problems.push(`${where} has no code, and no "why" saying the tool gives none. ${fix}`);
107
+ if (!state?.viewport) problems.push(`${where} doesn't say the viewport it was drawn at.`);
108
+ for (const kind of ['image', 'code']) {
109
+ const rel = state?.[kind];
110
+ if (!rel) continue;
111
+ const hash = sha256Of(root, rel);
112
+ if (hash === null) problems.push(`${where}: ${rel} isn't there. ${fix}`);
113
+ else if (!state.sha256?.[kind])
114
+ problems.push(`${where}: ${rel} has no approved hash in the register.`);
115
+ else if (state.sha256[kind] !== hash)
116
+ problems.push(
117
+ `${where}: ${rel} isn't the approved design: its hash differs from the one recorded. An approved design changes only with a new approval.`,
118
+ );
119
+ }
120
+ }
121
+ const wanted = screenStates(root, specs, entry.screen);
122
+ const have = new Set(entry.states.map((s) => String(s?.name ?? '').toLowerCase()));
123
+ for (const w of wanted ?? [])
124
+ if (!have.has(w))
125
+ problems.push(`${screen}'s ${w} state, which the spec lists, has no approved design. ${fix}`);
126
+ return problems;
127
+ }
128
+
129
+ /**
130
+ * HAND-3: the register entries a story's screens are built from: those its own id names, and those of
131
+ * the design stories it depends on. `stories` is the plan's.
132
+ */
133
+ export function designsFor(entries, story, stories = []) {
134
+ const s = stories.find((x) => x.id === story);
135
+ const from = new Set([story, ...(s?.dependsOn ?? [])]);
136
+ return entries.filter((e) => from.has(e.story));
137
+ }
@@ -114,9 +114,9 @@ export function classify(tool, input, config) {
114
114
  if (any(kit(String.raw`approve\b`))) return { kind: 'approve', target };
115
115
  if (any(kit(String.raw`publish\b`))) return { kind: 'push', target };
116
116
  if (any(kit(String.raw`(?:verify|security)\b.*\s--branch\b`))) return { kind: 'review', target };
117
- if (any(new RegExp(String.raw`^${GIT}commit\b`))) return { kind: 'commit', target };
117
+ if (any(new RegExp(String.raw`^${GIT}commit(?![\w-])`))) return { kind: 'commit', target };
118
118
  if (any(new RegExp(String.raw`^${GIT}push\b`))) return { kind: 'push', target };
119
- if (any(new RegExp(String.raw`^${GIT}merge\b`))) return { kind: 'merge', target };
119
+ if (any(new RegExp(String.raw`^${GIT}merge(?![\w-])`))) return { kind: 'merge', target };
120
120
  if (addedPackages(command).length) return { kind: 'install', target };
121
121
  if (unrepeatable(command, config)) return { kind: 'unrepeatable', target };
122
122
  const checks = (config.checks ?? []).flatMap((c) => c.run ?? []);
@@ -329,6 +329,11 @@ export function replay(events) {
329
329
  state.phase = 'handed back';
330
330
  continue;
331
331
  }
332
+ // Its agent was stopped by Claude's API (its usage limit) mid-story: restarted, it carries on.
333
+ if (e.kind === 'stopped') {
334
+ state.phase = 'stopped';
335
+ continue;
336
+ }
332
337
  if (!e.act) continue;
333
338
  const act = acts.get(e.act) ?? { start: null, end: null, reconciled: null };
334
339
  acts.set(e.act, act);
@@ -392,14 +397,14 @@ const REPEATABLE = new Set(['edit', 'read', 'run', 'test', 'install', 'dispatch'
392
397
 
393
398
  /**
394
399
  * Whether an open act's agent has stopped: its session isn't live, a later event from the same agent
395
- * says it handed back or went on, or it's older than the stall restart (LOOP-3).
400
+ * says it handed back or was stopped by an API error, or it's older than the stall restart (LOOP-3).
396
401
  */
397
402
  export function stopped(act, events, { liveSessions, restartMs, now }) {
398
403
  if (act.session && !liveSessions.has(act.session)) return true;
399
404
  if (now - Date.parse(act.at) >= restartMs) return true;
400
405
  return events.some(
401
406
  (e) =>
402
- e.kind === 'handback' &&
407
+ ['handback', 'stopped'].includes(e.kind) &&
403
408
  e.session === act.session &&
404
409
  (e.agent ?? null) === (act.agent ?? null) &&
405
410
  Date.parse(e.at) >= Date.parse(act.at),
@@ -1,5 +1,5 @@
1
1
  // What every hook starts with: the tool call from stdin, the project and its config.
2
- import { readFileSync } from 'node:fs';
2
+ import { closeSync, fstatSync, openSync, readFileSync, readSync } from 'node:fs';
3
3
  import { loadConfig } from './config.mjs';
4
4
  import { projectDir } from './rules.mjs';
5
5
  import { seeSession } from './sessions.mjs';
@@ -24,3 +24,43 @@ export function start() {
24
24
  }
25
25
  return { input, project, config, error };
26
26
  }
27
+
28
+ /** The most of a transcript's end read for its last entry. */
29
+ const TAIL_BYTES = 64 * 1024;
30
+
31
+ /**
32
+ * The API error a stopping turn ended on ('rate_limit', 'overloaded', …), from the last entry of its
33
+ * transcript (a lane agent's own, or the session's), or null when it ended as it meant to. A turn cut
34
+ * off by Claude's usage limit stops too, but nothing it was doing is finished.
35
+ */
36
+ export function apiStopOf(input) {
37
+ // A lane agent's own transcript: the session's ends where the lead is, not where the agent stopped.
38
+ const path = input?.agent_id ? input.agent_transcript_path : input?.transcript_path;
39
+ if (!path) return null;
40
+ let fd;
41
+ try {
42
+ fd = openSync(path, 'r');
43
+ const size = fstatSync(fd).size;
44
+ const length = Math.min(size, TAIL_BYTES);
45
+ const buffer = Buffer.alloc(length);
46
+ readSync(fd, buffer, 0, length, size - length);
47
+ // The last of the model's entries: what Claude Code adds after it (a hook's note) says nothing.
48
+ const entry = buffer
49
+ .toString('utf8')
50
+ .split('\n')
51
+ .reverse()
52
+ .map((line) => {
53
+ try {
54
+ return JSON.parse(line);
55
+ } catch {
56
+ return null;
57
+ }
58
+ })
59
+ .find((e) => e?.type === 'assistant');
60
+ return entry?.isApiErrorMessage ? (entry.error ?? 'unknown') : null;
61
+ } catch {
62
+ return null;
63
+ } finally {
64
+ if (fd !== undefined) closeSync(fd);
65
+ }
66
+ }