@warren-dean/code-kit 0.29.0 → 0.30.1

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.
@@ -11,6 +11,7 @@ import { readEvents } from './events.mjs';
11
11
  import { laneClaims } from './laneclaims.mjs';
12
12
  import { waitingStories } from './questions.mjs';
13
13
  import { sentBack } from './reviews.mjs';
14
+ import { isTestFile } from './testfiles.mjs';
14
15
  import { WORKTREES_DIR } from './worktrees.mjs';
15
16
 
16
17
  export const REQUIREMENT = /\b(?!ST-)([A-Z][A-Z0-9]*-\d+)\b/g;
@@ -22,9 +23,6 @@ export const DROPPED = 'dropped';
22
23
  export const LEAD = 'lead';
23
24
  /** ONB-2: the pseudo-lane for design stories, which the lead designs with the person before any screen is built. */
24
25
  export const DESIGN = 'design';
25
- // Test files, by the usual conventions. Tests name the requirement IDs they prove.
26
- const TEST =
27
- /(^|\/)(tests?|__tests__|e2e)\/|\.(test|spec)\.[^/]+$|_test\.(go|py)$|(^|\/)test_[^/]+\.py$/;
28
26
 
29
27
  /** The markdown files at `path`: the file itself, or every one under the folder, sorted. */
