@warren-dean/code-kit 0.28.0 → 0.30.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/CHANGELOG.md +31 -0
  4. package/README.md +17 -9
  5. package/bin/code-kit.mjs +498 -60
  6. package/hooks/act.mjs +30 -2
  7. package/hooks/guard-bash.mjs +59 -25
  8. package/hooks/lib/adapters/hub/client.mjs +7 -1
  9. package/hooks/lib/checkout.mjs +78 -1
  10. package/hooks/lib/checks.mjs +13 -3
  11. package/hooks/lib/deferrals.mjs +107 -0
  12. package/hooks/lib/designs.mjs +100 -42
  13. package/hooks/lib/events.mjs +49 -0
  14. package/hooks/lib/instructions.mjs +1 -1
  15. package/hooks/lib/next.mjs +124 -15
  16. package/hooks/lib/plan.mjs +186 -11
  17. package/hooks/lib/queue.mjs +61 -12
  18. package/hooks/lib/regression.mjs +18 -11
  19. package/hooks/lib/reviews.mjs +43 -2
  20. package/hooks/lib/rules.mjs +11 -2
  21. package/hooks/lib/security.mjs +50 -7
  22. package/hooks/lib/shell.mjs +97 -0
  23. package/hooks/lib/snapshot.mjs +125 -8
  24. package/hooks/lib/storymap.mjs +13 -7
  25. package/hooks/lib/team.mjs +35 -13
  26. package/hooks/lib/teamfacts.mjs +80 -2
  27. package/hooks/lib/testfiles.mjs +22 -0
  28. package/hooks/lib/verify.mjs +55 -11
  29. package/hooks/lib/worktrees.mjs +25 -3
  30. package/hooks/mod/board.mjs +12 -1
  31. package/hooks/mod/loop.mjs +9 -2
  32. package/hooks/mod/register.mjs +4 -3
  33. package/hooks/mod/view.mjs +51 -11
  34. package/package.json +1 -1
  35. package/skills/design/SKILL.md +4 -4
  36. package/skills/dispatch/SKILL.md +1 -1
  37. package/skills/init/SKILL.md +5 -0
  38. package/skills/next/SKILL.md +1 -0
  39. package/skills/review/SKILL.md +12 -4
  40. package/templates/agent.md +2 -1
  41. package/templates/claude-md.md +2 -0
@@ -22,6 +22,7 @@ import { globToRegExp } 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';
25
+ import { isSecurityReviewer } from './security.mjs';
25
26
 
26
27
  export const EVENTS_DIR = '.claude/state/events';
27
28
  const OPEN_DIR = `${EVENTS_DIR}/.open`;
@@ -253,9 +254,55 @@ function base(ctx, now) {
253
254
  target: ctx.target ?? null,
254
255
  branch: ctx.branch ?? null,
255
256
  head: ctx.head ?? null,
257
+ // The agent type an Agent call starts, for the security review's record (HUBR-2).
258
+ ...(ctx.agentType ? { agentType: ctx.agentType } : {}),
256
259
  };
257
260
  }
258
261
 
262
+ /** An agent's id in a tool's response (a background agent's launch names it), or null. */
263
+ export function agentIdOf(response, depth = 0) {
264
+ if (!response || typeof response !== 'object' || depth > 4) return null;
265
+ for (const [k, v] of Object.entries(response)) {
266
+ if ((k === 'agentId' || k === 'agent_id') && typeof v === 'string' && v) return v;
267
+ const found = agentIdOf(v, depth + 1);
268
+ if (found) return found;
269
+ }
270
+ return null;
271
+ }
272
+
273
+ /**
274
+ * HUBR-2: the security review a stopping security reviewer was started for: the Agent call's end that
275
+ * named `agentId` (one run in the background), else the latest call starting a security reviewer that
276
+ * hasn't ended (one the lead waits on). Each review is recorded once; null when none is open.
277
+ */
278
+ export function securityReviewFor(root, agentId) {
279
+ let open = null;
280
+ for (const story of loggedStories(root)) {
281
+ const events = readEvents(root, story);
282
+ const done = new Set(events.filter((e) => e.kind === 'security-review').map((e) => e.act));
283
+ const ended = new Set(events.filter((e) => e.phase === 'end').map((e) => e.act));
284
+ for (const e of events) {
285
+ if (!isSecurityReviewer(e.agentType) || !e.act || done.has(e.act)) continue;
286
+ if (e.phase === 'end' && agentId && e.result?.agent === agentId) return e;
287
+ if (e.phase === 'start' && !ended.has(e.act) && (!open || e.at > open.at)) open = e;
288
+ }
289
+ }
290
+ return open;
291
+ }
292
+
293
+ /**
294
+ * HUBR-2: each story's last security review, from its log: { at, findings, blockers } or { at, unread }
295
+ * when the reviewer's report had no findings block that reads. Map(story → review).
296
+ */
297
+ export function securityReviews(root) {
298
+ const found = new Map();
299
+ for (const story of loggedStories(root))
300
+ for (const e of readEvents(root, story))
301
+ if (e.kind === 'security-review' && e.phase === 'note')
302
+ found.set(story, { at: e.at, branch: e.branch ?? null, ...(e.result ?? {}) });
303
+ return found;
304
+ }
305
+
259
306
  /** The commit a checkout is at, short; null outside git. */
