@warren-dean/code-kit 0.26.2 → 0.27.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.
@@ -8,6 +8,7 @@ import { BASELINE_FILE, loadBaseline, newProblems } from './baseline.mjs';
8
8
  import { runChecks } from './checks.mjs';
9
9
  import { CONFIG_FILE } from './config.mjs';
10
10
  import { isDependencyFile } from './dependencies.mjs';
11
+ import { entryProblems, readRegister } from './designs.mjs';
11
12
  import { matchesAny } from './glob.mjs';
12
13
  import { layerProblems } from './layers.mjs';
13
14
  import { STANDARDS_APPROVAL, standardsFile, standardsWeakenings } from './standards.mjs';
@@ -19,6 +20,7 @@ import {
19
20
  ownerOf,
20
21
  owns,
21
22
  protectedEntry,
23
+ leadNeedsApproval,
22
24
  screenProblem,
23
25
  } from './rules.mjs';
24
26
 
@@ -65,11 +67,16 @@ function directChanges(root, from) {
65
67
  return new Set(out.split('\n').filter(Boolean));
66
68
  }
67
69
 
68
- /** Files changed on this branch since it left `base`. */
70
+ /**
71
+ * Files changed on this branch since it left `base`, and still different from `base` as it is now. A
72
+ * branch with two merge bases (it merged the base, and something it holds later reached the base too)
73
+ * can show a file from an older one as changed; one it holds exactly as the base does isn't its change.
74
+ */
69
75
  export function branchChanges(root, base) {
70
- return git(root, 'diff', '--name-only', '--no-renames', `${base}...HEAD`)
71
- .split('\n')
72
- .filter(Boolean);
76
+ const names = (range) =>
77
+ git(root, 'diff', '--name-only', '--no-renames', range).split('\n').filter(Boolean);
78
+ const differs = new Set(names(`${base}..HEAD`));
79
+ return names(`${base}...HEAD`).filter((f) => differs.has(f));
73
80
  }
74
81
 
75
82
  /**
@@ -232,6 +239,18 @@ export function verifyBranch({
232
239
  found.protected.push(
233
240
  `${f} is ${guarded.why}, but no approval-log entry records this change. Protected files are committed through Claude Code with code-kit, which logs them.`,
234
241
  );
242
+ // WHO-1: where the lead merges, its own change to what the person keeps needs the person's approval,
243
+ // unless the base already holds it as the branch does (the setup's rules, put onto the base first).
244
+ else if (
245
+ guarded &&
246
+ logged.get(f)?.approval === 'lead' &&
247
+ !signed &&
248
+ leadNeedsApproval(guarded.approval, config) &&
249
+ showAt(root, base, f) !== showAt(root, 'HEAD', f)
250
+ )
251
+ found.protected.push(
252
+ `${f} is ${guarded.why}, and the lead changed it without the person's ${guarded.approval} approval. The lead merges here, so nobody else reviews it: ask the person, and commit it again once their approval is in force.`,
253
+ );
235
254
  if (matchesAny(f, config.anyActor)) continue;
236
255
  if (lane === 'lead') {
237
256
  // The lead's branch is held to the lead's paths for what it changes itself; lane work reaches it
@@ -274,6 +293,20 @@ export function verifyBranch({
274
293
  if (screen) found.design.push(screen.split('\n')[0]);
275
294
  }
276
295
 
296
+ // HAND-2: each register entry the branch adds or changes, and each approved design whose files it
297
+ // changed, names the approved files with their hashes, every state the spec lists.
298
+ const register = config.designGate?.register;
299
+ if (register) {
300
+ const old = readRegister(root, config, showAt(root, from, register) ?? '{}').entries;
301
+ const touched = new Set(changed);
302
+ for (const e of readRegister(root, config).entries) {
303
+ const fresh = !old.some((o) => JSON.stringify(o) === JSON.stringify(e));
304
+ const files = (e.states ?? []).flatMap((st) => [st?.image, st?.code]).filter(Boolean);
305
+ if (fresh || files.some((f) => touched.has(f)))
306
+ found.design.push(...entryProblems(root, e, config.docs?.specs));
307
+ }
308
+ }
309
+
277
310
  // The baseline only shrinks once the kit is adopted (the adopting change may record it).
278
311
  if (showAt(root, from, CONFIG_FILE) !== null) {
279
312
  let before = {};
@@ -19,7 +19,7 @@ import {
19
19
  } from 'node:fs';
20
20
  import { tmpdir } from 'node:os';
21
21
  import { basename, dirname, join } from 'node:path';
22
- import { pruneLogs } from './events.mjs';
22
+ import { pruneLogs, readEvents } from './events.mjs';
23
23
  import { laneClaims } from './laneclaims.mjs';
24
24
  import { storyOfBranch } from './teamfacts.mjs';
25
25
 
@@ -144,6 +144,23 @@ export function worktrees(root, config, now = Date.now()) {
144
144
  });
145
145
  }
146
146
 
147
+ /** LEAN-6: how recently a lane agent's act counts as it still being at work on a story. */
148
+ export const BUSY_MS = 3 * 60_000;
149
+
150
+ /**
151
+ * LEAN-6: whether a lane agent is still at work on a worktree's story, by the story's event log (spec
152
+ * 26): its lane's last act is still open, or came within BUSY_MS, with no hand-back or stop after it. Releasing
153
+ * a worktree under a running agent takes its git away mid-step.
154
+ */
155
+ export function agentBusy(root, w, now = Date.now()) {
156
+ if (!w.story) return false;
157
+ const last = readEvents(root, w.story)
158
+ .filter((e) => e.actor && e.actor !== 'lead' && e.agent)
159
+ .at(-1);
160
+ if (!last || ['handback', 'stopped'].includes(last.kind)) return false;
161
+ return last.phase === 'start' || now - Date.parse(last.at) < BUSY_MS;
162
+ }
163
+
147
164
  /** Whether a worktree holds nothing uncommitted, read now where worktrees() didn't. */
