@warren-dean/code-kit 0.28.0 → 0.30.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 +31 -0
  4. package/README.md +17 -9
  5. package/bin/code-kit.mjs +498 -60
  6. package/hooks/act.mjs +30 -2
  7. package/hooks/guard-bash.mjs +59 -25
  8. package/hooks/lib/adapters/hub/client.mjs +7 -1
  9. package/hooks/lib/checkout.mjs +78 -1
  10. package/hooks/lib/checks.mjs +13 -3
  11. package/hooks/lib/deferrals.mjs +107 -0
  12. package/hooks/lib/designs.mjs +100 -42
  13. package/hooks/lib/events.mjs +49 -0
  14. package/hooks/lib/instructions.mjs +1 -1
  15. package/hooks/lib/next.mjs +124 -15
  16. package/hooks/lib/plan.mjs +186 -11
  17. package/hooks/lib/queue.mjs +61 -12
  18. package/hooks/lib/regression.mjs +18 -11
  19. package/hooks/lib/reviews.mjs +43 -2
  20. package/hooks/lib/rules.mjs +11 -2
  21. package/hooks/lib/security.mjs +50 -7
  22. package/hooks/lib/shell.mjs +97 -0
  23. package/hooks/lib/snapshot.mjs +125 -8
  24. package/hooks/lib/storymap.mjs +13 -7
  25. package/hooks/lib/team.mjs +35 -13
  26. package/hooks/lib/teamfacts.mjs +80 -2
  27. package/hooks/lib/testfiles.mjs +22 -0
  28. package/hooks/lib/verify.mjs +55 -11
  29. package/hooks/lib/worktrees.mjs +25 -3
  30. package/hooks/mod/board.mjs +12 -1
  31. package/hooks/mod/loop.mjs +9 -2
  32. package/hooks/mod/register.mjs +4 -3
  33. package/hooks/mod/view.mjs +51 -11
  34. package/package.json +1 -1
  35. package/skills/design/SKILL.md +4 -4
  36. package/skills/dispatch/SKILL.md +1 -1
  37. package/skills/init/SKILL.md +5 -0
  38. package/skills/next/SKILL.md +1 -0
  39. package/skills/review/SKILL.md +12 -4
  40. package/templates/agent.md +2 -1
  41. package/templates/claude-md.md +2 -0
package/hooks/act.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  // Durable lanes (spec 26): the event log's writer. PreToolUse records each act's start, PostToolUse
3
3
  // its end and PostToolUseFailure its failure, and SubagentStop a lane agent handing back, or stopped by
4
- // an API error. It never blocks a call (DUR-2): it runs in the background (`async` in hooks.json), so
4
+ // an API error, and the security reviewer's findings, on the story it reviewed (HUBR-2). It never blocks a call (DUR-2): it runs in the background (`async` in hooks.json), so
5
5
  // no call waits for it, and a write that fails is said once in the session while the work goes on.
6
6
  import { existsSync, realpathSync, writeFileSync } from 'node:fs';
7
7
  import { tmpdir } from 'node:os';
@@ -9,14 +9,17 @@ import { basename, dirname, isAbsolute, join, relative } from 'node:path';
9
9
  import { apiStopOf, start } from './lib/hook.mjs';
10
10
  import { actorFor, currentBranch, sessionRoot } from './lib/rules.mjs';
11
11
  import {
12
+ agentIdOf,
12
13
  classify,
13
14
  headOf,
14
15
  recordEnd,
15
16
  recordNote,
16
17
  recordStart,
17
18
  resultOf,
19
+ securityReviewFor,
18
20
  storyOf,
19
21
  } from './lib/events.mjs';
22
+ import { isSecurityReviewer, securityOutcome } from './lib/security.mjs';
20
23
 
21
24
  const mode = process.argv[2];
22
25
 
@@ -53,6 +56,21 @@ try {
53
56
  }
54
57
  const who = actor.kind === 'lane' ? actor.lane : actor.kind === 'lead' ? 'lead' : actor.label;
55
58
  const ctx = { session: input.session_id ?? null, agent: input.agent_id ?? null, actor: who };
