@warren-dean/code-kit 0.29.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.
package/bin/code-kit.mjs CHANGED
@@ -16,6 +16,8 @@
16
16
  // trace <path> [--json] what a file is for: the requirements it delivers, its lane, its layer rules
17
17
  // designs [<story>] [--json] the approved designs from the register: a story's screens' design files,
18
18
  // every state, for the lane's brief; or every entry and what's wrong with it
19
+ // designs evidence <story> <screen file or name> <state> <screenshot.png>
20
+ // the review records its screenshot of a built state beside its design (HAND-7)
19
21
  // next [--base ref] [--json]
20
22
  // the step to take now (spec-design, init, dispatch, review…), from the project's state
21
23
  // approve <name>... --reason "…" [--lane name]
@@ -51,6 +53,10 @@
51
53
  // ci check [--json] | ci usage [--days N] [--json]
52
54
  // what the project's CI spends and what multiplies it (spec 25)
53
55
  // release <version> cut release/<version> from the base and push it: the full CI runs there
56
+ // queue pause --reason "…" | queue resume
57
+ // the lead holds the whole merge queue on purpose, and lets it go (MQ-8)
58
+ // defer <story>... --reason "…" [--until <date|ISO time>] | defer release <story>... | defer [--json]
59
+ // stories the lead holds on purpose: not dispatched, reviewed or merged (LOOP-15)
54
60
  // --config <file> reads a draft (.claude/code-kit.draft.json) instead of .claude/code-kit.json.
55
61
  import { execFileSync, spawnSync } from 'node:child_process';
