@warren-dean/code-kit 0.26.2 → 0.28.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.
Files changed (41) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/CHANGELOG.md +24 -0
  4. package/README.md +8 -6
  5. package/bin/code-kit.mjs +269 -52
  6. package/hooks/act.mjs +14 -5
  7. package/hooks/guard-bash.mjs +82 -17
  8. package/hooks/lib/adapters/hub/client.mjs +22 -0
  9. package/hooks/lib/checkout.mjs +105 -0
  10. package/hooks/lib/checks.mjs +34 -8
  11. package/hooks/lib/config.mjs +16 -2
  12. package/hooks/lib/dependencies.mjs +4 -0
  13. package/hooks/lib/designs.mjs +138 -0
  14. package/hooks/lib/events.mjs +9 -4
  15. package/hooks/lib/hook.mjs +61 -2
  16. package/hooks/lib/next.mjs +26 -5
  17. package/hooks/lib/plan.mjs +55 -13
  18. package/hooks/lib/queue.mjs +86 -1
  19. package/hooks/lib/regression.mjs +54 -44
  20. package/hooks/lib/rules.mjs +63 -20
  21. package/hooks/lib/security.mjs +20 -0
  22. package/hooks/lib/sessions.mjs +49 -9
  23. package/hooks/lib/snapshot.mjs +227 -22
  24. package/hooks/lib/team.mjs +27 -1
  25. package/hooks/lib/verify.mjs +37 -4
  26. package/hooks/lib/worktrees.mjs +18 -1
  27. package/hooks/mod/board.mjs +10 -1
  28. package/hooks/mod/loop.mjs +44 -1
  29. package/hooks/mod/register.mjs +96 -8
  30. package/hooks/mod/view.mjs +8 -0
  31. package/hooks/post-edit-check.mjs +3 -1
  32. package/hooks/session.mjs +3 -1
  33. package/hooks/stop-check.mjs +6 -1
  34. package/package.json +1 -1
  35. package/skills/design/SKILL.md +36 -7
  36. package/skills/dispatch/SKILL.md +1 -0
  37. package/skills/init/SKILL.md +2 -0
  38. package/skills/review/SKILL.md +2 -1
  39. package/skills/spec-design/SKILL.md +1 -1
  40. package/skills/status/SKILL.md +1 -1
  41. package/templates/agent.md +2 -1
@@ -18,9 +18,12 @@ 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';
25
+ import { approverOf } from './lib/journal.mjs';
26
+ import { loginHere } from './lib/sessions.mjs';
24
27
  import { TESTS_APPROVAL, commitWeakenings } from './lib/regression.mjs';
