@warren-dean/code-kit 0.26.2 → 0.28.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 +24 -0
  4. package/README.md +8 -6
  5. package/bin/code-kit.mjs +269 -52
  6. package/hooks/act.mjs +14 -5
  7. package/hooks/guard-bash.mjs +82 -17
  8. package/hooks/lib/adapters/hub/client.mjs +22 -0
  9. package/hooks/lib/checkout.mjs +105 -0
  10. package/hooks/lib/checks.mjs +34 -8
  11. package/hooks/lib/config.mjs +16 -2
  12. package/hooks/lib/dependencies.mjs +4 -0
  13. package/hooks/lib/designs.mjs +138 -0
  14. package/hooks/lib/events.mjs +9 -4
  15. package/hooks/lib/hook.mjs +61 -2
  16. package/hooks/lib/next.mjs +26 -5
  17. package/hooks/lib/plan.mjs +55 -13
  18. package/hooks/lib/queue.mjs +86 -1
  19. package/hooks/lib/regression.mjs +54 -44
  20. package/hooks/lib/rules.mjs +63 -20
  21. package/hooks/lib/security.mjs +20 -0
  22. package/hooks/lib/sessions.mjs +49 -9
  23. package/hooks/lib/snapshot.mjs +227 -22
  24. package/hooks/lib/team.mjs +27 -1
  25. package/hooks/lib/verify.mjs +37 -4
  26. package/hooks/lib/worktrees.mjs +18 -1
  27. package/hooks/mod/board.mjs +10 -1
  28. package/hooks/mod/loop.mjs +44 -1
  29. package/hooks/mod/register.mjs +96 -8
  30. package/hooks/mod/view.mjs +8 -0
  31. package/hooks/post-edit-check.mjs +3 -1
  32. package/hooks/session.mjs +3 -1
  33. package/hooks/stop-check.mjs +6 -1
  34. package/package.json +1 -1
  35. package/skills/design/SKILL.md +36 -7
  36. package/skills/dispatch/SKILL.md +1 -0
  37. package/skills/init/SKILL.md +2 -0
  38. package/skills/review/SKILL.md +2 -1
  39. package/skills/spec-design/SKILL.md +1 -1
  40. package/skills/status/SKILL.md +1 -1
  41. package/templates/agent.md +2 -1
@@ -202,12 +202,19 @@ export function teamProvider(root, team) {
202
202
  ? { ...g, fallback: r?.why ?? "The team provider can't be reached." }
203
203
  : g;
204
204
  };
205
+ // A claim taken while the provider was down lives only on GitHub; one the provider doesn't know is
206
+ // released there too, so it can't outlive its story (a merged story's claim, stuck and going stale).
207
+ const eitherRelease = (story, opts) => {
208
+ const r = either('release')(story, opts);
209
+ if (!r?.ok || r.released) return r;
210
+ const g = github.release(story, opts);
211
+ return g?.ok && g.released ? g : r;
212
+ };
205
213
  return {
206
214
  ...Object.fromEntries(
207
215
  [
208
216
  'whoami',
209
217
  'claim',
210
- 'release',
211
218
  'state',
212
219
  'intend',
213
220
  'settle',
@@ -218,6 +225,7 @@ export function teamProvider(root, team) {
218
225
  'standards',
219
226
  ].map((op) => [op, either(op)]),
220
227
  ),
228
+ release: eitherRelease,
221
229
  forget: () => (command.forget(), github.forget()),
222
230
  };
223
231
  }
@@ -790,6 +798,24 @@ function commandProvider(root, team, command) {
790
798
  }
791
799
 
792
800
  /** The team's state as last read, for the hooks and the mod between polls. */
801
+ /**
802
+ * TEAM-1: the claimed stories whose branch has merged into `base`, by the merge commits' subjects
803
+ * ("Merge web/st-12 into main", "Merge pull request #4 from owner/web/st-12"): their claims outlived their merge and end now. A commit that only
804
+ * mentions a story doesn't end its claim.
805
+ */
806
+ export function mergedClaims(root, claims, base) {
807
+ if (!claims?.length) return [];
808
+ const log = spawnSync('git', ['-C', root, 'log', base, '--merges', '--format=%s'], {
809
+ encoding: 'utf8',
810
+ maxBuffer: 64 * 1024 * 1024,
811
+ });
812
+ if (log.status !== 0) return [];
813
+ const merged = new Set(
814
+ [...log.stdout.matchAll(/[\w.-]+\/(st-\d+)(?![\w-])/gi)].map((m) => m[1].toUpperCase()),
815
+ );
816
+ return claims.map((c) => c.story).filter((story) => merged.has(String(story).toUpperCase()));
817
+ }
818
+
793
819
  export function readCache(root) {
794
820
  try {
795
821
  const s = JSON.parse(readFileSync(join(root, TEAM_STATE), 'utf8'));
@@ -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({
@@ -10,7 +10,7 @@ import { 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 { projectWorktrees, relativeTo, worktreeRoot } from './lib/rules.mjs';
13
- import { noteWrite } from './lib/sessions.mjs';
13
+ import { noteEditing, noteWrite } from './lib/sessions.mjs';
14
14
 
15
15
  const { input, project, config, error } = start();
16
16
  const target = input.tool_input?.file_path;
@@ -23,6 +23,8 @@ const rel = relativeTo(root, target);
23
23
  if (!existsSync(join(root, rel))) process.exit(0);
24
24
  // SESS-5: in the checkout every session shares, which session wrote the file, for a blocked git to name.
25
25
  if (root === projectWorktrees(project)[0]) noteWrite(project, input.session_id, rel);
26
+ // The file the session is editing, in whichever checkout: for the team provider's presence and report.
27
+ noteEditing(project, input.session_id, rel);
26
28
 
27
29
  // Violations recorded in the baseline (brownfield code as it was adopted) don't block; new ones do.
28
30
  const layers = layerProblems(rel, readFileSync(join(root, rel), 'utf8'), config);
package/hooks/session.mjs CHANGED
@@ -9,6 +9,7 @@ import { readFileSync } from 'node:fs';
9
9
  import { fileURLToPath } from 'node:url';
10
10
  import { loadConfig } from './lib/config.mjs';
11
11
  import { releaseSession } from './lib/laneclaims.mjs';
12
+ import { modelOf } from './lib/hook.mjs';
12
13
  import { endSession, startSession } from './lib/sessions.mjs';
13
14
  import { projectDir } from './lib/rules.mjs';
14
15
 
@@ -22,7 +23,8 @@ const project = projectDir();
22
23
  const { config } = loadConfig(project);
23
24
  const session = input.session_id ?? null;
24
25
  if (config && session && process.argv[2] === 'start') {
25
- startSession(project, session);
26
+ // The model the session starts on, when Claude Code names it, or its transcript's (a resumed one).
27
+ startSession(project, session, Date.now(), { model: modelOf(input) });
26
28
  // LEAN-8: the worktrees left done with since the last session go, in the background: a project with
27
29
  // many of them never holds up a session's start.
28
30
  const cli = fileURLToPath(new URL('../bin/code-kit.mjs', import.meta.url));
@@ -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.28.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",