@turri-dev/cli 0.1.3 → 0.1.4-next.172be6f

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,30 @@ 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
+ }
226
253
  /** A provider error that passes: overloaded, rate limited, unreachable, timed out. */
227
254
  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
255
  /** Wait, unless the job is stopped first. */
@@ -251,7 +278,7 @@ async function askOnce(session, text, onDelta) {
251
278
  // Calls to one tool failing one after another - arguments it refuses, or errors - with nothing going through.
252
279
  let failing = 0;
253
280
  let failingTool;
254
- let stoppedFailing = false;
281
+ harnessStops.delete(session);
255
282
  reportNow("waiting for the model");
256
283
  // Every entry says which agent it is from, and what it runs on - for reading one agent at a time.
257
284
  const agent = agentOf(session);
@@ -308,14 +335,13 @@ async function askOnce(session, text, onDelta) {
308
335
  if (event.type === "tool_execution_end") {
309
336
  failing = event.isError ? (event.toolName === failingTool ? failing + 1 : 1) : 0;
310
337
  failingTool = event.isError ? event.toolName : undefined;
311
- if (failing >= FAILURES_BEFORE_STOP && !stoppedFailing) {
338
+ if (failing >= FAILURES_BEFORE_STOP && !harnessStops.has(session)) {
312
339
  // A call its tool refuses never reaches the tool, so no guard on the tools sees it: an agent can
313
340
  // make the same bad call, worded a little differently, thousands of times. Its turn ends here, and
314
341
  // the harness goes on from there, as after any turn.
315
- stoppedFailing = true;
316
342
  reportActivity(` stopped the agent's turn: ${failing} ${shownName(event.toolName)} calls failed in a row`);
317
343
  debugLogOf(session)?.note(`turn stopped: ${failing} ${event.toolName} calls failed in a row`);
318
- void session.abort();
344
+ stopTurn(session, `${failing} ${shownName(event.toolName)} calls failed in a row`);
319
345
  }
320
346
  const output = resultText(event.result);
321
347
  transcript({ kind: "result", text: clipText(output, MAX_TOOL_RESULT), error: event.isError, full: output });
@@ -376,7 +402,7 @@ async function askOnce(session, text, onDelta) {
376
402
  stopped = true;
377
403
  reportActivity(` stopped the agent's turn: its ${formatLimit(limitMs)} are up`);
378
404
  debug?.note(`turn stopped: its ${formatLimit(limitMs)} are up${how}`);
379
- void session.abort();
405
+ stopTurn(session, `its ${formatLimit(limitMs)} were up`);
380
406
  };
381
407
  const atNextRequest = timed
382
408
  ? session.subscribe((event) => {
@@ -417,14 +443,17 @@ async function askOnce(session, text, onDelta) {
417
443
  stop?.removeEventListener("abort", onStop);
418
444
  reportNow(undefined);
419
445
  }
420
- if (stopped)
421
- out = `${out.trim()}\n\n[the turn was stopped: its ${formatLimit(limitMs)} were up]`.trim();
446
+ // turri ended the turn itself - its time was up, the agent went round in a circle: the abort that ended it is its own.
447
+ const stoppedFor = harnessStops.get(session);
448
+ harnessStops.delete(session);
449
+ if (stoppedFor !== undefined)
450
+ out = `${out.trim()}\n\n[the turn was stopped: ${stoppedFor}]`.trim();
422
451
  if (stop?.aborted) {
423
452
  debug?.note(`turn stopped on request after ${seconds(Date.now() - turnStarted)}`);
424
453
  throw new JobStoppedError();
425
454
  }
426
- // A turn ended for its time is ended, whatever the provider was doing then.
427
- if (providerError !== undefined && !stopped) {
455
+ // A turn turri ended is ended, whatever the provider was doing then: what comes back of the abort is not the provider failing.
456
+ if (providerError !== undefined && stoppedFor === undefined) {
428
457
  debug?.note(`turn ended with a provider error after ${seconds(Date.now() - turnStarted)}: ${providerError}`);
429
458
  throw new ProviderError(`${session.model?.id ?? "model"}: ${providerError}`);
430
459
  }
@@ -614,7 +643,7 @@ export function guardRepeats(tools, session, budget) {
614
643
  refused += 1;
615
644
  if (refused > REFUSED_BEFORE_STOP) {
616
645
  reportActivity(` stopped the agent's turn: ${refused} calls to tools this turn does not have`);
617
- void current?.abort();
646
+ stopTurn(current, `${refused} calls to tools this turn does not have`);
618
647
  throw new Error(`Stopped: ${refused} calls to tools this turn does not have.`);
619
648
  }
620
649
  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 +653,7 @@ export function guardRepeats(tools, session, budget) {
624
653
  if (budget !== undefined && !budget.finish.includes(tool.name) && calls > budget.calls) {
625
654
  if (calls > budget.calls * 2) {
626
655
  reportActivity(` stopped the agent's turn: ${calls} tool calls, past its budget of ${budget.calls}`);
627
- void session()?.abort();
656
+ stopTurn(session(), `${calls} tool calls, past its budget of ${budget.calls}`);
628
657
  throw new Error(`Stopped: ${calls} tool calls, past the budget of ${budget.calls}.`);
629
658
  }
630
659
  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 +681,7 @@ export function guardRepeats(tools, session, budget) {
652
681
  }
653
682
  if (repeats > REPEATS_BEFORE_STOP) {
654
683
  reportActivity(` stopped the agent's turn: it made the same ${tool.name} call ${repeats} times with nothing changed`);
655
- void session()?.abort();
684
+ stopTurn(session(), `the same ${tool.name} call ${repeats} times with nothing changed`);
656
685
  throw new Error(`Stopped: the same ${tool.name} call ${repeats} times with nothing changed.`);
657
686
  }
658
687
  if (repeats > REPEATS_ALLOWED) {
@@ -695,7 +724,7 @@ export async function createExecutor(opts) {
695
724
  modelRuntime: await subAgentModelRuntime(),
696
725
  tools: hasShell ? [...opts.tools, ENVIRONMENT_ERROR_TOOL] : opts.tools,
697
726
  // 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),
727
+ customTools: guardRepeats(maskToolResults(withListArguments(withEnvironmentErrors)), () => session, opts.budget),
699
728
  sessionManager,
700
729
  resourceLoader: await subAgentResources(opts.cwd, opts.rules === true, [opts.system, opts.task].filter((part) => part !== undefined && part !== "").join("\n\n") || undefined),
701
730
  });
@@ -814,7 +843,7 @@ export async function createJudge(opts) {
814
843
  model,
815
844
  modelRuntime,
816
845
  tools: [...(opts.extraTools ?? []), "submit_verdict"],
817
- customTools: [opts.verdictTool],
846
+ customTools: withListArguments([opts.verdictTool]),
818
847
  sessionManager: SessionManager.inMemory(opts.cwd),
819
848
  // Judges assess specs against the rules, so they have them too.
820
849
  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,18 @@ export function onModelEvent(listener) {
90
90
  modelListeners.add(listener);
91
91
  return () => modelListeners.delete(listener);
92
92
  }
93
+ /** A provider retry or a stop, in a line for the person: the chat's notification, a headless run's console. */
94
+ export function describeTurnIncident(event) {
95
+ const who = event.role ?? event.label ?? "an agent";
96
+ const model = event.model !== undefined ? ` (${event.model})` : "";
97
+ if (event.kind === "provider_retry") {
98
+ const wait = Math.round((event.waitMs ?? 0) / 1000);
99
+ return `The model provider failed${model}: ${(event.error ?? "").slice(0, 160)} - trying ${who}'s turn again in ${wait}s (${event.attempt} of ${event.of}).`;
100
+ }
101
+ if (event.kind === "stopped")
102
+ return `turri stopped ${who}'s turn${model}: ${event.reason ?? "it was stopped"} - carrying on from there.`;
103
+ return undefined;
104
+ }
93
105
  export function reportModelEvent(event) {
94
106
  if (modelListeners.size === 0)
95
107
  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) => {
@@ -1,9 +1,9 @@
1
- import { readFileSync, writeFileSync } from "node:fs";
2
- import { join, relative, resolve, sep } from "node:path";
1
+ import { readFileSync } from "node:fs";
2
+ import { relative, resolve, sep } from "node:path";
3
3
  import { defineTool } from "@earendil-works/pi-coding-agent";
4
4
  import { Type } from "typebox";
5
5
  import { workDiff } from "./lineage.js";
6
- import { lastPassingMs, runOnCode } from "./test-scripts.js";
6
+ import { lastPassingMs, runOnCode, scriptsRunInPlace } from "./test-scripts.js";
7
7
  /**
8
8
  * Tools an agent checks its own work with, before the harness and the reviewer do: the diff the reviewer is shown, and
9
9
  * whether a test catches a change to the code. Neither decides anything - the testing scripts, run by the harness, still do.
@@ -43,16 +43,23 @@ export function canItFailLimitMs(buildDir, script) {
43
43
  */
44
44
  export function createCanItFailTool(options) {
45
45
  let left = options.runs ?? CAN_IT_FAIL_RUNS;
46
+ // In place, the change is made to the code itself for the run, and undone after it: the scripts run on the code there.
47
+ const inPlace = scriptsRunInPlace(options.buildDir);
46
48
  return defineTool({
47
49
  name: "can_it_fail",
48
50
  label: "Can it fail",
49
51
  description: "Check that the unit tests catch a bug: give one change to the code that breaks a behaviour the specification " +
50
52
  "states - a value or a status changed, a check taken out, a condition turned round where it cannot make a loop run for " +
51
53
  "ever - and the unit testing script " +
52
- "runs on a copy of the code with that change. The code itself is never touched. The tests should fail; if they all " +
54
+ (inPlace
55
+ ? "runs with that change made to the code, which is put back as it was once the run ends, whatever its result. "
56
+ : "runs on a copy of the code with that change. The code itself is never touched. ") +
57
+ "The tests should fail; if they all " +
53
58
  "pass, no test catches that bug. Make a change that still builds and runs: a failure only because it no longer " +
54
59
  `compiles or imports says nothing about the tests. ${options.runs ?? CAN_IT_FAIL_RUNS} runs at most.`,
55
- promptSnippet: "can_it_fail: whether the unit tests catch a bug you put in a copy of the code",
60
+ promptSnippet: "can_it_fail: whether the unit tests catch a bug you put in the code for one run",
61
+ // Never beside another call: in place, an edit made while the bug is in would be undone with it.
62
+ executionMode: "sequential",
56
63
  parameters: Type.Object({
57
64
  file: Type.String({ description: "The code file to change, relative to the code folder" }),
58
65
  find: Type.String({ description: "Text that is in the file exactly once - the code to change" }),
@@ -83,7 +90,7 @@ export function createCanItFailTool(options) {
83
90
  left -= 1;
84
91
  let run;
85
92
  try {
86
- run = await runOnCode(options.buildDir, options.script, "unit testing script, with the change", (copy) => writeFileSync(join(copy, relative(options.buildDir, path)), text.slice(0, at) + replace + text.slice(at + find.length)), canItFailLimitMs(options.buildDir, options.script));
93
+ run = await runOnCode(options.buildDir, options.script, "unit testing script, with the change", { file: relative(options.buildDir, path), text: text.slice(0, at) + replace + text.slice(at + find.length) }, canItFailLimitMs(options.buildDir, options.script));
87
94
  }
88
95
  catch (error) {
89
96
  return say(error instanceof Error ? error.message : String(error));