148
165
  export function cleanOf(w) {
149
166
  if (w.clean !== null) return w.clean;
@@ -48,6 +48,7 @@ export const STATE = {
48
48
  quiet: { word: 'quiet', color: 'yellow', glyph: '…' },
49
49
  ready: { word: 'ready', color: 'green', glyph: '○' },
50
50
  todo: { word: 'to do', color: undefined, glyph: '○' },
51
+ dropped: { word: 'dropped', color: undefined, glyph: '·' },
51
52
  idle: { word: 'resting', color: undefined, glyph: '·' },
52
53
  dispatched: { word: 'started', color: 'blue', glyph: '→' },
53
54
  };
@@ -195,6 +196,8 @@ export function buildWords(progress) {
195
196
  /** The Build panel's state in a word or two, from the loop and whether anything is at work. */
196
197
  export function buildState(loop, { atWork = 0, leadBusy = false } = {}) {
197
198
  if (loop?.state === 'paused') return 'paused';
199
+ // LOOP-14: nothing moves until Claude's usage limit resets.
200
+ if (loop?.limited) return 'usage limit';
198
201
  if (loop?.state === 'done' || loop?.state === 'stopped') return 'milestone done';
199
202
  if (loop?.state === 'elsewhere') return 'led elsewhere';
200
203
  if (loop?.state === 'unled') return 'no lead';
@@ -208,6 +211,7 @@ export function buildState(loop, { atWork = 0, leadBusy = false } = {}) {
208
211
  /** How urgent each kind of line is (UI-3): a held call first, notes last. */
209
212
  const URGENCY = [
210
213
  'notice',
214
+ 'limited',
211
215
  'held',
212
216
  'question',
213
217
  'waiting',
@@ -227,6 +231,7 @@ const NOTES = new Set(['usage', 'paused', 'finish', 'done', 'teamDown', 'elsewhe
227
231
  /** What a line is, in a word or two, for the Needs you panel. */
228
232
  const NEED_WORD = {
229
233
  notice: 'failed',
234
+ limited: 'usage limit',
230
235
  held: 'held call',
231
236
  question: 'question',
232
237
  waiting: 'the lead waits',
@@ -647,7 +652,11 @@ export function board(view, els, on) {
647
652
  'Build',
648
653
  loopWord,
649
654
  progress ? `${progress.tested}/${progress.total}` : null,
650
- loopWord === 'moving' ? 'green' : loopWord === 'paused' ? 'yellow' : undefined,
655
+ loopWord === 'moving'
656
+ ? 'green'
657
+ : ['paused', 'usage limit'].includes(loopWord)
658
+ ? 'yellow'
659
+ : undefined,
651
660
  ),
652
661
  ...(progress
653
662
  ? [
@@ -382,9 +382,52 @@ export const requestContext = (usage) =>
382
382
  (usage?.cache_read_input_tokens ?? 0) +
383
383
  (usage?.cache_creation_input_tokens ?? 0);
384
384
 
385
+ /** LOOP-14: the first wait after a failed turn with no used-up window, and the longest. */
386
+ export const RETRY_MS = 5 * 60 * 1000;
387
+ export const RETRY_MAX_MS = 60 * 60 * 1000;
388
+
389
+ /**
390
+ * LOOP-14: how long the loop holds after a lead turn ended on an API error: until the latest reset of
391
+ * the rate-limit windows that are used up, or, with none (an overloaded or failing API), 5 minutes
392
+ * doubling with each failure in a row (`failures`, from 1), at most an hour.
393
+ * { until, why: 'limit' | 'error' }.
394
+ */
395
+ export function limitHold({ rateLimits = [], now, failures = 1 }) {
396
+ const resets = rateLimits
397
+ .filter((w) => w.percentUsed >= 100 && w.resetsAt)
398
+ .map((w) => Date.parse(w.resetsAt))
399
+ .filter((at) => Number.isFinite(at) && at > now);
400
+ if (resets.length) return { until: Math.max(...resets), why: 'limit' };
401
+ const wait = Math.min(RETRY_MS * 2 ** Math.max(0, failures - 1), RETRY_MAX_MS);
402
+ return { until: now + wait, why: 'error' };
403
+ }
404
+
405
+ /** LOOP-14: the band's words for the hold: "Claude's usage limit is reached: the loop waits until …". */
406
+ export function limitText(hold) {
407
+ const when = new Date(hold.until).toLocaleString(undefined, {
408
+ weekday: 'short',
409
+ hour: 'numeric',
410
+ minute: '2-digit',
411
+ });
412
+ return hold.why === 'limit'
413
+ ? `Claude's usage limit is reached: the loop waits until ${when}`
414
+ : `Claude's API failed the lead's turn: the loop tries again at ${when}`;
415
+ }
416
+
385
417
  /** LEAN-5: what a lane agent past its context limit is told. */
386
418
  export const wrapUpText = (limit) =>
387
- `Your context is past ${Math.round(limit / 1000)}k tokens, and every step from here rereads all of it. Finish the step you're on, commit your work, write your report, and hand back now. The lead carries the story on with a fresh agent that reads your report.`;
419
+ `Your context is past ${Math.round(limit / 1000)}k tokens, and every step from here rereads all of it. Finish the step you're on, commit your work, write your report, and hand back now. If the story isn't done, start your hand-back with "${UNFINISHED}" and what's left: the lead carries it on with a fresh agent that reads your report. If it is done, hand back as usual.`;
420
+
421
+ /** LEAN-5: how a lane agent past its limit says its story isn't done. */
422
+ export const UNFINISHED = 'Not finished:';
423
+
424
+ /** LEAN-5: whether a hand-back says the story isn't done, so a fresh agent carries it on. */
425
+ export const unfinished = (answer) =>
426
+ String(answer ?? '')
427
+ .trimStart()
428
+ .replace(/^[*_#>\s]+/, '')
429
+ .toLowerCase()
430
+ .startsWith(UNFINISHED.toLowerCase());
388
431
 
389
432
  /** LEAN-5, LEAN-6: the lead's prompt to carry a story on with a fresh agent once its agent handed back at the limit. */
390
433
  export function continuePrompt({ type, story, branch, cli = 'code-kit' }) {
@@ -81,6 +81,9 @@ import {
81
81
  PARK_MS,
82
82
  compactInstructions,
83
83
  continuePrompt,
84
+ unfinished,
85
+ limitHold,
86
+ limitText,
84
87
  requestContext,
85
88
  wrapUpText,
86
89
  milestonesDone,
@@ -145,6 +148,10 @@ const loop = {
145
148
  steps: [], // { at, kind, target, prompt? }, kept for the session
146
149
  lastKey: null, // the last step submitted or proposed, and the project as it stood then
147
150
  lastPrint: null,
151
+ // LOOP-14: the steps prompted while the project stood as `print`, so steps taken in turn don't come round.
152
+ askedAt: { print: null, keys: new Set() },
153
+ // LOOP-14: a lead turn ended on an API error: { until, why, failures }, until the limit resets.
154
+ limited: null,
148
155
  asked: { key: null, times: 0 }, // the step the lead was last prompted with, and how often in a row
149
156
  proposal: null, // under autonomy propose, or a step asked too often: { prompt, label, kind, target }
150
157
  pending: [], // restarts waiting for the lead to be idle: { story, prompt }
@@ -188,6 +195,7 @@ const DENIED_KEPT = 20;
188
195
  const LANES_FREE_MS = 60000;
189
196
  let lanesFreed = -Infinity;
190
197
  let leadTurn = null; // the lead's running turn, if any
198
+ let leadTurns = 0; // the lead's turns started, so a step read before one began is known to be stale
191
199
  const activity = new Map(); // agent id → { at, inFlight, nudged, stopped, lane, story }
192
200
  const restarts = new Map(); // story → times the loop restarted it
193
201
  const flagged = new Map(); // story → { lane, story, count }: stalled past its restarts
@@ -204,6 +212,16 @@ const finishedWork = (a) => {
204
212
  (q) => q.branch === story.branch && ['waiting', 'merging'].includes(q.state),
205
213
  );
206
214
  };
215
+ /**
216
+ * LEAN-5: a story a fresh agent mustn't carry on: merged, sent back (its send-back goes to a fresh agent
217
+ * already), or waiting in the merge queue.
218
+ */
219
+ const carriedOnAlready = (story) =>
220
+ !story ||
221
+ ['done', 'sent back'].includes(story.state) ||
222
+ (model.queue ?? []).some(
223
+ (q) => q.branch === story.branch && ['waiting', 'merging', 'merged'].includes(q.state),
224
+ );
207
225
  /** An agent's activity record, made on first sight. */
208
226
  const activityOf = (agentId, now) => {
209
227
  let a = activity.get(agentId);
@@ -1334,6 +1352,7 @@ export function register(on) {
1334
1352
  return;
1335
1353
  }
1336
1354
  loop.lastKey = null;
1355
+ loop.askedAt = { print: null, keys: new Set() };
1337
1356
  await act.record('lead', 'this session');
1338
1357
  $.ui.invalidate('ui.render');
1339
1358
  await act.step('resume');
@@ -1572,6 +1591,7 @@ export function register(on) {
1572
1591
  for (const id of loop.waiting?.stories ?? []) loop.parked.delete(id);
1573
1592
  loop.waiting = null;
1574
1593
  loop.lastKey = null;
1594
+ loop.askedAt = { print: null, keys: new Set() };
1575
1595
  $.ui.invalidate('ui.render');
1576
1596
  await act.step('resume');
1577
1597
  },
@@ -1633,6 +1653,12 @@ export function register(on) {
1633
1653
  const h = harness();
1634
1654
  if (loop.paused || h.autonomy === 'off' || model.state?.kind !== 'ok' || loop.done) return;
1635
1655
  if (leadTurn) return;
1656
+ // A turn that starts while the step reads the project (the person prompting the lead) may change
1657
+ // what's next, as dropping the branch it would merge does: the step is read again once it ends.
1658
+ const turns = leadTurns;
1659
+ const stale = () => leadTurn || leadTurns !== turns;
1660
+ // LOOP-14: a prompt now would fail as the last turn did.
1661
+ if (loop.limited && (await $.clock.now()) < loop.limited.until) return;
1636
1662
  if (trigger === 'tick' && !loop.started && !loop.pending.length) return;
1637
1663
  const box = await $.prompt.read().catch(() => null);
1638
1664
  if (box?.text?.trim()) return;
@@ -1641,11 +1667,14 @@ export function register(on) {
1641
1667
  // LOOP-11: the lead's last reply first: one that waits on the person holds every step.
1642
1668
  await act.hear();
1643
1669
  if (loop.waiting && ['person', 'stopped'].includes(loop.waiting.kind)) return;
1644
- // #59: a restart or hand-back for a story that has since merged is stale, and goes unasked.
1645
- const finished = new Set(
1646
- (model.state?.stories ?? []).filter((s) => s.state === 'done').map((s) => s.id),
1647
- );
1648
- loop.pending = loop.pending.filter((p) => !finished.has(p.story));
1670
+ // #59: a restart or hand-back for a story that has since merged is stale, and goes unasked; LEAN-5:
1671
+ // so is carrying on a story that has since been sent back or queued to merge.
1672
+ const stories = model.state?.stories ?? [];
1673
+ loop.pending = loop.pending.filter((p) => {
1674
+ const story = stories.find((s) => s.id === p.story);
1675
+ return p.kind === 'continue' ? !carriedOnAlready(story) : story?.state !== 'done';
1676
+ });
1677
+ if (stale()) return;
1649
1678
  if (loop.pending.length) {
1650
1679
  const { story, prompt } = loop.pending.shift();
1651
1680
  // Until the person has chosen how hands-off the loop is, or under propose, a restart is offered
@@ -1677,6 +1706,7 @@ export function register(on) {
1677
1706
  loop.parked,
1678
1707
  )
1679
1708
  : null;
1709
+ if (stale()) return;
1680
1710
  // MISSION-1: the band shows what the loop takes next.
1681
1711
  loop.nextStep = step;
1682
1712
  if (!step) {
@@ -1730,7 +1760,12 @@ export function register(on) {
1730
1760
  }
1731
1761
  // Never the same step twice while the project stands still.
1732
1762
  const print = await act.fingerprint();
1763
+ if (stale()) return;
1733
1764
  if (key === loop.lastKey && print === loop.lastPrint) return;
1765
+ // LOOP-14: nor any step already prompted while it stood so, as steps taken in turn would be.
1766
+ if (loop.askedAt.print !== print) loop.askedAt = { print, keys: new Set() };
1767
+ if (loop.askedAt.keys.has(key)) return;
1768
+ loop.askedAt.keys.add(key);
1734
1769
  loop.lastKey = key;
1735
1770
  loop.lastPrint = print;
1736
1771
  // LOOP-8, WHO-4: a step the lead was asked for three times and that is still next didn't take:
@@ -1812,10 +1847,18 @@ export function register(on) {
1812
1847
  loop.paused = false;
1813
1848
  await $.process.run(['node', cli, 'loop', 'resume'], { cwd }).catch(() => {});
1814
1849
  loop.lastKey = null;
1850
+ loop.askedAt = { print: null, keys: new Set() };
1815
1851
  await act.record('resume', 'the loop');
1816
1852
  $.ui.invalidate('ui.render');
1817
1853
  await act.step('resume');
1818
1854
  },
1855
+ // LOOP-14: the person asks the loop not to wait out the limit; a turn that fails again holds it again.
1856
+ tryNow: async () => {
1857
+ loop.limited = null;
1858
+ loop.askedAt = { print: null, keys: new Set() };
1859
+ $.ui.invalidate('ui.render');
1860
+ await act.step('resume');
1861
+ },
1819
1862
  dismissDone: () => {
1820
1863
  loop.doneDismissed = true;
1821
1864
  $.ui.invalidate('ui.render');
@@ -1861,6 +1904,11 @@ export function register(on) {
1861
1904
  const h = harness();
1862
1905
  if (loop.paused || h.autonomy === 'off' || model.state?.kind !== 'ok') return;
1863
1906
  const now = await $.clock.now();
1907
+ // LOOP-14: lane agents quiet on the same limit aren't stalled, and a restart would fail too.
1908
+ if (loop.limited && now < loop.limited.until) {
1909
+ for (const a of activity.values()) a.at = now;
1910
+ return;
1911
+ }
1864
1912
  const lanes = Object.entries(model.check?.lanes ?? {});
1865
1913
  const waitingOnPerson = new Set([...held.values()].map((c) => c.agentId));
1866
1914
  for (const agent of (await $.agent.list().catch(() => [])) ?? []) {
@@ -2093,6 +2141,12 @@ export function register(on) {
2093
2141
  try {
2094
2142
  // LOOP-10: the lead session renews its lease; DECIDE-4: with the lead idle, a decision waiting.
2095
2143
  if (lease.mine) await act.lead();
2144
+ // LOOP-14: the limit has reset; the loop takes its step at once.
2145
+ if (loop.limited && !loop.limited.over && (await $.clock.now()) >= loop.limited.until) {
2146
+ loop.limited.over = true;
2147
+ $.ui.invalidate('ui.render');
2148
+ await act.step('resume');
2149
+ }
2096
2150
  if (!leadTurn) act.offer().catch(() => {});
2097
2151
  await act.notifyNew().catch(() => {});
2098
2152
  await act.beat().catch(() => {});
@@ -2402,6 +2456,7 @@ export function register(on) {
2402
2456
 
2403
2457
  on('turn.start', async ($, e, next) => {
2404
2458
  leadTurn = e.turnId;
2459
+ leadTurns += 1;
2405
2460
  // LOOP-11: the questions already open, so the loop knows which the lead asked in this turn.
2406
2461
  turnQuestions = (model.questions ?? []).map((q) => q.id);
2407
2462
  $.ui.invalidate('ui.render'); // the lead's lane reads working while its turn runs
@@ -2421,12 +2476,23 @@ export function register(on) {
2421
2476
  if (e.agentId) {
2422
2477
  const a = activityOf(e.agentId, await $.clock.now());
2423
2478
  a.handedBack = true;
2424
- // LEAN-5: an agent that handed back at its limit: the lead carries its story on with a fresh one.
2479
+ // LOOP-14: a turn that died on an API error stopped short; it didn't hand back at its limit.
2480
+ if (e.reason === 'error') a.failed = true;
2481
+ // LEAN-5: an agent that handed back at its limit saying its story isn't done: the lead carries it
2482
+ // on with a fresh one. A hand-back that doesn't say so finished the story, which goes to review.
2425
2483
  const story = (model.state?.stories ?? []).find((s) => s.id === a.story);
2426
- if (a.overflow && !a.continued && act && story?.state !== 'done') {
2484
+ if (
2485
+ a.overflow &&
2486
+ !a.failed &&
2487
+ !a.continued &&
2488
+ act &&
2489
+ unfinished(e.answer) &&
2490
+ !carriedOnAlready(story)
2491
+ ) {
2427
2492
  a.continued = true;
2428
2493
  const agent = agentsSeen.get(e.agentId);
2429
2494
  loop.pending.push({
2495
+ kind: 'continue',
2430
2496
  story: a.story,
2431
2497
  prompt: continuePrompt({
2432
2498
  type: agent?.type ?? 'The lane agent',
@@ -2454,6 +2520,23 @@ export function register(on) {
2454
2520
  };
2455
2521
  loop.sent = null;
2456
2522
  $.ui.invalidate('ui.render');
2523
+ // LOOP-14: a turn the API failed did nothing; the loop holds until the limit resets.
2524
+ if (e.reason === 'error') {
2525
+ rateLimits = (await $.session.usage().catch(() => null))?.rateLimits ?? rateLimits;
2526
+ const failures = (loop.limited?.failures ?? 0) + 1;
2527
+ loop.limited = {
2528
+ ...limitHold({ rateLimits, now: await $.clock.now(), failures }),
2529
+ failures,
2530
+ };
2531
+ // Nothing to read of a reply that never came, and the step it was prompted with is asked again
2532
+ // once the hold ends.
2533
+ if (lastReply.sent) loop.askedAt.keys.delete(lastReply.sent.key);
2534
+ lastReply = null;
2535
+ loop.lastKey = null;
2536
+ await act?.record('limited', limitText(loop.limited)).catch(() => {});
2537
+ return res;
2538
+ }
2539
+ if (loop.limited) loop.limited = null;
2457
2540
  // What the person asked for goes first, whatever the loop's state.
2458
2541
  if (personAsks.length) {
2459
2542
  const text = personAsks.shift();
@@ -2473,9 +2556,12 @@ export function register(on) {
2473
2556
  // loop reads the lead's reply to them before it prompts again. Designs stay theirs (LOOP-12).
2474
2557
  on('prompt.submit', async ($, e, next) => {
2475
2558
  if (['composer', 'bridge'].includes(e.origin?.kind) && loop.waiting?.kind !== 'design') {
2476
- if (loop.waiting) $.ui.invalidate('ui.render');
2559
+ if (loop.waiting || loop.limited) $.ui.invalidate('ui.render');
2477
2560
  loop.waiting = null;
2478
2561
  loop.asked = { key: null, times: 0 };
2562
+ // LOOP-14: the person tries again themselves; the turn's end says whether the limit still holds.
2563
+ loop.limited = null;
2564
+ loop.askedAt = { print: null, keys: new Set() };
2479
2565
  }
2480
2566
  return next(e);
2481
2567
  });
@@ -2536,6 +2622,8 @@ export function register(on) {
2536
2622
  current: leadTurn && loop.started ? (loop.steps.at(-1) ?? null) : null,
2537
2623
  nextText: nextText(loop.nextStep),
2538
2624
  laneNotes,
2625
+ // LOOP-14: the hold on Claude's usage limit, while it lasts.
2626
+ limited: loop.limited && now < loop.limited.until ? loop.limited : null,
2539
2627
  now,
2540
2628
  reviews: [...reviews.values()].map((r) => ({
2541
2629
  ...r,
@@ -7,6 +7,7 @@ export const NOT_CODE_KIT = "This project doesn't use code-kit.";
7
7
  const LEAD = 'lead';
8
8
 
9
9
  /** A CLI run's stdout as JSON, or null when it printed none. */
10
+ import { limitText } from './loop.mjs';
10
11
  import { teamLines } from './teamview.mjs';
11
12
 
12
13
  export function parseJson(stdout) {
@@ -489,6 +490,13 @@ export function bandLines({
489
490
  worktrees,
490
491
  actions: [{ id: 'openDecision', label: 'Look…' }],
491
492
  });
493
+ // LOOP-14: the loop waits out Claude's usage limit.
494
+ if (loop?.limited)
495
+ lines.push({
496
+ kind: 'limited',
497
+ text: limitText(loop.limited),
498
+ actions: [{ id: 'tryNow', label: 'Try now' }],
499
+ });
492
500
  // LOOP-7: the milestone is done; SESS-2: where the loop is led from, when it isn't this session.
493
501
  if (loop?.state === 'done')
494
502
  lines.push({
@@ -6,7 +6,7 @@ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node
6
6
  import { join } from 'node:path';
7
7
  import { loadBaseline, newProblems } from './lib/baseline.mjs';
8
8
  import { runChecks } from './lib/checks.mjs';
9
- import { block, start } from './lib/hook.mjs';
9
+ import { apiStopOf, block, start } from './lib/hook.mjs';
10
10
  import { brokenLayerRule, layerProblems } from './lib/layers.mjs';
11
11
  import { noteFor } from './lib/standards.mjs';
12
12
  import { actorFor, actorRoot, currentBranch, reportPath } from './lib/rules.mjs';
@@ -16,6 +16,11 @@ import { auditProblems, changedFiles } from './lane-audit.mjs';
16
16
 
17
17
  const { input, project, config, error } = start();
18
18
 
19
+ // A turn Claude's API ended (its usage limit, an overload) didn't finish its work: there's nothing to
20
+ // check, a refusal would only prompt it into the same error, and a lane agent keeps its lane for the
21
+ // restart.
22
+ if (apiStopOf(input)) process.exit(0);
23
+
19
24
  // SCHED-1: a lane agent whose finish goes through frees its lane for the next story. A refused finish
20
25
  // (exit 2) keeps it: the agent carries on.
21
26
  const finishingLane =
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@warren-dean/code-kit",
3
- "version": "0.26.2",
3
+ "version": "0.27.0",
4
4
  "description": "Keeps AI coding agents inside your project's rules: lanes, layer rules, protected paths and proof before finish, enforced by Claude Code hooks and in CI",
5
5
  "license": "MIT",
6
6
  "author": "Warren Langeveldt",
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: design
3
- description: Design a design story's screens with the person before any of them is built, and record each approved design so its screen can be coded. Reads the screens the specs list, designs them in the project's design tool (Paper, Figma, Pencil) or as design files under design/, shows them, iterates on the person's feedback, and adds each approved screen to the design register the design gate reads. Use when code-kit next or the loop gives the design step, when a lane was refused for a screen whose design isn't approved, or runs /code-kit:design [story IDs].
3
+ description: Design a design story's screens with the person before any of them is built, and record each approved design so its screen can be coded. Reads the screens the specs list, designs them in the project's design tool (Paper, Figma, Pencil) or as design files under design/, shows them, iterates on the person's feedback, exports each approved screen's states into design/ as files a lane can read, and adds them to the design register the design gate reads. --hand-over exports designs approved before that are still only in the tool. Use when code-kit next or the loop gives the design step, when a lane was refused for a screen whose design isn't approved, or runs /code-kit:design [story IDs].
4
4
  ---
5
5
 
6
6
  # Design before code
@@ -32,25 +32,54 @@ Use the spec's own content: the real labels, fields, messages and limits from it
32
32
 
33
33
  Show the person each screen (a screenshot, or the file to open) with one line on what it does and which requirements it serves. Ask what to change. Make the changes and show them again until they say a screen is approved. A screen they want rethought goes back to step 2; one that needs the spec changed goes to `/code-kit:spec-design` first.
34
34
 
35
- ## 4. Record the approved designs
35
+ ## 4. Export what's approved
36
36
 
37
- For each approved screen, add an entry to the register, naming the code file the lane will write (from the architecture's folders and the project's routing):
37
+ A lane agent has no connection to the design tool: it builds from files in the repository. So when the person approves a screen, export every state they approved into `design/<area>/<screen>/<state>.<ext>` (`design/bookings/list/empty.png`, `design/bookings/list/empty.jsx`) before you record it, as it was approved: an artboard changed afterwards is a new approval. For each state, its code where the tool gives code, and a PNG at the size the product targets; once per project, the design tokens as JSON (`design/tokens.json`).
38
+
39
+ - **Paper:** `get_jsx` and `get_computed_styles` for each artboard, `export` for its PNG, `get_tokens` for the tokens.
40
+ - **Figma:** its MCP server's code and screenshot tools for each frame, and its variables for the tokens.
41
+ - **Claude Design and artifacts:** the page's HTML, read through the artifact; a headless browser's screenshot of each state for the PNG.
42
+ - **Pencil, or HTML files under `design/`:** the HTML is already the code; a headless browser's screenshot gives the PNG.
43
+ - **Anything else:** whatever code it gives, and the PNG. A tool that gives no code has an image only, and the state says why.
44
+
45
+ The export is the target the lane matches, not code to paste: it builds the screen from the project's design system and components.
46
+
47
+ ## 5. Record the approved designs
48
+
49
+ For each approved screen, add an entry to the register, naming the code file the lane will write (from the architecture's folders and the project's routing), the screen as the spec's `## Screens` section names it, and every state with its files, the viewport it was drawn at and the sha256 of each file (`shasum -a 256 <file>`):
38
50
 
39
51
  ```json
40
52
  {
41
53
  "screens": [
42
54
  {
43
55
  "file": "apps/web/app/bookings/page.tsx",
44
- "design": "design/bookings/list.html",
45
- "story": "ST-2",
46
- "approved": "2026-10-11"
56
+ "screen": "Bookings list",
57
+ "story": "ST-1",
58
+ "approved": "2026-10-11",
59
+ "source": { "tool": "paper", "ref": "<file id> — Bookings list" },
60
+ "tokens": "design/tokens.json",
61
+ "states": [
62
+ {
63
+ "name": "default",
64
+ "code": "design/bookings/list/default.jsx",
65
+ "image": "design/bookings/list/default.png",
66
+ "viewport": "390x844",
67
+ "sha256": { "code": "<sha256>", "image": "<sha256>" }
68
+ }
69
+ ]
47
70
  }
48
71
  ]
49
72
  }
50
73
  ```
51
74
 
75
+ `story` is this design story. One design can serve several code files, such as the web and the mobile screen: each has its own entry, naming the same states. Committing the register is refused while an entry names a file that isn't there, a hash that isn't the file's, a state with no image, or leaves out a state the spec lists for the screen; `code-kit designs` lists every entry and what's wrong with it.
76
+
52
77
  The register is protected by the `design` approval, which is the person's: writing it is refused until they approve, and in a session with the code-kit mod the write waits in the band for their Approve. Give the approval a reason in their words ("bookings list and detail, as shown"). Then commit the designs and the register on `design/st-<n>`, and review and merge it like the lead's own story. Once it's merged, `code-kit next` dispatches the screen stories that waited on it.
53
78
 
54
- ## 5. Report
79
+ ## Handing over designs approved before (`--hand-over`)
80
+
81
+ `code-kit next` names register entries whose design is only in a design tool ("6 approved screens are only in paper"). For each, find the artboard the entry names, and ask the person whether it's still the design they approved: the tool's copy may have changed since. Once they confirm, export it as in step 4 and rewrite its entry as in step 5. Then, for each of those screens that's already built, compare the build with the export as the review does (each state's screenshot beside its PNG), and add a fix story to the plan for each difference, citing the screen's requirements.
82
+
83
+ ## 6. Report
55
84
 
56
85
  Say which screens were approved, which are still open and why, and what's dispatched next.
@@ -65,6 +65,7 @@ Requirements (read each one in full, with its acceptance criteria):
65
65
  What to build: <the story's description, and anything the lead decided that the spec doesn't say>
66
66
  Fixes: <for a fix story, what was broken and where it was seen; write the test that fails because of it first>
67
67
  Contracts to use: <paths of the schemas, events or tables this story relies on>
68
+ Designs: <for a story that builds screens, what `code-kit designs ST-<n>` lists: each screen file, and for every state its image, its code and its viewport, and the tokens file. Read every state's image and code before writing the screen; match its layout, copy, spacing and states exactly; build it from the design system's components rather than pasting the export; and account for every state in your report>
68
69
  Out of scope: <what neighbouring stories or other lanes will do>
69
70
 
70
71
  Steps:
@@ -48,6 +48,7 @@ Read the story and every requirement it cites. Then start from what's already be
48
48
  - **Its journeys still pass end to end:** where the project has a QA lane, run the end-to-end suites that cover this story's requirements (the qa lane's command, filtered to them) against the branch. A journey that broke fails the review, even when the story's own tests pass. A story the QA lane delivered is reviewed the same way: each journey's test proves the requirements it cites, through the real screens and services, with no mocked responses.
49
49
  - **The spec-check report matches:** its table has no row still `missing` or `conflicts` without an answer, and its questions were answered, not guessed.
50
50
  - **Only the story:** changes beyond the story (refactors elsewhere, other stories' requirements) are sent back, or split into their own story. A new dependency is yours to judge, as in `/code-kit:decide`: the story's requirements need it, nothing the project has does the job, and it fits the principles and the layer. Only what crosses a guardrail (the spec, a contract, the architecture) is the person's call.
51
+ - **Built to its design:** for a story that builds screens, `code-kit designs ST-<n>` lists each screen's approved states. Take a screenshot of each built state at the design's viewport (the project's end-to-end runner, or a headless browser) and set it beside the state's PNG. A missing state or a different layout is a blocker, naming the state and its design file; different copy or components fail it too; spacing within the design system's scale is a nit. A state the build can't serve yet (the contract has no field for what the design shows) goes in the report with what's missing, and you add the story that provides it, rather than leaving a gap nobody sees.
51
52
  - **Contracts respected:** the code uses the contracts as written. A lane that needed a contract change should have asked, not worked around it.
52
53
  - **Standards kept:** `code-kit standards --for <changed files>` lists the project's standards for those files' layers. Check each changed file against the ones marked `checked` (the hooks already refuse what an `enforced` one names). A broken required standard sends the branch back, naming the standard's id and where; a broken recommended one is a concern; advice is at most a nit.
53
54
 
@@ -77,7 +78,7 @@ Report the table, `verify`'s result, the security review's findings (or that non
77
78
  node "${CLAUDE_PLUGIN_ROOT}/bin/code-kit.mjs" queue add <branch>
78
79
  ```
79
80
 
80
- Branches merge from the queue one at a time, in the order their reviews passed, each verified against the base as it is then. Where `approvals.delegate.merge` is on and the harness's autonomy is `autonomous`, you merge the head: `code-kit queue merge --delegated` (code-kit's loop asks you when it's its turn). Otherwise the person merges it, with Merge in the code-kit band or `code-kit queue merge --person`. The queue records the commit your review passed and merges exactly that commit. A branch that moves on after your review leaves the queue: review it again, then queue it again. A head that no longer merges cleanly, or fails verify against the moved base, is sent back to its lane on its own; dispatch the fix as for any send-back. When the branch is merged, remove its worktree. Where the base's rules set `branches.publish`, the merge also reaches the remote's base on its own: pushed, or as a pull request code-kit opens from `code-kit/publish-<base>` (and merges, where pushing the base is delegated to you). Never merge a story into another branch to get it there: `code-kit publish --delegated` tries again when GitHub held it back.
81
+ Branches merge from the queue one at a time, in the order their reviews passed, each verified against the base as it is then. Where `approvals.delegate.merge` is on and the harness's autonomy is `autonomous`, you merge the head: `code-kit queue merge --delegated` (code-kit's loop asks you when it's its turn). Otherwise the person merges it, with Merge in the code-kit band or `code-kit queue merge --person`. The queue records the commit your review passed and merges exactly that commit. A branch that moves on after your review leaves the queue: review it again, then queue it again. A head that no longer merges cleanly, or fails verify against the moved base, is sent back to its lane on its own; dispatch the fix as for any send-back. When the branch is merged, remove its worktree. Where the base's rules set `branches.publish`, the merge also reaches the remote's base on its own: pushed, or as a pull request code-kit opens from `code-kit/publish-<base>` (and merges, where pushing the base is delegated to you). Never merge a story into another branch to get it there: `code-kit publish --delegated` tries again when GitHub held it back. A branch that breaks the base merged on its own (a new API whose callers another story updates) is queued with the branches it lands with: `queue add <branch> --with <other>`. It waits in the queue, without asking for review again, until they're reviewed and queued too, and then they're verified and merged as one.
81
82
 
82
83
  - **Send back.** List each problem, where it is, and what "fixed" looks like, with the requirement or the standard's id it breaks. Record the send-back, so `status` and `next` read the branch as waiting for its fix rather than finished:
83
84
 
@@ -88,7 +88,7 @@ Each requirement gets an ID (`<AREA>-<n>`, for example `BOOK-4`) and its own hea
88
88
  - **Acceptance criteria:** Given / When / Then for the main path and for each important error.
89
89
  - **Threat model:** a short `## Threat model` per area: what in it is sensitive (personal data, children's data, credentials, money), who might attack it (a signed-out visitor, another customer, a staff member with the wrong role), and its trust boundaries (where outside input enters). A few concrete lines, not a compliance checklist; leave it out for an area that holds nothing sensitive and takes no outside input.
90
90
  - **Security requirements:** under `## Security requirements`, the rules that stop the attacks the threat model names, each with an ID and heading like any other requirement (`### BOOK-9 A customer sees only their own bookings`) and acceptance criteria written from the attacker's side. Stories cite them like any other requirement; a story that cites one always gets the security review.
91
- - **Screens** (any area a person uses through a web, mobile or desktop interface): a `## Screens` section listing each screen, what it shows, what the person can do on it and which requirements it serves, with its empty, loading and error states. These are what gets designed before anything is built.
91
+ - **Screens** (any area a person uses through a web, mobile or desktop interface): a `## Screens` section with a `### <Screen name>` heading for each screen: what it shows, what the person can do on it and which requirements it serves, and a `**States:**` line naming its states (`default, empty, loading, error`, and any others it has). These are what gets designed before anything is built.
92
92
 
93
93
  A spec answers what and why, not how: no framework, file or function names unless the person requires them. Anything still undecided goes in the spec's open questions and the brief's, never into a requirement. `Status: specified`.
94
94
 
@@ -37,6 +37,6 @@ Then the detail only if the person asks: the story table and the requirement tab
37
37
 
38
38
  ## Keep the plan current
39
39
 
40
- `status` shows where the plan's `**Status:**` lines disagree with git ("the plan is out of date"). Offer to fix them. The lead edits the plan, updates the lines, and commits on the lead's branch. Git is right about branches; the plan is right about `done` for stories whose branch was merged and deleted.
40
+ `status` shows where the plan's `**Status:**` lines disagree with git ("the plan is out of date"). Offer to fix them. The lead edits the plan, updates the lines, and commits on the lead's branch. Git is right about branches; the plan is right about `done` for stories whose branch was merged and deleted. A story taken out of the plan (folded into another, or no longer wanted) gets `**Status:** dropped` rather than being deleted: code-kit never dispatches it or waits on it.
41
41
 
42
42
  Gaps between the specs and the plan (a requirement in no story, an unknown lane, a duplicate ID) are the lead's to fix in the plan or the spec. If fixing one needs a product decision, ask the person rather than guessing.