@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.
@@ -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
+ }
@@ -15,10 +15,10 @@ import {
15
15
  import { spawnSync } from 'node:child_process';
16
16
  import { randomUUID } from 'node:crypto';
17
17
  import { join } from 'node:path';
18
- import { CODE_KIT, GIT, commandsOf } from './shell.mjs';
18
+ import { CODE_KIT, GIT, commandsOf, ruleMatches } from './shell.mjs';
19
19
  import { addedPackages } from './dependencies.mjs';
20
20
  import { storyOfBranch } from './teamfacts.mjs';
21
- import { globToRegExp } from './glob.mjs';
21
+ import { globToRegExp, literalPath } from './glob.mjs';
22
22
  import { projectWorktrees } from './rules.mjs';
23
23
  import { readQueue, settle, waiting } from './queue.mjs';
24
24
  import { sessions } from './sessions.mjs';
@@ -65,20 +65,21 @@ const TEST =
65
65
  * approval protects), one the project blocks or restricts, or one in `execution.unrepeatable`.
66
66
  */
67
67
  export function unrepeatable(command, config) {
68
- const patterns = [
69
- ...(config.shell?.block ?? []).map((b) => b.pattern),
70
- ...(config.shell?.restricted ?? []).map((r) => r.pattern),
71
- ...(config.execution?.unrepeatable ?? []),
68
+ // The project's blocked and restricted commands are matched as the shell hook matches them.
69
+ const rules = [
70
+ ...(config.shell?.block ?? []),
71
+ ...(config.shell?.restricted ?? []),
72
+ ...(config.execution?.unrepeatable ?? []).map((pattern) => ({ pattern })),
72
73
  ];
73
- if (patterns.some((p) => safeTest(p, command))) return true;
74
+ if (rules.some((r) => safeTest(r, command))) return true;
74
75
  const migrations = (config.protected ?? []).filter((p) => p.approval === 'migration');
75
76
  return command
76
77
  .split(/\s+/)
77
78
  .some((w) => migrations.some((p) => globToRegExp(p.glob).test(w.replace(/^\.\//, ''))));
78
79
  }
79
- function safeTest(pattern, text) {
80
+ function safeTest(rule, text) {
80
81
  try {
81
- return new RegExp(pattern).test(text);
82
+ return ruleMatches(rule, text);
82
83
  } catch {
83
84
  return false;
84
85
  }
@@ -525,7 +526,7 @@ export function checkAct(root, act, base) {
525
526
  }
526
527
  if (act.kind === 'edit' && tree) {
527
528
  const rel = act.target?.startsWith(tree) ? act.target.slice(tree.length + 1) : act.target;
528
- const changed = out(git(tree, 'status', '--porcelain', '--', rel));
529
+ const changed = out(git(tree, 'status', '--porcelain', '--', literalPath(rel)));
529
530
  return {
530
531
  found: changed ? 'done' : 'not done',
531
532
  how: changed ? `${rel} holds uncommitted changes` : `${rel} is as committed`,
@@ -40,3 +40,10 @@ export function globToRegExp(glob) {
40
40
  }
41
41
 
42
42
  export const matchesAny = (path, globs = []) => globs.some((g) => globToRegExp(g).test(path));
43
+
44
+ /**
45
+ * A file's path as a git pathspec that names exactly that file: git reads `*`, `?` and `[…]` in a
46
+ * pathspec as a pattern, so a route file such as `app/[id].tsx` would otherwise match `app/i.tsx`
47
+ * and miss itself.
48
+ */
49
+ export const literalPath = (path) => `:(literal)${path}`;
@@ -14,7 +14,7 @@ import {
14
14
  } from './standards.mjs';
15
15
 
16
16
  /** The version of code-kit's instructions: raised whenever the templates' rules change. */
17
- export const INSTRUCTIONS_VERSION = 11;
17
+ export const INSTRUCTIONS_VERSION = 12;
18
18
 
19
19
  const TEMPLATES = fileURLToPath(new URL('../../templates/', import.meta.url));
20
20
  const BEGIN = (v) => `<!-- code-kit:begin v${v} -->`;
@@ -7,6 +7,7 @@ import { execFileSync } from 'node:child_process';
7
7
  import { existsSync, readFileSync } from 'node:fs';
8
8
  import { join } from 'node:path';
9
9
  import { dispatches } from './dispatches.mjs';
10
+ import { literalPath } from './glob.mjs';
10
11
  import { APPROVAL_LOG } from './rules.mjs';
11
12
  import { sendBacks } from './reviews.mjs';
12
13
  import { storyTimes } from './timeline.mjs';
@@ -27,7 +28,7 @@ const gitIn =
27
28
 
28
29
  /** When a file was first committed, in ms, or null. */
29
30
  const addedAt = (git, file) => {
30
- const t = git('log', '--diff-filter=A', '--format=%ct', '--', file)
31
+ const t = git('log', '--diff-filter=A', '--format=%ct', '--', literalPath(file))
31
32
  .split('\n')
32
33
  .filter(Boolean)
33
34
  .at(-1);
@@ -8,11 +8,13 @@ import { loadConfig, mergeDelegation } from './config.mjs';
8
8
  import { buildStatus, readStories, DESIGN, LEAD } from './plan.mjs';
9
9
  import { pendingSetup } from './adapters/index.mjs';
10
10
  import { CONFIG_FILE, SETUP_VERSION } from './config.mjs';
11
- import { mergingNow, nextToMerge, readQueue, waiting } from './queue.mjs';
12
- import { handedOver, readRegister, toolOf } from './designs.mjs';
11
+ import { mergingNow, nextToMerge, queuePause, readQueue, waiting } from './queue.mjs';
12
+ import { activeDeferrals, deferralWords } from './deferrals.mjs';
13
+ import { designsFor, handedOver, readRegister, toolOf } from './designs.mjs';
13
14
  import { decidedBy, laneOf, openRequests } from './rules.mjs';
14
15
  import { instructionsState } from './instructions.mjs';
15
16
  import { SECURITY_AGENT_FILE } from './security.mjs';
17
+ import { isTestFile } from './testfiles.mjs';
16
18
  import { laneClaims } from './laneclaims.mjs';
17
19
  import { keptBecause, worktrees } from './worktrees.mjs';
18
20
  import { ciFindings } from './ci.mjs';
@@ -20,7 +22,7 @@ import { storyModels } from './dispatches.mjs';
20
22
  import { pickPerLane } from './schedule.mjs';
21
23
  import { reconcileAll } from './events.mjs';
22
24
  import { readCache, teamOf } from './team.mjs';
23
- import { driftHoldWords, driftHolds, driftUnchecked } from './teamfacts.mjs';
25
+ import { driftHoldWords, driftHolds, driftUnchecked, storyOfBranch } from './teamfacts.mjs';
24
26
 
25
27
  export const DRAFT_FILE = '.claude/code-kit.draft.json';
26
28
  export const BRIEF_STATES = ['framed', 'explored', 'scoped', 'specified', 'planned', 'ready'];
@@ -84,7 +86,9 @@ const hasMarkdown = (dir) => {
84
86
  };
85
87
 
86
88
  /**
87
- * { step, why, args, then, attention, brief, worktrees }. `brief`: the brief's open questions (ASK-4);
89
+ * { step, why, args, then, attention, brief, worktrees, deferred, queuePaused }. `brief`: the brief's open
90
+ * questions (ASK-4); `deferred`: the stories the lead holds, { story, reason, until, at, branch } (LOOP-15);
91
+ * `queuePaused`: the lead's pause of the merge queue, { reason, at }, or null (MQ-8);
88
92
  * `worktrees`: the merged ones still holding changes, { branch, story, changes, files }, for the person (LEAN-8);
89
93
  * `models`: each story offered to a lane, with the model it runs on and why, { story, model, why } (SCHED-3). `step` is a skill (spec-design, init, check, dispatch,
90
94
  * review), `merge` (the head of the merge queue, where the lead merges), `wait` (lanes are
@@ -98,6 +102,9 @@ export function nextStep(root, base) {
98
102
  let holdingTrees = [];
99
103
  // SCHED-3: the model each story offered to a lane runs on, and why.
100
104
  let models = [];
105
+ // LOOP-15, MQ-8: what the lead holds on purpose: stories, and the whole merge queue.
106
+ let deferred = [];
107
+ let queuePaused = null;
101
108
  const result = (step, why, extra = {}) => ({
102
109
  step,
103
110
  why,
@@ -107,6 +114,8 @@ export function nextStep(root, base) {
107
114
  brief: briefQuestions,
108
115
  worktrees: holdingTrees,
109
116
  models,
117
+ deferred,
118
+ queuePaused,
110
119
  ...extra,
111
120
  });
112
121
  const isRepo = git(root, 'rev-parse', '--is-inside-work-tree') === 'true';
@@ -275,6 +284,20 @@ export function nextStep(root, base) {
275
284
  `${stopped.join(', ')} ${stopped.length === 1 ? 'has its branch but no commits, and no agent on it' : 'have their branches but no commits, and no agent on them'}: ${stopped.length === 1 ? 'it goes' : 'they go'} to a fresh agent, on the same branch.`,
276
285
  );
277
286
 
287
+ // LOOP-15: a story the lead holds isn't dispatched, reviewed or merged until the hold ends.
288
+ const holds = activeDeferrals(root);
289
+ const heldIds = new Set(holds.map((h) => h.story));
290
+ deferred = holds.map((h) => ({
291
+ ...h,
292
+ branch: status.stories.find((s) => s.id === h.story)?.branch ?? null,
293
+ words: deferralWords(h),
294
+ }));
295
+ for (const h of holds)
296
+ attention.push(
297
+ `${deferralWords(h)}. Nothing dispatches, reviews or merges it until ${h.until ? 'then, or ' : ''}code-kit defer release ${h.story}.`,
298
+ );
299
+ // MQ-8: the lead's pause of the merge queue: nothing merges, and no merge is offered.
300
+ queuePaused = queuePause(root);
278
301
  // A branch already in the merge queue has passed its review: it isn't reviewed again.
279
302
  const entries = readQueue(root);
280
303
  const inQueue = waiting(entries);
@@ -288,7 +311,14 @@ export function nextStep(root, base) {
288
311
  )
289
312
  : new Map();
290
313
  // MQ-7: what can merge next; a branch queued with partners waits until they're queued too.
291
- const { head: mergeHead, held: heldGroups, drifting } = nextToMerge(entries, drift);
314
+ const deferredBy = new Map(
315
+ inQueue.flatMap((e) => {
316
+ const story = storyOfBranch(e.branch);
317
+ const hold = story && holds.find((h) => h.story === story);
318
+ return hold ? [[e.branch, hold]] : [];
319
+ }),
320
+ );
321
+ const { head: mergeHead, held: heldGroups, drifting } = nextToMerge(entries, drift, deferredBy);
292
322
  const queued = inQueue.map((e) => e.branch);
293
323
  const driftWords = drifting.map((d) =>
294
324
  driftHoldWords(d.branch, d.findings, {
@@ -303,6 +333,7 @@ export function nextStep(root, base) {
303
333
  const ids = (state) =>
304
334
  status.stories
305
335
  .filter((s) => s.state === state && !(state === 'review' && queued.includes(s.branch)))
336
+ .filter((s) => state === 'in progress' || !heldIds.has(s.id))
306
337
  .map((s) => s.id);
307
338
  const [review, building, blocked, fixes] = ['review', 'in progress', 'blocked', 'sent back'].map(
308
339
  ids,
@@ -319,7 +350,7 @@ export function nextStep(root, base) {
319
350
  (Boolean(config.lanes[s.lane]) || s.lane === LEAD || s.lane === DESIGN) &&
320
351
  (s.requirements.length > 0 || s.noRequirements) &&
321
352
  s.requirements.every((r) => defined.has(r));
322
- const readyStories = status.stories.filter((s) => s.state === 'ready');
353
+ const readyStories = status.stories.filter((s) => s.state === 'ready' && !heldIds.has(s.id));
323
354
  // The lead's own stories are built by the lead, not dispatched to a lane agent.
324
355
  const forLead = readyStories.filter((s) => buildable(s) && s.lane === LEAD).map((s) => s.id);
325
356
  const ready = readyStories
@@ -387,14 +418,18 @@ export function nextStep(root, base) {
387
418
  const leadMerges = delegation.delegated && config.harness.autonomy === 'autonomous';
388
419
  // SETUP-2: a base with no rules committed (a project set up before setup committed them there): the
389
420
  // lead puts the approved rules onto it, and the queue merges under them from then on.
390
- if (queued.length && delegation.first)
421
+ if (queued.length && delegation.first && !queuePaused)
391
422
  return result(
392
423
  'rules',
393
424
  `${queued[0]} passed review and is next to merge, but ${delegation.into} has no code-kit rules committed yet. Put the rules the person approved onto it (code-kit queue rules); then the queue merges under them.`,
394
425
  { args: delegation.into },
395
426
  );
396
- const mergeable = queued.filter((b) => !heldByDrift.has(b));
397
- if (mergeable.length && !leadMerges)
427
+ const mergeable = queued.filter((b) => !heldByDrift.has(b) && !deferredBy.has(b));
428
+ if (queuePaused)
429
+ attention.push(
430
+ `The merge queue is paused: ${queuePaused.reason}. Nothing merges until code-kit queue resume${queued.length ? `; ${queued.join(', ')} ${queued.length === 1 ? 'waits' : 'wait'} in it` : ''}.`,
431
+ );
432
+ else if (mergeable.length && !leadMerges)
398
433
  attention.push(
399
434
  `${mergeable.join(', ')} passed review and ${mergeable.length === 1 ? 'waits' : 'wait'} for the person to merge (code-kit queue merge --person, or Merge in the code-kit band).`,
400
435
  );
@@ -408,12 +443,35 @@ export function nextStep(root, base) {
408
443
  attention.push(
409
444
  `${h.branch} passed review and merges together with ${h.missing.join(', ')}: it waits until ${h.missing.length === 1 ? 'that is' : 'they are'} reviewed and queued.`,
410
445
  );
411
- if (mergeHead && leadMerges && !merging)
446
+ if (mergeHead && leadMerges && !merging && !queuePaused)
412
447
  return result(
413
448
  'merge',
414
449
  `${mergeHead.branch} passed review and is next in the merge queue${queued.length > 1 ? ` (then ${queued.filter((b) => b !== mergeHead.branch).join(', ')})` : ''}.`,
415
450
  { args: mergeHead.branch },
416
451
  );
452
+ // HAND-6: a screen story whose screens' approved designs are only in a design tool can't be built:
453
+ // the gate refuses each screen until the lead hands its design over. It waits, and the hand-over is
454
+ // the step, rather than a lane dispatched to be refused.
455
+ const { entries: registered } = readRegister(root, config);
456
+ const toHandOver = new Map();
457
+ for (const list of [fixes, ready]) {
458
+ const kept = list.filter((id) => {
459
+ const s = status.stories.find((x) => x.id === id);
460
+ const toolOnly = designsFor(registered, id, status.stories).filter(
461
+ (e) => !handedOver(e) && laneOf(e.file, config) === s?.lane,
462
+ );
463
+ if (toolOnly.length) toHandOver.set(id, toolOnly);
464
+ return !toolOnly.length;
465
+ });
466
+ list.splice(0, list.length, ...kept);
467
+ }
468
+ const onlyInTool = [...toHandOver.values()].flat();
469
+ const distinct = (pick) => [...new Set(onlyInTool.map(pick))];
470
+ const handOver = distinct((e) => e.story).sort((a, b) => a.slice(3) - b.slice(3));
471
+ const one = toHandOver.size === 1;
472
+ const handOverWhy = toHandOver.size
473
+ ? `${[...toHandOver.keys()].join(', ')} ${one ? 'builds' : 'build'} screens whose approved designs (${distinct((e) => e.screen ?? e.file).join(', ')}) are only in ${distinct((e) => toolOf(e)).join(', ')}, not as files a lane can build from: hand ${handOver.join(', ')} over with /code-kit:design --hand-over ${handOver.join(' ')} before ${one ? 'it is' : 'they are'} dispatched.`
474
+ : '';
417
475
  // SCHED-1, SCHED-2: one story for each free lane, across every session; the open slice's first.
418
476
  const busy = new Set([
419
477
  ...laneClaims(root)
@@ -438,7 +496,7 @@ export function nextStep(root, base) {
438
496
  `${sched.waiting.join(', ')} ${sched.waiting.length === 1 ? 'waits' : 'wait'} for ${sched.waiting.length === 1 ? 'its lane' : 'their lanes'}: a lane runs one story at a time.`,
439
497
  );
440
498
  // HAND-5: approved designs still only in a design tool, which no lane can read, are handed over once.
441
- const toolOnly = readRegister(root, config).entries.filter((e) => !handedOver(e));
499
+ const toolOnly = registered.filter((e) => !handedOver(e));
442
500
  if (toolOnly.length)
443
501
  attention.push(
444
502
  `${toolOnly.length} approved screen${toolOnly.length === 1 ? ' is' : 's are'} only in ${[...new Set(toolOnly.map(toolOf))].join(', ')}, not as files a lane can build from: hand ${toolOnly.length === 1 ? 'it' : 'them'} over with /code-kit:design --hand-over.`,
@@ -453,6 +511,8 @@ export function nextStep(root, base) {
453
511
  );
454
512
  models = toDispatch.filter((id) => chosen[id]).map((id) => ({ story: id, ...chosen[id] }));
455
513
  if (review.length && forDesign.length) then.push({ step: 'design', args: forDesign.join(' ') });
514
+ const handOverStep = { step: 'design', args: handOver.join(' '), handOver: true };
515
+ if (review.length && handOver.length) then.push(handOverStep);
456
516
  if (review.length && toDispatch.length)
457
517
  then.push({ step: 'dispatch', args: toDispatch.join(' ') });
458
518
  if (forLead.length) then.push({ step: 'lead', args: forLead.join(' ') });
@@ -468,11 +528,21 @@ export function nextStep(root, base) {
468
528
  {
469
529
  args: forDesign.join(' '),
470
530
  then: [
531
+ ...(handOver.length ? [handOverStep] : []),
471
532
  ...(toDispatch.length ? [{ step: 'dispatch', args: toDispatch.join(' ') }] : []),
472
533
  ...(forLead.length ? [{ step: 'lead', args: forLead.join(' ') }] : []),
473
534
  ],
474
535
  },
475
536
  );
537
+ if (handOver.length)
538
+ return result('design', handOverWhy, {
539
+ args: handOver.join(' '),
540
+ handOver: true,
541
+ then: [
542
+ ...(toDispatch.length ? [{ step: 'dispatch', args: toDispatch.join(' ') }] : []),
543
+ ...(forLead.length ? [{ step: 'lead', args: forLead.join(' ') }] : []),
544
+ ],
545
+ });
476
546
  if (fixes.length)
477
547
  return result(
478
548
  'dispatch',
@@ -509,7 +579,11 @@ export function nextStep(root, base) {
509
579
  );
510
580
  // Stories waiting on branches in the merge queue wait for the merge, not on a broken plan. HUBR-9: a
511
581
  // queue that only drift findings hold says which, and how each clears.
512
- const heldOnly = !mergeHead && driftWords.length ? driftWords.join(' ') : null;
582
+ const heldOnly = queuePaused
583
+ ? `The merge queue is paused: ${queuePaused.reason}.`
584
+ : !mergeHead && driftWords.length
585
+ ? driftWords.join(' ')
586
+ : null;
513
587
  if (queued.length)
514
588
  return result(
515
589
  'wait',
@@ -528,6 +602,12 @@ export function nextStep(root, base) {
528
602
  'wait',
529
603
  `${waitingOnPerson.map((s) => `${s.id} waits on the person (${s.waitingFor.id})`).join('; ')}${blocked.length ? `; ${blocked.join(', ')} ${blocked.length === 1 ? 'waits' : 'wait'} on ${waitingOnPerson.length === 1 ? 'it' : 'them'}` : ''}. Carry on with anything else; their answer is sent to you.`,
530
604
  );
605
+ // LOOP-15: what's left waits on stories the lead holds, or is one of them.
606
+ if (holds.length && status.stories.some((s) => heldIds.has(s.id) && s.state !== 'done'))
607
+ return result(
608
+ 'wait',
609
+ `${holds.map(deferralWords).join('; ')}. Nothing else can start; the loop goes on when a hold ends or is released.`,
610
+ );
531
611
  if (blocked.length)
532
612
  return result(
533
613
  'spec-design',
@@ -546,7 +626,8 @@ export function nextStep(root, base) {
546
626
 
547
627
  const SCREEN_LANE = /(^|-)(web|mobile|frontend|front-end|ui|desktop|ios|android|admin|portal)(-|$)/;
548
628
  const SCREEN_FILE = /\.(tsx|jsx|vue|svelte|swift|dart)$/;
549
- const TEST_FILE = /(^|\/)(__tests__|e2e|tests?)\/|\.(test|spec|stories)\.\w+$/;
629
+ // A story file shows a screen in isolation; like a test, it isn't one.
630
+ const STORIES_FILE = /\.stories\.\w+$/;
550
631
  const QA_LANE = /(^|-)(qa|e2e|tests?)(-|$)/;
551
632
 
552
633
  /**
@@ -569,7 +650,9 @@ export function setupGaps(config, stories, files = []) {
569
650
  function screenGaps(config, stories, files) {
570
651
  const lanes = Object.entries(config.lanes);
571
652
  const holdsScreens = new Set(
572
- files.filter((f) => SCREEN_FILE.test(f) && !TEST_FILE.test(f)).map((f) => laneOf(f, config)),
653
+ files
654
+ .filter((f) => SCREEN_FILE.test(f) && !isTestFile(f, config) && !STORIES_FILE.test(f))
655
+ .map((f) => laneOf(f, config)),
573
656
  );
574
657
  const screens = lanes
575
658
  .filter(