56
62
  import {
@@ -103,13 +109,16 @@ import {
103
109
  import { traceFile } from '../hooks/lib/trace.mjs';
104
110
  import { buildStatus, readStories, specCheckRows } from '../hooks/lib/plan.mjs';
105
111
  import {
112
+ atViewport,
106
113
  designsFor,
107
114
  entryProblems,
108
115
  handedOver,
116
+ pngSize,
109
117
  readRegister,
118
+ sha256Of,
110
119
  toolOf,
111
120
  } from '../hooks/lib/designs.mjs';
112
- import { recordSentBack } from '../hooks/lib/reviews.mjs';
121
+ import { evidenceDir, recordEvidence, recordSentBack } from '../hooks/lib/reviews.mjs';
113
122
  import {
114
123
  SECURITY_AGENT,
115
124
  SECURITY_AGENT_FILE,
@@ -134,7 +143,10 @@ import {
134
143
  mergingNow,
135
144
  nextToMerge,
136
145
  setPartners,
146
+ pauseQueue,
147
+ queuePause,
137
148
  readQueue,
149
+ resumeQueue,
138
150
  settle,
139
151
  waiting,
140
152
  } from '../hooks/lib/queue.mjs';
@@ -193,7 +205,14 @@ import {
193
205
  import { heldTo, laneOfBranch, verifyBranch } from '../hooks/lib/verify.mjs';
194
206
  import { skippedLine } from '../hooks/lib/checks.mjs';
195
207
  import { TESTS_APPROVAL } from '../hooks/lib/regression.mjs';
196
- import { freshCheckout } from '../hooks/lib/checkout.mjs';
208
+ import { freshCheckout, matchInstalls } from '../hooks/lib/checkout.mjs';
209
+ import {
210
+ activeDeferrals,
211
+ deferStories,
212
+ deferralWords,
213
+ parseUntil,
214
+ releaseStories,
215
+ } from '../hooks/lib/deferrals.mjs';
197
216
  import { laneClaim, laneClaims, releaseLane, shortSession } from '../hooks/lib/laneclaims.mjs';
198
217
  import { slicesOf } from '../hooks/lib/schedule.mjs';
199
218
  import {
@@ -274,6 +293,7 @@ const storyGiven = option('--story');
274
293
  const whyGiven = option('--why');
275
294
  const whatGiven = option('--what');
276
295
  const withGiven = option('--with');
296
+ const untilGiven = option('--until');
277
297
  const expectedGiven = option('--expected');
278
298
  const commandGiven = option('--command');
279
299
  const refusalGiven = option('--refusal');
@@ -549,6 +569,7 @@ const VERIFY_GROUPS = {
549
569
  layers: 'Layer rules',
550
570
  baseline: 'Baseline',
551
571
  design: 'Designs before screens',
572
+ evidence: 'Builds compared with their designs',
552
573
  tests: 'Weakened tests',
553
574
  regression: 'Fixes and their tests',
554
575
  standards: 'Standards',
@@ -692,7 +713,7 @@ function publishAfter(config, byPerson) {
692
713
  const mode = target.branches.publish;
693
714
  if (!mode) return '';
694
715
  const mayMove = byPerson || target.approvals.delegate?.push === true;
695
- return ` ${publishBase(resolve('.'), into, { mode, mayMove }).message}`;
716
+ return ` ${publishBase(mainCheckout(resolve('.')), into, { mode, mayMove }).message}`;
696
717
  }
697
718
 
698
719
  /** `publish --delegated|--person`: publishes what's merged and not yet on the remote, as a merge does. */
@@ -737,14 +758,17 @@ function merge(branch) {
737
758
  const drift = driftNow(config, [branch], { fresh: true });
738
759
  const findings = drift.holds.get(branch);
739
760
  if (findings) die(`Nothing was merged. ${drift.words(branch, findings)}`);
761
+ const root = mainCheckout(resolve('.'));
740
762
  try {
741
763
  const { message } = mergeOne(branch, config, byPerson);
742
764
  // A branch merged outside the queue leaves it too, as one the queue merged would.
743
- settle(resolve('.'), branch, 'merged');
765
+ settle(root, branch, 'merged');
744
766
  out(`${message}${publishAfter(config, byPerson)}${drift.note ? ` ${drift.note}` : ''}`);
745
767
  } catch (e) {
746
- if (e instanceof MergeStop) die(e.message);
747
- throw e;
768
+ if (!(e instanceof MergeStop)) throw e;
769
+ if (e.kind !== 'already') die(e.message);
770
+ settle(root, branch, 'merged', 'already in the base');
771
+ out(e.message);
748
772
  }
749
773
  }
750
774
 
@@ -769,9 +793,15 @@ function mergeOne(branch, config, byPerson, commit = null, partners = []) {
769
793
  if (!target.branches.protected.includes(into))
770
794
  refuse(`${into} isn't a protected branch; merge into it with git.`);
771
795
  if (target.branches.protected.includes(branch)) refuse(`${branch} is itself a protected branch.`);
772
- const root = resolve('.');
796
+ // The main checkout, found once, before anything is removed: a merge run from inside the lane's own
797
+ // worktree must still reach the project's state when that worktree is done with.
798
+ const root = mainCheckout(resolve('.'));
773
799
  const g = (cwd, ...a) =>
774
- execFileSync('git', ['-C', cwd, ...a], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
800
+ execFileSync('git', ['-C', cwd, ...a], {
801
+ encoding: 'utf8',
802
+ stdio: ['ignore', 'pipe', 'pipe'],
803
+ maxBuffer: 64 * 1024 * 1024,
804
+ });
775
805
  try {
776
806
  g(root, 'rev-parse', '--verify', '--quiet', `refs/heads/${branch}`);
777
807
  } catch {
@@ -782,10 +812,31 @@ function mergeOne(branch, config, byPerson, commit = null, partners = []) {
782
812
  .split('\n\n')
783
813
  .map((w) => ({ path: w.match(/^worktree (.+)$/m)?.[1], ref: w.match(/^branch (.+)$/m)?.[1] }))
784
814
  .find((w) => w.ref === `refs/heads/${b}`)?.path;
785
- const clean = (dir, b) => {
786
- if (g(dir, 'status', '--porcelain', '--untracked-files=no').trim())
787
- fail(`${b} has uncommitted changes in ${dir}; commit or stash them first.`);
815
+ const contains = (ref, commit) =>
816
+ spawnSync('git', ['-C', root, 'merge-base', '--is-ancestor', commit, ref]).status === 0;
817
+ // What a checkout holds uncommitted, tracked or not: each path, a rename's both.
818
+ const uncommitted = (dir) => {
819
+ const parts = g(dir, 'status', '--porcelain=v1', '-z', '--untracked-files=all').split('\0');
820
+ const paths = [];
821
+ for (let i = 0; i < parts.length; i++) {
822
+ if (!parts[i]) continue;
823
+ paths.push(parts[i].slice(3));
824
+ if (/^[RC]/.test(parts[i])) paths.push(parts[++i]);
825
+ }
826
+ return paths;
788
827
  };
828
+ // MQ-1: only what the merge changes has to be committed in the base's checkout: git carries every other
829
+ // change, which tools sharing the checkout (a log a tool appends to each turn) make at any time.
830
+ const inTheWay = (dir, tips) => {
831
+ const lands = new Set(
832
+ tips.flatMap((t) =>
833
+ g(dir, 'diff', '--name-only', '--no-renames', `HEAD...${t}`).split('\n').filter(Boolean),
834
+ ),
835
+ );
836
+ return uncommitted(dir).filter((f) => lands.has(f));
837
+ };
838
+ const dirtyWords = (dir, files) =>
839
+ `Nothing was merged: ${into}'s checkout (${dir}) has uncommitted changes to ${files.length === 1 ? 'a file' : 'files'} this merge changes (${files.slice(0, 5).join(', ')}${files.length > 5 ? `, and ${files.length - 5} more` : ''}). Commit or stash ${files.length === 1 ? 'it' : 'them'} there, then merge again; changes to other files are carried as they are.`;
789
840
  const temporary = [];
790
841
  // A stop is thrown at once, so every way out of here removes the temporary worktrees first.
791
842
  const cleanup = () => {
@@ -819,14 +870,31 @@ function mergeOne(branch, config, byPerson, commit = null, partners = []) {
819
870
  `Nothing was merged: ${branch} has moved on since its review passed (${commit.slice(0, 7)} → ${tip.slice(0, 7)}). Review it again, then queue it.`,
820
871
  'moved',
821
872
  );
873
+ // A branch whose commit the base already holds has nothing left to merge: it isn't verified again
874
+ // (against the base it's an empty change, which says nothing) and never sent back.
875
+ if (contains(into, tip))
876
+ fail(
877
+ `${branch} is already merged into ${into}: ${into} holds its commit ${tip.slice(0, 7)}, so there's nothing of it left to merge.`,
878
+ 'already',
879
+ );
822
880
  // MQ-1: verified as it will land: the branch merged with the base as it is now, in a fresh checkout
823
- // with its own copy of the installs (the branch's worktree's, else the main checkout's), so neither
824
- // a stale branch head nor a checkout without dependencies decides it.
881
+ // with its own copy of the installs. They're the base's checkout's (the main checkout's), which match
882
+ // the base; where the merged tree's manifests or lockfiles differ from them, the install runs there.
883
+ // A branch's worktree can be far behind the base, or have no installs at all.
884
+ const baseCheckout = checkedOut(into);
885
+ const installsFrom = baseCheckout ?? root;
886
+ if (baseCheckout) {
887
+ const blocking = inTheWay(baseCheckout, [
888
+ tip,
889
+ ...partners.map((p) => `refs/heads/${p.branch}`),
890
+ ]);
891
+ if (blocking.length) fail(dirtyWords(baseCheckout, blocking));
892
+ }
825
893
  let fresh;
826
894
  try {
827
895
  fresh = freshCheckout(root, into, {
828
896
  merge: tip,
829
- installsFrom: checkedOut(branch) ?? root,
897
+ installsFrom,
830
898
  prefix: 'code-kit-merge-',
831
899
  });
832
900
  } catch (e) {
@@ -838,29 +906,47 @@ function mergeOne(branch, config, byPerson, commit = null, partners = []) {
838
906
  }
839
907
  temporary.push(fresh);
840
908
  const verifyIn = fresh.dir;
841
- // MQ-7: a group lands as one: its partners merged into the same tree, which the checks run on.
842
- const members = partners.map((p) => ({
843
- ...p,
844
- tip: g(root, 'rev-parse', `refs/heads/${p.branch}`).trim(),
845
- }));
846
- for (const m of members) {
847
- const merged = spawnSync(
909
+ // MQ-7: a group lands as one: its partners merged into the same tree, which the checks run on. A
910
+ // partner the base already holds has nothing left to merge.
911
+ const members = partners
912
+ .map((p) => ({ ...p, tip: g(root, 'rev-parse', `refs/heads/${p.branch}`).trim() }))
913
+ .filter((m) => !contains(into, m.tip));
914
+ const mergeInto = (dir, ref) =>
915
+ spawnSync(
848
916
  'git',
849
- ['-C', verifyIn, '-c', 'user.name=code-kit', '-c', 'user.email=code-kit@localhost'].concat([
917
+ ['-C', dir, '-c', 'user.name=code-kit', '-c', 'user.email=code-kit@localhost'].concat([
850
918
  'merge',
851
919
  '--no-ff',
852
920
  '--no-edit',
853
921
  '--quiet',
854
- m.tip,
922
+ ref,
855
923
  ]),
856
924
  { encoding: 'utf8' },
857
925
  );
926
+ for (const m of members) {
927
+ const merged = mergeInto(verifyIn, m.tip);
858
928
  if (merged.status !== 0)
859
929
  fail(
860
- `Nothing was merged: ${m.branch} doesn't merge cleanly with ${branch} on ${into}. Merge one into the other and resolve it there, then merge again.\n${`${merged.stdout}${merged.stderr}`.trim()}`,
930
+ `Nothing was merged: ${m.branch} doesn't merge cleanly with ${branch} on ${into}. Merge one into the other and resolve it there, then merge again.\n${`${merged.stdout ?? ''}${merged.stderr ?? ''}`.trim()}`,
861
931
  'conflict',
862
932
  );
863
933
  }
934
+ // MQ-1: the checks run with installs that match the merged tree, and say whose they were.
935
+ const installs = matchInstalls(verifyIn, installsFrom, { prepare: config.regression?.prepare });
936
+ const installedWith = installs.command
937
+ ? `installed with \`${installs.command}\` in the merged tree, since ${installs.differ.length ? `its ${installs.differ.join(', ')} differ${installs.differ.length === 1 ? 's' : ''} from ${installsFrom}'s` : `${installsFrom} had nothing installed`}`
938
+ : installs.differ.length
939
+ ? `with the installs of ${installsFrom}, which may not match: the merged tree's ${installs.differ.join(', ')} differ${installs.differ.length === 1 ? 's' : ''} from its, and code-kit knows no install for them (set regression.prepare to the command that installs, and the queue runs it there)`
940
+ : installs.copied
941
+ ? `with the installs of ${installsFrom}`
942
+ : installs.lockfile
943
+ ? `with no installs, since ${installsFrom} has none: install there, and the queue copies them`
944
+ : null;
945
+ if (installs.failed)
946
+ fail(
947
+ `Nothing was merged: the merged tree's checks need its own installs (${installs.differ.length ? `its ${installs.differ.join(', ')} differ from ${installsFrom}'s` : `${installsFrom} has nothing installed`}), and \`${installs.command}\` ${installs.failed.missing ? "isn't installed here" : 'failed'} in ${verifyIn}${installs.failed.output ? `:\n${installs.failed.output}` : '.'}\nThat says nothing against ${branch}, so it keeps its place in the queue. Make the install work (or set regression.prepare to the command that installs), then merge again.`,
948
+ 'installs',
949
+ );
864
950
  const lane = members.length ? null : laneOfBranch(branch, config);
865
951
  const { changed, found, skipped, unfinished } = verifyBranch({
866
952
  root: verifyIn,
@@ -870,13 +956,29 @@ function mergeOne(branch, config, byPerson, commit = null, partners = []) {
870
956
  checks: true,
871
957
  branch,
872
958
  });
873
- // Each member is still held to its own lane's paths, on its own tree.
959
+ // MQ-7: each member is still held to its own lane's paths, for its own changes alone: measured against
960
+ // the base merged with its partners, so a lane's branch built on its lead partner's (as dispatch has
961
+ // it) isn't held to the partner's files. A partner built on this member already holds the member's
962
+ // commits, so it's left out of the member's base, which would otherwise show no change at all.
874
963
  for (const b of members.length ? [{ branch, tip }, ...members] : []) {
875
- const own = freshCheckout(root, into, { merge: b.tip, prefix: 'code-kit-merge-' });
964
+ const own = freshCheckout(root, into, { prefix: 'code-kit-merge-' });
876
965
  temporary.push(own);
966
+ const others = [{ branch, tip }, ...members].filter(
967
+ (x) => x.branch !== b.branch && !contains(x.tip, b.tip),
968
+ );
969
+ for (const o of others) {
970
+ const merged = mergeInto(own.dir, o.tip);
971
+ if (merged.status !== 0)
972
+ fail(
973
+ `Nothing was merged: ${o.branch} doesn't merge cleanly with ${b.branch}'s partners on ${into}. Merge one into the other and resolve it there, then merge again.\n${`${merged.stdout ?? ''}${merged.stderr ?? ''}`.trim()}`,
974
+ 'conflict',
975
+ );
976
+ }
977
+ const withPartners = g(own.dir, 'rev-parse', 'HEAD').trim();
978
+ g(own.dir, 'checkout', '--quiet', '--detach', b.tip);
877
979
  const held = verifyBranch({
878
980
  root: own.dir,
879
- base: into,
981
+ base: withPartners,
880
982
  config,
881
983
  lane: laneOfBranch(b.branch, config),
882
984
  checks: false,
@@ -896,17 +998,19 @@ function mergeOne(branch, config, byPerson, commit = null, partners = []) {
896
998
  // #62: a check that only ran out of time says nothing against the branch: it's tried again.
897
999
  if (problems.length === 1 && unfinished)
898
1000
  fail(
899
- `Nothing was merged: a check on ${branch} didn't finish, which says nothing against the branch (checked in ${verifyIn}):\n ${problems[0]}\nIt stays at the head of the queue; merge again once fewer suites are running.`,
1001
+ `Nothing was merged: a check on ${branch} didn't finish, which says nothing against the branch (checked in ${verifyIn}${installedWith ? `, ${installedWith}` : ''}):\n ${problems[0]}\nIt stays at the head of the queue; merge again once fewer suites are running.`,
900
1002
  'unfinished',
901
1003
  );
902
1004
  if (problems.length)
903
1005
  fail(
904
- `Nothing was merged. code-kit verify found ${problems.length} problem(s) on ${branch} (checked in ${verifyIn}):\n ${problems.join('\n ')}\nSend it back to its lane, or fix it, then merge again.`,
1006
+ `Nothing was merged. code-kit verify found ${problems.length} problem(s) on ${branch} (checked in ${verifyIn}${installedWith ? `, ${installedWith}` : ''}):\n ${problems.join('\n ')}\nSend it back to its lane, or fix it, then merge again.`,
905
1007
  'verify',
906
1008
  problems[0].split('\n')[0],
907
1009
  );
908
1010
  const mergeIn = checkedOut(into) ?? worktree(into, false);
909
- clean(mergeIn, into);
1011
+ // Checked again now the verify is done: only changes to what the merge changes stop it.
1012
+ const blocking = inTheWay(mergeIn, [tip, ...members.map((m) => m.tip)]);
1013
+ if (blocking.length) fail(dirtyWords(mergeIn, blocking));
910
1014
  const before = g(mergeIn, 'rev-parse', 'HEAD').trim();
911
1015
  const together = members.length
912
1016
  ? ` together with ${members.map((m) => m.branch).join(', ')} (MQ-7)`
@@ -942,7 +1046,7 @@ function mergeOne(branch, config, byPerson, commit = null, partners = []) {
942
1046
  const stories = [branch, ...members.map((m) => m.branch)].map(storyOfBranch).filter(Boolean);
943
1047
  let unreleased = '';
944
1048
  if (team) {
945
- const provider = teamProvider(resolve('.'), team);
1049
+ const provider = teamProvider(root, team);
946
1050
  for (const story of stories) {
947
1051
  const left = provider.release(story, { merged: true });
948
1052
  if (!left?.ok)
@@ -951,20 +1055,50 @@ function mergeOne(branch, config, byPerson, commit = null, partners = []) {
951
1055
  for (const s of mergedClaims(root, provider.state()?.claims ?? [], into))
952
1056
  if (!stories.includes(s)) provider.release(s, { merged: true });
953
1057
  }
954
- // LEAN-8: the merged branch's worktree, and any other that's done with, go now.
955
- const pruned = pruneWorktrees(root, config).removed;
956
- const removed = pruned.length
957
- ? ` Removed ${pruned.length} worktree${pruned.length === 1 ? '' : 's'} that ${pruned.length === 1 ? 'was' : 'were'} done with.`
958
- : '';
1058
+ // LEAN-8: the merged branch's worktree, and any other that's done with, go now; not the one this
1059
+ // command runs in, which would leave its shell in a folder that's gone.
1060
+ const { removed: pruned, kept } = pruneWorktrees(root, config);
1061
+ const here = kept.find((k) => k.here);
1062
+ const removed = `${
1063
+ pruned.length
1064
+ ? ` Removed ${pruned.length} worktree${pruned.length === 1 ? '' : 's'} that ${pruned.length === 1 ? 'was' : 'were'} done with.`
1065
+ : ''
1066
+ }${here?.merged ? ` Kept ${here.label}'s worktree, since this command runs in it: it goes at the next merge.` : ''}`;
959
1067
  return {
960
1068
  into,
961
- message: `Merged ${branch}${together} into ${into}: verify passed on ${changed.length} file(s)${lane ? `, held to ${heldTo(lane)}` : ''}, at ${tip.slice(0, 7)}.${skipped.length ? ` ${notRun(skipped)}` : ''}${removed}${unreleased}`,
1069
+ message: `Merged ${branch}${together} into ${into}: verify passed on ${changed.length} file(s)${lane ? `, held to ${heldTo(lane)}` : ''}, at ${tip.slice(0, 7)}${installs.command ? `, ${installedWith}` : ''}.${skipped.length ? ` ${notRun(skipped)}` : ''}${removed}${unreleased}`,
962
1070
  };
963
1071
  } finally {
964
1072
  cleanup();
965
1073
  }
966
1074
  }
967
1075
 
1076
+ /** A local branch's commit, or null when there's no such branch. */
1077
+ function branchTip(branch) {
1078
+ try {
1079
+ return execFileSync('git', ['rev-parse', '--verify', '--quiet', `refs/heads/${branch}`], {
1080
+ encoding: 'utf8',
1081
+ stdio: ['ignore', 'pipe', 'ignore'],
1082
+ }).trim();
1083
+ } catch {
1084
+ return null;
1085
+ }
1086
+ }
1087
+
1088
+ /** LOOP-15: the branches of the stories the lead holds now, Map(branch → hold), by the plan's branch names. */
1089
+ function heldBranches(root, config) {
1090
+ const holds = activeDeferrals(root);
1091
+ if (!holds.length) return new Map();
1092
+ const byBranch = new Map();
1093
+ const branches = waiting(readQueue(root)).map((e) => e.branch);
1094
+ for (const b of branches) {
1095
+ const story = storyOfBranch(b);
1096
+ const hold = story && holds.find((h) => h.story === story.toUpperCase());
1097
+ if (hold) byBranch.set(b, hold);
1098
+ }
1099
+ return byBranch;
1100
+ }
1101
+
968
1102
  /**
969
1103
  * The merge queue (spec 09): `queue` lists it; `queue add <branch>` puts a branch the lead's review
970
1104
  * passed at the back; `queue drop <branch>` takes one out; `queue merge --delegated|--person` merges
@@ -973,8 +1107,31 @@ function mergeOne(branch, config, byPerson, commit = null, partners = []) {
973
1107
  */
974
1108
  function queue() {
975
1109
  const { config } = load();
976
- const root = resolve('.');
1110
+ // The main checkout, where the queue is kept, found once: a merge run from inside a lane's worktree
1111
+ // must still reach the queue once that worktree is done with.
1112
+ const root = mainCheckout(resolve('.'));
1113
+ const into = intoName ?? config.branches.protected[0];
977
1114
  const [sub, branch] = rest;
1115
+ // MQ-8: the lead pauses the whole queue on purpose, with why; branches are still queued meanwhile.
1116
+ if (sub === 'pause') {
1117
+ if (!reason?.trim())
1118
+ die(
1119
+ 'code-kit queue pause --reason "…": say why the queue waits, so the person and the band can see it.',
1120
+ );
1121
+ const was = queuePause(root);
1122
+ pauseQueue(root, reason.trim(), callerSession);
1123
+ return out(
1124
+ `${was ? 'The merge queue stays paused, now' : 'Paused the merge queue'}: ${reason.trim()}. Nothing merges, and nothing offers a merge, until code-kit queue resume.`,
1125
+ );
1126
+ }
1127
+ if (sub === 'resume') {
1128
+ const was = resumeQueue(root);
1129
+ return out(
1130
+ was
1131
+ ? `The merge queue merges again (it was paused: ${was.reason}).`
1132
+ : "The merge queue wasn't paused.",
1133
+ );
1134
+ }
978
1135
  if (sub === 'add' || sub === 'drop') {
979
1136
  if (!branch) die(`code-kit queue ${sub} <branch>`);
980
1137
  if (sub === 'drop')
@@ -1017,8 +1174,25 @@ function queue() {
1017
1174
  if (sub === 'rules') return rulesOntoBase(root, config);
1018
1175
  if (sub === 'merge') {
1019
1176
  const byPerson = mergeMode();
1177
+ const paused = queuePause(root);
1178
+ if (paused)
1179
+ return out(
1180
+ `The merge queue is paused (${paused.reason}, since ${paused.at.slice(0, 16).replace('T', ' ')}): nothing was merged. code-kit queue resume lets it merge again.`,
1181
+ );
1182
+ // A queued branch whose commit the base already holds (merged outside the queue, or by a run that
1183
+ // couldn't record it) is settled as merged: never verified again, never sent back.
1184
+ const already = waiting(readQueue(root)).filter((e) => {
1185
+ const at = e.commit ?? branchTip(e.branch);
1186
+ return (
1187
+ at && spawnSync('git', ['-C', root, 'merge-base', '--is-ancestor', at, into]).status === 0
1188
+ );
1189
+ });
1190
+ for (const e of already) settle(root, e.branch, 'merged', `already in ${into}`);
1191
+ const settledWords = already.length
1192
+ ? `${already.map((e) => e.branch).join(', ')} ${already.length === 1 ? 'was' : 'were'} already merged into ${into}, so ${already.length === 1 ? 'it leaves' : 'they leave'} the queue as merged. `
1193
+ : '';
1020
1194
  const entries = readQueue(root);
1021
- if (!waiting(entries).length) return out('The merge queue is empty.');
1195
+ if (!waiting(entries).length) return out(`${settledWords}The merge queue is empty.`);
1022
1196
  // MQ-7: the first branch that can merge: one queued with partners waits until they're queued too.
1023
1197
  // HUBR-9: and one the team provider's drift findings hold waits until they clear.
1024
1198
  const drift = driftNow(
@@ -1026,8 +1200,20 @@ function queue() {
1026
1200
  waiting(entries).map((e) => e.branch),
1027
1201
  { fresh: true },
1028
1202
  );
1029
- const { head, partners, held, drifting } = nextToMerge(entries, drift.holds);
1030
- const holding = drifting.map((d) => drift.words(d.branch, d.findings));
1203
+ // LOOP-15: a branch whose story the lead holds waits, with its group, until the hold ends.
1204
+ const deferredBy = heldBranches(root, config);
1205
+ const { head, partners, held, drifting, deferred } = nextToMerge(
1206
+ entries,
1207
+ drift.holds,
1208
+ deferredBy,
1209
+ );
1210
+ const holding = [
1211
+ ...drifting.map((d) => drift.words(d.branch, d.findings)),
1212
+ ...deferred.map(
1213
+ (d) =>
1214
+ `${d.branch} waits: ${deferralWords(d.hold)} (code-kit defer release ${d.hold.story}).`,
1215
+ ),
1216
+ ];
1031
1217
  const unchecked = drift.note ? ` ${drift.note}` : '';
1032
1218
  if (!head) {
1033
1219
  const waits = held.map(
@@ -1035,7 +1221,7 @@ function queue() {
1035
1221
  `${h.branch} merges together with ${h.missing.join(', ')}, which ${h.missing.length === 1 ? "isn't" : "aren't"} queued yet`,
1036
1222
  );
1037
1223
  return out(
1038
- `Nothing can merge yet${waits.length ? `: ${waits.join('; ')}.` : '.'}${holding.length ? ` ${holding.join(' ')}` : ''}`,
1224
+ `${settledWords}Nothing can merge yet${waits.length ? `: ${waits.join('; ')}.` : '.'}${holding.length ? ` ${holding.join(' ')}` : ''}`,
1039
1225
  );
1040
1226
  }
1041
1227
  const group = [head, ...partners];
@@ -1073,20 +1259,26 @@ function queue() {
1073
1259
  const published = publishAfter(config, byPerson);
1074
1260
  const left = waiting(readQueue(root));
1075
1261
  return out(
1076
- `${message}${published}${left.length ? ` Next in the queue: ${left[0].branch}.` : ' The queue is empty.'}${holding.length ? ` ${holding.join(' ')}` : ''}${unchecked}`,
1262
+ `${settledWords}${message}${published}${left.length ? ` Next in the queue: ${left[0].branch}.` : ' The queue is empty.'}${holding.length ? ` ${holding.join(' ')}` : ''}${unchecked}`,
1077
1263
  );
1078
1264
  } catch (e) {
1079
1265
  if (!(e instanceof MergeStop)) throw e;
1080
- // MQ-3: a conflict or a failed verify goes back to the lane; a refusal leaves the queue as it is.
1081
- if (e.kind === 'refused') die(e.message);
1266
+ // MQ-3: a conflict or a failed verify goes back to the lane; a refusal leaves the queue as it is,
1267
+ // and so does an install or a check that couldn't run, which says nothing against the branch.
1268
+ if (['refused', 'unfinished', 'installs'].includes(e.kind)) die(e.message);
1269
+ if (e.kind === 'already') {
1270
+ for (const m of group) settle(root, m.branch, 'merged', `already in ${into}`);
1271
+ const left = waiting(readQueue(root));
1272
+ return out(
1273
+ `${e.message} It leaves the queue as merged.${left.length ? ` Next in the queue: ${left[0].branch}.` : ' The queue is empty.'}`,
1274
+ );
1275
+ }
1082
1276
  // A branch that moved after its review leaves the queue for the lead to review it again; it
1083
1277
  // isn't sent back, since nothing is wrong with it yet.
1084
- if (e.kind === 'unfinished') die(e.message);
1085
1278
  if (e.kind === 'moved') {
1086
1279
  settle(root, head.branch, 'moved', 'changed after its review');
1087
1280
  die(`${e.message}\n${head.branch} leaves the queue until then.`);
1088
1281
  }
1089
- const into = intoName ?? config.branches.protected[0];
1090
1282
  const after = lastMerged(entries);
1091
1283
  const why =
1092
1284
  e.kind === 'conflict'
@@ -1108,10 +1300,12 @@ function queue() {
1108
1300
  }
1109
1301
  if (sub !== undefined)
1110
1302
  die(
1111
- 'code-kit queue [--json] | queue add <branch> [--with <branch>,…] | queue drop <branch> | queue rules | queue merge --delegated|--person',
1303
+ 'code-kit queue [--json] | queue add <branch> [--with <branch>,…] | queue drop <branch> | queue rules | queue merge --delegated|--person | queue pause --reason "…" | queue resume',
1112
1304
  );
1113
1305
  const entries = readQueue(root);
1114
1306
  const left = waiting(entries);
1307
+ const paused = queuePause(root);
1308
+ const deferredBy = heldBranches(root, config);
1115
1309
  // HUBR-9: what the team provider's findings hold, as last read (a merge asks it again).
1116
1310
  const drift = driftNow(
1117
1311
  config,
@@ -1120,20 +1314,29 @@ function queue() {
1120
1314
  if (flag('--json'))
1121
1315
  return out(
1122
1316
  JSON.stringify(
1123
- entries.map((e) =>
1124
- left.includes(e) && drift.holds.has(e.branch)
1125
- ? { ...e, drift: drift.holds.get(e.branch) }
1126
- : e,
1127
- ),
1317
+ entries.map((e) => ({
1318
+ ...e,
1319
+ ...(left.includes(e) && drift.holds.has(e.branch)
1320
+ ? { drift: drift.holds.get(e.branch) }
1321
+ : {}),
1322
+ ...(left.includes(e) && deferredBy.has(e.branch)
1323
+ ? { deferred: deferredBy.get(e.branch) }
1324
+ : {}),
1325
+ ...(left.includes(e) && paused ? { paused } : {}),
1326
+ })),
1128
1327
  null,
1129
1328
  2,
1130
1329
  ),
1131
1330
  );
1331
+ if (paused)
1332
+ out(
1333
+ `The merge queue is paused: ${paused.reason} (since ${paused.at.slice(0, 16).replace('T', ' ')}). code-kit queue resume lets it merge again.`,
1334
+ );
1132
1335
  if (!left.length) out('The merge queue is empty.');
1133
1336
  else out(`${left.length} waiting to merge, in order:`);
1134
1337
  left.forEach((e, i) =>
1135
1338
  out(
1136
- ` ${i + 1}. ${e.branch} (passed review ${e.passed}${e.commit ? ` at ${e.commit.slice(0, 7)}` : ''})${drift.holds.has(e.branch) ? ' · held by the drift check' : ''}`,
1339
+ ` ${i + 1}. ${e.branch} (passed review ${e.passed}${e.commit ? ` at ${e.commit.slice(0, 7)}` : ''})${drift.holds.has(e.branch) ? ' · held by the drift check' : ''}${deferredBy.has(e.branch) ? ` · ${deferralWords(deferredBy.get(e.branch))}` : ''}`,
1137
1340
  ),
1138
1341
  );
1139
1342
  for (const [branch, findings] of drift.holds) out(drift.words(branch, findings));
@@ -1207,7 +1410,7 @@ function trailCommand() {
1207
1410
  die('trail needs docs.specs and docs.plan in the config. The spec-design skill writes both.');
1208
1411
  const from = base(config, false);
1209
1412
  const status = buildStatus('.', config, from, tracked());
1210
- const rows = trail(resolve('.'), status, from);
1413
+ const rows = trail(resolve('.'), status, from, config);
1211
1414
  if (flag('--json')) return out(JSON.stringify({ base: from, requirements: rows }, null, 2));
1212
1415
  for (const r of rows)
1213
1416
  out(
@@ -1671,6 +1874,69 @@ function releaseCommand(version) {
1671
1874
  );
1672
1875
  }
1673
1876
 
1877
+ /**
1878
+ * LOOP-15: stories the lead holds on purpose. `defer <story>… --reason "…" [--until <date|ISO time>]`
1879
+ * holds them: `next`, the loop and the merge queue don't dispatch, review or merge them until the time
1880
+ * comes or `defer release <story>…`. `defer [--json]` lists the holds in force.
1881
+ */
1882
+ function deferCommand() {
1883
+ const { config } = load();
1884
+ const root = mainCheckout(resolve('.'));
1885
+ const [sub, ...ids] = rest;
1886
+ const usageLine =
1887
+ 'code-kit defer <story>… --reason "…" [--until <date|ISO time>] | defer release <story>… | defer [--json]';
1888
+ if (sub === undefined) {
1889
+ const holds = activeDeferrals(root);
1890
+ if (flag('--json')) return out(JSON.stringify(holds, null, 2));
1891
+ if (!holds.length) return out('No story is held.');
1892
+ out(`${holds.length} ${holds.length === 1 ? 'story is' : 'stories are'} held:`);
1893
+ for (const h of holds) out(` ${deferralWords(h)}`);
1894
+ return;
1895
+ }
1896
+ const isStory = (id) => /^[a-z][a-z0-9]*-\d+$/i.test(id);
1897
+ if (sub === 'release') {
1898
+ if (!ids.length || !ids.every(isStory)) die(usageLine);
1899
+ const ended = releaseStories(root, ids);
1900
+ const was = new Set(ended.map((h) => h.story));
1901
+ const notHeld = ids.map((id) => id.toUpperCase()).filter((id) => !was.has(id));
1902
+ return out(
1903
+ [
1904
+ ended.length
1905
+ ? `Released ${ended.map((h) => h.story).join(', ')}: ${ended.length === 1 ? 'it goes' : 'they go'} on as the plan has ${ended.length === 1 ? 'it' : 'them'}.`
1906
+ : null,
1907
+ notHeld.length
1908
+ ? `${notHeld.join(', ')} ${notHeld.length === 1 ? "wasn't" : "weren't"} held.`
1909
+ : null,
1910
+ ]
1911
+ .filter(Boolean)
1912
+ .join(' '),
1913
+ );
1914
+ }
1915
+ const stories = [sub, ...ids];
1916
+ if (!stories.every(isStory)) die(usageLine);
1917
+ if (!reason?.trim())
1918
+ die(
1919
+ 'code-kit defer needs --reason "…": what the story waits on, so the person and the band can see why it isn\'t moving.',
1920
+ );
1921
+ const { until, error } = parseUntil(untilGiven);
1922
+ if (error) die(error);
1923
+ const plan = config.docs?.plan;
1924
+ if (plan) {
1925
+ const known = new Set(readStories(root, plan).map((s) => s.id));
1926
+ const unknown = stories.map((s) => s.toUpperCase()).filter((s) => !known.has(s));
1927
+ if (unknown.length)
1928
+ die(`There is no story ${unknown.join(', ')} in ${plan}; nothing was held.`);
1929
+ }
1930
+ const made = deferStories(root, stories, {
1931
+ reason: reason.trim(),
1932
+ until,
1933
+ session: callerSession,
1934
+ });
1935
+ out(
1936
+ `${made.map(deferralWords).join('. ')}. Nothing dispatches, reviews or merges ${made.length === 1 ? 'it' : 'them'} until ${until ? 'then, or ' : ''}code-kit defer release ${made.map((h) => h.story).join(' ')}.`,
1937
+ );
1938
+ }
1939
+
1674
1940
  /** Records the review's send-back of `branch` at its current commit (lib/reviews.mjs). */
1675
1941
  function sentBackCommand(branch) {
1676
1942
  load();
@@ -1757,7 +2023,7 @@ function verify() {
1757
2023
  }
1758
2024
  }
1759
2025
  const lane = laneOfBranch(branch, config);
1760
- const { changed, found, skipped } = verifyBranch({
2026
+ const { changed, found, skipped, evidenceUnchecked } = verifyBranch({
1761
2027
  root: resolve('.'),
1762
2028
  base: from,
1763
2029
  config,
@@ -1771,7 +2037,16 @@ function verify() {
1771
2037
  const count = Object.values(found).reduce((n, list) => n + list.length, 0);
1772
2038
  out(
1773
2039
  JSON.stringify(
1774
- { base: from, branch, lane, changed: changed.length, found, problems: count, skipped },
2040
+ {
2041
+ base: from,
2042
+ branch,
2043
+ lane,
2044
+ changed: changed.length,
2045
+ found,
2046
+ problems: count,
2047
+ skipped,
2048
+ evidenceUnchecked: Boolean(evidenceUnchecked),
2049
+ },
1775
2050
  null,
1776
2051
  2,
1777
2052
  ),
@@ -1790,6 +2065,10 @@ function verify() {
1790
2065
  for (const p of found[key]) out(` ${p.split('\n').join('\n ')}`);
1791
2066
  }
1792
2067
  if (skipped.length) out(`\n${notRun(skipped)}`);
2068
+ if (evidenceUnchecked)
2069
+ out(
2070
+ `\nNot checked: whether the review compared each built screen with its design (HAND-7). The review's records are kept with the lead (.claude/state/), not here; the merge queue checks them.`,
2071
+ );
1793
2072
  if (count) die(`\n${count} problem(s). Fix them on this branch.`);
1794
2073
  out(skipped.length ? 'No problems in what ran.' : 'No problems.');
1795
2074
  }
@@ -2947,6 +3226,7 @@ function designsCommand() {
2947
3226
  if (!config.designGate) die('The project has no design gate (designGate in the config).');
2948
3227
  const { entries, error } = readRegister(root, config);
2949
3228
  if (error) die(error);
3229
+ if (rest[0] === 'evidence') return designEvidence(root, config, entries);
2950
3230
  const story = rest[0];
2951
3231
  const stories = config.docs?.plan ? readStories(root, config.docs.plan) : [];
2952
3232
  const shown = (story ? designsFor(entries, story, stories) : entries).map((e) => ({
@@ -2974,6 +3254,86 @@ function designsCommand() {
2974
3254
  }
2975
3255
  }
2976
3256
 
3257
+ /**
3258
+ * HAND-7: `designs evidence <story> <screen> <state> <screenshot.png>`: the review's screenshot of a
3259
+ * built state, taken at its design's viewport and set beside the design's PNG, recorded for the story's
3260
+ * branch at its current commit. verify, and so the merge queue, report each approved state of the
3261
+ * screens a branch builds that has none.
3262
+ */
3263
+ function designEvidence(root, config, entries) {
3264
+ const [, storyArg, screenArg, stateArg, png] = rest;
3265
+ if (!storyArg || !screenArg || !stateArg || !png)
3266
+ die(
3267
+ 'Usage: code-kit designs evidence <story> <screen file or name> <state> <screenshot.png>, after setting the screenshot of the built state beside its design.',
3268
+ );
3269
+ const stories = config.docs?.plan ? readStories(root, config.docs.plan) : [];
3270
+ const story = stories.find((s) => s.id.toLowerCase() === storyArg.toLowerCase());
3271
+ const branch = story ? `${story.lane}/${story.id.toLowerCase()}` : storyArg;
3272
+ const sha =
3273
+ spawnSync('git', ['-C', root, 'rev-parse', '--verify', '--quiet', `${branch}^{commit}`], {
3274
+ encoding: 'utf8',
3275
+ }).stdout?.trim() ?? '';
3276
+ if (!sha)
3277
+ die(
3278
+ `${storyArg} has no branch here (${branch}): name the story whose branch you reviewed, or its branch.`,
3279
+ );
3280
+ const designs = (story ? designsFor(entries, story.id, stories) : entries).filter(handedOver);
3281
+ const key = (v) =>
3282
+ String(v ?? '')
3283
+ .trim()
3284
+ .toLowerCase();
3285
+ const byFile = designs.filter((e) => e.file === screenArg);
3286
+ const matching = byFile.length ? byFile : designs.filter((e) => key(e.screen) === key(screenArg));
3287
+ if (!matching.length)
3288
+ die(
3289
+ `${screenArg} isn't a screen with an approved design ${story ? `for ${story.id}` : 'in the register'}. \`code-kit designs${story ? ` ${story.id}` : ''}\` lists them; name its file or its screen.`,
3290
+ );
3291
+ if (matching.length > 1)
3292
+ die(
3293
+ `${screenArg} names more than one screen file (${matching.map((e) => e.file).join(', ')}): name the file the screenshot is of.`,
3294
+ );
3295
+ const [entry] = matching;
3296
+ const state = entry.states.find((st) => key(st?.name) === key(stateArg));
3297
+ if (!state)
3298
+ die(
3299
+ `${entry.screen ?? entry.file} has no approved ${stateArg} state; its states are ${entry.states.map((st) => st.name).join(', ')}.`,
3300
+ );
3301
+ let bytes;
3302
+ try {
3303
+ bytes = readFileSync(resolve(png));
3304
+ } catch {
3305
+ die(`${png} isn't there: take the screenshot of the built state first.`);
3306
+ }
3307
+ const size = pngSize(bytes);
3308
+ if (!size) die(`${png} isn't a PNG: save the screenshot as a PNG.`);
3309
+ if (!atViewport(size, state.viewport))
3310
+ die(
3311
+ `${png} is ${size.width}x${size.height}, not taken at the design's viewport (${state.viewport}, at 1x to 4x): take it again at ${state.viewport}, so it can be set beside ${state.image}.`,
3312
+ );
3313
+ const slug = (v) => String(v).replace(/[^\w.-]+/g, '_');
3314
+ const kept = posix.join(slug(branch), slug(entry.file), `${slug(state.name)}.png`);
3315
+ const dir = evidenceDir(root);
3316
+ mkdirSync(join(dir, posix.dirname(kept)), { recursive: true });
3317
+ writeFileSync(join(dir, kept), bytes);
3318
+ const image = posix.join('.claude/state/reviews', kept);
3319
+ recordEvidence(root, {
3320
+ branch,
3321
+ sha,
3322
+ story: story?.id ?? null,
3323
+ file: entry.file,
3324
+ screen: entry.screen ?? null,
3325
+ state: state.name,
3326
+ design: state.image,
3327
+ image,
3328
+ sha256: sha256Of(dir, kept),
3329
+ viewport: state.viewport ?? null,
3330
+ size: `${size.width}x${size.height}`,
3331
+ });
3332
+ out(
3333
+ `Recorded: ${entry.screen ?? entry.file}'s ${state.name} state on ${branch} at ${sha.slice(0, 7)}, beside ${state.image} (kept as ${image}).`,
3334
+ );
3335
+ }
3336
+
2977
3337
  const commands = {
2978
3338
  check,
2979
3339
  designs: designsCommand,
@@ -2992,6 +3352,7 @@ const commands = {
2992
3352
  decisions: decisionsCommand,
2993
3353
  task: taskCommand,
2994
3354
  hold: () => (rest.length === 1 ? hold(rest[0]) : usage()),
3355
+ defer: deferCommand,
2995
3356
  queue,
2996
3357
  team: teamCommand,
2997
3358
  intend: intendCommand,
@@ -3027,6 +3388,7 @@ function usage() {
3027
3388
  ' | next [--base ref] [--json] | adapters | trace <path>... [--json]\n' +
3028
3389
  ' | instructions [--write] [--json] | instructions show lead|lane [<lane>]\n' +
3029
3390
  ' | standards [--json] [--for <path>...] | designs [<story>] [--json]\n' +
3391
+ ' | designs evidence <story> <screen file or name> <state> <screenshot.png>\n' +
3030
3392
  ' | worktrees [--json] | worktrees release|discard <branch> | worktrees prune [--quiet]\n' +
3031
3393
  ' | approve <name>... --reason "…" [--lane name] [--config file]\n' +
3032
3394
  ' | merge <branch> --delegated|--person [--into branch] | publish --delegated|--person\n' +
@@ -3044,6 +3406,8 @@ function usage() {
3044
3406
  ' | ci check [--json] | ci usage [--days N] [--json] | release <version>\n' +
3045
3407
  ' | hold <id> [--minutes N] | hold <id> --answer approved|refused\n' +
3046
3408
  ' | queue [--json] | queue add|drop <branch> | queue rules | queue merge --delegated|--person\n' +
3409
+ ' | queue pause --reason "…" | queue resume\n' +
3410
+ ' | defer <story>... --reason "…" [--until <date|ISO time>] | defer release <story>... | defer [--json]\n' +
3047
3411
  ' | loop [--json] | loop pause|resume | loop lead|release --session id [--take]\n' +
3048
3412
  ' | map <story>|project [--json] | trail [--json] | journal [--json]\n' +
3049
3413
  ' | story <id> [--json] | timeline [--json]\n' +