@turri-dev/cli 0.1.3 → 0.1.4-next.01530aa

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/dist/pi.js CHANGED
@@ -4,6 +4,7 @@ import { createAgentSession, DefaultResourceLoader, getAgentDir, ModelRegistry,
4
4
  import { loadRules, renderRulesBlock } from "./rules.js";
5
5
  import { inheritModel, stackOf, readProjectConfig, ROLE_THINKING, roleModel, roleTurnLimitMs, splitModelSpec } from "./config.js";
6
6
  import { maskToolResults } from "./regenerate/masking.js";
7
+ import { withListArguments } from "./regenerate/list-arguments.js";
7
8
  import { checkAgainstScript, ENVIRONMENT_ERROR_TOOL, EnvironmentError, environmentErrorTool, sandboxGapOf } from "./regenerate/environment-error.js";
8
9
  import { MODULES_DIR, projectRootOf, sessionsDir } from "./regenerate/paths.js";
9
10
  import { currentStopSignal, describeToolCall, describeToolResult, JobStoppedError, shownName, reportActivity, reportNow, reportAgent, reportTranscript, reportModelEvent, reportUsage, } from "./regenerate/activity.js";
@@ -146,6 +147,19 @@ export class ProviderError extends Error {
146
147
  this.name = "ProviderError";
147
148
  }
148
149
  }
150
+ /** Why turri itself ended a session's turn under way: the abort that comes back is its own, not the provider failing. */
151
+ const harnessStops = new WeakMap();
152
+ /**
153
+ * End the agent's turn, turri's own doing - it is going round in a circle, its time is up. The turn ends as any turn
154
+ * does: what the agent said stands, and the harness goes on from there. Never a provider error.
155
+ */
156
+ export function stopTurn(session, reason) {
157
+ if (session === undefined || harnessStops.has(session))
158
+ return;
159
+ harnessStops.set(session, reason);
160
+ reportModelEvent({ kind: "stopped", ...modelEventOf(session), reason });
161
+ void session.abort();
162
+ }
149
163
  /**
150
164
  * Run one turn and return the assistant's text, streaming deltas to `onDelta`.
151
165
  *
@@ -212,17 +226,32 @@ async function askUnrestricted(session, text, onDelta) {
212
226
  catch (error) {
213
227
  if (!(error instanceof ProviderError) || !TRANSIENT_PROVIDER_ERROR.test(error.message) || attempt >= PROVIDER_RETRIES)
214
228
  throw error;
215
- const wait = PROVIDER_RETRY_DELAY_MS * 2 ** attempt;
216
- reportActivity(` the model provider is failing for now - trying again in ${Math.round(wait / 1000)}s (${attempt + 1} of ${PROVIDER_RETRIES})`);
217
- debugLogOf(session)?.note(`provider failing - trying again in ${Math.round(wait / 1000)}s: ${error.message.slice(0, 200)}`);
229
+ const wait = providerRetryDelay(attempt);
230
+ const shown = `${Math.round(wait / 1000)}s (${attempt + 1} of ${PROVIDER_RETRIES})`;
231
+ reportActivity(` the model provider is failing for now - trying again in ${shown}`);
232
+ reportNow(`the model provider is failing - trying again in ${shown}`);
233
+ reportModelEvent({ kind: "provider_retry", ...modelEventOf(session), error: error.message, attempt: attempt + 1, of: PROVIDER_RETRIES, waitMs: wait });
234
+ debugLogOf(session)?.note(`provider failing - trying again in ${shown}: ${error.message.slice(0, 200)}`);
218
235
  await waitOrStop(wait);
236
+ reportNow(undefined);
219
237
  prompt = "Carry on where you were: the model provider failed part-way through your last turn.";
220
238
  }
221
239
  }
222
240
  }
223
- /** How many times, after pi's own retries, a turn whose provider failed for a moment is tried again - and the first wait, doubled each time. */
224
- export const PROVIDER_RETRIES = 3;
241
+ /**
242
+ * How many times, after pi's own retries, a turn whose provider failed for a moment is tried again; the first wait,
243
+ * doubled each time up to the longest - 15s, 30s, 1m, 2m, 4m, 5m: an outage of about 13 minutes is waited out.
244
+ */
245
+ export const PROVIDER_RETRIES = 6;
225
246
  export const PROVIDER_RETRY_DELAY_MS = Number(process.env.TURRI_PROVIDER_RETRY_DELAY ?? 15) * 1000;
247
+ export const PROVIDER_RETRY_MAX_DELAY_MS = 20 * PROVIDER_RETRY_DELAY_MS;
248
+ /** The wait before try `attempt + 1`: doubled each time, up to the longest, with a tenth either way so parallel jobs do not all come back at once. */
249
+ export function providerRetryDelay(attempt, random = Math.random) {
250
+ const base = Math.min(PROVIDER_RETRY_DELAY_MS * 2 ** attempt, PROVIDER_RETRY_MAX_DELAY_MS);
251
+ return Math.round(base * (0.9 + 0.2 * random()));
252
+ }
253
+ /** How long a request to the model may go without anything coming back before the provider is said to be stalling; 0 never. */
254
+ export const PROVIDER_STALL_MS = Number(process.env.TURRI_PROVIDER_STALL ?? 120) * 1000;
226
255
  /** A provider error that passes: overloaded, rate limited, unreachable, timed out. */