30
28
  export const markdownFiles = (root, path) => {
@@ -85,6 +83,134 @@ export function readSpecs(root, specsPath, plan = null) {
85
83
  return found;
86
84
  }
87
85
 
86
+ /** A screen's name as the specs and the register give it, compared: no markdown, one case, one space. */
87
+ export const screenKey = (name) =>
88
+ String(name ?? '')
89
+ .replace(/\[([^\]]*)\]\([^)]*\)/g, '$1')
90
+ .replace(/[*_`]/g, '')
91
+ .replace(/\s+/g, ' ')
92
+ .trim()
93
+ .toLowerCase();
94
+
95
+ /** The states a `**States:**` line or a States cell lists, in lower case. */
96
+ const statesOf = (text) =>
97
+ String(text)
98
+ .replace(/<br\s*\/?>/gi, ',')
99
+ .split(/[,;/]/)
100
+ .map((s) => screenKey(s).replace(/\.$/, ''))
101
+ .filter(Boolean);
102
+
103
+ /** A `- **Name** …` bullet that lists a screen: { indent, title }, or null (a field such as `**States:**`). */
104
+ function screenBullet(line) {
105
+ const m = line.match(/^(\s*)[-*]\s+\*\*([^*]+?)\*\*/);
106
+ return m && !/:\s*$/.test(m[2]) ? { indent: m[1].length, title: m[2] } : null;
107
+ }
108
+
109
+ const cellsOf = (line) =>
110
+ line
111
+ .trim()
112
+ .replace(/^\||\|$/g, '')
113
+ .split('|')
114
+ .map((c) => c.trim());
115
+
116
+ /**
117
+ * The screens one `## Screens` section lists, from its lines: `### Name` and `#### Name` headings (a
118
+ * trailing `(…)` left out of the name), `- **Name** …` bullets (by the bold title; a bold title ending in
119
+ * a colon, such as `**States:**`, is a field, not a screen), and a table's rows (by its Screen or Name
120
+ * column, else its first; a States column gives the states).
121
+ */
122
+ function screensIn(lines, file) {
123
+ const found = [];
124
+ const fieldStates = (body) => body.match(/\*\*States:\*\*\s*(.+)/i)?.[1] ?? null;
125
+ lines.forEach((line, i) => {
126
+ const heading = line.match(/^#{3,4}\s+(.+?)\s*$/);
127
+ if (heading) {
128
+ const end = lines.findIndex((l, j) => j > i && /^#{1,4}\s/.test(l));
129
+ const block = lines.slice(i, end < 0 ? undefined : end);
130
+ // Its own States line comes before any screen listed under it.
131
+ const own = block.findIndex((l, j) => j > 0 && screenBullet(l));
132
+ const listed = fieldStates(block.slice(0, own < 0 ? undefined : own).join('\n'));
133
+ const name = heading[1].replace(/\s*\([^)]*\)\s*$/, '');
134
+ found.push({
135
+ name: screenKey(name),
136
+ title: name.replace(/[*_`]/g, '').trim(),
137
+ file,
138
+ states: listed ? statesOf(listed) : null,
139
+ body: block.join('\n'),
140
+ });
141
+ return;
142
+ }
143
+ const bullet = screenBullet(line);
144
+ if (bullet) {
145
+ const { indent } = bullet;
146
+ const end = lines.findIndex(
147
+ (l, j) =>
148
+ j > i &&
149
+ (/^#{1,4}\s/.test(l) ||
150
+ /^\s*\|/.test(l) ||
151
+ (/^\s*[-*]\s/.test(l) && l.match(/^\s*/)[0].length <= indent)),
152
+ );
153
+ const body = lines.slice(i, end < 0 ? undefined : end).join('\n');
154
+ const listed = fieldStates(body);
155
+ found.push({
156
+ name: screenKey(bullet.title),
157
+ title: bullet.title.trim(),
158
+ file,
159
+ states: listed ? statesOf(listed) : null,
160
+ body,
161
+ });
162
+ }
163
+ });
164
+ // Tables: a header row, its separator, then a row per screen.
165
+ for (let i = 0; i + 1 < lines.length; i++) {
166
+ if (!/^\s*\|/.test(lines[i]) || !/^\s*\|[\s:|-]+\|\s*$/.test(lines[i + 1])) continue;
167
+ if (i > 0 && /^\s*\|/.test(lines[i - 1])) continue;
168
+ const header = cellsOf(lines[i]).map((c) => screenKey(c));
169
+ const nameAt = Math.max(
170
+ header.findIndex((c) => /^(screen|name)\b/.test(c)),
171
+ 0,
172
+ );
173
+ const statesAt = header.findIndex((c) => /^states?\b/.test(c));
174
+ for (let j = i + 2; j < lines.length && /^\s*\|/.test(lines[j]); j++) {
175
+ const cells = cellsOf(lines[j]);
176
+ const title = (cells[nameAt] ?? '').replace(/\s*\([^)]*\)\s*$/, '');
177
+ if (!screenKey(title)) continue;
178
+ found.push({
179
+ name: screenKey(title),
180
+ title: title.replace(/[*_`]/g, '').trim(),
181
+ file,
182
+ states: statesAt >= 0 && cells[statesAt] ? statesOf(cells[statesAt]) : null,
183
+ body: lines[j],
184
+ });
185
+ }
186
+ }
187
+ return found;
188
+ }
189
+
190
+ /**
191
+ * HAND-9: every screen the specs' `## Screens` sections list: [{ name, title, file, states, body }].
192
+ * `name` is the screen's name compared (screenKey), `title` as written; `states` what a `**States:**`
193
+ * line or a States column lists, or null when neither does; `body` its text, for the states it mentions.
194
+ */
195
+ export function readScreens(root, specsPath) {
196
+ if (!specsPath) return [];
197
+ const found = [];
198
+ for (const file of markdownFiles(root, specsPath)) {
199
+ let lines;
200
+ try {
201
+ lines = readFileSync(join(root, file), 'utf8').split('\n');
202
+ } catch {
203
+ continue;
204
+ }
205
+ lines.forEach((line, i) => {
206
+ if (!/^##\s+Screens\b/i.test(line)) return;
207
+ const end = lines.findIndex((l, j) => j > i && /^#{1,2}\s/.test(l));
208
+ found.push(...screensIn(lines.slice(i + 1, end < 0 ? undefined : end), file));
209
+ });
210
+ }
211
+ return found;
212
+ }
213
+
88
214
  /** The first paragraph under a story's `**Field:**` lines, on one line, or null. */
89
215
  function summaryOf(body) {
90
216
  const start = body.findIndex((l) => l.trim() && !/^\*\*[^*]+:\*\*/.test(l.trim()));
@@ -99,7 +225,7 @@ function summaryOf(body) {
99
225
  }
100
226
 
101
227
  /**
102
- * Every story in the plan: [{ id, title, lane, requirements, dependsOn, status, fixes, milestone, slice, size, summary }].
228
+ * Every story in the plan: [{ id, title, lane, requirements, dependsOn, status, fixes, milestone, slice, size, screens, summary }].
103
229
  * A story's milestone is the `## ` heading above it ("Milestone 5: Your own key"), or null; its summary the
104
230
  * paragraph under its fields, on one line, or null.
105
231
  */
@@ -135,6 +261,13 @@ export function readStories(root, planPath) {
135
261
  field(body, 'Size')
136
262
  .toLowerCase()
137
263
  .match(/^(small|medium|large)\b/)?.[1] ?? null,
264
+ // HAND-10: the screens a design story designs, where the plan names them, or null.
265
+ screens: field(body, 'Screens')
266
+ ? field(body, 'Screens')
267
+ .split(/[,;]/)
268
+ .map((n) => n.trim())
269
+ .filter(Boolean)
270
+ : null,
138
271
  summary: summaryOf(body),
139
272
  });
140
273
  });
@@ -168,11 +301,11 @@ export function readMilestones(root, planPath) {
168
301
 
169
302
  export const storyBranch = (story) => `${story.lane}/${story.id.toLowerCase()}`;
170
303
 
171
- /** Requirement IDs each tracked test file names: { id: [file, ...] }. */
172
- export function testedRequirements(root, files, specsPath) {
304
+ /** Requirement IDs each tracked test file names (tests name the IDs they prove): { id: [file, ...] }. */
305
+ export function testedRequirements(root, files, specsPath, config) {
173
306
  const tested = {};
174
307
  for (const file of files) {
175
- if (!TEST.test(file) || file.endsWith('.md') || file.startsWith(`${specsPath}/`)) continue;
308
+ if (!isTestFile(file, config) || file.startsWith(`${specsPath}/`)) continue;
176
309
  let body;
177
310
  try {
178
311
  body = readFileSync(join(root, file), 'utf8');
@@ -279,8 +412,12 @@ function worktrees(root) {
279
412
  * whatever the plan says yet. A lane's branch that never moved is `stopped`: its agent stopped before its
280
413
  * first commit, and the story is ready again (or blocked) for a fresh agent, so its lane isn't held by
281
414
  * nothing. A branch only on origin may be a teammate's, and stays in progress unless the base holds it.
415
+ *
416
+ * HAND-10: a design story's branch is committed to as each screen is approved, so with commits ahead it
417
+ * stays in progress while `designing(story, ref)` says screens it designs aren't in its register yet,
418
+ * until the plan's status says `review`.
282
419
  */
283
- export function storyStates(root, stories, base) {
420
+ export function storyStates(root, stories, base, { designing = null } = {}) {
284
421
  const trees = worktrees(root);
285
422
  const backs = sentBack(root);
286
423
  const refs = branchRefs(root, base);
@@ -322,7 +459,11 @@ export function storyStates(root, stories, base) {
322
459
  if (ref && !['done', DROPPED].includes(story.status)) {
323
460
  const head = backs[branch] ? refs[ref].sha : null;
324
461
  if (head && head === backs[branch].sha) state = 'sent back';
325
- else if (ahead > 0) state = building(story) ? 'in progress' : 'review';
462
+ else if (ahead > 0)
463
+ state =
464
+ building(story) || (story.lane === DESIGN && designing?.(story, ref))
465
+ ? 'in progress'
466
+ : 'review';
326
467
  else if (story.status === 'review') state = 'done';
327
468
  else if (builtBy(story, branch)) state = 'in progress';
328
469
  else {
@@ -398,12 +539,46 @@ export function traceProblems(requirements, stories, lanes) {
398
539
  return problems;
399
540
  }
400
541
 
542
+ /**
543
+ * HAND-10: (story, ref) => whether a design story still has screens to design on its branch: a screen
544
+ * its plan entry names (`**Screens:**`), or else one the `## Screens` sections of its requirements'
545
+ * specs list, with no entry in the register as `ref` has it. The plan's `**Status:** review` says the
546
+ * lead is done with it, whatever is left. Null without a design gate.
547
+ */
548
+ function stillDesigning(root, config, requirements) {
549
+ const register = config.designGate?.register;
550
+ if (!register) return null;
551
+ let screens = null;
552
+ return (story, ref) => {
553
+ if (story.status === 'review') return false;
554
+ let wanted = story.screens?.map(screenKey);
555
+ if (!wanted) {
556
+ screens ??= readScreens(root, config.docs?.specs);
557
+ const files = new Set(
558
+ requirements.filter((r) => story.requirements.includes(r.id)).map((r) => r.file),
559
+ );
560
+ wanted = screens.filter((s) => files.has(s.file)).map((s) => s.name);
561
+ }
562
+ if (!wanted.length) return false;
563
+ let entries = [];
564
+ try {
565
+ entries = JSON.parse(git(root, 'show', `${ref}:${register}`) ?? '{}').screens ?? [];
566
+ } catch {
567
+ // an unreadable register on the branch holds no screen yet
568
+ }
569
+ const named = new Set((Array.isArray(entries) ? entries : []).map((e) => screenKey(e?.screen)));
570
+ return wanted.some((w) => !named.has(w));
571
+ };
572
+ }
573
+
401
574
  /** The whole picture for `code-kit status` and `code-kit next`: stories, requirements, gaps, drift. */
402
575
  export function buildStatus(root, config, base, files) {
403
576
  const { specs, plan } = config.docs;
404
577
  const requirements = readRequirements(root, specs).filter((r) => r.file !== plan);
405
- const stories = storyStates(root, readStories(root, plan), base);
406
- const tested = testedRequirements(root, files, specs);
578
+ const stories = storyStates(root, readStories(root, plan), base, {
579
+ designing: stillDesigning(root, config, requirements),
580
+ });
581
+ const tested = testedRequirements(root, files, specs, config);
407
582
  const problems = traceProblems(requirements, stories, Object.keys(config.lanes));
408
583
  const byRequirement = requirements.map((r) => {
409
584
  const covering = stories.filter((s) => s.state !== DROPPED && s.requirements.includes(r.id));
@@ -1,7 +1,7 @@
1
1
  // The merge queue (docs/specs/09-merge-queue.md): branches that passed the lead's review, merged one at
2
2
  // a time in the order they passed, each verified against the base as it is then. Kept in the main
3
3
  // checkout, beside the requests and reviews, so every worktree and a restarted session see the same.
4
- import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
4
+ import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
5
5
  import { dirname, join } from 'node:path';
6
6
  import { projectWorktrees } from './rules.mjs';
7
7
  import { GIT, commandsOf } from './shell.mjs';
@@ -80,11 +80,12 @@ export function dequeue(root, branch) {
80
80
  * review, so it's reviewed again), or waiting again.
81
81
  */
82
82
  export function settle(root, branch, state, reason = null, now = Date.now()) {
83
- const entries = readQueue(root).map((e) =>
84
- e.branch === branch && ['waiting', 'merging'].includes(e.state)
85
- ? { ...e, state, at: new Date(now).toISOString(), ...(reason ? { reason } : {}) }
86
- : e,
87
- );
83
+ const entries = readQueue(root).map((e) => {
84
+ if (e.branch !== branch || !['waiting', 'merging'].includes(e.state)) return e;
85
+ // The merge that settled it is over: its process no longer marks the entry.
86
+ const { pid: _pid, ...rest } = e;
87
+ return { ...rest, state, at: new Date(now).toISOString(), ...(reason ? { reason } : {}) };
88
+ });
88
89
  // Merged and sent-back entries move behind the waiting ones' history, in the order they settled.
89
90
  const settled = entries.filter((e) => e.branch === branch && e.state === state);
90
91
  writeQueue(root, [...entries.filter((e) => !settled.includes(e)), ...settled]);
@@ -122,11 +123,13 @@ export function mergingNow(entry) {
122
123
  * MQ-7: what the queue merges next. A branch queued `with` others merges only together with them, once
123
124
  * each is queued too: verified as one tree, merged one after another. Until then it waits, and the
124
125
  * queue goes on with the next. HUBR-9: a branch the team provider's drift findings hold (`drift`,
125
- * Map(branch → findings), from `driftHolds`) waits too, with its group, until they clear. `{ head,
126
- * partners, held, drifting }`: `head` null when nothing can merge yet; `held` lists each waiting branch
127
- * with the partners it still needs queued; `drifting` each one waiting on findings, with them.
126
+ * Map(branch → findings), from `driftHolds`) waits too, with its group, until they clear. MQ-8: so does
127
+ * a branch whose story the lead holds (`deferred`, Map(branch → hold), from `activeDeferrals`). `{ head,
128
+ * partners, held, drifting, deferred }`: `head` null when nothing can merge yet; `held` lists each
129
+ * waiting branch with the partners it still needs queued; `drifting` each one waiting on findings,
130
+ * with them; `deferred` each one whose group holds a held story, with that hold.
128
131
  */
129
- export function nextToMerge(entries, drift = new Map()) {
132
+ export function nextToMerge(entries, drift = new Map(), deferredBy = new Map()) {
130
133
  const queue = waiting(entries);
131
134
  const queued = new Set(queue.map((e) => e.branch));
132
135
  // A partner already merged on its own is no longer waited for.
@@ -151,6 +154,7 @@ export function nextToMerge(entries, drift = new Map()) {
151
154
  };
152
155
  const held = [];
153
156
  const drifting = [];
157
+ const deferred = [];
154
158
  let head = null;
155
159
  let partners = [];
156
160
  for (const e of queue) {
@@ -158,7 +162,9 @@ export function nextToMerge(entries, drift = new Map()) {
158
162
  // A group lands as one, so a finding on any of its branches holds them all.
159
163
  const findings = [...group].flatMap((b) => drift.get(b) ?? []);
160
164
  if (findings.length) drifting.push({ branch: e.branch, findings });
161
- if (head) continue;
165
+ const hold = [...group].map((b) => deferredBy.get(b)).find(Boolean);
166
+ if (hold) deferred.push({ branch: e.branch, hold });
167
+ if (head || hold) continue;
162
168
  const missing = [...group]
163
169
  .flatMap((b) => queue.find((y) => y.branch === b)?.with ?? [])
164
170
  .filter((b) => !queued.has(b) && !merged.has(b));
@@ -170,7 +176,40 @@ export function nextToMerge(entries, drift = new Map()) {
170
176
  head = e;
171
177
  partners = queue.filter((x) => x.branch !== e.branch && group.has(x.branch));
172
178
  }
173
- return { head, partners, held, drifting };
179
+ return { head, partners, held, drifting, deferred };
180
+ }
181
+
182
+ export const PAUSE_FILE = '.claude/state/merge-queue-paused.json';
183
+
184
+ const pauseFile = (root) => join(projectWorktrees(root)[0] ?? root, PAUSE_FILE);
185
+
186
+ /**
187
+ * MQ-8: the lead's deliberate pause of the whole queue, { reason, at, session } or null: while it's
188
+ * paused, the queue merges nothing and nothing offers a merge; branches are still queued.
189
+ */
190
+ export function queuePause(root) {
191
+ try {
192
+ const p = JSON.parse(readFileSync(pauseFile(root), 'utf8'));
193
+ return p && typeof p.reason === 'string' ? p : null;
194
+ } catch {
195
+ return null;
196
+ }
197
+ }
198
+
199
+ /** MQ-8: pauses the queue with why; a pause already in force takes the new reason. */
200
+ export function pauseQueue(root, reason, session = null, now = Date.now()) {
201
+ const file = pauseFile(root);
202
+ mkdirSync(dirname(file), { recursive: true });
203
+ const pause = { reason, at: new Date(now).toISOString(), ...(session ? { session } : {}) };
204
+ writeFileSync(file, `${JSON.stringify(pause, null, 2)}\n`);
205
+ return pause;
206
+ }
207
+
208
+ /** MQ-8: lets the queue merge again; the pause it ended, or null when it wasn't paused. */
209
+ export function resumeQueue(root) {
210
+ const was = queuePause(root);
211
+ if (was) rmSync(pauseFile(root), { force: true });
212
+ return was;
174
213
  }
175
214
 
176
215
  /** MQ-7: a queued branch's partners, which it merges together with. */
@@ -8,21 +8,16 @@ import { existsSync, readFileSync, rmSync } from 'node:fs';
8
8
  import { join } from 'node:path';
9
9
  import { freshCheckout } from './checkout.mjs';
10
10
  import { runChecks } from './checks.mjs';
11
- import { matchesAny } from './glob.mjs';
11
+ import { isDependencyFile } from './dependencies.mjs';
12
+ import { literalPath, matchesAny } from './glob.mjs';
12
13
  import { readStories } from './plan.mjs';
14
+ import { isNamedTest, isTestFile } from './testfiles.mjs';
13
15
 
14
16
  /** The approval that lets a test be weakened: the person's only. */
15
17
  export const TESTS_APPROVAL = 'tests';
16
18
 
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
19
  export const SNAPSHOT = /(^|\/)__snapshots__\/|\.snap$/;
21
20
 
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
21
  // A case's name: it('…') / test('…') in JavaScript, def test_… in Python, func Test… in Go, @Test in JVM.
27
22
  const JS_CASE =
28
23
  /\b(?:it|test)(?:\.(?:each\s*\([^)]*\)|concurrent|serial|skip|only|todo|fixme|fails))*\s*\(\s*(['"`])((?:\\.|(?!\1)[^\\])*)\1/g;
@@ -255,16 +250,35 @@ export const onlyUnreachable = (output) =>
255
250
  */
256
251
  export function proveFix({ root, from, base, changed, config, fix }) {
257
252
  const what = `This branch fixes ${fix.what}${fix.story ? ` (${fix.story})` : ''}`;
258
- const tests = changed.filter(
253
+ // A test file, named as one or in a test folder (a smoke folder's scripts), brings the fix a test.
254
+ const brought = changed.filter(
259
255
  (f) => isTestFile(f, config) && !SNAPSHOT.test(f) && showAt(root, 'HEAD', f) !== null,
260
256
  );
261
- if (!tests.length)
257
+ if (!brought.length)
262
258
  return [
263
259
  `${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
260
  ];
261
+ // Records a tool writes for everyone (files any actor may write, such as an adapter's, but not the
262
+ // manifests and lockfiles, which can be a fix) are neither the fix's code nor its tests: they don't
263
+ // make a fix more than its tests, and they don't go back.
264
+ const shared = (f) => matchesAny(f, config.anyActor) && !isDependencyFile(f);
265
+ changed = changed.filter((f) => !shared(f));
265
266
  // A fix made wholly in the tests (a flaky test, a broken helper) has no code to take back: its tests
266
267
  // are the fix. REG-2 still holds them, so it can't be made by weakening one.
267
268
  if (changed.every((f) => isTestFile(f, config) || SNAPSHOT.test(f))) return [];
269
+ // The tests that prove it are the ones named as tests; a helper or harness module beside them is code
270
+ // the fix may have changed, so it goes back with the rest. Only where the fix brings no named test do
271
+ // the files in its test folders stand as its tests.
272
+ const named = brought.filter((f) => isNamedTest(f, config));
273
+ const tests = named.length ? named : brought;
274
+ // What goes back: everything but those tests and the snapshots, except test code the branch adds,
275
+ // which the code without the fix never had and its tests need to load.
276
+ const revert = changed.filter(
277
+ (f) =>
278
+ !tests.includes(f) &&
279
+ !SNAPSHOT.test(f) &&
280
+ !(isTestFile(f, config) && showAt(root, from, f) === null),
281
+ );
268
282
  const covering = config.checks.filter((c) =>
269
283
  tests.some((f) => matchesAny(f, c.files) && !matchesAny(f, c.exclude)),
270
284
  );
@@ -289,12 +303,29 @@ export function proveFix({ root, from, base, changed, config, fix }) {
289
303
  return [
290
304
  `${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
305
  ];
292
- for (const f of changed) {
293
- if (isTestFile(f, config) || SNAPSHOT.test(f)) continue;
294
- if (showAt(root, from, f) !== null) git(dir, 'checkout', from, '--', f);
306
+ for (const f of revert) {
307
+ if (showAt(root, from, f) !== null) git(dir, 'checkout', from, '--', literalPath(f));
295
308
  else rmSync(join(dir, f), { force: true });
296
309
  }
297
310
  const { failure: without } = runChecks(strict, tests, dir, actor);
311
+ // Test code the branch adds was kept for the tests to load. Where they pass without the rest of
312
+ // the fix, and fail without that code, the fix is the new test code itself: the base's code never
313
+ // had it, so the tests can't show the bug there, like tests that call only what a fix adds.
314
+ const added = changed.filter(
315
+ (f) =>
316
+ !tests.includes(f) &&
317
+ !SNAPSHOT.test(f) &&
318
+ isTestFile(f, config) &&
319
+ showAt(root, from, f) === null,
320
+ );
321
+ if (!without && added.length) {
322
+ for (const f of added) rmSync(join(dir, f), { force: true });
323
+ const { failure: unloaded } = runChecks(strict, tests, dir, actor);
324
+ if (unloaded)
325
+ return [
326
+ `${what}, but its tests (${tests.join(', ')}) pass without the fix's other changes, and fail without it only because they load test code the fix adds (${added.join(', ')}), which the base never had. A test that goes through the code the fix changed fails on an assertion when the bug is there: write that one. If the fix is only in the tests and their helpers, keep the branch to test files.`,
327
+ ];
328
+ }
298
329
  if (!without)
299
330
  return [
300
331
  `${what}, but its tests (${tests.join(', ')}) also pass without the fix, so they don't prove the bug and it can come back. Write a test that fails on ${base} and passes here.`,
@@ -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
+ }
@@ -30,7 +30,7 @@ import { homedir } from 'node:os';
30
30
  import { basename, dirname, join, relative, resolve } from 'node:path';
31
31
  import { fileURLToPath } from 'node:url';
32
32
  import { DEPENDENCY_APPROVAL, isDependencyFile } from './dependencies.mjs';
33
- import { globToRegExp, matchesAny } from './glob.mjs';
33
+ import { globToRegExp, literalPath, matchesAny } from './glob.mjs';
34
34
  import { noteFor } from './standards.mjs';
35
35
 
36
36
  export const APPROVAL_LOG = '.claude/approval-log.jsonl';
@@ -572,7 +572,7 @@ function commitsFrom(root, path, at) {
572
572
  [
573
573
  ...['-C', root, 'log', '--all', '--format=%H'],
574
574
  `--since=@${Math.floor(Date.parse(at) / 1000)}`,
575
- ...['--', path],
575
+ ...['--', literalPath(path)],
576
576
  ],
577
577
  { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] },
578
578
  )
@@ -795,7 +795,7 @@ export function writeProblem(actor, rel, root, config) {
795
795
  if (target === approvals || target.startsWith(`${approvals}/`))
796
796
  return `${rel} is an approval. Only a person creates approvals, with a \`!\` shell command.`;
797
797
  if (rel.startsWith('..'))
798
- return outsideAllowed(actor, rel, root, config) ? null : `${rel} is outside the repository.`;
798
+ return outsideAllowed(actor, rel, root, config) ? null : outsideProblem(actor, rel);
799
799
  if (SECRETS(rel))
800
800
  return `${rel} may hold secrets. Secrets never go in files an agent writes; use the secret store.`;
801
801
  if (rel === APPROVAL_LOG)
@@ -830,13 +830,42 @@ export function writeProblem(actor, rel, root, config) {
830
830
  const readonlyProblem = (actor, rel) =>
831
831
  `${actor.label} is read-only; it may not write ${rel}. If a command you ran changed it (a build, a formatter or a code generator), put it back with git restore -- ${rel} (or delete it if it's new), and run such commands only in a throwaway worktree of the branch.`;
832
832
 
833
- // Claude Code's own temporary folders (a session's scratchpad, its tool output): no repository's files.
834
- const CLAUDE_TEMP = ['/private/tmp/claude-*/**', '/tmp/claude-*/**'];
833
+ /**
834
+ * Whether `rel` is in the folder Claude Code gives this session for its own temporary files
835
+ * (`/tmp/claude-<uid>/<project>/<session id>/`: its scratchpad and its tool output), outside every
836
+ * repository. A session's id is its own, so the folder is no other session's or project's.
837
+ */
838
+ function inSessionTemp(actor, rel, root) {
839
+ if (!actor.session || !/^[\w.-]+$/.test(actor.session)) return false;
840
+ // `rel` is from the root's real path: /tmp is /private/tmp on macOS.
841
+ const parts = resolve(realPath(root), rel)
842
+ .replace(/^\/private(?=\/tmp\/)/, '')
843
+ .split('/');
844
+ return (
845
+ parts[1] === 'tmp' &&
846
+ /^claude-[^/]+$/.test(parts[2] ?? '') &&
847
+ Boolean(parts[3]) &&
848
+ parts[4] === actor.session &&
849
+ parts.length > 5
850
+ );
851
+ }
852
+
853
+ /** Why a write outside the repository is refused, and where the actor's temporary files go instead. */
854
+ function outsideProblem(actor, rel) {
855
+ if (actor.kind === 'readonly')
856
+ return `${rel} is outside the repository, and ${actor.label} is read-only: it writes no files, temporary ones included.`;
857
+ const own = actor.session
858
+ ? `this session's own scratchpad, the folder Claude Code gives it under /tmp/claude-<uid>/<project>/${actor.session}/scratchpad/`
859
+ : "this session's own scratchpad, the folder Claude Code gives it under /tmp/claude-<uid>/<project>/<session id>/scratchpad/";
860
+ return `${rel} is outside the repository. Temporary files (a probe, a throwaway harness) go in ${own}; another session's is not this one's to write.${actor.kind === 'lead' ? ' Anywhere else outside the repository is the config\'s "lead.outside".' : ''}`;
861
+ }
835
862
 
836
863
  function outsideAllowed(actor, rel, root, config) {
837
864
  const target = resolve(root, rel);
838
- // A lane's scratch files go where Claude Code's own do, outside every repository.
839
- if (actor.kind === 'lane') return CLAUDE_TEMP.some((g) => globToRegExp(g).test(target));
865
+ // The session's scratch files go where Claude Code's own do, outside every repository.
866
+ if (actor.kind === 'lane' || actor.kind === 'lead') {
867
+ if (inSessionTemp(actor, rel, root)) return true;
868
+ }
840
869
  if (actor.kind !== 'lead') return false;
841
870
  return config.lead.outside.some((g) =>
842
871
  globToRegExp(resolve(root, g.replace(/^~(?=\/)/, homedir()))).test(target),
@@ -905,7 +934,8 @@ function specCheckProblem(rel, root) {
905
934
  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
935
  }
907
936
 
908
- // Screens are designed first: a screen file can be written once the register lists it.
937
+ // Screens are designed first: a screen file can be written once the register holds its approved
938
+ // design as files (HAND-6). An entry naming only a design tool's artboard isn't one: no lane can read it.
909
939
  export function screenProblem(rel, root, config) {
910
940
  const gate = config.designGate;
911
941
  if (!gate) return null;
@@ -919,6 +949,14 @@ export function screenProblem(rel, root, config) {
919
949
  } catch {
920
950
  return `${gate.register} is missing or invalid, so no screen can be built yet.`;
921
951
  }
922
- if (screens.some((s) => s.file === rel)) return null;
952
+ // Handed over, as designs.mjs's handedOver() says: kept here, so the path guard loads no more than this.
953
+ const listed = (Array.isArray(screens) ? screens : []).filter((s) => s?.file === rel);
954
+ if (listed.some((s) => Array.isArray(s.states) && s.states.length > 0)) return null;
955
+ if (listed.length) {
956
+ const s = listed[0];
957
+ const tool =
958
+ s.source?.tool ?? String(s.design ?? '').match(/^([a-z][\w-]*):/i)?.[1] ?? 'the design tool';
959
+ 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.`;
960
+ }
923
961
  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
962
  }