260
307
  export const headOf = (cwd) => out(git(cwd, 'rev-parse', '--short', 'HEAD')) || null;
261
308
 
@@ -334,6 +381,8 @@ export function replay(events) {
334
381
  state.phase = 'stopped';
335
382
  continue;
336
383
  }
384
+ // What the security reviewer found is a record of its review, not the end of an act.
385
+ if (e.kind === 'security-review') continue;
337
386
  if (!e.act) continue;
338
387
  const act = acts.get(e.act) ?? { start: null, end: null, reconciled: null };
339
388
  acts.set(e.act, act);
@@ -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} -->`;
@@ -8,17 +8,21 @@ 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';
19
21
  import { storyModels } from './dispatches.mjs';
20
22
  import { pickPerLane } from './schedule.mjs';
21
23
  import { reconcileAll } from './events.mjs';
24
+ import { readCache, teamOf } from './team.mjs';
25
+ import { driftHoldWords, driftHolds, driftUnchecked, storyOfBranch } from './teamfacts.mjs';
22
26
 
23
27
  export const DRAFT_FILE = '.claude/code-kit.draft.json';
24
28
  export const BRIEF_STATES = ['framed', 'explored', 'scoped', 'specified', 'planned', 'ready'];
@@ -82,7 +86,9 @@ const hasMarkdown = (dir) => {
82
86
  };
83
87
 
84
88
  /**
85
- * { 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);
86
92
  * `worktrees`: the merged ones still holding changes, { branch, story, changes, files }, for the person (LEAN-8);
87
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,
88
94
  * review), `merge` (the head of the merge queue, where the lead merges), `wait` (lanes are
@@ -96,6 +102,9 @@ export function nextStep(root, base) {
96
102
  let holdingTrees = [];
97
103
  // SCHED-3: the model each story offered to a lane runs on, and why.
98
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;
99
108
  const result = (step, why, extra = {}) => ({
100
109
  step,
101
110
  why,
@@ -105,6 +114,8 @@ export function nextStep(root, base) {
105
114
  brief: briefQuestions,
106
115
  worktrees: holdingTrees,
107
116
  models,
117
+ deferred,
118
+ queuePaused,
108
119
  ...extra,
109
120
  });
110
121
  const isRepo = git(root, 'rev-parse', '--is-inside-work-tree') === 'true';
@@ -273,17 +284,56 @@ export function nextStep(root, base) {
273
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.`,
274
285
  );
275
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);
276
301
  // A branch already in the merge queue has passed its review: it isn't reviewed again.
277
302
  const entries = readQueue(root);
278
303
  const inQueue = waiting(entries);
304
+ // HUBR-9: the team provider's drift findings, as last read, hold the branches they're on.
305
+ const team = teamOf(config);
306
+ const teamState = team && team.provider !== 'github' && inQueue.length ? readCache(root) : null;
307
+ const drift = teamState
308
+ ? driftHolds(
309
+ teamState,
310
+ inQueue.map((e) => e.branch),
311
+ )
312
+ : new Map();
279
313
  // MQ-7: what can merge next; a branch queued with partners waits until they're queued too.
