@warren-dean/code-kit 0.33.0 → 0.35.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.
@@ -7,7 +7,9 @@
7
7
  // project's installs in and deleting them again on every merge is millions of files each time, which
8
8
  // keeps the machine's file-change tracking and search indexing busy. Each run checks out the tree it
9
9
  // needs, and installs again only where its manifests and lockfiles differ from the ones the kept
10
- // installs were made for. The folder's name ends in .noindex, which Spotlight leaves alone.
10
+ // installs were made for. The folder's name ends in .noindex, which Spotlight leaves alone. The OS
11
+ // empties old files out of its temporary folder and leaves the folders and links, so a run counts the
12
+ // kept installs' files, and copies them again when any have gone.
11
13
  import { createHash } from 'node:crypto';
12
14
  import { execFileSync, spawnSync } from 'node:child_process';
13
15
  import {
@@ -16,6 +18,7 @@ import {
16
18
  mkdirSync,
17
19
  mkdtempSync,
18
20
  openSync,
21
+ readdirSync,
19
22
  readFileSync,
20
23
  realpathSync,
21
24
  rmSync,
@@ -106,6 +109,26 @@ function dependencyHashes(dir) {
106
109
  return hashes;
107
110
  }
108
111
 
112
+ // The files in a kept checkout's installs, and how many there were when they were made. Tools' caches
113
+ // come and go on their own, so they don't count. A folder that can't be read counts as empty.
114
+ const countOf = (dir) => `${dir}.installs.count`;
115
+ function installedFiles(dir) {
116
+ let files = 0;
117
+ for (const rel of installsOf(dir)) {
118
+ try {
119
+ for (const e of readdirSync(join(dir, rel), { recursive: true, withFileTypes: true }))
120
+ if (e.isFile() && !/[\\/]\.cache(?:[\\/]|$)/.test(e.parentPath)) files++;
121
+ } catch {
122
+ // gone while being read: fewer files, so it's copied again
123
+ }
124
+ }
125
+ return files;
126
+ }
127
+ const recordInstalled = (dir) => writeFileSync(countOf(dir), String(installedFiles(dir)));
128
+ /** Whether a kept checkout's installs have lost files, or lost the records of what they were made for. */
129
+ const hollow = (dir) =>
130
+ !existsSync(stampOf(dir)) || !(installedFiles(dir) >= Number(readFileSafe(countOf(dir)) || NaN));
131
+
109
132
  /** Takes the kept checkout's lock for this process, or false while another live process holds it. */
110
133
  function lock(slot) {
111
134
  const file = `${slot}.lock`;
@@ -243,10 +266,19 @@ export function freshCheckout(
243
266
  throw Object.assign(new Error(why || 'the merge conflicts'), { conflict: true });
244
267
  }
245
268
  }
269
+ // MQ-9: the OS took files out of the kept installs: they can't be trusted, so they're copied again.
270
+ // What they're copied from may be behind the base by now, so the stamp names nothing, and the
271
+ // project's install runs over the copy for this tree.
272
+ const emptied = installsFrom && dir === slot && installsOf(dir).length > 0 && hollow(dir);
273
+ if (emptied)
274
+ for (const rel of installsOf(dir)) rmSync(join(dir, rel), { recursive: true, force: true });
246
275
  if (installsFrom && !installsOf(dir).length) {
247
276
  copyInstalls(installsFrom, dir);
248
277
  // The copied installs were made for installsFrom's manifests and lockfiles.
249
- if (dir === slot) writeFileSync(stampOf(dir), JSON.stringify(dependencyHashes(installsFrom)));
278
+ if (dir === slot) {
279
+ writeFileSync(stampOf(dir), JSON.stringify(emptied ? {} : dependencyHashes(installsFrom)));
280
+ recordInstalled(dir);
281
+ }
250
282
  }
251
283
  return { dir, remove };
252
284
  }
@@ -351,7 +383,10 @@ export function matchInstalls(dir, from, { prepare = null, timeout = 900000 } =
351
383
  const stamp = stampOf(dir);
352
384
  if (res.status === 0) {
353
385
  // A kept checkout's installs now match this tree.
354
- if (existsSync(stamp)) writeFileSync(stamp, JSON.stringify(dependencyHashes(dir)));
386
+ if (existsSync(stamp)) {
387
+ writeFileSync(stamp, JSON.stringify(dependencyHashes(dir)));
388
+ recordInstalled(dir);
389
+ }
355
390
  return { ...facts, command, failed: null };
356
391
  }
357
392
  // What a failed install left can't be trusted: the next run copies the installs afresh.
@@ -28,6 +28,21 @@ export const SETTINGS = {
28
28
  about:
29
29
  "How the lead loop acts: on its own, by proposing each step, or not at all; vibe is on its own with every decision the lead's, and you only asked for accounts, keys and payments",
30
30
  },
31
+ 'loop.quietMinutes': {
32
+ default: 10,
33
+ problem: (v) =>
34
+ Number.isFinite(v) && v >= 0 && v <= 120
35
+ ? null
36
+ : 'must be a number of minutes from 0 (off) to 120',
37
+ about:
38
+ "How long the loop waits after you last spoke, while you're talking with the lead about something other than the build; 0 for not at all",
39
+ },
40
+ 'loop.check': {
41
+ default: true,
42
+ problem: (v) => (typeof v === 'boolean' ? null : 'must be true or false'),
43
+ about:
44
+ "Check each step against the project as it is now (git, the queue, the agents at work, the lead's last replies) before the lead is prompted with it",
45
+ },
31
46
  'hold.minutes': {
32
47
  default: 2,
33
48
  problem: (v) =>
@@ -15,7 +15,7 @@ import {
15
15
  import { registerFile } from './costs.mjs';
16
16
 
17
17
  /** The version of code-kit's instructions: raised whenever the templates' rules change. */
18
- export const INSTRUCTIONS_VERSION = 12;
18
+ export const INSTRUCTIONS_VERSION = 14;
19
19
 
20
20
  const TEMPLATES = fileURLToPath(new URL('../../templates/', import.meta.url));
21
21
  const BEGIN = (v) => `<!-- code-kit:begin v${v} -->`;
@@ -111,12 +111,14 @@ const AGENT_LEGACY = /^Always:\s*$/;
111
111
 
112
112
  /**
113
113
  * Where a file's code-kit part stands: `current`; `stale` (marked, from an older code-kit or an older
114
- * config); `legacy` (written before the markers, often tailored by hand, so merged once by the lead, not
114
+ * config); `ahead` (marked by a newer code-kit than this one, as when a teammate has updated: never
115
+ * written back to this one's older rules); `legacy` (written before the markers, often tailored by hand, so merged once by the lead, not
115
116
  * overwritten); or `missing` (none yet).
116
117
  */
117
118
  function stateOf(text, block, legacy) {
118
119
  const m = MARKED.exec(text);
119
120
  // A formatter that rewraps the project's markdown doesn't make code-kit's part out of date.
121
+ if (m && Number(m[1]) > INSTRUCTIONS_VERSION) return { state: 'ahead', version: Number(m[1]) };
120
122
  if (m) return { state: same(m[0], block) ? 'current' : 'stale', version: Number(m[1]) };
121
123
  if (text.split('\n').some((l) => legacy.test(l))) return { state: 'legacy', version: 0 };
122
124
  return { state: 'missing', version: null };
@@ -437,6 +437,12 @@ export function nextStep(root, base) {
437
437
  attention.push(
438
438
  `${none.map((f) => f.file).join(', ')} ${none.length === 1 ? 'has' : 'have'} none of code-kit's instructions; \`code-kit instructions --write\` adds them.`,
439
439
  );
440
+ // Newer than this code-kit: a teammate updated first. The session's own code-kit is what's behind.
441
+ const ahead = instructions.filter((f) => f.state === 'ahead');
442
+ if (ahead.length)
443
+ attention.push(
444
+ `code-kit's instructions in ${ahead.map((f) => f.file).join(', ')} come from a newer code-kit than this session's: don't write them back. Run /plugin marketplace update code-kit and restart Claude Code.`,
445
+ );
440
446
  if (behind.length) {
441
447
  const legacy = behind.filter((f) => f.state === 'legacy');
442
448
  return result(
@@ -9,6 +9,7 @@ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
9
9
  import { isAbsolute, join } from 'node:path';
10
10
  import { readEvents } from './events.mjs';
11
11
  import { laneClaims } from './laneclaims.mjs';
12
+ import { readQueue, waiting } from './queue.mjs';
12
13
  import { waitingStories } from './questions.mjs';
13
14
  import { sentBack } from './reviews.mjs';
14
15
  import { isTestFile } from './testfiles.mjs';
@@ -405,7 +406,7 @@ function worktrees(root) {
405
406
  /**
406
407
  * Where each story is. The plan's `done` stands (the lead marks it after merging, and merged
407
408
  * branches are often deleted or squashed). Otherwise git decides: a branch with commits not in
408
- * `base` is in review. A branch still at the commit a review sent back is `sent back`, waiting for
409
+ * `base` is in review. A branch with commits ahead, still at the commit a review sent back, is `sent back`, waiting for
409
410
  * its lane's fix. Without a branch, the plan's status stands. A story is `blocked` while a story it
410
411
  * depends on isn't done, whatever its branch holds; a todo story whose dependencies are done is `ready`.
411
412
  * A story with an open question for the person that holds it (`code-kit ask --blocks`) is `waiting on
@@ -426,6 +427,10 @@ function worktrees(root) {
426
427
  export function storyStates(root, stories, base, { designing = null } = {}) {
427
428
  const trees = worktrees(root);
428
429
  const backs = sentBack(root);
430
+ // Queued again since its send-back, at that same commit: a review passed it, and it waits to merge.
431
+ const queued = waiting(readQueue(root));
432
+ const requeued = (branch, back) =>
433
+ queued.some((e) => e.branch === branch && e.commit === back.sha && e.passed > back.at);
429
434
  const refs = branchRefs(root, base);
430
435
  const claims = laneClaims(root).filter((c) => !c.stale);
431
436
  const live = new Set(claims.map((c) => `${c.lane}|${c.story ?? ''}`));
@@ -464,7 +469,8 @@ export function storyStates(root, stories, base, { designing = null } = {}) {
464
469
  let stopped = false;
465
470
  if (ref && !['done', DROPPED].includes(story.status)) {
466
471
  const head = backs[branch] ? refs[ref].sha : null;
467
- if (head && head === backs[branch].sha) state = 'sent back';
472
+ if (ahead > 0 && head && head === backs[branch].sha && !requeued(branch, backs[branch]))
473
+ state = 'sent back';
468
474
  else if (ahead > 0)
469
475
  state =
470
476
  building(story) || (story.lane === DESIGN && designing?.(story, ref))
@@ -35,8 +35,9 @@ const SKIPS = [
35
35
  /@(?:Disabled|Ignore)\b/,
36
36
  ];
37
37
  // `expect(` and its retrying and soft forms (`expect.poll(`, `expect.soft(`), each one assertion.
38
+ // Python's and pytest's bare `assert x == y` statements count too, one per statement.
38
39
  const ASSERTION =
39
- /\bexpect(?:\.(?:poll|soft))?\s*\(|\bassert\w*\s*[.(]|\bt\.(?:Error|Errorf|Fatal|Fatalf|Fail)\b|\bshould\.\w/g;
40
+ /\bexpect(?:\.(?:poll|soft))?\s*\(|\bassert\w*\s*[.(]|(?<=^|\n)[ \t]*assert[ \t]+(?=[^\s(.=])|\bt\.(?:Error|Errorf|Fatal|Fatalf|Fail)\b|\bshould\.\w/g;
40
41
 
41
42
  const skipLines = (text) =>
42
43
  String(text ?? '')
@@ -3,23 +3,28 @@
3
3
  // (`git commit`, `code-kit merge`) look only at the simple commands it runs, each from its own start.
4
4
  // Rules about text the command carries (a commit trailer, a path in a redirect) still read it whole.
5
5
 
6
- /** The command with each heredoc's body taken out: the lines after `<<WORD` up to the line `WORD`. */
7
- export function withoutHeredocs(cmd) {
8
- const out = [];
6
+ /** The command's lines and its heredocs' bodies apart: a body is the lines after `<<WORD` up to the line `WORD`. */
7
+ function heredocsApart(cmd) {
8
+ const kept = [];
9
+ const bodies = [];
9
10
  let until = null;
10
11
  for (const line of String(cmd).split('\n')) {
11
12
  if (until) {
12
13
  if (line.trim() === until) until = null;
14
+ else bodies.push(line);
13
15
  continue;
14
16
  }
15
- out.push(line);
17
+ kept.push(line);
16
18
  // `<<WORD`, `<<-WORD`, `<<'WORD'` or `<<"WORD"`; not a `<<<` here-string, whose text is on the line.
17
19
  const m = line.match(/(?<!<)<<-?\s*(['"]?)([\w.-]+)\1(?!<)/);
18
20
  if (m && !line.includes('<<<')) until = m[2];
19
21
  }
20
- return out.join('\n');
22
+ return { kept: kept.join('\n'), bodies: bodies.join('\n') };
21
23
  }
22
24
 
25
+ /** The command with each heredoc's body taken out: the lines after `<<WORD` up to the line `WORD`. */
26
+ export const withoutHeredocs = (cmd) => heredocsApart(cmd).kept;
27
+
23
28
  /** `text` with every quoted character replaced by `_`, the quotes kept: same length, nothing inside to match. */
24
29
  export function maskQuotes(text) {
25
30
  let out = '';
@@ -113,7 +118,7 @@ const READERS = [
113
118
  /^(?:cd|pwd|cat|head|tail|wc|grep|egrep|fgrep|cut|jq|nl|tr|ls|stat|diff|cmp|echo|printf|true)(?:\s|$)/,
114
119
  // less with no log file of what it shows.
115
120
  /^(?!.*\s(?:-[a-zA-Z]*[oO]|--log-file\b|--LOG-FILE\b))less(?:\s|$)/,
116
- /^(?!.*\s(?:--output\b|-O|--open-files-in-pager\b))git(?:\s+(?:-C\s+\S+|--no-pager|-P))*\s+(?:diff|log|show|blame|grep|status|cat-file|ls-files|shortlog|rev-parse)(?:\s|$)/,
121
+ /^(?!.*\s(?:--output\b|-O|--open-files-in-pager\b))git(?:\s+(?:-C\s+\S+|--no-pager|-P))*\s+(?:diff|log|show|blame|grep|status|cat-file|ls-files|ls-tree|shortlog|rev-parse|rev-list|merge-base|check-ignore|check-attr|describe|name-rev|show-ref|for-each-ref|cherry)(?:\s|$)/,
117
122
  // git branch only listing branches or naming the current one: no name to create, move or delete.
118
123
  /^git(?:\s+(?:-C\s+\S+|--no-pager|-P))*\s+branch(?:\s+(?:--show-current|--list|-l|-a|--all|-r|--remotes|-vv?|--verbose|--no-color|--color|--merged|--no-merged))*\s*$/,
119
124
  // rg with no preprocessor; sort with no output file or compressor.
@@ -275,21 +280,48 @@ export function readsOnly(cmd) {
275
280
  );
276
281
  }
277
282
 
278
- // What could change what a later command in the line runs: a function or alias defined, a variable
279
- // set (PATH among them), a file sourced, a shell option.
283
+ // What could change what a later command in the line runs: a function or alias defined, a file sourced,
284
+ // a shell option, a variable exported, or one the shell or a command reads (PATH among them).
280
285
  const REDEFINES =
281
- /(?:^|[;&|\n(]\s*)(?:[\w.-]+\s*\(\s*\)|function\s|alias\s|unalias\s|source\s|\.\s|hash\s|enable\s|builtin\s|set\s|setopt\s|shopt\s|unset\s|export\s|typeset\s|declare\s|local\s|readonly\s|[A-Za-z_]\w*=)/;
286
+ /(?:^|[;&|\n(]\s*)(?:[\w.-]+\s*\(\s*\)|function\s|alias\s|unalias\s|source\s|\.\s|hash\s|enable\s|builtin\s|set\s|setopt\s|shopt\s|unset\s|export\s|typeset\s|declare\s|local\s|readonly\s)/;
287
+ const SHELL_READS =
288
+ /^(?:PATH|path|FPATH|fpath|CDPATH|cdpath|IFS|ENV|BASH_ENV|ZDOTDIR|HOME|LD_\w*|DYLD_\w*|GIT_\w*|XDG_\w*)$/;
289
+ // A function defined in the line: `name() {` or `function name`. One that no reading part calls can't
290
+ // change what that part runs; what its body runs is judged as the line's other commands are.
291
+ const DEFINES_FUNCTION =
292
+ /(?:^|[;&|\n(]\s*)(?:function\s+([\w.-]+)(?:\s*\(\s*\))?|([\w.-]+)\s*\(\s*\))/g;
293
+ function definedFunctions(code) {
294
+ const names = [...code.matchAll(DEFINES_FUNCTION)].map(([, a, b]) => a ?? b);
295
+ // What else the line redefines, a function's body counted, since a call runs it.
296
+ const rest = code.replace(DEFINES_FUNCTION, ';').replace(/[{}]/g, ';');
297
+ return { names, rest };
298
+ }
299
+ // Any other variable set in the line (`CK=…/code-kit.mjs`) stays in the shell: no command it runs sees
300
+ // it, unless it was exported already, and what names it is judged on its own.
301
+ const setsWhatRuns = (code) =>
302
+ [...code.matchAll(/(?:^|[;&|\n(]\s*)([A-Za-z_]\w*)(?:\[[^\]]*\])?\+?=/g)].some(
303
+ ([, name]) => SHELL_READS.test(name) || name in process.env,
304
+ );
282
305
 
283
306
  /**
284
307
  * The parts of `cmd` that name `pattern`, each a pipeline (`a | b`) of its own, that don't only read
285
- * (readsOnly): what a rule for a file only reads may hold. A line with a heredoc, or one that could
286
- * change what its commands run (REDEFINES), is one part, judged whole.
308
+ * (readsOnly): what a rule for a file only reads may hold. A line with a heredoc whose body names
309
+ * `pattern`, or one that could change what its commands run (REDEFINES), is one part, judged whole; a
310
+ * heredoc that doesn't name it is judged like any other command that doesn't, and so is a function
311
+ * defined, unless a part that names `pattern` calls it.
287
312
  */
288
313
  export function unreadNames(cmd, pattern) {
289
314
  const read = withoutHarmlessRedirects(cmd);
290
315
  const code = codeOf(read);
291
316
  if (!pattern.test(cmd)) return [];
292
- if (/<</.test(cmd) || REDEFINES.test(code)) return readsOnly(cmd) ? [] : [cmd];
317
+ const functions = definedFunctions(code);
318
+ if (
319
+ pattern.test(heredocsApart(cmd).bodies) ||
320
+ REDEFINES.test(functions.rest) ||
321
+ setsWhatRuns(code)
322
+ )
323
+ return readsOnly(cmd) ? [] : [cmd];
324
+ const calls = (p) => commandsOf(p).some(({ text: t }) => functions.names.includes(wordsOf(t)[0]));
293
325
  const text = withoutHeredocs(read);
294
326
  const parts = [];
295
327
  let start = 0;
@@ -310,7 +342,9 @@ export function unreadNames(cmd, pattern) {
310
342
  new RegExp(String.raw`^${GIT}(?:commit|merge|revert|cherry-pick|rebase|am|pull)(?![\w-])`),
311
343
  );
312
344
  return parts.filter(
313
- (p) => pattern.test(p) && !readsOnly(p) && !(restores && restoresFromHead(p, pattern)),
345
+ (p) =>
346
+ pattern.test(p) &&
347
+ (calls(p) || (!readsOnly(p) && !(restores && restoresFromHead(p, pattern)))),
314
348
  );
315
349
  }
316
350
 
@@ -237,6 +237,8 @@ const NOTES = new Set([
237
237
  'drift',
238
238
  'queuePaused',
239
239
  'deferred',
240
+ 'talking',
241
+ 'holding',
240
242
  ]);
241
243
 
242
244
  /** What a line is, in a word or two, for the Needs you panel. */
@@ -113,6 +113,13 @@ export function storiesSignature(ids, stories = [], heads = new Map(), inFlight
113
113
  .join('|');
114
114
  }
115
115
 
116
+ /**
117
+ * LOOP-15: what the lead is told about stories it was asked about before, that waited the park's half
118
+ * hour with nothing they watch moving.
119
+ */
120
+ export const holdHint = (ids, { cli = 'code-kit' } = {}) =>
121
+ `${ids.join(', ')} ${ids.length === 1 ? 'was' : 'were'} left half an hour ago with nothing ${ids.length === 1 ? 'it waits' : 'they wait'} on moving since. If ${ids.length === 1 ? 'it waits' : 'they wait'} on a date or on something outside the build, hold ${ids.length === 1 ? 'it' : 'each'} instead, so the loop stops asking: node "${cli}" defer ${ids[0]} --reason "<what it waits on>" [--until <date>].`;
122
+
116
123
  /** The story ids a step names, upper-cased: `review ST-158 ST-172` gives ST-158 and ST-172. */
117
124
  export const stepStories = (step) =>
118
125
  STORY_STEPS.has(step?.stepKind ?? step?.kind ?? step?.step)
@@ -260,25 +267,37 @@ const ANSWER_SHOWN = 4000;
260
267
  * lead's own conversation (so it knows the whole exchange), with the reply itself for a call that
261
268
  * can't fork. `prompt` is the loop's own prompt for that turn, or null when the person started it.
262
269
  */
263
- export function outcomePrompt({ prompt = null, answer = '' }) {
270
+ export function outcomePrompt({ prompt = null, answer = '', said = null }) {
264
271
  const reply = String(answer ?? '').trim();
265
272
  const shown =
266
273
  reply.length > ANSWER_SHOWN ? `${reply.slice(0, ANSWER_SHOWN)}\n[… cut short]` : reply;
274
+ const person = !prompt && String(said ?? '').trim() ? clip(String(said).trim()) : null;
267
275
  return [
268
276
  prompt
269
277
  ? `code-kit's lead loop prompted you: "${prompt}"`
270
- : "The person prompted you, and code-kit's lead loop is about to prompt you with the build's next step.",
278
+ : person
279
+ ? `The person prompted you:\n"""\n${person}\n"""\ncode-kit's lead loop is about to prompt you with the build's next step.`
280
+ : "The person prompted you, and code-kit's lead loop is about to prompt you with the build's next step.",
271
281
  `Your reply ended your turn. It read:\n"""\n${shown}\n"""`,
272
282
  'Say where that reply left things, so the loop knows whether to prompt you again. Answer with one JSON object and nothing else:',
273
- '{"outcome": "done" | "started" | "needs-person" | "blocked" | "waiting", "question": "…", "options": [{"label": "…", "effect": "…"}], "reason": "…", "waits": [{"story": "ST-n", "on": ["ST-n"], "why": "…"}]}',
283
+ `{"outcome": "done" | "started" | "needs-person" | "blocked" | "waiting", "question": "…", "options": [{"label": "…", "effect": "…"}], "reason": "…", "waits": [{"story": "ST-n", "on": ["ST-n"], "why": "…"}]${person ? ', "talk": "build" | "conversation"' : ''}}`,
274
284
  '- done: you finished what was asked, or there was nothing to do.',
275
285
  '- started: you started work that carries on without you, such as lane agents.',
276
286
  "- needs-person: you asked the person something, or wait on their answer, approval or feedback before you go on. question: what you wait on, as one question; options: 2 to 4 answers they could give (a label of at most five words, and what it does), or [] when it's theirs to put in words.",
277
287
  "- waiting: the step isn't due yet for some or all of its stories: they wait on other work still going (a lane building a story they merge with, a rebuild, a check running). waits: one entry per story that waits, with the stories it waits on (their ST ids, [] when it's other work) and why, in a few words. Use this, not done, when you said a story can't be taken yet.",
278
288
  "- blocked: you didn't take the step, for a reason no answer from the person settles now and no work in flight will change. reason: why, in a sentence.",
289
+ ...(person
290
+ ? [
291
+ "- talk (LOOP-16): build when the person asked you to carry on with the build or to do its work; conversation when they're talking with you about something else (a question, a discussion, another task) or said not to build now, so a prompt from the loop would cut in.",
292
+ ]
293
+ : []),
279
294
  ].join('\n');
280
295
  }
281
296
 
297
+ /** A text cut to what a side call is shown. */
298
+ const clip = (text) =>
299
+ text.length > ANSWER_SHOWN ? `${text.slice(0, ANSWER_SHOWN)}\n[… cut short]` : text;
300
+
282
301
  /**
283
302
  * LOOP-11: the side call's answer: { outcome, question, options: [{ label, effect }], reason }, or
284
303
  * null when it isn't one (the loop then goes on as before).
@@ -314,9 +333,53 @@ export function readOutcome(text) {
314
333
  options: options.length >= 2 ? options : [],
315
334
  reason: words(parsed.reason, 300),
316
335
  waits,
336
+ talk: ['build', 'conversation'].includes(parsed.talk) ? parsed.talk : null,
317
337
  };
318
338
  }
319
339
 
340
+ /** LOOP-16: the band's words while the person talks with the lead. */
341
+ export const talkingText = (minutes) =>
342
+ `You're talking with the lead: the loop waits until you've been quiet for ${minutes} minute${minutes === 1 ? '' : 's'}`;
343
+
344
+ /** LOOP-17: the steps checked against the project before the lead is prompted (a design is the person's). */
345
+ export const CHECKED_STEPS = new Set([...LEAD_STEPS].filter((s) => s !== 'design'));
346
+
347
+ /** LOOP-17: how long a step judged not due waits before it's checked again, with the project moving. */
348
+ export const RECHECK_MS = 5 * 60_000;
349
+
350
+ /**
351
+ * LOOP-17: the side call that checks a step against the project as it is now, before the lead is
352
+ * prompted with it. `facts` is what the mod read itself: the step's stories and branches, the merge
353
+ * queue, the agents at work, the base's and this checkout's latest commits, and the lead's last replies.
354
+ */
355
+ export function checkPrompt({ prompt, facts }) {
356
+ return [
357
+ `code-kit's lead loop is about to prompt the lead: "${prompt}"`,
358
+ "The loop's step comes from code-kit's records, which can lag the work: a story already merged or committed, work already under way in an agent or a background run, or a step the lead already said why it won't take. Judge from the project as it is now, below, whether prompting the lead is still useful.",
359
+ `The project now:\n"""\n${clip(String(facts ?? '').trim())}\n"""`,
360
+ 'Answer with one JSON object and nothing else: {"due": true | false, "why": "…"}',
361
+ '- due false: the step is done already (its branch merged, its change on the base or this checkout), its work is under way (an agent at work on it, or the lead said a run is going and nothing since shows it finished), or the lead said why it is not taking the step and nothing it named has changed since. why: what shows it, in one sentence.',
362
+ '- due true: none of that shows; when unsure, due. why: what makes it due, in a few words.',
363
+ ].join('\n');
364
+ }
365
+
366
+ /** LOOP-17: the check's answer: { due, why }, or null when it isn't one (the step is then prompted). */
367
+ export function readCheck(text) {
368
+ const raw = String(text ?? '');
369
+ let parsed;
370
+ try {
371
+ parsed = JSON.parse(raw.slice(raw.indexOf('{'), raw.lastIndexOf('}') + 1));
372
+ } catch {
373
+ return null;
374
+ }
375
+ if (typeof parsed?.due !== 'boolean') return null;
376
+ const why =
377
+ typeof parsed.why === 'string' && parsed.why.trim()
378
+ ? parsed.why.replace(/\s+/g, ' ').trim().slice(0, 300)
379
+ : null;
380
+ return { due: parsed.due, why };
381
+ }
382
+
320
383
  /**
321
384
  * LOOP-12: a design is made with the person, so the loop hands a design story to the lead once; while
322
385
  * the stories `next` names have all been handed over, it leaves them to the person and the lead.