59
+ if (mode === 'handback' && isSecurityReviewer(input.agent_type)) {
60
+ // HUBR-2: the security review that ran, on the story it was started for, with what it found.
61
+ const review = securityReviewFor(root, input.agent_id ?? null);
62
+ if (review)
63
+ recordNote(root, {
64
+ ...ctx,
65
+ act: review.act,
66
+ story: review.story,
67
+ branch: review.branch,
68
+ kind: 'security-review',
69
+ agentType: input.agent_type,
70
+ result: securityOutcome(input.last_assistant_message) ?? { unread: true },
71
+ });
72
+ process.exit(0);
73
+ }
56
74
  if (mode === 'handback') {
57
75
  const story = storyOf({ kind: 'handback', target: '', branch }).story;
58
76
  // An agent Claude's API stopped (its usage limit) didn't hand back: it stopped, mid-story.
@@ -71,6 +89,9 @@ try {
71
89
  const { kind, target } = classify(input.tool_name, input.tool_input, config);
72
90
  const shown = kind === 'edit' || kind === 'read' ? inRoot(root, target) : target;
73
91
  const { story, branch: storyBranch } = storyOf({ kind, target: shown, branch, root });
92
+ const started = ['Agent', 'Task'].includes(input.tool_name)
93
+ ? (input.tool_input?.subagent_type ?? null)
94
+ : null;
74
95
  const act = {
75
96
  ...ctx,
76
97
  act: input.tool_use_id ?? null,
@@ -79,9 +100,16 @@ try {
79
100
  target: shown,
80
101
  branch: storyBranch ?? branch,
81
102
  head: headOf(root),
103
+ agentType: started,
82
104
  };
105
+ // A security reviewer started in the background: its id, so its findings find this review as it stops.
106
+ const launched = isSecurityReviewer(started) ? agentIdOf(input.tool_response) : null;
83
107
  if (mode === 'start') recordStart(root, act);
84
- else if (mode === 'end') recordEnd(root, act, resultOf(kind, null, root));
108
+ else if (mode === 'end')
109
+ recordEnd(root, act, {
110
+ ...resultOf(kind, null, root),
111
+ ...(launched ? { agent: launched } : {}),
112
+ });
85
113
  else if (mode === 'fail') recordEnd(root, act, resultOf(kind, input.error ?? 'failed', root));
86
114
  } catch (e) {
87
115
  // DUR-2: once per session, the person hears the log isn't being kept; the call goes on.
@@ -14,11 +14,11 @@ import {
14
14
  ecosystemOf,
15
15
  isDependencyFile,
16
16
  } from './lib/dependencies.mjs';
17
- import { CODE_KIT, GIT, codeOf, commandsOf, runs } from './lib/shell.mjs';
17
+ import { CODE_KIT, GIT, codeOf, commandsOf, readsOnly, 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
+ import { entryProblems, freshEntries, readRegister } from './lib/designs.mjs';
22
22
  import { globToRegExp, matchesAny } from './lib/glob.mjs';
23
23
  import { noteBefore } from './lane-audit.mjs';
24
24
  import { storyMerges } from './lib/queue.mjs';
@@ -72,21 +72,6 @@ const RUNS = [
72
72
  for (const [re, why] of RUNS) {
73
73
  if (runs(cmd, re, { quoted: false })) block(`Blocked: ${why}\nCommand: ${cmd}`);
74
74
  }
75
- /**
76
- * Whether `cmd` only reads git's history, with what it prints piped into read-only filters: `git diff
77
- * main...HEAD -- .claude/approval-log.jsonl`, `git log -p -- … | head`. No redirect, no tee, nothing else.
78
- */
79
- function gitReadsOnly(cmd) {
80
- const code = codeOf(cmd);
81
- if (/>|\btee\b|`|\$\(/.test(code)) return false;
82
- const parts = commandsOf(cmd);
83
- return (
84
- parts.length > 0 &&
85
- new RegExp(String.raw`^${GIT}(?:diff|log|show|blame)\b`).test(parts[0].code) &&
86
- parts.slice(1).every((c) => /^(?:grep|head|tail|wc|cat|sort|uniq|less)\b/.test(c.code))
87
- );
88
- }
89
-
90
75
  // These read the command whole: a pipe spans commands, and an approval or the log can be written
91
76
  // through a quoted path.
92
77
  const ALWAYS = [
@@ -102,8 +87,8 @@ const ALWAYS = [
102
87
  ],
103
88
  [
104
89
  /approval-log\.jsonl/,
105
- "The approval audit log is appended only by the commit hook; nobody edits it. A shell command may not name it except to read its history with git (git diff, log or show, piped only into grep, head, tail or wc); read the file itself with the Read tool, which can't write.",
106
- gitReadsOnly(cmd) ? '' : cmd,
90
+ "The approval audit log is appended only by the commit hook; nobody edits it. A shell command may name it only to read it: git diff, log, show or blame, or cat, head, tail, grep, wc, jq, cut, sort, uniq, awk or sed -n printing lines, after a `cd` and piped or chained only into each other, with no redirect but 2>&1 or into /dev/null, no command's output in its arguments ($(…) or backticks) and no variable set before a command. Run the read in that form, or read the file with the Read tool, which can't write.",
91
+ readsOnly(cmd) ? '' : cmd,
107
92
  ],
108
93
  ];
109
94
  for (const [re, why, text] of ALWAYS) {
@@ -564,6 +549,26 @@ function committedFiles() {
564
549
  return { files: [...new Set([...staged, ...added, ...removed, ...reset])], gone, git };
565
550
  }
566
551
 
552
+ /** The approval log's last entry for each file, as the checkout has the log. */
553
+ function lastEntries(root) {
554
+ const last = new Map();
555
+ let text = '';
556
+ try {
557
+ text = readFileSync(join(root, APPROVAL_LOG), 'utf8');
558
+ } catch {
559
+ return last;
560
+ }
561
+ for (const line of text.split('\n').filter(Boolean)) {
562
+ try {
563
+ const e = JSON.parse(line);
564
+ if (e?.file) last.set(e.file, e);
565
+ } catch {
566
+ // an unreadable line records nothing; verify reports it
567
+ }
568
+ }
569
+ return last;
570
+ }
571
+
567
572
  // Every committed protected file is recorded in the audit log, with the person's reason when an
568
573
  // approval is in force. So is a lane's manifest or lockfile change, outside its own paths, made under a
569
574
  // dependency approval: that entry is how `code-kit verify` accepts it. The log is staged into the same
@@ -652,6 +657,27 @@ function recordApprovals() {
652
657
  grantedAt: null,
653
658
  });
654
659
  }
660
+ // WHO-1: where the lead merges, its own change to what the person keeps needs the person's approval.
661
+ // Given after the change was committed, it has nothing left to commit: so the lead's next commit, one
662
+ // of its own if need be, records it for each such file as the branch holds it, by its content's hash,
663
+ // and verify accepts that entry while the file is unchanged.
664
+ if (actor.kind === 'lead') {
665
+ const inThisCommit = new Set(files);
666
+ for (const [file, last] of lastEntries(root)) {
667
+ if (last.approval !== 'lead' || last.branch !== branch || inThisCommit.has(file)) continue;
668
+ const entry = protectedEntry(file, config);
669
+ if (!entry || !leadNeedsApproval(entry.approval, config)) continue;
670
+ const granted = approval(root, entry.approval, actor);
671
+ const blob = git('rev-parse', '--verify', '-q', `HEAD:${file}`).trim();
672
+ if (granted && blob)
673
+ record(file, {
674
+ approval: entry.approval,
675
+ reason: granted.reason,
676
+ grantedAt: granted.grantedAt,
677
+ blob,
678
+ });
679
+ }
680
+ }
655
681
  // REG-2: a commit that weakens a test waits for a `tests` approval: WHO-2, the lead's on a lane's
656
682
  // branch where tests are delegated, otherwise the person's (always on the lead's own). It's recorded in
657
683
  // the log, so verify accepts the branch, and used up by this commit.
@@ -738,14 +764,22 @@ if (commits) {
738
764
  `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
765
  );
740
766
  // HAND-2: a register entry this commit adds or changes names the approved design's files, as approved.
767
+ // HAND-11: one the branch already has, the base has, or a merge being concluded brings in isn't this
768
+ // commit's: a lane merging the base into its branch isn't held to the base's entries.
741
769
  const register = config.designGate?.register;
742
770
  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));
771
+ const at = (ref) => {
772
+ const shown = spawnSync('git', ['-C', root, 'show', `${ref}:${register}`], {
773
+ encoding: 'utf8',
774
+ });
775
+ return shown.status === 0 ? readRegister(root, config, shown.stdout).entries : [];
776
+ };
777
+ const problems = freshEntries(
778
+ readRegister(root, config).entries,
779
+ at('HEAD'),
780
+ at(config.branches.protected[0]),
781
+ at('MERGE_HEAD'),
782
+ ).flatMap((e) => entryProblems(root, e, config.docs?.specs));
749
783
  if (problems.length)
750
784
  block(
751
785
  `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}`,
@@ -294,7 +294,13 @@ function mirrorClaim(root, op, input, result) {
294
294
  'commit-tree',
295
295
  tree,
296
296
  '-m',
297
- JSON.stringify({ story: c.story, by: c.by, at: c.at, lease: c.lease }),
297
+ JSON.stringify({
298
+ story: c.story,
299
+ by: c.by,
300
+ at: c.at,
301
+ lease: c.lease,
302
+ ...(Number.isInteger(c.intent) && c.intent > 0 ? { intent: c.intent } : {}),
303
+ }),
298
304
  ],
299
305
  { encoding: 'utf8', env },
300
306
  ).trim();
@@ -4,9 +4,10 @@
4
4
  // the like): a link back to a worktree's installs resolves outside the checkout, which path-sensitive
5
5
  // tools refuse, and an install run in it would rewrite the worktree's own.
6
6
  import { execFileSync, spawnSync } from 'node:child_process';
7
- import { existsSync, mkdtempSync, rmSync } from 'node:fs';
7
+ import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
8
8
  import { platform, tmpdir } from 'node:os';
9
9
  import { basename, dirname, join } from 'node:path';
10
+ import { isDependencyFile } from './dependencies.mjs';
10
11
 
11
12
  // The folders an install puts beside the code, which a fresh checkout lacks.
12
13
  const INSTALLS = new Set(['node_modules', '.venv', 'venv']);
@@ -103,3 +104,79 @@ export function freshCheckout(
103
104
  copyInstalls(installsFrom, dir);
104
105
  return { dir, remove };
105
106
  }
107
+
108
+ /**
109
+ * The manifests and lockfiles tracked in either checkout whose content differs between the two working
110
+ * trees: where installs copied from `from` may not match the code in `dir`.
111
+ */
112
+ export function dependencyDifferences(from, dir) {
113
+ const tracked = (d) => {
114
+ try {
115
+ return git(d, 'ls-files')
116
+ .split('\n')
117
+ .filter((f) => f && isDependencyFile(f));
118
+ } catch {
119
+ return [];
120
+ }
121
+ };
122
+ const read = (d, f) => {
123
+ try {
124
+ return readFileSync(join(d, f), 'utf8');
125
+ } catch {
126
+ return null;
127
+ }
128
+ };
129
+ return [...new Set([...tracked(from), ...tracked(dir)])]
130
+ .filter((f) => read(from, f) !== read(dir, f))
131
+ .sort();
132
+ }
133
+
134
+ // The install each lockfile at the top of a checkout calls for, run without changing the lockfile, and
135
+ // the manifests and lockfiles of its ecosystem, whose changes it installs.
136
+ const JS = [
137
+ 'package.json',
138
+ 'pnpm-lock.yaml',
139
+ 'package-lock.json',
140
+ 'npm-shrinkwrap.json',
141
+ 'yarn.lock',
142
+ ];
143
+ const INSTALLERS = [
144
+ ['pnpm-lock.yaml', 'pnpm install --frozen-lockfile --prefer-offline', JS],
145
+ ['package-lock.json', 'npm ci --prefer-offline --no-audit --no-fund', JS],
146
+ ['npm-shrinkwrap.json', 'npm ci --prefer-offline --no-audit --no-fund', JS],
147
+ ['yarn.lock', 'yarn install --frozen-lockfile', JS],
148
+ ['bun.lock', 'bun install --frozen-lockfile', [...JS, 'bun.lock']],
149
+ ['bun.lockb', 'bun install --frozen-lockfile', [...JS, 'bun.lockb']],
150
+ ['uv.lock', 'uv sync --frozen', ['pyproject.toml', 'uv.lock']],
151
+ ];
152
+
153
+ /**
154
+ * MQ-1: makes the installs in the fresh checkout `dir` match its tree. Installs copied from `from` match
155
+ * only while their manifests and lockfiles are the same: where they differ (the base gained a workspace
156
+ * package since they were installed), the project's install runs in `dir`, never in `from`: `prepare`
157
+ * where the project sets one, else the install its lockfile calls for, when the files that differ are
158
+ * that lockfile's ecosystem's. `{ differ, copied, lockfile, command, failed }`: `differ`, the files that
159
+ * differ; `copied`, whether any installs were copied in; `lockfile`, whether a lockfile code-kit knows
160
+ * is there; `command`, the install run (null when none was needed or none is known); `failed`,
161
+ * { missing, output } when it didn't succeed.
162
+ */
163
+ export function matchInstalls(dir, from, { prepare = null, timeout = 900000 } = {}) {
164
+ const differ = dependencyDifferences(from, dir);
165
+ 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 };
170
+ if (!command) return { ...facts, command: null, failed: null };
171
+ const res = spawnSync(command, { cwd: dir, shell: true, encoding: 'utf8', timeout });
172
+ if (res.status === 0) return { ...facts, command, failed: null };
173
+ const output = `${res.stdout ?? ''}${res.stderr ?? ''}`.trim().split('\n').slice(-20).join('\n');
174
+ return {
175
+ ...facts,
176
+ command,
177
+ failed: {
178
+ missing: res.status === 127,
179
+ output: output || (res.error ? String(res.error.code ?? res.error.message) : ''),
180
+ },
181
+ };
182
+ }
@@ -36,6 +36,9 @@ function runCommand(command, cwd, timeout) {
36
36
  }
37
37
  }
38
38
 
39
+ // pnpm exec's word for a command that isn't installed, which it exits 254 with (after a bare "undefined").
40
+ const MISSING_TOOL = /ERR_PNPM_\w+\s+Command "([^"]+)" not found/;
41
+
39
42
  /** The directories a check runs in: each changed one matching `each` that still exists, or the worktree. */