280
- const { head: mergeHead, held: heldGroups } = nextToMerge(entries);
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);
281
322
  const queued = inQueue.map((e) => e.branch);
323
+ const driftWords = drifting.map((d) =>
324
+ driftHoldWords(d.branch, d.findings, {
325
+ techLead: team?.techLead,
326
+ provider: teamState?.provider?.name ?? team?.provider?.name ?? null,
327
+ }),
328
+ );
329
+ const driftNote = teamState ? driftUnchecked(teamState) : null;
330
+ const heldByDrift = new Set(drifting.map((d) => d.branch));
282
331
  // MQ-1: a queue merge running now (its verify takes minutes) isn't asked for again.
283
332
  const merging = mergingNow(inQueue[0]) ? inQueue[0].branch : null;
284
333
  const ids = (state) =>
285
334
  status.stories
286
335
  .filter((s) => s.state === state && !(state === 'review' && queued.includes(s.branch)))
336
+ .filter((s) => state === 'in progress' || !heldIds.has(s.id))
287
337
  .map((s) => s.id);
288
338
  const [review, building, blocked, fixes] = ['review', 'in progress', 'blocked', 'sent back'].map(
289
339
  ids,
@@ -300,7 +350,7 @@ export function nextStep(root, base) {
300
350
  (Boolean(config.lanes[s.lane]) || s.lane === LEAD || s.lane === DESIGN) &&
301
351
  (s.requirements.length > 0 || s.noRequirements) &&
302
352
  s.requirements.every((r) => defined.has(r));
303
- const readyStories = status.stories.filter((s) => s.state === 'ready');
353
+ const readyStories = status.stories.filter((s) => s.state === 'ready' && !heldIds.has(s.id));
304
354
  // The lead's own stories are built by the lead, not dispatched to a lane agent.
305
355
  const forLead = readyStories.filter((s) => buildable(s) && s.lane === LEAD).map((s) => s.id);
306
356
  const ready = readyStories
@@ -368,16 +418,23 @@ export function nextStep(root, base) {
368
418
  const leadMerges = delegation.delegated && config.harness.autonomy === 'autonomous';
369
419
  // SETUP-2: a base with no rules committed (a project set up before setup committed them there): the
370
420
  // lead puts the approved rules onto it, and the queue merges under them from then on.
371
- if (queued.length && delegation.first)
421
+ if (queued.length && delegation.first && !queuePaused)
372
422
  return result(
373
423
  'rules',
374
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.`,
375
425
  { args: delegation.into },
376
426
  );
377
- if (queued.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)
378
433
  attention.push(
379
- `${queued.join(', ')} passed review and ${queued.length === 1 ? 'waits' : 'wait'} for the person to merge (code-kit queue merge --person, or Merge in the code-kit band).`,
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).`,
380
435
  );
436
+ attention.push(...driftWords);
437
+ if (driftNote) attention.push(driftNote);
381
438
  if (merging)
382
439
  attention.push(
383
440
  `${merging} is being merged now (queue merge is running); it says when it's done.`,
@@ -386,12 +443,35 @@ export function nextStep(root, base) {
386
443
  attention.push(
387
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.`,
388
445
  );
389
- if (mergeHead && leadMerges && !merging)
446
+ if (mergeHead && leadMerges && !merging && !queuePaused)
390
447
  return result(
391
448
  'merge',
392
449
  `${mergeHead.branch} passed review and is next in the merge queue${queued.length > 1 ? ` (then ${queued.filter((b) => b !== mergeHead.branch).join(', ')})` : ''}.`,
393
450
  { args: mergeHead.branch },
394
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
+ : '';
395
475
  // SCHED-1, SCHED-2: one story for each free lane, across every session; the open slice's first.
396
476
  const busy = new Set([
397
477
  ...laneClaims(root)
@@ -416,7 +496,7 @@ export function nextStep(root, base) {
416
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.`,
417
497
  );
418
498
  // HAND-5: approved designs still only in a design tool, which no lane can read, are handed over once.
419
- const toolOnly = readRegister(root, config).entries.filter((e) => !handedOver(e));
499
+ const toolOnly = registered.filter((e) => !handedOver(e));
420
500
  if (toolOnly.length)
421
501
  attention.push(
422
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.`,
@@ -431,6 +511,8 @@ export function nextStep(root, base) {
431
511
  );
432
512
  models = toDispatch.filter((id) => chosen[id]).map((id) => ({ story: id, ...chosen[id] }));
433
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);
434
516
  if (review.length && toDispatch.length)
435
517
  then.push({ step: 'dispatch', args: toDispatch.join(' ') });
436
518
  if (forLead.length) then.push({ step: 'lead', args: forLead.join(' ') });
@@ -446,11 +528,21 @@ export function nextStep(root, base) {
446
528
  {
447
529
  args: forDesign.join(' '),
448
530
  then: [
531
+ ...(handOver.length ? [handOverStep] : []),
449
532
  ...(toDispatch.length ? [{ step: 'dispatch', args: toDispatch.join(' ') }] : []),
450
533
  ...(forLead.length ? [{ step: 'lead', args: forLead.join(' ') }] : []),
451
534
  ],
452
535
  },
453
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
+ });
454
546
  if (fixes.length)
455
547
  return result(
456
548
  'dispatch',
@@ -485,11 +577,19 @@ export function nextStep(root, base) {
485
577
  'wait',
486
578
  `${building.join(', ')} ${building.length === 1 ? 'is' : 'are'} being built; nothing else can start until one finishes. A lane that stopped without finishing is dispatched again.`,
487
579
  );
488
- // Stories waiting on branches in the merge queue wait for the merge, not on a broken plan.
580
+ // Stories waiting on branches in the merge queue wait for the merge, not on a broken plan. HUBR-9: a
581
+ // queue that only drift findings hold says which, and how each clears.
582
+ const heldOnly = queuePaused
583
+ ? `The merge queue is paused: ${queuePaused.reason}.`
584
+ : !mergeHead && driftWords.length
585
+ ? driftWords.join(' ')
586
+ : null;
489
587
  if (queued.length)
490
588
  return result(
491
589
  'wait',
492
- `${queued.join(', ')} passed review and ${queued.length === 1 ? 'waits' : 'wait'} to be merged; the stories that depend on ${queued.length === 1 ? 'it' : 'them'} start after.`,
590
+ heldOnly
591
+ ? `${heldOnly} The stories that depend on ${queued.length === 1 ? 'it' : 'them'} start after.`
592
+ : `${queued.join(', ')} passed review and ${queued.length === 1 ? 'waits' : 'wait'} to be merged; the stories that depend on ${queued.length === 1 ? 'it' : 'them'} start after.`,
493
593
  );
494
594
  if (unbuildable.length)
495
595
  return result(
@@ -502,6 +602,12 @@ export function nextStep(root, base) {
502
602
  'wait',
503
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.`,
504
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
+ );
505
611
  if (blocked.length)
506
612
  return result(
507
613
  'spec-design',
@@ -510,7 +616,7 @@ export function nextStep(root, base) {
510
616
  if (queued.length)
511
617
  return result(
512
618
  'wait',
513
- `${queued.join(', ')} ${queued.length === 1 ? 'waits' : 'wait'} to be merged.`,
619
+ heldOnly ?? `${queued.join(', ')} ${queued.length === 1 ? 'waits' : 'wait'} to be merged.`,
514
620
  );
515
621
  return result(
516
622
  'done',
@@ -520,7 +626,8 @@ export function nextStep(root, base) {
520
626
 
521
627
  const SCREEN_LANE = /(^|-)(web|mobile|frontend|front-end|ui|desktop|ios|android|admin|portal)(-|$)/;
522
628
  const SCREEN_FILE = /\.(tsx|jsx|vue|svelte|swift|dart)$/;
523
- 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+$/;
524
631
  const QA_LANE = /(^|-)(qa|e2e|tests?)(-|$)/;
525
632
 
526
633
  /**
@@ -543,7 +650,9 @@ export function setupGaps(config, stories, files = []) {
543
650
  function screenGaps(config, stories, files) {
544
651
  const lanes = Object.entries(config.lanes);
545
652
  const holdsScreens = new Set(
546
- 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)),
547
656
  );
548
657
  const screens = lanes
549
658
  .filter(
@@ -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));