25
28
  import {
26
29
  STANDARDS_APPROVAL,
@@ -44,6 +47,8 @@ import {
44
47
  useApproval,
45
48
  owns,
46
49
  protectedEntry,
50
+ leadNeedsApproval,
51
+ approvalEnded,
47
52
  recordRequest,
48
53
  sessionRoot,
49
54
  } from './lib/rules.mjs';
@@ -115,7 +120,7 @@ const queues = runs(cmd, new RegExp(String.raw`^${CODE_KIT}\s+queue\s+(?:add|dro
115
120
  const rulesOntoBase = runs(cmd, new RegExp(String.raw`^${CODE_KIT}\s+queue\s+rules\b`));
116
121
  const asks = runs(cmd, new RegExp(String.raw`^${CODE_KIT}\s+ask\b\s+(?!--json\b)\S`));
117
122
  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`));
123
+ const commits = runs(cmd, new RegExp(String.raw`^${GIT}commit(?![\w-])`));
119
124
  if (error) {
120
125
  if (commits) block(`Blocked: ${error}\nFix the config before committing.`);
121
126
  if (approves) block(`Blocked: ${error}\nApprovals wait until the config is valid.`);
@@ -141,7 +146,7 @@ function committedOnHead(root, file) {
141
146
 
142
147
  const writesHistory = runs(
143
148
  cmd,
144
- new RegExp(String.raw`^${GIT}(commit|merge|cherry-pick|rebase|revert|am)\b`),
149
+ new RegExp(String.raw`^${GIT}(commit|merge|cherry-pick|rebase|revert|am)(?![\w-])`),
145
150
  );
146
151
  const switchesToProtected = runs(
147
152
  cmd,
@@ -393,8 +398,8 @@ try {
393
398
  // that commit on, the branch is protected by the rules it now holds.
394
399
  const settingUp =
395
400
  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`)) &&
401
+ runs(cmd, new RegExp(String.raw`^${GIT}commit(?![\w-])`)) &&
402
+ !runs(cmd, new RegExp(String.raw`^${GIT}(merge|cherry-pick|rebase|revert|am)(?![\w-])`)) &&
398
403
  !committedOnHead(root, CONFIG_FILE);
399
404
  if (writesHistory && config.branches.protected.includes(branch) && !settingUp) {
400
405
  block(
@@ -513,12 +518,27 @@ function committedFiles() {
513
518
  const changed = names(git('status', '--porcelain', '-uall', '--no-renames')).map((l) =>
514
519
  l.slice(3),
515
520
  );
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'));
521
+ // Each git command of the chain, however it's run (`git -C <worktree> add`).
522
+ const pieces = commandsOf(cmd).map((c) => c.text);
523
+ const gitRun = (sub) =>
524
+ pieces.map((p) => p.match(new RegExp(String.raw`^${GIT}${sub}`))).filter(Boolean);
525
+ const commitAll = gitRun(String.raw`commit(?![\w-])(.*)`).some((m) =>
526
+ /\s(-a|--all|-[b-zB-Z]*a[a-zA-Z]*)(\s|$)/.test(` ${m[1]}`),
527
+ );
528
+ const argsOf = (m) =>
529
+ m[1]
530
+ .trim()
531
+ .split(/\s+/)
532
+ .filter((a) => a && !a.startsWith('-'))
533
+ .map((a) => a.replace(/^(['"])(.*)\1$/, '$2'));
534
+ const addRuns = gitRun(String.raw`add\b(.*)`);
535
+ const addAll = addRuns.some((m) => /\s(-A|--all|\.)(\s|$)/.test(` ${m[1]}`));
536
+ // `git rm` and `git mv` stage as they run: their files count though nothing has changed them yet, and
537
+ // what they take away is gone from the commit though it's still on disk now.
538
+ const rmArgs = gitRun(String.raw`rm\b(.*)`).flatMap(argsOf);
539
+ const mvArgs = gitRun(String.raw`mv\b(.*)`).map(argsOf);
540
+ const moved = [...rmArgs, ...mvArgs.flat()];
541
+ const addArgs = [...addRuns.flatMap(argsOf), ...moved];
522
542
  // What the shell expands before git sees it (#76): an argument it can't be read from, such as a
523
543
  // variable or a command's output, could be any file, so every changed file counts.
524
544
  const unknowable = addArgs.some((a) => /[$`]/.test(a));
@@ -532,12 +552,16 @@ function committedFiles() {
532
552
  const added = changed.filter(
533
553
  (f) => commitAll || addAll || unknowable || addArgs.some((a) => matches(f, a)),
534
554
  );
555
+ const tracked = moved.length ? names(git('ls-files')) : [];
556
+ const removed = tracked.filter((f) => moved.some((a) => matches(f, a)));
557
+ const takenAway = [...rmArgs, ...mvArgs.flatMap((args) => args.slice(0, -1))];
558
+ const gone = new Set(tracked.filter((f) => takenAway.some((a) => matches(f, a))));
535
559
  // `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]);
560
+ const resetTo = gitRun(String.raw`reset\s+--soft\s+(\S+)`).map((m) => m[1]);
537
561
  const reset = resetTo.flatMap((ref) =>
538
562
  names(git('diff', '--name-only', '--no-renames', ref, 'HEAD')),
539
563
  );
540
- return { files: [...new Set([...staged, ...added, ...reset])], git };
564
+ return { files: [...new Set([...staged, ...added, ...removed, ...reset])], gone, git };
541
565
  }
542
566
 
543
567
  // Every committed protected file is recorded in the audit log, with the person's reason when an
@@ -545,13 +569,17 @@ function committedFiles() {
545
569
  // dependency approval: that entry is how `code-kit verify` accepts it. The log is staged into the same
546
570
  // commit, so record and change land together.
547
571
  function recordApprovals() {
548
- const { files, git } = committedFiles();
572
+ const { files, gone, git } = committedFiles();
549
573
  const lines = [];
574
+ // The person who gave an approval, by their GitHub login: the developer at this machine, where it was
575
+ // given. Only when code-kit has the login cached; the lead's own approvals have no approver.
576
+ const login = loginHere(root);
550
577
  const record = (file, fields) =>
551
578
  lines.push(
552
579
  JSON.stringify({
553
580
  at: new Date().toISOString(),
554
581
  ...fields,
582
+ ...(login && approverOf(fields) === 'person' ? { approver: login } : {}),
555
583
  file,
556
584
  branch,
557
585
  actor: actor.label,
@@ -595,10 +623,11 @@ function recordApprovals() {
595
623
  : null);
596
624
  const granted = entry && approval(root, entry.approval, actor);
597
625
  const byDependency = actor.kind === 'lane' && dependencyChange(actor, file, root, config);
598
- if (entry && !granted && actor.kind !== 'lead' && !byDependency) {
626
+ const leadFree = actor.kind === 'lead' && !leadNeedsApproval(entry?.approval, config);
627
+ if (entry && !granted && !leadFree && !byDependency) {
599
628
  recordRequest(root, actor, entry.approval, file, entry.why);
600
629
  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)}`,
630
+ `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
631
  );
603
632
  }
604
633
  if (granted)
@@ -630,6 +659,8 @@ function recordApprovals() {
630
659
  root,
631
660
  files.filter((f) => !arrivesWithMerge(root, f, { staged: true })),
632
661
  config,
662
+ gone,
663
+ config.branches.protected[0],
633
664
  );
634
665
  if (weakened.length) {
635
666
  const granted = approval(root, TESTS_APPROVAL, actor);
@@ -646,7 +677,7 @@ function recordApprovals() {
646
677
  ? `Also weakened: ${more.map((x) => `${x.file} (${said(x)})`).join('; ')}.
647
678
  `
648
679
  : '') +
649
- `A weakened test can hide a regression. Fix the code so the test passes as it was. ` +
680
+ `A weakened test can hide a regression.${approvalEnded(root, TESTS_APPROVAL, actor)} Fix the code so the test passes as it was. ` +
650
681
  (leads
651
682
  ? `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
683
  : `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 +717,41 @@ ${approvalHowTo(TESTS_APPROVAL, actor, root, 'weakening tests in one commit', pe
686
717
  git('add', APPROVAL_LOG);
687
718
  }
688
719
 
720
+ // The commit hook judges what the commit holds before the command runs, so a file a command earlier in
721
+ // the chain writes (a formatter, a script, a heredoc) can't be seen, and would go in unjudged and
722
+ // unlogged. Before the commit, a chain may only move into the checkout and stage.
723
+ const BEFORE_COMMIT = new RegExp(
724
+ String.raw`^(?:cd\s|${GIT}(?:add|rm|mv|status|diff|log|show|restore\s+--staged|reset\s+--soft)(?![\w-]))`,
725
+ );
726
+ function writesBeforeCommit() {
727
+ const pieces = commandsOf(cmd);
728
+ const at = pieces.findIndex((c) => new RegExp(String.raw`^${GIT}commit(?![\w-])`).test(c.text));
729
+ return pieces
730
+ .slice(0, Math.max(at, 0))
731
+ .find((c) => !BEFORE_COMMIT.test(c.text) || /[<>]/.test(c.code));
732
+ }
733
+
689
734
  if (commits) {
690
- recordApprovals();
735
+ const writer = writesBeforeCommit();
736
+ if (writer)
737
+ block(
738
+ `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}`,
739
+ );
740
+ // HAND-2: a register entry this commit adds or changes names the approved design's files, as approved.
741
+ const register = config.designGate?.register;
742
+ if (register && committedFiles().files.includes(register)) {
743
+ const before = spawnSync('git', ['-C', root, 'show', `HEAD:${register}`], { encoding: 'utf8' });
744
+ const old = before.status === 0 ? readRegister(root, config, before.stdout).entries : [];
745
+ const same = (e) => old.some((o) => JSON.stringify(o) === JSON.stringify(e));
746
+ const problems = readRegister(root, config)
747
+ .entries.filter((e) => !same(e))
748
+ .flatMap((e) => entryProblems(root, e, config.docs?.specs));
749
+ if (problems.length)
750
+ block(
751
+ `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}`,
752
+ );
753
+ }
754
+ // Every refusal comes before approvals are spent and logged, so a refused commit spends none.
691
755
  const scan = spawnSync('gitleaks', ['protect', '--staged', '--redact', '--no-banner'], {
692
756
  cwd: root,
693
757
  encoding: 'utf8',
@@ -697,5 +761,6 @@ if (commits) {
697
761
  `Blocked: gitleaks found possible secrets in staged changes.\n${scan.stdout}${scan.stderr}`,
698
762
  );
699
763
  }
764
+ recordApprovals();
700
765
  }
701
766
  process.exit(0);
@@ -646,6 +646,7 @@ async function daemon({ root, session, watch }) {
646
646
  session,
647
647
  branch: git(root, 'symbolic-ref', '--short', '-q', 'HEAD'),
648
648
  agents: agents.map(({ type, tool, branch }) => ({ type, tool, branch })),
649
+ ...sessionFacts(root, session),
649
650
  });
650
651
  } catch {
651
652
  // reported on the next try
@@ -742,6 +743,27 @@ function trim(file) {
742
743
  } catch {}
743
744
  }
744
745
 
746
+ /**
747
+ * What code-kit recorded of the session (SESS-1): the code-kit and model it runs, when it started (ms),
748
+ * and the file it last edited, by path only, while that was in the last ten minutes.
749
+ */
750
+ export function sessionFacts(root, session, now = Date.now()) {
751
+ const record = readJson(
752
+ join(stateDir(root), 'sessions', `${String(session).replace(/[^\w.-]/g, '_')}.json`),
753
+ {},
754
+ );
755
+ const str = (v, max) =>
756
+ typeof v === 'string' && v && !/[\r\n]/.test(v) ? v.slice(0, max) : null;
757
+ const started = Date.parse(record?.started ?? '');
758
+ const edited = Date.parse(record?.editing?.at ?? '');
759
+ return {
760
+ codeKit: str(record?.codeKit, 40),
761
+ model: str(record?.model, 120),
762
+ started: Number.isFinite(started) ? started : null,
763
+ editing: now - edited < 10 * 60_000 ? str(record?.editing?.path, 300) : null,
764
+ };
765
+ }
766
+
745
767
  /** Starts the daemon for a session, detached; one per session. */
746
768
  export function startDaemon(root, session, watch, url) {
747
769
  const dir = stateDir(root);
@@ -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/**'],
@@ -436,6 +439,9 @@ export function validate(c) {
436
439
  return p;
437
440
  }
438
441
 
442
+ /** A deliverable kind's name (a layer's or lane's `label`): one line, at most 60 characters. */
443
+ const isLabel = (v) => isStr(v) && v.trim().length > 0 && v.length <= 60 && !/[\r\n]/.test(v);
444
+
439
445
  function validateLanes(c, need) {
440
446
  if (!need(isObj(c.lanes), '"lanes" must be an object (it may be empty)')) return;
441
447
  const agents = new Set();
@@ -450,6 +456,10 @@ function validateLanes(c, need) {
450
456
  lane.exclude === undefined || isList(lane.exclude),
451
457
  `lanes.${name}.exclude must be a list of globs`,
452
458
  );
459
+ need(
460
+ lane.label === undefined || isLabel(lane.label),
461
+ `lanes.${name}.label must be a short name for what the lane delivers, such as "Screens" or "API contract" (one line, at most 60 characters)`,
462
+ );
453
463
  need(!agents.has(lane.agent), `lanes.${name}.agent "${lane.agent}" is used by another lane`);
454
464
  agents.add(lane.agent);
455
465
  }
@@ -480,6 +490,10 @@ function validateLayers(c, need, each) {
480
490
  l.denyPackages === undefined || isList(l.denyPackages),
481
491
  `${at}.denyPackages must be a list of globs`,
482
492
  );
493
+ need(
494
+ l.label === undefined || isLabel(l.label),
495
+ `${at}.label must be a short name for what the layer delivers, such as "Data" or "Service" (one line, at most 60 characters)`,
496
+ );
483
497
  });
484
498
  const aliases = c.importAliases;
485
499
  need(
@@ -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,138 @@
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
+ /**
40
+ * The tool an entry's design lives in: "paper" from "paper:…" for an entry not handed over yet, or
41
+ * `fallback` when the entry doesn't say.
42
+ */
43
+ export const toolOf = (entry, fallback = 'the design tool') =>
44
+ entry?.source?.tool ?? String(entry?.design ?? '').match(/^([a-z][\w-]*):/i)?.[1] ?? fallback;
45
+
46
+ /**
47
+ * HAND-2: the states the specs' `## Screens` sections give `screen`: its `**States:**` line, or else the
48
+ * usual state words its text mentions (default always). Null when no spec lists the screen.
49
+ */
50
+ export function screenStates(root, specs, screen) {
51
+ if (!specs || !screen) return null;
52
+ const name = String(screen).toLowerCase();
53
+ for (const file of markdownFiles(root, specs)) {
54
+ let text;
55
+ try {
56
+ text = readFileSync(join(root, file), 'utf8');
57
+ } catch {
58
+ continue;
59
+ }
60
+ const section = text.split(/^## /m).find((s) => /^Screens\b/i.test(s));
61
+ if (!section) continue;
62
+ const lines = section.split('\n');
63
+ const at = lines.findIndex(
64
+ (l, i) => i > 0 && /^(#{3,4}\s|\s*[-*]\s)/.test(l) && l.toLowerCase().includes(name),
65
+ );
66
+ if (at < 0) continue;
67
+ const ownIndent = lines[at].match(/^\s*/)[0].length;
68
+ const isHeading = /^#{3,4}\s/.test(lines[at]);
69
+ const block = [lines[at]];
70
+ for (const l of lines.slice(at + 1)) {
71
+ if (/^#{1,4}\s/.test(l)) break;
72
+ if (!isHeading && /^\s*[-*]\s/.test(l) && l.match(/^\s*/)[0].length <= ownIndent) break;
73
+ block.push(l);
74
+ }
75
+ const body = block.join('\n');
76
+ const listed = body.match(/\*\*States:\*\*\s*(.+)/i)?.[1];
77
+ if (listed)
78
+ return listed
79
+ .split(/[,;]/)
80
+ .map((s) => s.trim().toLowerCase().replace(/\.$/, ''))
81
+ .filter(Boolean);
82
+ return STATE_WORDS.filter((w) => w === 'default' || new RegExp(`\\b${w}\\b`, 'i').test(body));
83
+ }
84
+ return null;
85
+ }
86
+
87
+ /**
88
+ * HAND-2: what's wrong with a register entry, in sentences naming the screen, the state and the file:
89
+ * a design only in a tool, a field missing, a file not there, a hash that isn't the approved one, or a
90
+ * state the spec lists with none. `specs` is the specs' folder, for the states each screen should have.
91
+ */
92
+ export function entryProblems(root, entry, specs = null) {
93
+ const screen = entry.screen ?? entry.file;
94
+ const fix = 'Export it from the design tool with /code-kit:design, as the person approved it.';
95
+ if (!handedOver(entry))
96
+ return [
97
+ `${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.`,
98
+ ];
99
+ const problems = [];
100
+ for (const field of ['screen', 'story', 'approved', 'source'])
101
+ if (!entry[field]) problems.push(`${entry.file}: its register entry has no "${field}".`);
102
+ for (const state of entry.states) {
103
+ const name = state?.name ?? '(unnamed)';
104
+ const where = `${screen}'s ${name} state`;
105
+ if (!state?.image) problems.push(`${where} has no image. ${fix}`);
106
+ if (!state?.code && !state?.why)
107
+ problems.push(`${where} has no code, and no "why" saying the tool gives none. ${fix}`);
108
+ if (!state?.viewport) problems.push(`${where} doesn't say the viewport it was drawn at.`);
109
+ for (const kind of ['image', 'code']) {
110
+ const rel = state?.[kind];
111
+ if (!rel) continue;
112
+ const hash = sha256Of(root, rel);
113
+ if (hash === null) problems.push(`${where}: ${rel} isn't there. ${fix}`);
114
+ else if (!state.sha256?.[kind])
115
+ problems.push(`${where}: ${rel} has no approved hash in the register.`);
116
+ else if (state.sha256[kind] !== hash)
117
+ problems.push(
118
+ `${where}: ${rel} isn't the approved design: its hash differs from the one recorded. An approved design changes only with a new approval.`,
119
+ );
120
+ }
121
+ }
122
+ const wanted = screenStates(root, specs, entry.screen);
123
+ const have = new Set(entry.states.map((s) => String(s?.name ?? '').toLowerCase()));
124
+ for (const w of wanted ?? [])
125
+ if (!have.has(w))
126
+ problems.push(`${screen}'s ${w} state, which the spec lists, has no approved design. ${fix}`);
127
+ return problems;
128
+ }
129
+
130
+ /**
131
+ * HAND-3: the register entries a story's screens are built from: those its own id names, and those of
132
+ * the design stories it depends on. `stories` is the plan's.
133
+ */
134
+ export function designsFor(entries, story, stories = []) {
135
+ const s = stories.find((x) => x.id === story);
136
+ const from = new Set([story, ...(s?.dependsOn ?? [])]);
137
+ return entries.filter((e) => from.has(e.story));
138
+ }
@@ -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),