227
256
  const TRANSIENT_PROVIDER_ERROR = /\b(429|500|502|503|504|529)\b|overloaded|high demand|rate.?limit|too many requests|unavailable|fetch failed|network|connection|timed? ?out|ECONNRESET|socket|terminated/i;
228
257
  /** Wait, unless the job is stopped first. */
@@ -251,7 +280,7 @@ async function askOnce(session, text, onDelta) {
251
280
  // Calls to one tool failing one after another - arguments it refuses, or errors - with nothing going through.
252
281
  let failing = 0;
253
282
  let failingTool;
254
- let stoppedFailing = false;
283
+ harnessStops.delete(session);
255
284
  reportNow("waiting for the model");
256
285
  // Every entry says which agent it is from, and what it runs on - for reading one agent at a time.
257
286
  const agent = agentOf(session);
@@ -263,7 +292,30 @@ async function askOnce(session, text, onDelta) {
263
292
  if (agent !== undefined)
264
293
  reportAgent({ label: agent.label, ...(agent.model !== undefined ? { model: agent.model } : {}), turns: 1 });
265
294
  reportModelEvent({ kind: "turn", ...modelEventOf(session) });
295
+ // The provider stalling: a request to the model that nothing has come back on - not a token, not an error - for
296
+ // long. Said once for each silence; the turn goes on waiting, its own time limit ending it if it must.
297
+ let toolsRunning = 0;
298
+ let stall;
299
+ const watchForStall = (afterMs = PROVIDER_STALL_MS) => {
300
+ if (stall !== undefined)
301
+ clearTimeout(stall);
302
+ stall = toolsRunning > 0 || PROVIDER_STALL_MS <= 0 ? undefined : setTimeout(() => {
303
+ reportModelEvent({ kind: "provider_stall", ...modelEventOf(session), waitMs: PROVIDER_STALL_MS });
304
+ debugLogOf(session)?.note(`the provider has sent nothing back for ${seconds(PROVIDER_STALL_MS)}`);
305
+ }, afterMs);
306
+ };
266
307
  const unsubscribe = session.subscribe((event) => {
308
+ if (event.type === "tool_execution_start")
309
+ toolsRunning += 1;
310
+ if (event.type === "tool_execution_end")
311
+ toolsRunning = Math.max(0, toolsRunning - 1);
312
+ // pi tries a failed request again itself first: the provider failing is said then, not only once pi gives up.
313
+ if (event.type === "auto_retry_start") {
314
+ reportModelEvent({ kind: "provider_retry", ...modelEventOf(session), error: event.errorMessage, attempt: event.attempt, of: event.maxAttempts, waitMs: event.delayMs });
315
+ watchForStall(event.delayMs + PROVIDER_STALL_MS);
316
+ }
317
+ else
318
+ watchForStall();
267
319
  if (event.type === "message_update") {
268
320
  const update = event.assistantMessageEvent;
269
321
  if (update.type === "text_delta") {
@@ -308,14 +360,13 @@ async function askOnce(session, text, onDelta) {
308
360
  if (event.type === "tool_execution_end") {
309
361
  failing = event.isError ? (event.toolName === failingTool ? failing + 1 : 1) : 0;
310
362
  failingTool = event.isError ? event.toolName : undefined;
311
- if (failing >= FAILURES_BEFORE_STOP && !stoppedFailing) {
363
+ if (failing >= FAILURES_BEFORE_STOP && !harnessStops.has(session)) {
312
364
  // A call its tool refuses never reaches the tool, so no guard on the tools sees it: an agent can
313
365
  // make the same bad call, worded a little differently, thousands of times. Its turn ends here, and
314
366
  // the harness goes on from there, as after any turn.
315
- stoppedFailing = true;
316
367
  reportActivity(` stopped the agent's turn: ${failing} ${shownName(event.toolName)} calls failed in a row`);
317
368
  debugLogOf(session)?.note(`turn stopped: ${failing} ${event.toolName} calls failed in a row`);
318
- void session.abort();
369
+ stopTurn(session, `${failing} ${shownName(event.toolName)} calls failed in a row`);
319
370
  }
320
371
  const output = resultText(event.result);
321
372
  transcript({ kind: "result", text: clipText(output, MAX_TOOL_RESULT), error: event.isError, full: output });
@@ -376,7 +427,7 @@ async function askOnce(session, text, onDelta) {
376
427
  stopped = true;
377
428
  reportActivity(` stopped the agent's turn: its ${formatLimit(limitMs)} are up`);
378
429
  debug?.note(`turn stopped: its ${formatLimit(limitMs)} are up${how}`);
379
- void session.abort();
430
+ stopTurn(session, `its ${formatLimit(limitMs)} were up`);
380
431
  };
381
432
  const atNextRequest = timed
382
433
  ? session.subscribe((event) => {
@@ -392,6 +443,7 @@ async function askOnce(session, text, onDelta) {
392
443
  }
393
444
  // What the model is sent, and only that: its task is its system prompt, which the log already holds whole.
394
445
  debug?.prompt(text);
446
+ watchForStall();
395
447
  try {
396
448
  // Its images, when its conversation does not hold them: the first turn, and the first after a compaction.
397
449
  const images = sessionImages.get(session);
@@ -412,19 +464,24 @@ async function askOnce(session, text, onDelta) {
412
464
  clearTimeout(timer);
413
465
  if (backstop !== undefined)
414
466
  clearTimeout(backstop);
467
+ if (stall !== undefined)
468
+ clearTimeout(stall);
415
469
  atNextRequest?.();
416
470
  unsubscribe();
417
471
  stop?.removeEventListener("abort", onStop);
418
472
  reportNow(undefined);
419
473
  }
420
- if (stopped)
421
- out = `${out.trim()}\n\n[the turn was stopped: its ${formatLimit(limitMs)} were up]`.trim();
474
+ // turri ended the turn itself - its time was up, the agent went round in a circle: the abort that ended it is its own.
475
+ const stoppedFor = harnessStops.get(session);
476
+ harnessStops.delete(session);
477
+ if (stoppedFor !== undefined)
478
+ out = `${out.trim()}\n\n[the turn was stopped: ${stoppedFor}]`.trim();
422
479
  if (stop?.aborted) {
423
480
  debug?.note(`turn stopped on request after ${seconds(Date.now() - turnStarted)}`);
424
481
  throw new JobStoppedError();
425
482
  }
426
- // A turn ended for its time is ended, whatever the provider was doing then.
427
- if (providerError !== undefined && !stopped) {
483
+ // A turn turri ended is ended, whatever the provider was doing then: what comes back of the abort is not the provider failing.
484
+ if (providerError !== undefined && stoppedFor === undefined) {
428
485
  debug?.note(`turn ended with a provider error after ${seconds(Date.now() - turnStarted)}: ${providerError}`);
429
486
  throw new ProviderError(`${session.model?.id ?? "model"}: ${providerError}`);
430
487
  }
@@ -614,7 +671,7 @@ export function guardRepeats(tools, session, budget) {
614
671
  refused += 1;
615
672
  if (refused > REFUSED_BEFORE_STOP) {
616
673
  reportActivity(` stopped the agent's turn: ${refused} calls to tools this turn does not have`);
617
- void current?.abort();
674
+ stopTurn(current, `${refused} calls to tools this turn does not have`);
618
675
  throw new Error(`Stopped: ${refused} calls to tools this turn does not have.`);
619
676
  }
620
677
  throw new Error(`Not run: your work is done and checked - this turn is for ${[...only].join(" and ")} alone, and nothing else is ` +
@@ -624,7 +681,7 @@ export function guardRepeats(tools, session, budget) {
624
681
  if (budget !== undefined && !budget.finish.includes(tool.name) && calls > budget.calls) {
625
682
  if (calls > budget.calls * 2) {
626
683
  reportActivity(` stopped the agent's turn: ${calls} tool calls, past its budget of ${budget.calls}`);
627
- void session()?.abort();
684
+ stopTurn(session(), `${calls} tool calls, past its budget of ${budget.calls}`);
628
685
  throw new Error(`Stopped: ${calls} tool calls, past the budget of ${budget.calls}.`);
629
686
  }
630
687
  throw new Error(`Not run: you have made ${budget.calls} tool calls, which is all you have. Decide now with what you know: call ` +
@@ -652,7 +709,7 @@ export function guardRepeats(tools, session, budget) {
652
709
  }
653
710
  if (repeats > REPEATS_BEFORE_STOP) {
654
711
  reportActivity(` stopped the agent's turn: it made the same ${tool.name} call ${repeats} times with nothing changed`);
655
- void session()?.abort();
712
+ stopTurn(session(), `the same ${tool.name} call ${repeats} times with nothing changed`);
656
713
  throw new Error(`Stopped: the same ${tool.name} call ${repeats} times with nothing changed.`);
657
714
  }
658
715
  if (repeats > REPEATS_ALLOWED) {
@@ -695,7 +752,7 @@ export async function createExecutor(opts) {
695
752
  modelRuntime: await subAgentModelRuntime(),
696
753
  tools: hasShell ? [...opts.tools, ENVIRONMENT_ERROR_TOOL] : opts.tools,
697
754
  // What an agent is shown never holds a credential the project passed: each value is its name (masking.ts).
698
- customTools: guardRepeats(maskToolResults(withEnvironmentErrors), () => session, opts.budget),
755
+ customTools: guardRepeats(maskToolResults(withListArguments(withEnvironmentErrors)), () => session, opts.budget),
699
756
  sessionManager,
700
757
  resourceLoader: await subAgentResources(opts.cwd, opts.rules === true, [opts.system, opts.task].filter((part) => part !== undefined && part !== "").join("\n\n") || undefined),
701
758
  });
@@ -814,7 +871,7 @@ export async function createJudge(opts) {
814
871
  model,
815
872
  modelRuntime,
816
873
  tools: [...(opts.extraTools ?? []), "submit_verdict"],
817
- customTools: [opts.verdictTool],
874
+ customTools: withListArguments([opts.verdictTool]),
818
875
  sessionManager: SessionManager.inMemory(opts.cwd),
819
876
  // Judges assess specs against the rules, so they have them too.
820
877
  resourceLoader: await subAgentResources(opts.cwd, true, opts.task),
@@ -25,6 +25,7 @@ export class QuestionDialog {
25
25
  }
26
26
  else {
27
27
  this.input = undefined;
28
+ this.selected = Math.min(Math.max(0, options.selected ?? 0), options.options.length - 1);
28
29
  }
29
30
  }
30
31
  get focused() {
@@ -90,6 +90,27 @@ export function onModelEvent(listener) {
90
90
  modelListeners.add(listener);
91
91
  return () => modelListeners.delete(listener);
92
92
  }
93
+ /**
94
+ * The model provider failing or stalling, in a line for the person: the chat's notification, a headless run's console.
95
+ * A turn turri stopped itself is the work going its normal course - kept in the activity, the pulse's log and the run
96
+ * report, not said.
97
+ */
98
+ export function describeTurnIncident(event) {
99
+ const who = event.role ?? event.label ?? "an agent";
100
+ const model = event.model !== undefined ? ` (${event.model})` : "";
101
+ if (event.kind === "provider_retry") {
102
+ const wait = Math.round((event.waitMs ?? 0) / 1000);
103
+ return `The model provider failed${model}: ${(event.error ?? "").slice(0, 160)} - trying ${who}'s request again in ${wait}s (${event.attempt} of ${event.of}).`;
104
+ }
105
+ if (event.kind === "provider_stall") {
106
+ return `The model provider has sent nothing back to ${who}${model} for ${formatSilence(event.waitMs ?? 0)} - still waiting.`;
107
+ }
108
+ return undefined;
109
+ }
110
+ function formatSilence(ms) {
111
+ const seconds = Math.round(ms / 1000);
112
+ return seconds >= 60 && seconds % 60 === 0 ? `${seconds / 60}m` : seconds >= 60 ? `${Math.floor(seconds / 60)}m ${seconds % 60}s` : `${seconds}s`;
113
+ }
93
114
  export function reportModelEvent(event) {
94
115
  if (modelListeners.size === 0)
95
116
  return;
@@ -0,0 +1,121 @@
1
+ const isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
2
+ /** The tool's arguments that take a list of objects. */
3
+ function listArguments(schema) {
4
+ const required = new Set(schema.required ?? []);
5
+ return Object.entries(schema.properties ?? {})
6
+ .filter(([, property]) => property.type === "array" && property.items?.type === "object")
7
+ .map(([name, property]) => ({ name, required: required.has(name), item: property.items }));
8
+ }
9
+ /** JSON text, fenced or not, as what it holds; anything else as it is. */
10
+ function parsed(value) {
11
+ if (typeof value !== "string")
12
+ return value;
13
+ const text = value
14
+ .trim()
15
+ .replace(/^```(?:json)?\s*/i, "")
16
+ .replace(/\s*```$/, "");
17
+ if (!/^[[{]/.test(text))
18
+ return value;
19
+ try {
20
+ return JSON.parse(text);
21
+ }
22
+ catch {
23
+ return value;
24
+ }
25
+ }
26
+ const escaped = (name) => name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
27
+ /**
28
+ * Arguments the model wrote inside another argument's text - `answer</a>\n<b>[...]</b>\n<c>...` - taken out of it and
29
+ * given as their own, where they were not given already. Which argument each was found in, for the refusal.
30
+ */
31
+ function untucked(args, names) {
32
+ const out = { ...args };
33
+ const foundIn = new Map();
34
+ const anyTag = names.map(escaped).join("|");
35
+ for (const [key, value] of Object.entries(args)) {
36
+ if (typeof value !== "string")
37
+ continue;
38
+ let cut = value.search(new RegExp(`</${escaped(key)}>`));
39
+ for (const name of names) {
40
+ if (name === key || (out[name] !== undefined && out[name] !== ""))
41
+ continue;
42
+ const match = new RegExp(`<${escaped(name)}>([\\s\\S]*?)(?:</${escaped(name)}>|(?=<(?:${anyTag})>)|$)`).exec(value);
43
+ if (match === null)
44
+ continue;
45
+ out[name] = match[1].trim();
46
+ foundIn.set(name, key);
47
+ cut = cut === -1 ? match.index : Math.min(cut, match.index);
48
+ }
49
+ if (cut !== -1)
50
+ out[key] = value.slice(0, cut).trim();
51
+ }
52
+ return { args: out, foundIn };
53
+ }
54
+ /** What an entry of the list looks like, as JSON: its fields, the optional ones marked. */
55
+ function shapeOf(item) {
56
+ const required = new Set(item.required ?? []);
57
+ const entries = Object.entries(item.properties ?? {});
58
+ const fields = entries.map(([name, field]) => `"${name}"${required.has(name) ? "" : "?"}: ${field.type ?? "value"}`).join(", ");
59
+ const sample = (field) => (field.type === "number" || field.type === "integer" ? "1" : field.type === "boolean" ? "true" : field.type === "string" ? '"..."' : "...");
60
+ const example = entries
61
+ .filter(([name]) => required.has(name))
62
+ .map(([name, field]) => `"${name}": ${sample(field)}`)
63
+ .join(", ");
64
+ return { fields: `{${fields}}`, example: `{${example}}` };
65
+ }
66
+ /** Why a list argument is not one, said so a model can make the call right next time - or undefined when it is. */
67
+ function problemOf(list, value, foundIn) {
68
+ if (value === undefined)
69
+ return list.required ? "you left it out" : undefined;
70
+ if (!Array.isArray(value)) {
71
+ if (foundIn !== undefined)
72
+ return `you wrote it inside \`${foundIn}\``;
73
+ return typeof value === "string" ? "you sent it as text, not a list" : `you sent ${isObject(value) ? "an object" : `a ${typeof value}`}, not a list`;
74
+ }
75
+ const bad = value.findIndex((entry) => !isObject(entry));
76
+ if (bad === -1)
77
+ return undefined;
78
+ return `entry ${bad + 1} is ${typeof value[bad] === "string" ? "text" : `a ${typeof value[bad]}`}, not an object`;
79
+ }
80
+ /** The arguments with their lists made lists where they plainly are; refused, saying what is wanted, where they are not. */
81
+ export function prepareListArguments(toolName, schema, raw) {
82
+ const lists = listArguments(schema);
83
+ if (lists.length === 0 || !isObject(raw))
84
+ return raw;
85
+ const { args, foundIn } = untucked(raw, Object.keys(schema.properties ?? {}));
86
+ const problems = [];
87
+ for (const list of lists) {
88
+ let value = parsed(args[list.name]);
89
+ if (isObject(value))
90
+ value = [value];
91
+ if (Array.isArray(value))
92
+ value = value.map(parsed);
93
+ if (value !== undefined)
94
+ args[list.name] = value;
95
+ const problem = problemOf(list, value, foundIn.get(list.name));
96
+ if (problem === undefined)
97
+ continue;
98
+ const { fields, example } = shapeOf(list.item);
99
+ problems.push(`- \`${list.name}\`: ${problem}. It is a list of objects, each ${fields} - e.g. "${list.name}": [${example}].`);
100
+ }
101
+ if (problems.length === 0)
102
+ return args;
103
+ throw new Error([
104
+ `${toolName} was not run - its arguments are not in the shape it takes:`,
105
+ ...problems,
106
+ "Each argument is a field of its own in the call, at the top level: a list is a JSON array of objects, never text, and never written inside another argument's text.",
107
+ ].join("\n"));
108
+ }
109
+ /** The tools, each that takes a list of objects preparing its arguments so before they are checked. */
110
+ export function withListArguments(tools) {
111
+ return tools.map((tool) => {
112
+ const schema = tool.parameters;
113
+ if (listArguments(schema).length === 0)
114
+ return tool;
115
+ const before = tool.prepareArguments;
116
+ return {
117
+ ...tool,
118
+ prepareArguments: (args) => prepareListArguments(tool.name, schema, before !== undefined ? before(args) : args),
119
+ };
120
+ });
121
+ }
@@ -378,6 +378,8 @@ export function createWorkLoop(options) {
378
378
  const waiting = (why) => ({ module: entry.moduleName, why: `waiting for ${entry.moduleName}: ${why}` });
379
379
  if (below.running !== undefined)
380
380
  return waiting(below.running.planned.track === "conformance" ? "its conformance tests are being written" : "the code it is built on is not built yet");
381
+ if (below.held !== undefined)
382
+ return waiting("you halted it - nothing is built on it until it is asked for again");
381
383
  const spec = chainSpec(below.chain);
382
384
  if (codeWork(builtOf(below), spec.tree).length > 0)
383
385
  return waiting("the code it is built on is not built yet");
@@ -486,6 +488,11 @@ export function createWorkLoop(options) {
486
488
  /** A dry run's first jobs, by codebase: what each would start. */
487
489
  const firsts = new Map();
488
490
  const startJob = (state, spec, from, planned) => {
491
+ // Halted while it was being planned: the plan is made, nothing starts.
492
+ if (state.held !== undefined) {
493
+ state.why = state.held.why;
494
+ return;
495
+ }
489
496
  const tip = tipEntry(state);
490
497
  if (options.dryRun === true) {
491
498
  firsts.set(tip.buildDir, { spec: planned.track === "conformance" ? spec : { ...spec, tree: planned.step.tree }, planned });
@@ -590,7 +597,14 @@ export function createWorkLoop(options) {
590
597
  }
591
598
  return {
592
599
  report: released !== undefined ? `${report}\n\n${released}` : report,
593
- details: { passed: result.landed, landed: result.landed, ...(released !== undefined ? { released: true } : {}), ...(result.story !== undefined ? { story: result.story } : {}) },
600
+ details: {
601
+ passed: result.landed,
602
+ landed: result.landed,
603
+ ...(released !== undefined ? { released: true } : {}),
604
+ ...(result.story !== undefined ? { story: result.story } : {}),
605
+ // The spec gaps its agents met, for a headless run to say - in the chat the report puts them to the person.
606
+ ...(result.specGaps !== undefined && result.specGaps.length > 0 ? { specGaps: result.specGaps } : {}),
607
+ },
594
608
  };
595
609
  },
596
610
  });
@@ -773,16 +787,37 @@ export function createWorkLoop(options) {
773
787
  }
774
788
  return states;
775
789
  };
790
+ /** A codebase the loop no longer looks after: nothing of it is shown, planned or waited for. */
791
+ const forget = (state) => {
792
+ const key = tipEntry(state).buildDir;
793
+ modules.delete(key);
794
+ order.splice(order.indexOf(key), 1);
795
+ };
776
796
  const lookAll = async () => {
797
+ // A .plain file taken out of the project is asked for no more, and a codebase whose module's file is gone is
798
+ // forgotten - nothing running there - rather than shown waiting for a plan it will never have.
799
+ for (const file of [...asked.keys()])
800
+ if (!existsSync(file))
801
+ asked.delete(file);
802
+ for (const key of [...order]) {
803
+ const state = modules.get(key);
804
+ if (state.running === undefined && !existsSync(tipEntry(state).plainFile))
805
+ forget(state);
806
+ }
777
807
  const now = active();
778
808
  looking = now;
779
809
  for (const key of order) {
780
810
  const state = modules.get(key);
781
- // A codebase left behind - built on since - is not looked at, unless a job of it is still running.
811
+ // A codebase left behind - built on since - is not looked at, unless a job of it is still running; what it had
812
+ // planned, or waited for, is no longer shown.
782
813
  if (now.has(state) || state.running !== undefined)
783
814
  await look(state);
784
- else
815
+ else {
785
816
  state.why = "left behind: the code is built on further up the chain, where changes to it are made";
817
+ state.waitsFor = undefined;
818
+ state.plan = undefined;
819
+ state.conformancePlan = undefined;
820
+ }
786
821
  }
787
822
  };
788
823
  const look = async (state) => {
@@ -793,6 +828,12 @@ export function createWorkLoop(options) {
793
828
  }
794
829
  catch (error) {
795
830
  state.why = `its spec does not parse: ${error instanceof Error ? error.message : String(error)}`;
831
+ // Not planned from a spec that does not parse: what it waited for, and the plan, were the spec's before.
832
+ state.waitsFor = undefined;
833
+ if (state.running === undefined) {
834
+ state.plan = undefined;
835
+ state.conformancePlan = undefined;
836
+ }
796
837
  return;
797
838
  }
798
839
  const specKey = keyOf(spec);
@@ -845,6 +886,11 @@ export function createWorkLoop(options) {
845
886
  return;
846
887
  }
847
888
  hashResources(state, spec);
889
+ if (state.held !== undefined) {
890
+ state.why = state.held.why;
891
+ state.waitsFor = undefined;
892
+ return;
893
+ }
848
894
  if (state.halted !== undefined) {
849
895
  if (state.halted.specKey === specKey) {
850
896
  state.why = state.halted.why;
@@ -1005,14 +1051,18 @@ export function createWorkLoop(options) {
1005
1051
  return state;
1006
1052
  };
1007
1053
  const loop = {
1008
- async bringUp(plainFile, request = {}) {
1054
+ async bringUp(plainFile, given = {}) {
1055
+ const { specChange, ...request } = given;
1009
1056
  const files = codebasesOf(resolve(options.cwd, plainFile));
1010
1057
  for (const file of files)
1011
1058
  asked.set(file, { ...asked.get(file), ...request });
1012
1059
  const states = withParseCache(() => files.flatMap((file) => chainsFor(file).flatMap((chain) => toBuild(chain).map((entry) => track(chain.slice(0, chain.indexOf(entry) + 1), file, request)))));
1013
- // Asked again, a halted codebase is tried again.
1014
- for (const state of states)
1060
+ // Asked again, a halted codebase is tried again - one the person halted too, unless only its spec changed.
1061
+ for (const state of states) {
1015
1062
  state.halted = undefined;
1063
+ if (specChange !== true)
1064
+ state.held = undefined;
1065
+ }
1016
1066
  await tick();
1017
1067
  return [...new Set(states)].map(statusOf);
1018
1068
  },
@@ -1080,7 +1130,7 @@ export function createWorkLoop(options) {
1080
1130
  report.scheduled = (state.scheduled ?? []).map((group) => ({ frids: group.specs.map((touched) => touched.frid), unbuilt: group.unbuilt }));
1081
1131
  if (state.running !== undefined)
1082
1132
  report.running = { jobId: state.running.jobId, title: state.running.planned.title };
1083
- const halted = state.halted?.why ?? state.conformanceHalted?.why;
1133
+ const halted = state.held?.why ?? state.halted?.why ?? state.conformanceHalted?.why;
1084
1134
  if (halted !== undefined)
1085
1135
  report.why = halted;
1086
1136
  if (state.startOver !== undefined)
@@ -1167,6 +1217,7 @@ export function createWorkLoop(options) {
1167
1217
  }
1168
1218
  state.conformanceHalted = undefined;
1169
1219
  state.halted = undefined;
1220
+ state.held = undefined;
1170
1221
  }
1171
1222
  await tick();
1172
1223
  return [...new Set(states)].map((state) => {
@@ -1196,19 +1247,67 @@ export function createWorkLoop(options) {
1196
1247
  startAgain(entry, `it now requires ${requires.join(", ")}, which its code was not built on`);
1197
1248
  return loop.bringUp(plainFile, request);
1198
1249
  },
1199
- async fromScratch(plainFile, request = {}) {
1250
+ async fromScratch(plainFile, { chain, ...request } = {}) {
1200
1251
  const file = resolve(options.cwd, plainFile);
1201
- // Where its code lives: the tips its module is built in, or - none built yet - its own codebase.
1202
- const codebases = chainsFor(file).map(tipOf);
1252
+ // Where its code lives: the tips its module is built in, or - none built yet - its own codebase. The whole chain:
1253
+ // every codebase in those chains, bottom first - a tip taken back to nothing is otherwise started from a copy of
1254
+ // the code below it.
1255
+ const chains = chainsFor(file);
1256
+ const codebases = [...new Map((chain === true ? chains.flat() : chains.map(tipOf)).map((entry) => [entry.buildDir, entry])).values()];
1203
1257
  for (const entry of codebases) {
1204
1258
  if (modules.get(entry.buildDir)?.running !== undefined)
1205
1259
  throw new Error(`${entry.moduleName} has a pulse running: halt it, or ask again once it is done.`);
1206
1260
  }
1261
+ const why = chain === true ? "asked to be regenerated from scratch, with its whole chain" : "asked to be regenerated from scratch";
1207
1262
  for (const entry of codebases)
1208
1263
  if (started(entry))
1209
- startAgain(entry, "asked to be regenerated from scratch");
1264
+ startAgain(entry, why);
1210
1265
  return loop.bringUp(plainFile, request);
1211
1266
  },
1267
+ halt(target, reason) {
1268
+ const named = target.trim();
1269
+ // A planned row's module - the longest name its id starts with, as a name may hold a hyphen - or a module by its name.
1270
+ const state = order
1271
+ .map((key) => modules.get(key))
1272
+ .filter((candidate) => {
1273
+ const name = tipEntry(candidate).moduleName;
1274
+ return named === name || named.startsWith(`planned-${name}-`);
1275
+ })
1276
+ .sort((a, b) => tipEntry(b).moduleName.length - tipEntry(a).moduleName.length)[0];
1277
+ if (state === undefined)
1278
+ return undefined;
1279
+ const tip = tipEntry(state);
1280
+ if (state.running === undefined && !existsSync(tip.plainFile)) {
1281
+ forget(state);
1282
+ asked.delete(tip.plainFile);
1283
+ return `${tip.moduleName} is no longer in the project - ${basename(tip.plainFile)} is gone - so nothing was to be built there: it is dropped from the regeneration.`;
1284
+ }
1285
+ const planned = statusOf(state).planned.length;
1286
+ const said = reason !== undefined && reason.trim() !== "" ? ` (${reason.trim()})` : "";
1287
+ state.held = { why: `you halted it${said} - nothing runs here until it is asked for again` };
1288
+ state.why = state.held.why;
1289
+ state.waitsFor = undefined;
1290
+ state.plan = undefined;
1291
+ state.conformancePlan = undefined;
1292
+ const running = state.running;
1293
+ if (running !== undefined && running.stopping !== true) {
1294
+ running.stopping = true;
1295
+ options.registry.stop(running.jobId, `Halted by you${said}: what it had done is rolled back, and nothing more runs in ${tip.moduleName} until it is asked for again.`);
1296
+ }
1297
+ const above = order
1298
+ .map((key) => modules.get(key))
1299
+ .filter((other) => other !== state && looking.has(other) && other.chain.some((entry) => entry.buildDir === tip.buildDir))
1300
+ .map((other) => tipEntry(other).moduleName);
1301
+ void tick();
1302
+ return [
1303
+ `Halted ${tip.moduleName}${said}:`,
1304
+ running !== undefined ? ` its running pulse ${running.jobId} is being stopped, and what it had done rolled back;` : "",
1305
+ planned > 0 ? ` its ${planned} planned pulse${planned === 1 ? "" : "s"} will not start.` : " nothing more is planned there.",
1306
+ " Pulses that landed stay.",
1307
+ above.length > 0 ? ` ${above.join(", ")} ${above.length === 1 ? "waits" : "wait"} for it.` : "",
1308
+ ` It runs again only when asked for - regenerate ${basename(tip.plainFile)} - a spec change does not start it.`,
1309
+ ].join("");
1310
+ },
1212
1311
  status() {
1213
1312
  return order.map((key) => statusOf(modules.get(key)));
1214
1313
  },
@@ -1423,7 +1522,7 @@ export function describeModules(statuses, options = {}) {
1423
1522
  ` Ask the user whether to start ${codebases.join(", ")} over, and say why: ${codebases.join(", ")} was built without ` +
1424
1523
  `${requires.join(", ")}, so no change to its code can bring ${requires.join(", ")} in - its code and conformance ` +
1425
1524
  "tests are taken out, kept in its history, and built again from the bottom of the chain. Only if they agree, " +
1426
- `call regenerate with ${basename(status.plainFile)} and from_scratch.`,
1525
+ `call regenerate with ${basename(status.plainFile)} and from_scratch: "module".`,
1427
1526
  ];
1428
1527
  };
1429
1528
  return statuses
@@ -1477,7 +1576,7 @@ const defaultConformanceRunner = async (job, onDelta) => {
1477
1576
  writeTestsRecord(result.conformanceDir, job.planned.step.tree);
1478
1577
  recordHistory(job.buildDir, `conformance tests: ${job.planned.title}`);
1479
1578
  }
1480
- return { landed: result.passed, report: describeSpecDiffConformance(result) };
1579
+ return { landed: result.passed, report: describeSpecDiffConformance(result), ...(result.specGaps !== undefined ? { specGaps: result.specGaps } : {}) };
1481
1580
  };
1482
1581
  /** A job as a spec diff render, landed on its unit tests: conformance is a track of its own. */
1483
1582
  const defaultRunner = async (job, onDelta) => {
@@ -1493,7 +1592,9 @@ const defaultRunner = async (job, onDelta) => {
1493
1592
  onDelta,
1494
1593
  });
1495
1594
  // Landed code can be tried.
1496
- return { landed: result.passed, report: withTryItLine(describeSpecDiff(result), result.passed && result.restructured !== true), story: codeStory(result) };
1595
+ return { landed: result.passed, report: withTryItLine(describeSpecDiff(result), result.passed && result.restructured !== true), story: codeStory(result),
1596
+ ...(result.specGaps !== undefined ? { specGaps: result.specGaps } : {}),
1597
+ };
1497
1598
  };
1498
1599
  /** How a code pulse went, for its line in the notes: the rounds it took, its test runs, what the debugger found. */
1499
1600
  export function codeStory(result) {
@@ -281,9 +281,11 @@ export async function renderSpecDiff(options) {
281
281
  const work = createWorkLedger();
282
282
  // What it checks its own work with: the diff its reviewer is shown, and whether a test catches a bug - neither decides anything.
283
283
  const gate = createUnitGate(buildDir, scripts.unit);
284
+ // can_it_fail, for the coding agent and its reviewer: on unless mutation-testing says otherwise.
285
+ const mutationTesting = scripts.unit !== undefined && configForSpec(tip.plainFile).mutationTesting !== false;
284
286
  const selfChecks = [
285
287
  createMyDiffTool({ dir: buildDir, what: "code" }),
286
- ...(scripts.runOn === "copy" ? [createCanItFailTool({ buildDir, script: scripts.unit })] : []),
288
+ ...(mutationTesting ? [createCanItFailTool({ buildDir, script: scripts.unit })] : []),
287
289
  ];
288
290
  // A server it built, it can start and try from outside - stopped when it is done.
289
291
  const services = createServiceTools({ dir: buildDir });
@@ -499,7 +501,7 @@ export async function renderSpecDiff(options) {
499
501
  forChange: true,
500
502
  ...(options.cases !== undefined ? { cases: options.cases } : {}),
501
503
  label: `${moduleName} spec change`,
502
- ...(scripts.runOn === "copy" ? { unitScript: scripts.unit } : {}),
504
+ ...(mutationTesting ? { unitScript: scripts.unit } : {}),
503
505
  testingScript: { path: relative(root, scripts.unit), content: readFileSync(scripts.unit, "utf8") },
504
506
  model: options.judgeModel ?? modelSpec(inheritModel(configForSpec(tip.plainFile).judgeModel, modelOnly(options.model))),
505
507
  send: async (next) => {