40
43
  function directories(check, files, root) {
41
44
  if (!check.each) return [root];
@@ -63,13 +66,20 @@ function runCheck(check, files, root, actor, skipped) {
63
66
  for (const command of check.run) {
64
67
  const res = runCommand(command, cwd, (check.timeoutSeconds ?? 240) * 1000);
65
68
  const where = cwd === root ? '' : ` in ${cwd.slice(root.length + 1)}`;
66
- if (res.status === 127) {
69
+ // A tool that isn't there: the shell's 127, or a package manager's own word for it (pnpm exec's).
70
+ const tool = res.status === 254 ? res.output.match(MISSING_TOOL)?.[1] : null;
71
+ if (res.status === 127 || tool) {
72
+ const what = tool ?? command;
67
73
  if (check.ifMissing === 'fail')
68
74
  return {
69
75
  check: check.name,
70
- title: `${check.name}: \`${command}\` is not installed${where}. Install it so the check can run.`,
76
+ title: `${check.name}: \`${what}\` is not installed${where}. Install it so the check can run.`,
71
77
  };
72
- skipped.push({ check: check.name, command, where: where.replace(/^ in /, '') || null });
78
+ skipped.push({
79
+ check: check.name,
80
+ command: what,
81
+ where: where.replace(/^ in /, '') || null,
82
+ });
73
83
  return null; // not installed yet (fresh clone): the check can't run
74
84
  }
75
85
  // #62: a check that ran out of time didn't fail; it's marked so a merge can try it again.
@@ -0,0 +1,107 @@
1
+ // LOOP-15: stories the lead holds on purpose, until a date or until it releases them, with why. A held
2
+ // story isn't dispatched, reviewed or merged by `code-kit next`, the loop or the merge queue, so a lead
3
+ // waiting on something outside the build (a person's answer elsewhere, a partner's release, a date) isn't
4
+ // asked about the same story again every half hour. Kept in the main checkout beside the merge queue, so
5
+ // every worktree and a restarted session see the same.
6
+ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
7
+ import { dirname, join } from 'node:path';
8
+ import { projectWorktrees } from './rules.mjs';
9
+
10
+ export const DEFERRED_FILE = '.claude/state/deferred.json';
11
+
12
+ const deferredFile = (root) => join(projectWorktrees(root)[0] ?? root, DEFERRED_FILE);
13
+
14
+ /** Every hold recorded, past ones included: [{ story, reason, until, at, session? }]. */
15
+ function readAll(root) {
16
+ try {
17
+ const list = JSON.parse(readFileSync(deferredFile(root), 'utf8'));
18
+ return Array.isArray(list) ? list.filter((h) => h && typeof h.story === 'string') : [];
19
+ } catch {
20
+ return [];
21
+ }
22
+ }
23
+
24
+ function writeAll(root, list) {
25
+ const file = deferredFile(root);
26
+ mkdirSync(dirname(file), { recursive: true });
27
+ writeFileSync(file, `${JSON.stringify(list, null, 2)}\n`);
28
+ }
29
+
30
+ /** Whether a hold is still in force at `now`: no end, or an end still to come. */
31
+ const inForce = (h, now) => !h.until || Date.parse(h.until) > now;
32
+
33
+ /** The holds in force, in the order they were made: [{ story, reason, until, at, session? }]. */
34
+ export function activeDeferrals(root, now = Date.now()) {
35
+ return readAll(root).filter((h) => inForce(h, now));
36
+ }
37
+
38
+ /**
39
+ * What `--until` says, as an ISO time, or { error } in words. A date (2026-11-10) holds until that day
40
+ * begins, in local time; an ISO time holds until then. A time already past holds nothing.
41
+ */
42
+ export function parseUntil(text, now = Date.now()) {
43
+ if (text === undefined || text === null) return { until: null };
44
+ const date = /^\d{4}-\d{2}-\d{2}$/.test(text) ? new Date(`${text}T00:00:00`) : new Date(text);
45
+ if (Number.isNaN(date.getTime()))
46
+ return {
47
+ error: `--until ${text} isn't a date (2026-11-10) or an ISO time (2026-11-10T09:00:00+10:00).`,
48
+ };
49
+ if (date.getTime() <= now)
50
+ return { error: `--until ${text} has already passed; give a date or time still to come.` };
51
+ return { until: date.toISOString() };
52
+ }
53
+
54
+ /**
55
+ * Holds each of `stories` (upper-cased ids) with `reason`, until `until` (ISO) or until released. A
56
+ * story already held takes the new reason and end. Returns the holds made.
57
+ */
58
+ export function deferStories(
59
+ root,
60
+ stories,
61
+ { reason, until = null, session = null },
62
+ now = Date.now(),
63
+ ) {
64
+ const ids = [...new Set(stories.map((s) => s.toUpperCase()))];
65
+ const at = new Date(now).toISOString();
66
+ const made = ids.map((story) => ({
67
+ story,
68
+ reason,
69
+ until,
70
+ at,
71
+ ...(session ? { session } : {}),
72
+ }));
73
+ // Holds that ended are dropped as the list is written: only those in force are worth keeping.
74
+ writeAll(root, [
75
+ ...readAll(root).filter((h) => inForce(h, now) && !ids.includes(h.story)),
76
+ ...made,
77
+ ]);
78
+ return made;
79
+ }
80
+
81
+ /** Releases each of `stories`; returns the holds it ended (none for a story that wasn't held). */
82
+ export function releaseStories(root, stories, now = Date.now()) {
83
+ const ids = new Set(stories.map((s) => s.toUpperCase()));
84
+ const all = readAll(root);
85
+ const ended = all.filter((h) => ids.has(h.story) && inForce(h, now));
86
+ if (ended.length || all.some((h) => !inForce(h, now)))
87
+ writeAll(
88
+ root,
89
+ all.filter((h) => !ids.has(h.story) && inForce(h, now)),
90
+ );
91
+ return ended;
92
+ }
93
+
94
+ /** A local time as "2026-11-10", or "2026-11-10 09:30" when it isn't midnight. */
95
+ function localTime(iso) {
96
+ const d = new Date(iso);
97
+ const two = (n) => String(n).padStart(2, '0');
98
+ const day = `${d.getFullYear()}-${two(d.getMonth() + 1)}-${two(d.getDate())}`;
99
+ return d.getHours() || d.getMinutes()
100
+ ? `${day} ${two(d.getHours())}:${two(d.getMinutes())}`
101
+ : day;
102
+ }
103
+
104
+ /** A hold in words: "ST-4 is held until 2026-11-10: waiting on the partner's API". */
105
+ export function deferralWords(h) {
106
+ return `${h.story} is held${h.until ? ` until ${localTime(h.until)}` : ''}: ${h.reason}`;
107
+ }
@@ -1,11 +1,12 @@
1
1
  // Designs handed over (docs/specs/24-designs-handed-over.md). An approved design is files in the
2
2
  // repository, each state's code where the tool gives it and a PNG, named in the design register with a
3
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.
4
+ // design gate (ONB-2, HAND-6) refuses a screen until the register holds its exported design; this checks
5
+ // what the register holds.
5
6
  import { createHash } from 'node:crypto';
6
7
  import { readFileSync } from 'node:fs';
7
8
  import { join } from 'node:path';
8
- import { markdownFiles } from './plan.mjs';
9
+ import { readScreens, screenKey } from './plan.mjs';
9
10
 
10
11
  /** The states a screen has when its spec names none: the ones every screen is asked for. */
11
12
  export const STATE_WORDS = ['default', 'empty', 'loading', 'error'];
@@ -33,6 +34,28 @@ export function readRegister(root, config, text = null) {
33
34
  }
34
35
  }
35
36
 
37
+ /** An entry as JSON with its keys in order, so the same entry written differently compares equal. */
38
+ const canonical = (value) =>
39
+ JSON.stringify(value, (_, v) =>
40
+ v && typeof v === 'object' && !Array.isArray(v)
41
+ ? Object.fromEntries(
42
+ Object.keys(v)
43
+ .sort()
44
+ .map((k) => [k, v[k]]),
45
+ )
46
+ : v,
47
+ );
48
+
49
+ /**
50
+ * HAND-11: the entries of `entries` that none of `olds` (the registers a branch is held against: its
51
+ * base's, the commit it's on, a branch it's merging in) already holds as they are. A branch answers
52
+ * only for the entries it adds or changes; the rest came from elsewhere and were judged there.
53
+ */
54
+ export function freshEntries(entries, ...olds) {
55
+ const known = new Set(olds.flat().map(canonical));
56
+ return entries.filter((e) => !known.has(canonical(e)));
57
+ }
58
+
36
59
  /** HAND-2: whether an entry's design is files in the repository rather than only in a design tool. */
37
60
  export const handedOver = (entry) => Array.isArray(entry?.states) && entry.states.length > 0;
38
61
 
@@ -44,50 +67,35 @@ export const toolOf = (entry, fallback = 'the design tool') =>
44
67
  entry?.source?.tool ?? String(entry?.design ?? '').match(/^([a-z][\w-]*):/i)?.[1] ?? fallback;
45
68
 
46
69
  /**
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.
70
+ * HAND-9: the screens the specs' `## Screens` sections list under exactly `screen`'s name (a heading, a
71
+ * bullet's bold title or a table row's name cell): none, one, or more when the name is ambiguous.
72
+ */
73
+ export function screenMatches(root, specs, screen) {
74
+ if (!specs || !screen) return [];
75
+ const name = screenKey(screen);
76
+ return readScreens(root, specs).filter((s) => s.name === name);
77
+ }
78
+
79
+ /** The states one listed screen has: those it lists, or else the default and the state words it mentions. */
80
+ const statesOfScreen = (s) =>
81
+ s.states ??
82
+ STATE_WORDS.filter((w) => w === 'default' || new RegExp(`\\b${w}\\b`, 'i').test(s.body));
83
+
84
+ /**
85
+ * HAND-2: the states the specs' `## Screens` sections give `screen`: its `**States:**` line or States
86
+ * column, or else the usual state words its text mentions (default always). Null when no spec lists the
87
+ * screen, or more than one screen has its name (HAND-9).
49
88
  */
50
89
  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;
90
+ const found = screenMatches(root, specs, screen);
91
+ return found.length === 1 ? statesOfScreen(found[0]) : null;
85
92
  }
86
93
 
87
94
  /**
88
95
  * 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.
96
+ * a design only in a tool, a field missing, a file not there, a hash that isn't the approved one, a
97
+ * state the spec lists with none, or a screen name more than one spec screen has (HAND-9). `specs` is
98
+ * the specs' folder, for the states each screen should have.
91
99
  */
92
100
  export function entryProblems(root, entry, specs = null) {
93
101
  const screen = entry.screen ?? entry.file;
@@ -119,9 +127,17 @@ export function entryProblems(root, entry, specs = null) {
119
127
  );
120
128
  }
121
129
  }
122
- const wanted = screenStates(root, specs, entry.screen);
130
+ const listed = entry.screen ? screenMatches(root, specs, entry.screen) : [];
131
+ if (listed.length > 1) {
132
+ const where = listed.map((s) => `"${s.title}" in ${s.file}`).join(', ');
133
+ problems.push(
134
+ `${screen}: more than one screen in the specs has this name (${where}), so which states it needs can't be told. Give each screen a name of its own under ## Screens, and the entry the one it designs.`,
135
+ );
136
+ return problems;
137
+ }
138
+ const wanted = listed.length ? statesOfScreen(listed[0]) : [];
123
139
  const have = new Set(entry.states.map((s) => String(s?.name ?? '').toLowerCase()));
124
- for (const w of wanted ?? [])
140
+ for (const w of wanted)
125
141
  if (!have.has(w))
126
142
  problems.push(`${screen}'s ${w} state, which the spec lists, has no approved design. ${fix}`);
127
143
  return problems;
@@ -136,3 +152,45 @@ export function designsFor(entries, story, stories = []) {
136
152
  const from = new Set([story, ...(s?.dependsOn ?? [])]);
137
153
  return entries.filter((e) => from.has(e.story));
138
154
  }
155
+
156
+ /** A PNG's size in pixels, from its header: { width, height }, or null when it isn't a PNG. */
157
+ export function pngSize(bytes) {
158
+ const png = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
159
+ if (!bytes || bytes.length < 24 || !bytes.subarray(0, 8).equals(png)) return null;
160
+ if (bytes.subarray(12, 16).toString('latin1') !== 'IHDR') return null;
161
+ return { width: bytes.readUInt32BE(16), height: bytes.readUInt32BE(20) };
162
+ }
163
+
164
+ /**
165
+ * HAND-7: whether a screenshot of `size` was taken at `viewport` ("390x844"): its width the viewport's
166
+ * at 1x to 4x, and its height at least the viewport's at the same scale (a full-page screenshot is
167
+ * taller). True when the viewport can't be read.
168
+ */
169
+ export function atViewport(size, viewport) {
170
+ const m = String(viewport ?? '').match(/^(\d+)\s*[x×]\s*(\d+)$/i);
171
+ if (!m) return true;
172
+ const [w, h] = [Number(m[1]), Number(m[2])];
173
+ return [1, 2, 3, 4].some((k) => size.width === w * k && size.height >= h * k);
174
+ }
175
+
176
+ /**
177
+ * HAND-7: the approved states of the screens a branch builds (`files`, the screen files it changed)
178
+ * that the review recorded no screenshot for: [{ entry, state }]. `records` are the branch's evidence
179
+ * records; `current(record)` says whether one still stands for the branch as it is (its file unchanged
180
+ * since).
181
+ */
182
+ export function statesWithoutEvidence(entries, files, records, current = () => true) {
183
+ const changed = new Set(files);
184
+ const missing = [];
185
+ for (const entry of entries) {
186
+ if (!changed.has(entry.file) || !handedOver(entry)) continue;
187
+ for (const state of entry.states) {
188
+ const name = String(state?.name ?? '').toLowerCase();
189
+ const seen = records.some(
190
+ (r) => r.file === entry.file && String(r.state).toLowerCase() === name && current(r),
191
+ );
192
+ if (!seen) missing.push({ entry, state });
193
+ }
194
+ }
195
+ return missing;
196
+ }