@warren-dean/code-kit 0.29.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.
@@ -10,19 +10,13 @@ import { freshCheckout } from './checkout.mjs';
10
10
  import { runChecks } from './checks.mjs';
11
11
  import { matchesAny } from './glob.mjs';
12
12
  import { readStories } from './plan.mjs';
13
+ import { isNamedTest, isTestFile } from './testfiles.mjs';
13
14
 
14
15
  /** The approval that lets a test be weakened: the person's only. */
15
16
  export const TESTS_APPROVAL = 'tests';
16
17
 
17
- // Test files by the usual conventions, when the config names none (`tests`).
18
- const TEST =
19
- /(^|\/)(tests?|__tests__|e2e)\/|\.(test|spec)\.[^/]+$|_test\.(go|py)$|(^|\/)test_[^/]+\.py$/;
20
18
  export const SNAPSHOT = /(^|\/)__snapshots__\/|\.snap$/;
21
19
 
22
- /** Whether `rel` is a test: the config's `tests` globs, or the usual conventions. */
23
- export const isTestFile = (rel, config) =>
24
- !rel.endsWith('.md') && (config?.tests?.length ? matchesAny(rel, config.tests) : TEST.test(rel));
25
-
26
20
  // A case's name: it('…') / test('…') in JavaScript, def test_… in Python, func Test… in Go, @Test in JVM.
27
21
  const JS_CASE =
