@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
@@ -6,6 +6,7 @@ import { existsSync, readFileSync } from 'node:fs';
6
6
  import { join, posix } from 'node:path';
7
7
  import { matchesAny } from './glob.mjs';
8
8
  import { CODE, importsOf, layerOf, targetOf } from './layers.mjs';
9
+ import { isTestFile } from './testfiles.mjs';
9
10
 
10
11
  const git = (root, ...args) => {
11
12
  try {
@@ -126,8 +127,6 @@ export function laneOfFile(rel, config) {
126
127
  : null;
127
128
  }
128
129
 
129
- const TEST = /(^|\/)(tests?|e2e|__tests__)\/|\.(test|spec)\.[cm]?[jt]sx?$/;
130
-
131
130
  /**
132
131
  * MAP-1: a story's code: { story, layers, files: [{ path, layer, lane, imports }] }. `layers` are the
133
132
  * config's layers in their order, then `tests` and `other` where any file falls there; each file's
@@ -151,7 +150,9 @@ export function storyMap(root, story, config, from) {
151
150
  .filter((t) => t && t !== rel),
152
151
  ),
153
152
  ];
154
- const layer = TEST.test(rel) ? 'tests' : (layerOf(rel, config.layers)?.name ?? 'other');
153
+ const layer = isTestFile(rel, config)
154
+ ? 'tests'
155
+ : (layerOf(rel, config.layers)?.name ?? 'other');
155
156
  return { path: rel, layer, lane: laneOfFile(rel, config), imports };
156
157
  });
157
158
  const used = new Set(files.map((f) => f.layer));
@@ -165,9 +166,10 @@ export function storyMap(root, story, config, from) {
165
166
 
166
167
  /**
167
168
  * TRAIL-1: each requirement's trail: { id, title, spec, state, stories: [{ id, state, lane }],
168
- * files, tests }. Files are the code its stories changed, tests aside; tests are the files that name it.
169
+ * files, tests }. Files are the code its stories changed, tests aside (by `config`'s `tests`); tests are the
170
+ * files that name it.
169
171
  */
170
- export function trail(root, status, from) {
172
+ export function trail(root, status, from, config) {
171
173
  const byStory = new Map();
172
174
  const named = namedFiles(root);
173
175
  const filesOf = (s) => {
@@ -178,7 +180,9 @@ export function trail(root, status, from) {
178
180
  .filter((r) => !r.removed)
179
181
  .map((r) => {
180
182
  const stories = status.stories.filter((s) => s.requirements.includes(r.id));
181
- const files = [...new Set(stories.flatMap((s) => filesOf(s)).filter((f) => !TEST.test(f)))];
183
+ const files = [
184
+ ...new Set(stories.flatMap((s) => filesOf(s)).filter((f) => !isTestFile(f, config))),
185
+ ];
182
186
  return {
183
187
  id: r.id,
184
188
  title: r.title,
@@ -221,7 +225,9 @@ export function projectMap(root, config, tracked, { depth = 3, most = 60 } = {})
221
225
  files: 0,
222
226
  };
223
227
  nodes.set(path, node);
224
- const layer = TEST.test(rel) ? 'tests' : (layerOf(rel, config.layers)?.name ?? 'other');
228
+ const layer = isTestFile(rel, config)
229
+ ? 'tests'
230
+ : (layerOf(rel, config.layers)?.name ?? 'other');
225
231
  node.layers.set(layer, (node.layers.get(layer) ?? 0) + 1);
226
232
  node.files += 1;
227
233
  let source = '';
@@ -33,6 +33,8 @@ export {
33
33
  };
34
34
 
35
35
  const isObj = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
36
+ /** An intent's number, as the provider keeps it. */
37
+ export const isIntentId = (n) => Number.isInteger(n) && n > 0;
36
38
 
37
39
  /** What's wrong with `team` and the lanes' `owners`, as the config's other problems are worded. */
38
40
  export function teamProblems(c) {
@@ -154,9 +156,11 @@ export function whoami(root, now = Date.now()) {
154
156
 
155
157
  // --- the provider (TEAM-2) ----------------------------------------------------------------------------
156
158
  //
157
- // The core talks to the team through one interface: whoami, claim(story, lease), release(story),
159
+ // The core talks to the team through one interface: whoami, claim(story, lease, intent), release(story),
158
160
  // state() and intend(about, touches), report(snapshot) (HUBR-1) and standards() (STD-6: an
159
- // organisation's standards and this project's waivers, `{ standards, waivers, version }`). The GitHub
161
+ // organisation's standards and this project's waivers, `{ standards, waivers, version }`). A provider
162
+ // that checks drift says in its state what holds a merge (`mergeHolds`) and lists its open `findings`
163
+ // (HUBR-9); GitHub's checks none, so it holds nothing. The GitHub
160
164
  // provider is built in; any other is a command named in the config, called with the operation's name
161
165
  // and its input as JSON on stdin, answering JSON.
162
166
 
@@ -173,7 +177,14 @@ function claimOf(message) {
173
177
  try {
174
178
  const c = JSON.parse(message);
175
179
  return isStoryId(c.story) && isHandle(c.by)
176
- ? { story: c.story, by: c.by, at: c.at, lease: Array.isArray(c.lease) ? c.lease : [] }
180
+ ? {
181
+ story: c.story,
182
+ by: c.by,
183
+ at: c.at,
184
+ lease: Array.isArray(c.lease) ? c.lease : [],
185
+ // HUBR-2: the intent the story carries out, when its claim names one.
186
+ ...(isIntentId(c.intent) ? { intent: c.intent } : {}),
187
+ }
177
188
  : null;
178
189
  } catch {
179
190
  return null;
@@ -197,10 +208,12 @@ export function teamProvider(root, team) {
197
208
  const r = command[op](...args);
198
209
  if (!down(r) && r !== null) return r;
199
210
  const g = github[op](...args);
200
- // The state says it came through GitHub, and why, for the band.
201
- return op === 'state' && g
202
- ? { ...g, fallback: r?.why ?? "The team provider can't be reached." }
203
- : g;
211
+ if (op !== 'state' || !g) return g;
212
+ // The state says it came through GitHub, and why, for the band; kept so, so the hooks, `next` and
213
+ // the queue reading it later know the provider didn't answer (HUBR-9: no drift was checked).
214
+ const fell = { ...g, fallback: r?.why ?? "The team provider can't be reached." };
215
+ writeCache(root, fell);
216
+ return fell;
204
217
  };
205
218
  // A claim taken while the provider was down lives only on GitHub; one the provider doesn't know is
206
219
  // released there too, so it can't outlive its story (a merged story's claim, stuck and going stale).
@@ -403,7 +416,8 @@ function githubProvider(root, team) {
403
416
 
404
417
  const provider = {
405
418
  whoami: () => ({ login: me() }),
406
- claim(story, lease = []) {
419
+ /** `intent`: the intent the story carries out (HUBR-2); a claim again keeps the one it has. */
420
+ claim(story, lease = [], intent = null) {
407
421
  if (!isStoryId(story)) return { ok: false, why: `"${story}" isn't a story id.` };
408
422
  const by = me();
409
423
  if (!by) return { ok: false, why: 'Sign in to GitHub first (gh auth login).' };
@@ -423,8 +437,9 @@ function githubProvider(root, team) {
423
437
  const tree = git(['mktree'], { input: '' }).stdout.trim();
424
438
  // A lease only grows while the story is open: a claim again adds to it.
425
439
  lease = [...new Set([...(held?.lease ?? []), ...lease])];
426
- const message = JSON.stringify({ story, by, at, lease });
427
- const sha = git(['commit-tree', tree, '-m', message], { env }).stdout.trim();
440
+ const named = isIntentId(intent) ? intent : (held?.intent ?? null);
441
+ const claim = { story, by, at, lease, ...(named ? { intent: named } : {}) };
442
+ const sha = git(['commit-tree', tree, '-m', JSON.stringify(claim)], { env }).stdout.trim();
428
443
  const pushed = pushClaim(story, sha, held?.sha ?? '');
429
444
  if (!ok(pushed)) {
430
445
  // Someone claimed it between our fetch and push: say who.
@@ -433,7 +448,7 @@ function githubProvider(root, team) {
433
448
  return holder && holder.by !== by ? { ok: false, holder } : notReached();
434
449
  }
435
450
  provider.forget();
436
- return { ok: true, claim: { story, by, at, lease } };
451
+ return { ok: true, claim };
437
452
  },
438
453
  /** `merged`: the story merged, so its claim ends whoever releases it. */
439
454
  release(story, { merged = false } = {}) {
@@ -575,7 +590,13 @@ function githubProvider(root, team) {
575
590
  GIT_COMMITTER_EMAIL: email,
576
591
  };
577
592
  const tree = git(['mktree'], { input: '' }).stdout.trim();
578
- const message = JSON.stringify({ story, by: to, at, lease: held.lease });
593
+ const message = JSON.stringify({
594
+ story,
595
+ by: to,
596
+ at,
597
+ lease: held.lease,
598
+ ...(held.intent ? { intent: held.intent } : {}),
599
+ });
579
600
  const sha = git(['commit-tree', tree, '-m', message], { env }).stdout.trim();
580
601
  if (!ok(pushClaim(story, sha, held.sha))) return notReached();
581
602
  provider.forget();
@@ -770,7 +791,8 @@ function commandProvider(root, team, command) {
770
791
  };
771
792
  return {
772
793
  whoami: () => call('whoami'),
773
- claim: (story, lease = []) => call('claim', { story, lease }),
794
+ claim: (story, lease = [], intent = null) =>
795
+ call('claim', { story, lease, ...(isIntentId(intent) ? { intent } : {}) }),
774
796
  release: (story, { merged = false } = {}) => call('release', { story, merged }),
775
797
  state: ({ fresh = false } = {}) => {
776
798
  const s = call('state', { fresh });
@@ -1,5 +1,5 @@
1
- // Teams (docs/specs/16-teams.md), the pure parts: names, story branches, staleness and what an intent
2
- // touches. Shared by the hooks and CLI (team.mjs) and the mod, which runs without Node.
1
+ // Teams (docs/specs/16-teams.md), the pure parts: names, story branches, staleness, what an intent
2
+ // touches and which drift findings hold a merge (spec 21, HUBR-9). Shared by the hooks and CLI (team.mjs) and the mod, which runs without Node.
3
3
 
4
4
  /** A GitHub handle: letters, digits and single hyphens, at most 39 characters. */
5
5
  export const isHandle = (h) =>
@@ -189,3 +189,81 @@ export const boardValues = (story, claim) => ({
189
189
  /** The fields whose value changed since the last sync: [[field, value]]. */
190
190
  export const boardChanges = (before = {}, now) =>
191
191
  BOARD_FIELDS.filter((f) => (before[f] ?? '') !== now[f]).map((f) => [f, now[f]]);
192
+
193
+ // --- drift holds (spec 21, HUBR-9) ---------------------------------------------------------------------
194
+
195
+ /**
196
+ * What a team provider's "What blocks a merge" setting may say: a finding against a spec or decision,
197
+ * any finding, or nothing. A provider that says none (GitHub, or an older hosted one) holds nothing.
198
+ */
199
+ export const MERGE_HOLDS = ['spec-or-decision', 'any', 'nothing'];
200
+
201
+ /** What a drift finding is against, from its `conflictsWith`: spec, decision, branch or intent. */
202
+ export const findingKind = (f) => String(f?.conflictsWith ?? '').split(/[\s#]/)[0] || null;
203
+
204
+ /** Whether a finding holds a merge at the provider's level. Its severity doesn't change that. */
205
+ export function holdsMerge(finding, level) {
206
+ if (level === 'any') return true;
207
+ if (level === 'spec-or-decision') return ['spec', 'decision'].includes(findingKind(finding));
208
+ return false;
209
+ }
210
+
211
+ /** Whether the team's state came from its provider, not its fallback or a cache it couldn't renew. */
212
+ export const providerAnswered = (state) =>
213
+ Boolean(state) && state.reachable !== false && !state.fallback;
214
+
215
+ /**
216
+ * The open drift findings that hold `branch` in the merge queue, by the provider's state: its level
217
+ * (`mergeHolds`) and its findings. None when the provider didn't answer: code-kit doesn't hold on what
218
+ * it couldn't check (`driftUnchecked` says so).
219
+ */
220
+ export function driftHoldsOf(state, branch) {
221
+ if (!providerAnswered(state)) return [];
222
+ const level = MERGE_HOLDS.includes(state.mergeHolds) ? state.mergeHolds : 'nothing';
223
+ if (level === 'nothing') return [];
224
+ return (Array.isArray(state.findings) ? state.findings : []).filter(
225
+ (f) => f && f.branch === branch && !f.resolved && holdsMerge(f, level),
226
+ );
227
+ }
228
+
229
+ /** Each of `branches` the provider's findings hold: Map(branch → findings). */
230
+ export function driftHolds(state, branches) {
231
+ const held = new Map();
232
+ for (const b of branches) {
233
+ const found = driftHoldsOf(state, b);
234
+ if (found.length) held.set(b, found);
235
+ }
236
+ return held;
237
+ }
238
+
239
+ const against = (f) =>
240
+ findingKind(f) === 'intent' ? f.conflictsWith : `the ${f.conflictsWith ?? 'work in flight'}`;
241
+ const oneLine = (s, max = 200) =>
242
+ String(s ?? '')
243
+ .replace(/\s+/g, ' ')
244
+ .trim()
245
+ .slice(0, max);
246
+
247
+ /**
248
+ * Why a branch is held, in words an agent or person can act on: each finding, who decides, and how it
249
+ * clears. `provider` is the team provider's name as its state gives it; `techLead` the team's.
250
+ */
251
+ export function driftHoldWords(branch, findings, { techLead = null, provider = null } = {}) {
252
+ const where = provider ?? 'the team provider';
253
+ const each = findings.map(
254
+ (f) =>
255
+ `against ${against(f)}${f.severity ? ` (a ${f.severity})` : ''}: ${oneLine(f.title || f.text)}${f.url ? ` (${f.url})` : ''}`,
256
+ );
257
+ const one = each.length === 1;
258
+ const found = one
259
+ ? `the drift check found it ${each[0]}`
260
+ : `the drift check found it ${each.length} times: ${each.join('; ')}`;
261
+ return `${branch} is held from merging: ${found}. ${techLead ? `The tech lead (${techLead})` : 'The tech lead'} decides: if the work still stands, resolve ${one ? 'the finding' : 'the findings'} on ${where}; otherwise push a fix to ${branch}, and the drift check clears ${one ? 'it' : 'each'} once a push no longer conflicts. It merges as soon as nothing holds it.`;
262
+ }
263
+
264
+ /** When the provider didn't answer, that drift findings weren't checked, in words; null when they were. */
265
+ export function driftUnchecked(state) {
266
+ if (providerAnswered(state)) return null;
267
+ const why = oneLine(state?.fallback ?? state?.why ?? "The team provider can't be reached.");
268
+ return `${why.replace(/\.$/, '')}, so drift findings weren't checked: merges don't wait on them until it answers.`;
269
+ }
@@ -0,0 +1,22 @@
1
+ // What counts as a test (docs/specs/18-regression.md), in one place for every check that asks: a fix's
2
+ // proof (REG-1), weakened tests (REG-2), the tests that name a requirement, the code map's tests layer,
3
+ // what the security review leaves out and which files are screens. A project's `tests` globs replace
4
+ // the conventions; without them, a file is a test when it's named as one or sits in a test folder.
5
+ import { matchesAny } from './glob.mjs';
6
+
7
+ // Named as a test: `*.test.*`, `*.spec.*`, `*.smoke.*`, `test_*.py`, `*_test.go` and `*_test.py`.
8
+ const NAMED = /\.(test|spec|smoke)\.[^/]+$|_test\.(go|py)$|(^|\/)test_[^/]+\.py$/;
9
+ // Inside a test folder, where a test's helpers, fixtures and harness live too.
10
+ const FOLDER = /(^|\/)(tests?|__tests__|e2e|smoke)\//;
11
+
12
+ /** Whether `rel` is a test or test code: the config's `tests` globs, or named as a test or in a test folder. */
13
+ export const isTestFile = (rel, config) =>
14
+ !rel.endsWith('.md') &&
15
+ (config?.tests?.length ? matchesAny(rel, config.tests) : NAMED.test(rel) || FOLDER.test(rel));
16
+
17
+ /**
18
+ * Whether `rel` is a test itself, by its name, and not a helper beside one: the config's `tests` globs,
19
+ * or the naming conventions. A fix's proof keeps these and takes everything else back (REG-1).
20
+ */
21
+ export const isNamedTest = (rel, config) =>
22
+ !rel.endsWith('.md') && (config?.tests?.length ? matchesAny(rel, config.tests) : NAMED.test(rel));
@@ -8,19 +8,23 @@ 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
+ import { entryProblems, freshEntries, readRegister, statesWithoutEvidence } from './designs.mjs';
12
+ import { evidenceRecords } from './reviews.mjs';
13
+ import { storyOfBranch } from './teamfacts.mjs';
12
14
  import { matchesAny } from './glob.mjs';
13
15
  import { layerProblems } from './layers.mjs';
14
16
  import { STANDARDS_APPROVAL, standardsFile, standardsWeakenings } from './standards.mjs';
15
17
  import { TESTS_APPROVAL, branchWeakenings, fixOf, proveFix } from './regression.mjs';
16
18
  import {
17
19
  APPROVAL_LOG,
20
+ APPROVALS_DIR,
18
21
  SECRETS,
19
22
  laneOf,
20
23
  ownerOf,
21
24
  owns,
22
25
  protectedEntry,
23
26
  leadNeedsApproval,
27
+ relayCommand,
24
28
  screenProblem,
25
29
  } from './rules.mjs';
26
30
 
@@ -40,6 +44,15 @@ function showAt(root, ref, rel) {
40
44
  }
41
45
  }
42
46
 
47
+ /** The hash of a file's content at `ref` (git's blob id), or null when it doesn't exist there. */
48
+ function blobAt(root, ref, rel) {
49
+ try {
50
+ return git(root, 'rev-parse', '--verify', '-q', `${ref}:${rel}`).trim();
51
+ } catch {
52
+ return null;
53
+ }
54
+ }
55
+
43
56
  /** The lane a branch belongs to by its name (`<lane>/<story>`), or null. */
44
57
  export function laneOfBranch(branch, config) {
45
58
  const lane = branch?.split('/')[0];
@@ -176,6 +189,8 @@ const NOISE = [
176
189
  /^\(node:\d+\) \[?\w*\]? ?(DeprecationWarning|ExperimentalWarning|Warning)\b/,
177
190
  /^\(Use `node --trace-(deprecation|warnings) /,
178
191
  /^\s*$/,
192
+ // A tool printing a value it never had (pnpm exec, before it says a command isn't installed).
193
+ /^\s*undefined\s*$/,
179
194
  ];
180
195
  const FAILING = /\b(fail(ed|ing|s)?|error|✗|✘|×|expected|received|assert|panic|traceback)\b/i;
181
196
 
@@ -194,8 +209,8 @@ export function failureOutput(output) {
194
209
 
195
210
  /**
196
211
  * The files changed, every problem with the branch, grouped as { ownership, protected, layers,
197
- * baseline, design, tests, regression, standards, checks }, and the checks `skipped` because a tool isn't
198
- * installed. `lane` holds the branch to that lane's paths; `checks: false` leaves the project's
212
+ * baseline, design, evidence, tests, regression, standards, checks }, and the checks `skipped` because a
213
+ * tool isn't installed; `evidenceUnchecked` where the review's records aren't kept (HAND-7: CI). `lane` holds the branch to that lane's paths; `checks: false` leaves the project's
199
214
  * checks to CI's own steps. `fixes` runs a fix's tests without the fix (REG-1; with the
200
215
  * checks unless said); `branch` names the branch when the checkout is detached.
201
216
  */
@@ -218,6 +233,7 @@ export function verifyBranch({
218
233
  layers: [],
219
234
  baseline: [],
220
235
  design: [],
236
+ evidence: [],
221
237
  tests: [],
222
238
  regression: [],
223
239
  standards: [],
@@ -241,15 +257,17 @@ export function verifyBranch({
241
257
  );
242
258
  // WHO-1: where the lead merges, its own change to what the person keeps needs the person's approval,
243
259
  // unless the base already holds it as the branch does (the setup's rules, put onto the base first).
260
+ // An approval recorded after the change names the content it approved (`blob`), and covers only that.
244
261
  else if (
245
262
  guarded &&
246
- logged.get(f)?.approval === 'lead' &&
247
263
  !signed &&
248
264
  leadNeedsApproval(guarded.approval, config) &&
265
+ (logged.get(f)?.approval === 'lead' ||
266
+ (logged.get(f)?.blob && logged.get(f).blob !== blobAt(root, 'HEAD', f))) &&
249
267
  showAt(root, base, f) !== showAt(root, 'HEAD', f)
250
268
  )
251
269
  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.`,
270
+ `${f} is ${guarded.why}, and the lead ${logged.get(f)?.approval === 'lead' ? 'changed it without' : 'changed it since it had'} the person's ${guarded.approval} approval. The lead merges here, so nobody else reviews it. Ask the person; once they approve it (they run \`! echo "<what you are approving>" > ${APPROVALS_DIR}/${guarded.approval}\`${config.approvals?.lead ? `, or you record their words with \`${relayCommand(guarded.approval)}\`` : ''}), record their approval for the file as it is with a commit of its own: \`git commit -m "Record the person's ${guarded.approval} approval for ${f}"\`. The commit hook logs it; the file doesn't need to change.`,
253
271
  );
254
272
  if (matchesAny(f, config.anyActor)) continue;
255
273
  if (lane === 'lead') {
@@ -294,17 +312,43 @@ export function verifyBranch({
294
312
  }
295
313
 
296
314
  // 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.
315
+ // changed, names the approved files with their hashes, every state the spec lists. HAND-11: an entry
316
+ // the base already holds (where the branch left it, as it is now, or the first protected branch's,
317
+ // which a lane may have merged in) is the base's, not the branch's.
298
318
  const register = config.designGate?.register;
319
+ let evidenceUnchecked = false;
299
320
  if (register) {
300
- const old = readRegister(root, config, showAt(root, from, register) ?? '{}').entries;
321
+ const at = (ref) => readRegister(root, config, showAt(root, ref, register) ?? '{}').entries;
322
+ const entries = readRegister(root, config).entries;
323
+ const protectedBase = config.branches?.protected?.[0];
324
+ const fresh = new Set(
325
+ freshEntries(entries, at(from), at(base), protectedBase ? at(protectedBase) : []),
326
+ );
301
327
  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));
328
+ for (const e of entries) {
304
329
  const files = (e.states ?? []).flatMap((st) => [st?.image, st?.code]).filter(Boolean);
305
- if (fresh || files.some((f) => touched.has(f)))
330
+ if (fresh.has(e) || files.some((f) => touched.has(f)))
306
331
  found.design.push(...entryProblems(root, e, config.docs?.specs));
307
332
  }
333
+ // HAND-7: a lane's branch that builds screens has the review's screenshot of each approved state.
334
+ const name = branch ?? currentBranchOf(root);
335
+ if (lane && lane !== 'lead' && name) {
336
+ const records = evidenceRecords(root, name);
337
+ if (records === null) evidenceUnchecked = true;
338
+ else {
339
+ const current = (r) =>
340
+ Boolean(r.sha) &&
341
+ spawnSync('git', ['-C', root, 'merge-base', '--is-ancestor', r.sha, 'HEAD']).status ===
342
+ 0 &&
343
+ spawnSync('git', ['-C', root, 'diff', '--quiet', r.sha, 'HEAD', '--', r.file]).status ===
344
+ 0;
345
+ const story = storyOfBranch(name) ?? name;
346
+ for (const { entry, state } of statesWithoutEvidence(entries, present, records, current))
347
+ found.evidence.push(
348
+ `${entry.screen ?? entry.file}'s ${state.name} state (${entry.file}) has no screenshot from the review beside its design (${state.image}). The review takes one of the built state at ${state.viewport ?? "the design's viewport"} and records it: code-kit designs evidence ${story} ${entry.file} ${state.name} <screenshot.png>.`,
349
+ );
350
+ }
351
+ }
308
352
  }
309
353
 
310
354
  // The baseline only shrinks once the kit is adopted (the adopting change may record it).
@@ -368,5 +412,5 @@ export function verifyBranch({
368
412
  unfinished = Boolean(failure.timedOut);
369
413
  }
370
414
  }
371
- return { changed, found, skipped, unfinished };
415
+ return { changed, found, skipped, unfinished, evidenceUnchecked };
372
416
  }
@@ -37,6 +37,14 @@ const real = (p) => {
37
37
  return p;
38
38
  }
39
39
  };
40
+ /** The folder this process runs in, or null when it has gone. */
41
+ const cwdNow = () => {
42
+ try {
43
+ return real(process.cwd());
44
+ } catch {
45
+ return null;
46
+ }
47
+ };
40
48
  const alive = (pid) => {
41
49
  try {
42
50
  process.kill(pid, 0);
@@ -74,11 +82,12 @@ function hasOwnCommits(root, branch) {
74
82
 
75
83
  /**
76
84
  * LEAN-6: each worktree but the main checkout: { path, branch, story, merged, clean, changes, report,
77
- * kind, missing, locked: { reason, pid, live } | null, agentAtWork }. `kind` is `agent` (under
85
+ * kind, missing, locked: { reason, pid, live } | null, agentAtWork, here }. `here`: this command runs in
86
+ * it (`cwd`, the process's own folder unless given), so taking it away would leave the shell nowhere. `kind` is `agent` (under
78
87
  * .claude/worktrees), `merge` (a temporary merge checkout) or `other` (one the person made). `clean` and
79
88
  * `changes` are null where they weren't read: an unmerged worktree stays whatever it holds (cleanOf reads it).
80
89
  */
81
- export function worktrees(root, config, now = Date.now()) {
90
+ export function worktrees(root, config, now = Date.now(), cwd = cwdNow()) {
82
91
  const list = git(root, 'worktree', 'list', '--porcelain');
83
92
  if (list.status !== 0) return [];
84
93
  const main = list.stdout.split('\n\n')[0];
@@ -98,6 +107,7 @@ export function worktrees(root, config, now = Date.now()) {
98
107
  const pid = Number(/\bpid (\d+)/.exec(lockLine?.[1] ?? '')?.[1]) || null;
99
108
  const missing = !existsSync(path);
100
109
  const where = real(path);
110
+ const here = Boolean(cwd && (cwd === where || cwd.startsWith(`${where}/`)));
101
111
  const kind = where.startsWith(`${agents}/`)
102
112
  ? 'agent'
103
113
  : where.startsWith(`${temp}/`) && TEMP_MERGE.test(basename(path))
@@ -140,6 +150,7 @@ export function worktrees(root, config, now = Date.now()) {
140
150
  lane && claims.some((c) => c.lane === lane && (c.story ?? null) === (story ?? c.story)),
141
151
  ),
142
152
  age: missing ? null : now - statSync(path).mtimeMs,
153
+ here,
143
154
  };
144
155
  });
145
156
  }
@@ -174,6 +185,9 @@ export function keptBecause(w) {
174
185
  if (w.missing) return null;
175
186
  if (w.kind === 'merge') return w.age < TEMP_MERGE_MS ? 'a merge may be using it now' : null;
176
187
  if (w.kind === 'other') return "it isn't one code-kit made; release it by name if it's done";
188
+ // A merge run from inside a lane's worktree mustn't take away the folder its own shell is in.
189
+ if (w.here)
190
+ return 'this command runs in it; it goes at the next merge or `code-kit worktrees prune` run from elsewhere';
177
191
  if (w.locked && !w.locked.pid)
178
192
  return `it's locked${w.locked.reason ? ` (${w.locked.reason})` : ''}`;
179
193
  if (!w.branch) return 'it has no branch checked out';
@@ -246,7 +260,15 @@ export function pruneWorktrees(root, config, now = Date.now()) {
246
260
  const label = w.branch ?? w.path;
247
261
  const why = keptBecause(w);
248
262
  if (why) {
249
- kept.push({ label, why, branch: w.branch, changes: w.changes, kind: w.kind });
263
+ kept.push({
264
+ label,
265
+ why,
266
+ branch: w.branch,
267
+ changes: w.changes,
268
+ kind: w.kind,
269
+ here: w.here,
270
+ merged: w.merged,
271
+ });
250
272
  continue;
251
273
  }
252
274
  if (w.missing) continue;
@@ -226,7 +226,18 @@ const URGENCY = [
226
226
  'report',
227
227
  'worktree',
228
228
  ];
229
- const NOTES = new Set(['usage', 'paused', 'finish', 'done', 'teamDown', 'elsewhere', 'loop']);
229
+ const NOTES = new Set([
230
+ 'usage',
231
+ 'paused',
232
+ 'finish',
233
+ 'done',
234
+ 'teamDown',
235
+ 'elsewhere',
236
+ 'loop',
237
+ 'drift',
238
+ 'queuePaused',
239
+ 'deferred',
240
+ ]);
230
241
 
231
242
  /** What a line is, in a word or two, for the Needs you panel. */
232
243
  const NEED_WORD = {
@@ -172,6 +172,11 @@ export function leadPrompt(step, { cli = 'code-kit' } = {}) {
172
172
  // ONB-6: an older setup brought up to date before the next story; init shows the person the diff.
173
173
  if (step.step === 'update')
174
174
  return `Before the next story, bring code-kit's setup up to date: run /code-kit:init. ${step.why ?? ''}`.trim();
175
+ // HAND-6: approved designs only in a design tool, exported before the screens built from them.
176
+ if (step.step === 'design' && step.handOver)
177
+ return ids.length
178
+ ? `${step.why ?? `${ids.join(', ')} approved designs that are only in the design tool.`} Run /code-kit:design --hand-over ${ids.join(' ')}: the person confirms each is still the design they approved, and you export it.`
179
+ : null;
175
180
  // ONB-2: the screens designed, and approved by the person, before they're built.
176
181
  if (step.step === 'design')
177
182
  return ids.length
@@ -192,7 +197,8 @@ export function leadPrompt(step, { cli = 'code-kit' } = {}) {
192
197
  }
193
198
 
194
199
  /** A step's identity: the loop never submits the same step twice while the project stands still. */
195
- export const stepKey = (step) => `${step.step}:${step.args ?? ''}`;
200
+ export const stepKey = (step) =>
201
+ `${step.step}${step.handOver ? ' --hand-over' : ''}:${step.args ?? ''}`;
196
202
 
197
203
  /** The band's words for a step (LOOP-5): "Dispatch ST-7, ST-9". */
198
204
  export function stepLabel(step) {
@@ -210,7 +216,8 @@ export function stepLabel(step) {
210
216
  design: 'Design',
211
217
  setup: 'Set up',
212
218
  update: 'Update the setup',
213
- }[step.step] ?? step.step;
219
+ 'hand-over': 'Hand over',
220
+ }[step.handOver ? 'hand-over' : step.step] ?? step.step;
214
221
  return ids ? `${verb} ${ids}` : verb;
215
222
  }
216
223
 
@@ -1261,11 +1261,12 @@ export function register(on) {
1261
1261
  $.ui.invalidate('ui.render');
1262
1262
  },
1263
1263
  // USE-1: a model request's tokens, put down to the agent that made it and its story and lane.
1264
- measure: async (agentId, usage) => {
1264
+ measure: async (agentId, usage, ranOn = null) => {
1265
1265
  if (agentId && !agentsSeen.has(agentId))
1266
1266
  for (const a of (await $.agent.list().catch(() => [])) ?? []) agentsSeen.set(a.id, a);
1267
1267
  const who = attribution(agentId, agentsSeen.get(agentId) ?? null, model.check, model.state);
1268
- ledger = withUsage(ledger, who, usage);
1268
+ // HUBR-2, report version 6: by the model the request ran on, as the step names it.
1269
+ ledger = withUsage(ledger, who, usage, ranOn);
1269
1270
  $.ui.invalidate('ui.render');
1270
1271
  // LEAN-5: a lane agent past its context limit is told to wrap up; its story goes on fresh.
1271
1272
  const limit = harness().agents.lanes.contextLimit;
@@ -2436,7 +2437,7 @@ export function register(on) {
2436
2437
  on('turn.step', async function* ($, e, next) {
2437
2438
  const res = yield* next(e);
2438
2439
  if (e.agentId) activityOf(e.agentId, 0).at = await $.clock.now();
2439
- if (res?.usage && act) await act.measure(e.agentId, res.usage).catch(() => {});
2440
+ if (res?.usage && act) await act.measure(e.agentId, res.usage, e.model).catch(() => {});
2440
2441
  return res;
2441
2442
  });
2442
2443
  // USE-4: the plan's 5-hour use, as Claude Code measures it.