28
22
  /\b(?:it|test)(?:\.(?:each\s*\([^)]*\)|concurrent|serial|skip|only|todo|fixme|fails))*\s*\(\s*(['"`])((?:\\.|(?!\1)[^\\])*)\1/g;
@@ -255,16 +249,30 @@ export const onlyUnreachable = (output) =>
255
249
  */
256
250
  export function proveFix({ root, from, base, changed, config, fix }) {
257
251
  const what = `This branch fixes ${fix.what}${fix.story ? ` (${fix.story})` : ''}`;
258
- const tests = changed.filter(
252
+ // A test file, named as one or in a test folder (a smoke folder's scripts), brings the fix a test.
253
+ const brought = changed.filter(
259
254
  (f) => isTestFile(f, config) && !SNAPSHOT.test(f) && showAt(root, 'HEAD', f) !== null,
260
255
  );
261
- if (!tests.length)
256
+ if (!brought.length)
262
257
  return [
263
258
  `${what}, but it adds or changes no test. Add a test that fails without the fix: it's what stops the bug coming back.`,
264
259
  ];
265
260
  // A fix made wholly in the tests (a flaky test, a broken helper) has no code to take back: its tests
266
261
  // are the fix. REG-2 still holds them, so it can't be made by weakening one.
267
262
  if (changed.every((f) => isTestFile(f, config) || SNAPSHOT.test(f))) return [];
263
+ // The tests that prove it are the ones named as tests; a helper or harness module beside them is code
264
+ // the fix may have changed, so it goes back with the rest. Only where the fix brings no named test do
265
+ // the files in its test folders stand as its tests.
266
+ const named = brought.filter((f) => isNamedTest(f, config));
267
+ const tests = named.length ? named : brought;
268
+ // What goes back: everything but those tests and the snapshots, except test code the branch adds,
269
+ // which the code without the fix never had and its tests need to load.
270
+ const revert = changed.filter(
271
+ (f) =>
272
+ !tests.includes(f) &&
273
+ !SNAPSHOT.test(f) &&
274
+ !(isTestFile(f, config) && showAt(root, from, f) === null),
275
+ );
268
276
  const covering = config.checks.filter((c) =>
269
277
  tests.some((f) => matchesAny(f, c.files) && !matchesAny(f, c.exclude)),
270
278
  );
@@ -289,8 +297,7 @@ export function proveFix({ root, from, base, changed, config, fix }) {
289
297
  return [
290
298
  `${what}, but its tests don't pass in a fresh checkout of the branch (${withFix.title.replace(/ Fix it:$/, '')}), so code-kit can't tell whether they fail without it. If they need an install or a build first, set regression.prepare.${withFix.output ? `\n${String(withFix.output).trim().split('\n').slice(-20).join('\n')}` : ''}`,
291
299
  ];
292
- for (const f of changed) {
293
- if (isTestFile(f, config) || SNAPSHOT.test(f)) continue;
300
+ for (const f of revert) {
294
301
  if (showAt(root, from, f) !== null) git(dir, 'checkout', from, '--', f);
295
302
  else rmSync(join(dir, f), { force: true });
296
303
  }
@@ -1,7 +1,8 @@
1
1
  // The lead's send-backs: which commit of a branch a review sent back. Until the branch moves past it,
2
2
  // status reads the story as waiting for its lane's fix, not as finished again (and next proposes the
3
- // fix, not a second review of the same commits). Kept beside the requests, in the main checkout.
4
- import { appendFileSync, mkdirSync, readFileSync } from 'node:fs';
3
+ // fix, not a second review of the same commits). And the screenshots a review compared with each
4
+ // screen's approved design (HAND-7). Kept beside the requests, in the main checkout.
5
+ import { appendFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs';
5
6
  import { dirname, join } from 'node:path';
6
7
  import { projectWorktrees } from './rules.mjs';
7
8
 
@@ -55,3 +56,43 @@ export function sendBacks(root) {
55
56
  }
56
57
  });
57
58
  }
59
+
60
+ /** HAND-7: where the review keeps the screenshots it compared, in the main checkout. */
61
+ export const EVIDENCE_DIR = '.claude/state/reviews';
62
+ export const evidenceDir = (root) => join(projectWorktrees(root)[0] ?? root, EVIDENCE_DIR);
63
+
64
+ /**
65
+ * HAND-7: records that the review of `branch` at commit `sha` took a screenshot of a screen's approved
66
+ * state and set it beside the design: `{ story, file, screen, state, image, sha256, viewport, size }`.
67
+ */
68
+ export function recordEvidence(root, record, now = Date.now()) {
69
+ const file = reviewsFile(root);
70
+ mkdirSync(dirname(file), { recursive: true });
71
+ appendFileSync(
72
+ file,
73
+ `${JSON.stringify({ at: new Date(now).toISOString(), verdict: 'evidence', ...record })}\n`,
74
+ );
75
+ }
76
+
77
+ /**
78
+ * HAND-7: the screenshots the reviews recorded for `branch`, oldest first; null where the project's
79
+ * state isn't kept (CI, a fresh clone), so nothing can be said about them.
80
+ */
81
+ export function evidenceRecords(root, branch) {
82
+ const file = reviewsFile(root);
83
+ if (!existsSync(dirname(file))) return null;
84
+ let lines = [];
85
+ try {
86
+ lines = readFileSync(file, 'utf8').split('\n').filter(Boolean);
87
+ } catch {
88
+ return [];
89
+ }
90
+ return lines.flatMap((line) => {
91
+ try {
92
+ const r = JSON.parse(line);
93
+ return r.verdict === 'evidence' && r.branch === branch ? [r] : [];
94
+ } catch {
95
+ return [];
96
+ }
97
+ });
98
+ }
@@ -905,7 +905,8 @@ function specCheckProblem(rel, root) {
905
905
  return `Run the spec-check skill before writing code on this branch. Save its report (the requirement table, questions and recommendation) to ${report}, then continue.`;
906
906
  }
907
907
 
908
- // Screens are designed first: a screen file can be written once the register lists it.
908
+ // Screens are designed first: a screen file can be written once the register holds its approved
909
+ // design as files (HAND-6). An entry naming only a design tool's artboard isn't one: no lane can read it.
909
910
  export function screenProblem(rel, root, config) {
910
911
  const gate = config.designGate;
911
912
  if (!gate) return null;
@@ -919,6 +920,14 @@ export function screenProblem(rel, root, config) {
919
920
  } catch {
920
921
  return `${gate.register} is missing or invalid, so no screen can be built yet.`;
921
922
  }
922
- if (screens.some((s) => s.file === rel)) return null;
923
+ // Handed over, as designs.mjs's handedOver() says: kept here, so the path guard loads no more than this.
924
+ const listed = (Array.isArray(screens) ? screens : []).filter((s) => s?.file === rel);
925
+ if (listed.some((s) => Array.isArray(s.states) && s.states.length > 0)) return null;
926
+ if (listed.length) {
927
+ const s = listed[0];
928
+ const tool =
929
+ s.source?.tool ?? String(s.design ?? '').match(/^([a-z][\w-]*):/i)?.[1] ?? 'the design tool';
930
+ return `${rel} is a screen, and its approved design${s.screen ? ` (${s.screen})` : ''} is only in ${tool}, not as files a lane can build from, so it can't be built yet.\nThe lead hands it over first with /code-kit:design --hand-over, which exports every state into design/ and rewrites its entry in ${gate.register}; then build it from those files. Until then, write a change request for the lead and work on what doesn't need the screen.`;
931
+ }
923
932
  return `${rel} is a screen, and its design is not approved yet.\n${gate.howTo}\nOnce a person approves it, the lead adds { "file": "${rel}", ... } to ${gate.register}.`;
924
933
  }
@@ -9,6 +9,7 @@ import { join } from 'node:path';
9
9
  import { isDependencyFile } from './dependencies.mjs';
10
10
  import { markdownFiles, readStories } from './plan.mjs';
11
11
  import { storyOfBranch } from './teamfacts.mjs';
12
+ import { isTestFile } from './testfiles.mjs';
12
13
 
13
14
  export const SECURITY_AGENT = 'security-reviewer';
14
15
  export const SECURITY_AGENT_FILE = `.claude/agents/${SECURITY_AGENT}.md`;
@@ -42,8 +43,9 @@ export function securityOutcome(report) {
42
43
  }
43
44
 
44
45
  // Tests, docs and design files describe the change; the review looks at the code that ships.
45
- const NOT_SHIPPED =
46
- /(^|\/)(tests?|__tests__|e2e|docs?|design)\/|\.(test|spec|stories)\.[^/]+$|_test\.(go|py)$|(^|\/)test_[^/]+\.py$|\.(md|mdx|txt|png|jpe?g|gif|svg|webp)$/i;
46
+ const DESCRIBES =
47
+ /(^|\/)(docs?|design)\/|\.stories\.[^/]+$|\.(md|mdx|txt|png|jpe?g|gif|svg|webp)$/i;
48
+ const notShipped = (f, config) => isTestFile(f, config) || DESCRIBES.test(f);
47
49
 
48
50
  /**
49
51
  * What makes a change sensitive, by kind: `path` matches a changed file's path, `code` (one pattern or
@@ -148,12 +150,19 @@ const examples = (list) =>
148
150
  /**
149
151
  * Why a change needs the security review, in words, one per kind: [{ kind, why, where: [...] }].
150
152
  * Empty when it touches nothing sensitive. `files` are the changed files, `added` the added lines,
151
- * `cites` the story's requirements and `security` the IDs of the specs' security requirements.
153
+ * `cites` the story's requirements and `security` the IDs of the specs' security requirements; the
154
+ * `config`'s `tests` say which files are tests.
152
155
  */
153
- export function securityReasons({ files = [], added = [], cites = [], security = new Set() }) {
156
+ export function securityReasons({
157
+ files = [],
158
+ added = [],
159
+ cites = [],
160
+ security = new Set(),
161
+ config,
162
+ }) {
154
163
  const reasons = [];
155
- const shipped = files.filter((f) => !NOT_SHIPPED.test(f));
156
- const lines = added.filter((a) => !NOT_SHIPPED.test(a.file));
164
+ const shipped = files.filter((f) => !notShipped(f, config));
165
+ const lines = added.filter((a) => !notShipped(a.file, config));
157
166
  for (const s of SENSITIVE) {
158
167
  const code = [s.code].flat();
159
168
  const where = [
@@ -217,7 +226,13 @@ export function securityReview(root, { base, branch, config }) {
217
226
  const texts = specs
218
227
  ? markdownFiles(root, specs).map((f) => readFileSync(join(root, f), 'utf8'))
219
228
  : [];
220
- const reasons = securityReasons({ files, added, cites, security: securityRequirementIds(texts) });
229
+ const reasons = securityReasons({
230
+ files,
231
+ added,
232
+ cites,
233
+ security: securityRequirementIds(texts),
234
+ config,
235
+ });
221
236
  return {
222
237
  branch,
223
238
  story,
@@ -92,3 +92,100 @@ export const GIT = String.raw`git\s+(?:-[Cc]\s+(?:"[^"]*"|'[^']*'|\S+)\s+)*`;
92
92
 
93
93
  /** code-kit's command line however it's run: installed, through node (its path quoted or not), or npx. */
94
94
  export const CODE_KIT = String.raw`(?:code-kit|node\s+(?:"[^"]*code-kit(?:\.mjs)?"|'[^']*code-kit(?:\.mjs)?'|\S*code-kit(?:\.mjs)?)|npx\s+(?:--yes\s+|-y\s+)?@warren-dean\/code-kit(?:@\S+)?)`;
95
+
96
+ // What a read may redirect: its errors into its output (2>&1, >&2), or anything into /dev/null.
97
+ const HARMLESS_REDIRECT = /(?:\d+|&)?>>?\s*(?:&\d+|\/dev\/null(?![\w/.-]))/g;
98
+ // An assignment before a command (GIT_PAGER=…, GIT_EXTERNAL_DIFF=…, LESSOPEN=…) can make a reader run a
99
+ // program, so a read that sets one isn't only a read.
100
+ const ASSIGNS = /^\s*(?:(?:sudo|exec|time|command|nohup|env)\s+|!\s+)*[A-Za-z_]\w*=/;
101
+
102
+ // Commands that read files or what comes down the pipe and print, and write nothing whatever their
103
+ // arguments. git reads its history: only `-C` before the subcommand (a `-c` setting can name a program
104
+ // to run), and no output file or pager program.
105
+ const READERS = [
106
+ /^(?:cd|pwd|cat|head|tail|wc|grep|egrep|fgrep|cut|jq|nl|tr|ls|stat|diff|cmp|echo|printf|true)(?:\s|$)/,
107
+ // less with no log file of what it shows.
108
+ /^(?!.*\s(?:-[a-zA-Z]*[oO]|--log-file\b|--LOG-FILE\b))less(?:\s|$)/,
109
+ /^(?!.*\s(?:--output\b|-O|--open-files-in-pager\b))git(?:\s+(?:-C\s+\S+|--no-pager|-P))*\s+(?:diff|log|show|blame|grep|status|cat-file|ls-files|shortlog|rev-parse)(?:\s|$)/,
110
+ // rg with no preprocessor; sort with no output file or compressor.
111
+ /^(?!.*\s--pre\b)rg(?:\s|$)/,
112
+ /^(?!.*\s(?:-[a-zA-Z]*o|--output\b|--compress-program\b))sort(?:\s|$)/,
113
+ ];
114
+
115
+ /** A command's words, quotes taken off. */
116
+ const wordsOf = (text) =>
117
+ (text.match(/'[^']*'|"(?:\\.|[^"\\])*"|\S+/g) ?? []).map((w) =>
118
+ w.replace(/^(['"])(.*)\1$/s, '$2'),
119
+ );
120
+
121
+ // A sed script that only prints, deletes from what it prints, numbers or quits: `5,20p`, `$p`, `/x/p`.
122
+ const SED_ADDRESS = String.raw`(?:\d+|\$|/(?:[^/\\]|\\.)*/)`;
123
+ const SED_PRINTS = new RegExp(
124
+ String.raw`^(?:\s*(?:${SED_ADDRESS}(?:\s*,\s*${SED_ADDRESS})?)?\s*[pdq=]\s*)(?:;(?:\s*(?:${SED_ADDRESS}(?:\s*,\s*${SED_ADDRESS})?)?\s*[pdq=]\s*))*;?$`,
125
+ );
126
+
127
+ /** Whether a sed command only prints: no in-place edit, no script file, and every script only prints. */
128
+ function sedPrints(text) {
129
+ const words = wordsOf(text).slice(1);
130
+ const scripts = [];
131
+ let expressions = false;
132
+ const files = [];
133
+ for (let i = 0; i < words.length; i++) {
134
+ const w = words[i];
135
+ if (w === '-e' || w === '--expression') {
136
+ expressions = true;
137
+ scripts.push(words[++i] ?? '');
138
+ } else if (w.startsWith('--expression=')) {
139
+ expressions = true;
140
+ scripts.push(w.slice('--expression='.length));
141
+ } else if (w === '--quiet' || w === '--silent' || w === '-n') continue;
142
+ else if (/^-[nErsuz]+$/.test(w)) continue;
143
+ else if (w.startsWith('-'))
144
+ return false; // -i, -I, -f and anything else
145
+ else files.push(w);
146
+ }
147
+ if (!expressions && files.length) scripts.push(files.shift());
148
+ return scripts.length > 0 && scripts.every((s) => SED_PRINTS.test(s));
149
+ }
150
+
151
+ /** Whether an awk command only prints: -F and -v only, and no redirect, pipe, system() or getline. */
152
+ function awkPrints(text) {
153
+ const words = wordsOf(text).slice(1);
154
+ for (let i = 0; i < words.length; i++) {
155
+ if (!words[i].startsWith('-')) break;
156
+ if (words[i] === '-v') i++;
157
+ else if (!/^-F/.test(words[i])) return false;
158
+ }
159
+ return !/[>|]|\b(?:system|getline|fflush|close)\b/.test(text);
160
+ }
161
+
162
+ /** Whether a uniq command names no output file: at most one file, the one it reads. */
163
+ const uniqPrints = (text) =>
164
+ wordsOf(text)
165
+ .slice(1)
166
+ .filter((w) => !w.startsWith('-')).length <= 1;
167
+
168
+ /**
169
+ * Whether `cmd` only reads and prints, so it can't write any file: every command of the chain is a
170
+ * reader (`cd`, git's history, cat, head, tail, grep, wc, jq, cut, sort, uniq, awk without redirects,
171
+ * sed -n printing lines…), piped or chained into each other, with no command's output in its
172
+ * arguments, no variable set before a command, and no redirect but `2>&1` or into /dev/null.
173
+ */
174
+ export function readsOnly(cmd) {
175
+ // Taken out first: `&` in `2>&1` would otherwise split the command there.
176
+ const read = String(cmd).replace(HARMLESS_REDIRECT, ' ');
177
+ const code = codeOf(read);
178
+ if (/[>`]|\$\(|<\(|<>/.test(code)) return false;
179
+ if (code.split(/[;&|\n()]/).some((piece) => ASSIGNS.test(piece))) return false;
180
+ const parts = commandsOf(read);
181
+ return (
182
+ parts.length > 0 &&
183
+ parts.every(({ text, code: c }) => {
184
+ if (READERS.some((re) => re.test(c))) return true;
185
+ if (/^sed(?:\s|$)/.test(c)) return sedPrints(text);
186
+ if (/^awk(?:\s|$)/.test(c)) return awkPrints(text);
187
+ if (/^uniq(?:\s|$)/.test(c)) return uniqPrints(text);
188
+ return false;
189
+ })
190
+ );
191
+ }
@@ -503,7 +503,7 @@ export function buildSnapshot({
503
503
  const checks = new Map();
504
504
  for (const rows of rowsOf.values())
505
505
  for (const row of rows) checks.set(row.requirement, row.status);
506
- const requirements = trail(root, status, base).map((r) => ({
506
+ const requirements = trail(root, status, base, config).map((r) => ({
507
507
  id: r.id,
508
508
  title: line(r.title),
509
509
  stories: r.stories.map((s) => s.id),
@@ -6,6 +6,7 @@ import { existsSync, readFileSync } from 'node:fs';
6
6
  import { join, posix } from 'node:path';
7
7
  import { matchesAny } from './glob.mjs';
8
8
  import { CODE, importsOf, layerOf, targetOf } from './layers.mjs';
9
+ import { isTestFile } from './testfiles.mjs';
9
10
 
10
11
  const git = (root, ...args) => {
11
12
  try {
@@ -126,8 +127,6 @@ export function laneOfFile(rel, config) {
126
127
  : null;
127
128
  }
128
129
 
129
- const TEST = /(^|\/)(tests?|e2e|__tests__)\/|\.(test|spec)\.[cm]?[jt]sx?$/;
130
-
131
130
  /**
132
131
  * MAP-1: a story's code: { story, layers, files: [{ path, layer, lane, imports }] }. `layers` are the
133
132
  * config's layers in their order, then `tests` and `other` where any file falls there; each file's
@@ -151,7 +150,9 @@ export function storyMap(root, story, config, from) {
151
150
  .filter((t) => t && t !== rel),
152
151
  ),
153
152
  ];
154
- const layer = TEST.test(rel) ? 'tests' : (layerOf(rel, config.layers)?.name ?? 'other');
153
+ const layer = isTestFile(rel, config)
154
+ ? 'tests'
155
+ : (layerOf(rel, config.layers)?.name ?? 'other');
155
156
  return { path: rel, layer, lane: laneOfFile(rel, config), imports };
156
157
  });
157
158
  const used = new Set(files.map((f) => f.layer));
@@ -165,9 +166,10 @@ export function storyMap(root, story, config, from) {
165
166
 
166
167
  /**
167
168
  * TRAIL-1: each requirement's trail: { id, title, spec, state, stories: [{ id, state, lane }],
168
- * files, tests }. Files are the code its stories changed, tests aside; tests are the files that name it.
169
+ * files, tests }. Files are the code its stories changed, tests aside (by `config`'s `tests`); tests are the
170
+ * files that name it.
169
171
  */
170
- export function trail(root, status, from) {
172
+ export function trail(root, status, from, config) {
171
173
  const byStory = new Map();
172
174
  const named = namedFiles(root);
173
175
  const filesOf = (s) => {
@@ -178,7 +180,9 @@ export function trail(root, status, from) {
178
180
  .filter((r) => !r.removed)
179
181
  .map((r) => {
180
182
  const stories = status.stories.filter((s) => s.requirements.includes(r.id));
181
- const files = [...new Set(stories.flatMap((s) => filesOf(s)).filter((f) => !TEST.test(f)))];
183
+ const files = [
184
+ ...new Set(stories.flatMap((s) => filesOf(s)).filter((f) => !isTestFile(f, config))),
185
+ ];
182
186
  return {
183
187
  id: r.id,
184
188
  title: r.title,
@@ -221,7 +225,9 @@ export function projectMap(root, config, tracked, { depth = 3, most = 60 } = {})
221
225
  files: 0,
222
226
  };
223
227
  nodes.set(path, node);
224
- const layer = TEST.test(rel) ? 'tests' : (layerOf(rel, config.layers)?.name ?? 'other');
228
+ const layer = isTestFile(rel, config)
229
+ ? 'tests'
230
+ : (layerOf(rel, config.layers)?.name ?? 'other');
225
231
  node.layers.set(layer, (node.layers.get(layer) ?? 0) + 1);
226
232
  node.files += 1;
227
233
  let source = '';
@@ -0,0 +1,22 @@
1
+ // What counts as a test (docs/specs/18-regression.md), in one place for every check that asks: a fix's
2
+ // proof (REG-1), weakened tests (REG-2), the tests that name a requirement, the code map's tests layer,
3
+ // what the security review leaves out and which files are screens. A project's `tests` globs replace
4
+ // the conventions; without them, a file is a test when it's named as one or sits in a test folder.
5
+ import { matchesAny } from './glob.mjs';
6
+
7
+ // Named as a test: `*.test.*`, `*.spec.*`, `*.smoke.*`, `test_*.py`, `*_test.go` and `*_test.py`.
8
+ const NAMED = /\.(test|spec|smoke)\.[^/]+$|_test\.(go|py)$|(^|\/)test_[^/]+\.py$/;
9
+ // Inside a test folder, where a test's helpers, fixtures and harness live too.
10
+ const FOLDER = /(^|\/)(tests?|__tests__|e2e|smoke)\//;
11
+
12
+ /** Whether `rel` is a test or test code: the config's `tests` globs, or named as a test or in a test folder. */
13
+ export const isTestFile = (rel, config) =>
14
+ !rel.endsWith('.md') &&
15
+ (config?.tests?.length ? matchesAny(rel, config.tests) : NAMED.test(rel) || FOLDER.test(rel));
16
+
17
+ /**
18
+ * Whether `rel` is a test itself, by its name, and not a helper beside one: the config's `tests` globs,
19
+ * or the naming conventions. A fix's proof keeps these and takes everything else back (REG-1).
20
+ */
21
+ export const isNamedTest = (rel, config) =>
22
+ !rel.endsWith('.md') && (config?.tests?.length ? matchesAny(rel, config.tests) : NAMED.test(rel));
@@ -8,19 +8,23 @@ import { BASELINE_FILE, loadBaseline, newProblems } from './baseline.mjs';
8
8
  import { runChecks } from './checks.mjs';
9
9
  import { CONFIG_FILE } from './config.mjs';
10
10
  import { isDependencyFile } from './dependencies.mjs';
11
- import { entryProblems, readRegister } from './designs.mjs';
11
+ import { entryProblems, freshEntries, readRegister, statesWithoutEvidence } from './designs.mjs';
12
+ import { evidenceRecords } from './reviews.mjs';
13
+ import { storyOfBranch } from './teamfacts.mjs';
12
14
  import { matchesAny } from './glob.mjs';
13
15
  import { layerProblems } from './layers.mjs';
14
16
  import { STANDARDS_APPROVAL, standardsFile, standardsWeakenings } from './standards.mjs';
15
17
  import { TESTS_APPROVAL, branchWeakenings, fixOf, proveFix } from './regression.mjs';
16
18
  import {
17
19
  APPROVAL_LOG,
20
+ APPROVALS_DIR,
18
21
  SECRETS,
19
22
  laneOf,
20
23
  ownerOf,
21
24
  owns,
22
25
  protectedEntry,
23
26
  leadNeedsApproval,
27
+ relayCommand,
24
28
  screenProblem,
25
29
  } from './rules.mjs';
26
30
 
@@ -40,6 +44,15 @@ function showAt(root, ref, rel) {
40
44
  }
41
45
  }
42
46
 
47
+ /** The hash of a file's content at `ref` (git's blob id), or null when it doesn't exist there. */
48
+ function blobAt(root, ref, rel) {
49
+ try {
50
+ return git(root, 'rev-parse', '--verify', '-q', `${ref}:${rel}`).trim();
51
+ } catch {
52
+ return null;
53
+ }
54
+ }
55
+
43
56
  /** The lane a branch belongs to by its name (`<lane>/<story>`), or null. */
44
57
  export function laneOfBranch(branch, config) {
45
58
  const lane = branch?.split('/')[0];
@@ -176,6 +189,8 @@ const NOISE = [
176
189
  /^\(node:\d+\) \[?\w*\]? ?(DeprecationWarning|ExperimentalWarning|Warning)\b/,
177
190
  /^\(Use `node --trace-(deprecation|warnings) /,
178
191
  /^\s*$/,
192
+ // A tool printing a value it never had (pnpm exec, before it says a command isn't installed).
193
+ /^\s*undefined\s*$/,
179
194
  ];
180
195
  const FAILING = /\b(fail(ed|ing|s)?|error|✗|✘|×|expected|received|assert|panic|traceback)\b/i;
181
196
 
@@ -194,8 +209,8 @@ export function failureOutput(output) {
194
209
 
195
210
  /**
196
211
  * The files changed, every problem with the branch, grouped as { ownership, protected, layers,
197
- * baseline, design, tests, regression, standards, checks }, and the checks `skipped` because a tool isn't
198
- * installed. `lane` holds the branch to that lane's paths; `checks: false` leaves the project's
212
+ * baseline, design, evidence, tests, regression, standards, checks }, and the checks `skipped` because a
213
+ * tool isn't installed; `evidenceUnchecked` where the review's records aren't kept (HAND-7: CI). `lane` holds the branch to that lane's paths; `checks: false` leaves the project's
199
214
  * checks to CI's own steps. `fixes` runs a fix's tests without the fix (REG-1; with the
200
215
  * checks unless said); `branch` names the branch when the checkout is detached.
201
216
  */
@@ -218,6 +233,7 @@ export function verifyBranch({
218
233
  layers: [],
219
234
  baseline: [],
220
235
  design: [],
236
+ evidence: [],
221
237
  tests: [],
222
238
  regression: [],
223
239
  standards: [],
@@ -241,15 +257,17 @@ export function verifyBranch({
241
257
  );
242
258
  // WHO-1: where the lead merges, its own change to what the person keeps needs the person's approval,
243
259
  // unless the base already holds it as the branch does (the setup's rules, put onto the base first).
260
+ // An approval recorded after the change names the content it approved (`blob`), and covers only that.
244
261
  else if (
245
262
  guarded &&
246
- logged.get(f)?.approval === 'lead' &&
247
263
  !signed &&
248
264
  leadNeedsApproval(guarded.approval, config) &&
265
+ (logged.get(f)?.approval === 'lead' ||
266
+ (logged.get(f)?.blob && logged.get(f).blob !== blobAt(root, 'HEAD', f))) &&
249
267
  showAt(root, base, f) !== showAt(root, 'HEAD', f)
250
268
  )
251
269
  found.protected.push(
252
- `${f} is ${guarded.why}, and the lead changed it without the person's ${guarded.approval} approval. The lead merges here, so nobody else reviews it: ask the person, and commit it again once their approval is in force.`,
270
+ `${f} is ${guarded.why}, and the lead ${logged.get(f)?.approval === 'lead' ? 'changed it without' : 'changed it since it had'} the person's ${guarded.approval} approval. The lead merges here, so nobody else reviews it. Ask the person; once they approve it (they run \`! echo "<what you are approving>" > ${APPROVALS_DIR}/${guarded.approval}\`${config.approvals?.lead ? `, or you record their words with \`${relayCommand(guarded.approval)}\`` : ''}), record their approval for the file as it is with a commit of its own: \`git commit -m "Record the person's ${guarded.approval} approval for ${f}"\`. The commit hook logs it; the file doesn't need to change.`,
253
271
  );
254
272
  if (matchesAny(f, config.anyActor)) continue;
255
273
  if (lane === 'lead') {
@@ -294,17 +312,43 @@ export function verifyBranch({
294
312
  }
295
313
 
296
314
  // HAND-2: each register entry the branch adds or changes, and each approved design whose files it
297
- // changed, names the approved files with their hashes, every state the spec lists.
315
+ // changed, names the approved files with their hashes, every state the spec lists. HAND-11: an entry
316
+ // the base already holds (where the branch left it, as it is now, or the first protected branch's,
317
+ // which a lane may have merged in) is the base's, not the branch's.
298
318
  const register = config.designGate?.register;
319
+ let evidenceUnchecked = false;
299
320
  if (register) {
300
- const old = readRegister(root, config, showAt(root, from, register) ?? '{}').entries;
321
+ const at = (ref) => readRegister(root, config, showAt(root, ref, register) ?? '{}').entries;
322
+ const entries = readRegister(root, config).entries;
323
+ const protectedBase = config.branches?.protected?.[0];
324
+ const fresh = new Set(
325
+ freshEntries(entries, at(from), at(base), protectedBase ? at(protectedBase) : []),
326
+ );
301
327
  const touched = new Set(changed);
302
- for (const e of readRegister(root, config).entries) {
303
- const fresh = !old.some((o) => JSON.stringify(o) === JSON.stringify(e));
328
+ for (const e of entries) {
304
329
  const files = (e.states ?? []).flatMap((st) => [st?.image, st?.code]).filter(Boolean);
305
- if (fresh || files.some((f) => touched.has(f)))
330
+ if (fresh.has(e) || files.some((f) => touched.has(f)))
306
331
  found.design.push(...entryProblems(root, e, config.docs?.specs));
307
332
  }
333
+ // HAND-7: a lane's branch that builds screens has the review's screenshot of each approved state.
334
+ const name = branch ?? currentBranchOf(root);
335
+ if (lane && lane !== 'lead' && name) {
336
+ const records = evidenceRecords(root, name);
337
+ if (records === null) evidenceUnchecked = true;
338
+ else {
339
+ const current = (r) =>
340
+ Boolean(r.sha) &&
341
+ spawnSync('git', ['-C', root, 'merge-base', '--is-ancestor', r.sha, 'HEAD']).status ===
342
+ 0 &&
343
+ spawnSync('git', ['-C', root, 'diff', '--quiet', r.sha, 'HEAD', '--', r.file]).status ===
344
+ 0;
345
+ const story = storyOfBranch(name) ?? name;
346
+ for (const { entry, state } of statesWithoutEvidence(entries, present, records, current))
347
+ found.evidence.push(
348
+ `${entry.screen ?? entry.file}'s ${state.name} state (${entry.file}) has no screenshot from the review beside its design (${state.image}). The review takes one of the built state at ${state.viewport ?? "the design's viewport"} and records it: code-kit designs evidence ${story} ${entry.file} ${state.name} <screenshot.png>.`,
349
+ );
350
+ }
351
+ }
308
352
  }
309
353
 
310
354
  // The baseline only shrinks once the kit is adopted (the adopting change may record it).
@@ -368,5 +412,5 @@ export function verifyBranch({
368
412
  unfinished = Boolean(failure.timedOut);
369
413
  }
370
414
  }
371
- return { changed, found, skipped, unfinished };
415
+ return { changed, found, skipped, unfinished, evidenceUnchecked };
372
416
  }
@@ -37,6 +37,14 @@ const real = (p) => {
37
37
  return p;
38
38
  }
39
39
  };
40
+ /** The folder this process runs in, or null when it has gone. */
41
+ const cwdNow = () => {
42
+ try {
43
+ return real(process.cwd());
44
+ } catch {
45
+ return null;
46
+ }
47
+ };
40
48
  const alive = (pid) => {
41
49
  try {
42
50
  process.kill(pid, 0);
@@ -74,11 +82,12 @@ function hasOwnCommits(root, branch) {
74
82
 
75
83
  /**
76
84
  * LEAN-6: each worktree but the main checkout: { path, branch, story, merged, clean, changes, report,
77
- * kind, missing, locked: { reason, pid, live } | null, agentAtWork }. `kind` is `agent` (under
85
+ * kind, missing, locked: { reason, pid, live } | null, agentAtWork, here }. `here`: this command runs in
86
+ * it (`cwd`, the process's own folder unless given), so taking it away would leave the shell nowhere. `kind` is `agent` (under
78
87
  * .claude/worktrees), `merge` (a temporary merge checkout) or `other` (one the person made). `clean` and
79
88
  * `changes` are null where they weren't read: an unmerged worktree stays whatever it holds (cleanOf reads it).
80
89
  */
81
- export function worktrees(root, config, now = Date.now()) {
90
+ export function worktrees(root, config, now = Date.now(), cwd = cwdNow()) {
82
91
  const list = git(root, 'worktree', 'list', '--porcelain');
83
92
  if (list.status !== 0) return [];
84
93
  const main = list.stdout.split('\n\n')[0];
@@ -98,6 +107,7 @@ export function worktrees(root, config, now = Date.now()) {
98
107
  const pid = Number(/\bpid (\d+)/.exec(lockLine?.[1] ?? '')?.[1]) || null;
99
108
  const missing = !existsSync(path);
100
109
  const where = real(path);
110
+ const here = Boolean(cwd && (cwd === where || cwd.startsWith(`${where}/`)));
101
111
  const kind = where.startsWith(`${agents}/`)
102
112
  ? 'agent'
103
113
  : where.startsWith(`${temp}/`) && TEMP_MERGE.test(basename(path))
@@ -140,6 +150,7 @@ export function worktrees(root, config, now = Date.now()) {
140
150
  lane && claims.some((c) => c.lane === lane && (c.story ?? null) === (story ?? c.story)),
141
151
  ),
142
152
  age: missing ? null : now - statSync(path).mtimeMs,
153
+ here,
143
154
  };
144
155
  });
145
156
  }
@@ -174,6 +185,9 @@ export function keptBecause(w) {
174
185
  if (w.missing) return null;
175
186
  if (w.kind === 'merge') return w.age < TEMP_MERGE_MS ? 'a merge may be using it now' : null;
176
187
  if (w.kind === 'other') return "it isn't one code-kit made; release it by name if it's done";
188
+ // A merge run from inside a lane's worktree mustn't take away the folder its own shell is in.
189
+ if (w.here)
190
+ return 'this command runs in it; it goes at the next merge or `code-kit worktrees prune` run from elsewhere';
177
191
  if (w.locked && !w.locked.pid)
178
192
  return `it's locked${w.locked.reason ? ` (${w.locked.reason})` : ''}`;
179
193
  if (!w.branch) return 'it has no branch checked out';
@@ -246,7 +260,15 @@ export function pruneWorktrees(root, config, now = Date.now()) {
246
260
  const label = w.branch ?? w.path;
247
261
  const why = keptBecause(w);
248
262
  if (why) {
249
- kept.push({ label, why, branch: w.branch, changes: w.changes, kind: w.kind });
263
+ kept.push({
264
+ label,
265
+ why,
266
+ branch: w.branch,
267
+ changes: w.changes,
268
+ kind: w.kind,
269
+ here: w.here,
270
+ merged: w.merged,
271
+ });
250
272
  continue;
251
273
  }
252
274
  if (w.missing) continue;
@@ -235,6 +235,8 @@ const NOTES = new Set([
235
235
  'elsewhere',
236
236
  'loop',
237
237
  'drift',
238
+ 'queuePaused',
239
+ 'deferred',
238
240
  ]);
239
241
 
240
242
  /** What a line is, in a word or two, for the Needs you panel. */