@turri-dev/cli 0.1.4-next.318a98a → 0.1.4-next.afc43a8

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.
@@ -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
+ }
@@ -597,7 +597,14 @@ export function createWorkLoop(options) {
597
597
  }
598
598
  return {
599
599
  report: released !== undefined ? `${report}\n\n${released}` : report,
600
- 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
+ },
601
608
  };
602
609
  },
603
610
  });
@@ -1240,17 +1247,21 @@ export function createWorkLoop(options) {
1240
1247
  startAgain(entry, `it now requires ${requires.join(", ")}, which its code was not built on`);
1241
1248
  return loop.bringUp(plainFile, request);
1242
1249
  },
1243
- async fromScratch(plainFile, request = {}) {
1250
+ async fromScratch(plainFile, { chain, ...request } = {}) {
1244
1251
  const file = resolve(options.cwd, plainFile);
1245
- // Where its code lives: the tips its module is built in, or - none built yet - its own codebase.
1246
- 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()];
1247
1257
  for (const entry of codebases) {
1248
1258
  if (modules.get(entry.buildDir)?.running !== undefined)
1249
1259
  throw new Error(`${entry.moduleName} has a pulse running: halt it, or ask again once it is done.`);
1250
1260
  }
1261
+ const why = chain === true ? "asked to be regenerated from scratch, with its whole chain" : "asked to be regenerated from scratch";
1251
1262
  for (const entry of codebases)
1252
1263
  if (started(entry))
1253
- startAgain(entry, "asked to be regenerated from scratch");
1264
+ startAgain(entry, why);
1254
1265
  return loop.bringUp(plainFile, request);
1255
1266
  },
1256
1267
  halt(target, reason) {
@@ -1511,7 +1522,7 @@ export function describeModules(statuses, options = {}) {
1511
1522
  ` Ask the user whether to start ${codebases.join(", ")} over, and say why: ${codebases.join(", ")} was built without ` +
1512
1523
  `${requires.join(", ")}, so no change to its code can bring ${requires.join(", ")} in - its code and conformance ` +
1513
1524
  "tests are taken out, kept in its history, and built again from the bottom of the chain. Only if they agree, " +
1514
- `call regenerate with ${basename(status.plainFile)} and from_scratch.`,
1525
+ `call regenerate with ${basename(status.plainFile)} and from_scratch: "module".`,
1515
1526
  ];
1516
1527
  };
1517
1528
  return statuses
@@ -1565,7 +1576,7 @@ const defaultConformanceRunner = async (job, onDelta) => {
1565
1576
  writeTestsRecord(result.conformanceDir, job.planned.step.tree);
1566
1577
  recordHistory(job.buildDir, `conformance tests: ${job.planned.title}`);
1567
1578
  }
1568
- return { landed: result.passed, report: describeSpecDiffConformance(result) };
1579
+ return { landed: result.passed, report: describeSpecDiffConformance(result), ...(result.specGaps !== undefined ? { specGaps: result.specGaps } : {}) };
1569
1580
  };
1570
1581
  /** A job as a spec diff render, landed on its unit tests: conformance is a track of its own. */
1571
1582
  const defaultRunner = async (job, onDelta) => {
@@ -1581,7 +1592,9 @@ const defaultRunner = async (job, onDelta) => {
1581
1592
  onDelta,
1582
1593
  });
1583
1594
  // Landed code can be tried.
1584
- 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
+ };
1585
1598
  };
1586
1599
  /** How a code pulse went, for its line in the notes: the rounds it took, its test runs, what the debugger found. */
1587
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));
@@ -297,6 +297,10 @@ export function setScriptTimeoutForTests(ms) {
297
297
  * own paths start - and whether they run on the code in place (the default), rather than on a fresh copy
298
298
  * (`testing-scripts-run-on: copy`).
299
299
  */
300
+ /** Whether the testing scripts run on the code in `buildDir` itself, not on a copy of it. */
301
+ export function scriptsRunInPlace(buildDir) {
302
+ return projectOfBuild(buildDir).inPlace;
303
+ }
300
304
  function projectOfBuild(buildDir) {
301
305
  const parts = resolve(buildDir).split(sep);
302
306
  const index = parts.lastIndexOf("plain_modules");
@@ -401,30 +405,70 @@ const lastPassing = new Map();
401
405
  export function lastPassingMs(buildDir, script) {
402
406
  return lastPassing.get(`${resolve(buildDir)}\n${script}`);
403
407
  }
408
+ /** Files changed in place for a run under way, and what each held: put back however the run ends - the process exiting too. */
409
+ const changedInPlace = new Map();
410
+ let restoreOnExit = false;
411
+ function putBack(path) {
412
+ const original = changedInPlace.get(path);
413
+ if (original === undefined)
414
+ return;
415
+ writeFileSync(path, original);
416
+ changedInPlace.delete(path);
417
+ }
418
+ /**
419
+ * `run` with `change` made to the code itself, and undone once it ends - passed, failed, timed out, thrown, or the process
420
+ * exiting. Killed outright, the change is left: the next unit of work starts from the last commit (lineage.ts startWork).
421
+ */
422
+ async function withChangeInPlace(buildDir, change, run) {
423
+ const path = resolve(buildDir, change.file);
424
+ if (changedInPlace.has(path))
425
+ throw new Error(`${change.file} is being changed for another run already.`);
426
+ if (!restoreOnExit) {
427
+ restoreOnExit = true;
428
+ process.once("exit", () => {
429
+ for (const changed of [...changedInPlace.keys()])
430
+ putBack(changed);
431
+ });
432
+ }
433
+ changedInPlace.set(path, readFileSync(path));
434
+ try {
435
+ writeFileSync(path, change.text);
436
+ return await run();
437
+ }
438
+ finally {
439
+ putBack(path);
440
+ }
441
+ }
404
442
  /**
405
- * A script that takes the code folder - the unit testing script - run where the testing scripts
406
- * run. `change`: what to do to the fresh copy before it runs - only where there is a copy; never in place.
443
+ * A script that takes the code folder - the unit testing script - run where the testing scripts run. `change`: one file
444
+ * as it is for this run - made to the fresh copy, or, in place, to the code itself and undone once the run ends.
407
445
  */
408
446
  export async function runOnCode(buildDir, script, what, change,
409
447
  /** A time limit of its own, in place of a test run's. */
410
448
  limitMs) {
411
449
  const project = projectOfBuild(buildDir);
450
+ const passed = (run, started) => {
451
+ if (change === undefined && run.exitCode === 0)
452
+ lastPassing.set(`${resolve(buildDir)}\n${script}`, Date.now() - started);
453
+ return run;
454
+ };
412
455
  if (project.inPlace) {
413
- if (change !== undefined)
414
- throw new Error("This runs only where the testing scripts run on a copy: here they run in place, on the code itself.");
415
- return runScript(project.root, script, [resolve(buildDir)], buildDir);
456
+ const inPlace = () => runScript(project.root, script, [resolve(buildDir)], buildDir, limitMs !== undefined ? { limitMs } : {});
457
+ const started = Date.now();
458
+ if (change === undefined)
459
+ return passed(await inPlace(), started);
460
+ reportActivity(` changing ${change.file} in place for the ${what} - put back once it has run`);
461
+ return withChangeInPlace(buildDir, change, inPlace);
416
462
  }
417
463
  const staging = stagingFor(buildDir);
418
464
  rmSync(staging.root, { recursive: true, force: true });
419
465
  ensureInModulesScratch(buildDir, staging.root);
420
466
  try {
421
467
  reportActivity(` copying ${stageBuild(buildDir, staging.build)} files of the code for the ${what}`);
422
- change?.(staging.build);
468
+ if (change !== undefined)
469
+ writeFileSync(join(staging.build, change.file), change.text);
423
470
  const started = Date.now();
424
- const run = await runOnCopy(staging.root, script, [staging.build], buildDir, limitMs);
425
- if (change === undefined && run.exitCode === 0)
426
- lastPassing.set(`${resolve(buildDir)}\n${script}`, Date.now() - started);
427
- return run;
471
+ return passed(await runOnCopy(staging.root, script, [staging.build], buildDir, limitMs), started);
428
472
  }
429
473
  finally {
430
474
  rmSync(staging.root, { recursive: true, force: true });
@@ -96,7 +96,7 @@ export function unitReviewTask(options) {
96
96
  " assertion so loose any answer passes, an expected value computed the way the code computes it.",
97
97
  ...(options.canItFail === true
98
98
  ? [
99
- "- A test you doubt can fail, check: can_it_fail puts a bug in a copy of the code - a condition turned round, a",
99
+ "- A test you doubt can fail, check: can_it_fail puts a bug in the code for one run - a condition turned round, a",
100
100
  " value changed - and runs the unit tests on it. A test that still passes cannot fail: raise it as bad, with the",
101
101
  ` bug it missed. ${REVIEWER_CAN_IT_FAIL_RUNS} runs a session: spend them on the tests the work rests on.`,
102
102
  ]
@@ -19,10 +19,15 @@ its conformance tests too when they are on.
19
19
  --start-over start over, without asking, a codebase regenerated without a module it now requires -
20
20
  with no terminal to ask and without it, the run stops there
21
21
  --from-scratch delete the module's code and conformance tests (its lineage keeps them) and regenerate all of it
22
+ --from-scratch-chain the same for every module of its requires chain, built again from the bottom - after
23
+ modules were split or moved
22
24
  --harness-model <p/id> config.turri.yaml's harness-model for this run: the planner and the conformance chooser
23
25
  --coding-model <p/id> its coding-model, --model too: the agents that build; p/id:level for how hard a model thinks
24
26
  --judge-model <p/id> its judge-model: the judge and the test review
25
27
  --review <true|false> its review: whether the code and its tests are reviewed once they pass
28
+ --mutation-testing <true|false>
29
+ its mutation-testing: whether the coding agent and the reviewer can put a bug in the code
30
+ for one test run (can_it_fail), to see that a test catches it
26
31
  --conformance-tests <all|chosen|module|false>
27
32
  its conformance-tests: which conformance tests are written and run
28
33
  --build-dir <dir> as the run ends, however it ends, export the code there: the furthest-built codebase's
@@ -31,7 +36,7 @@ its conformance tests too when they are on.
31
36
  as it starts, as each pulse ends and as it exits (docs/headless.md)
32
37
 
33
38
  PLAIN_TEMPLATE_DIRS colon-separated template directories`;
34
- const { positional, options } = parseArgs(process.argv.slice(2), ["--dry-run", "--start-over", "--from-scratch"], USAGE, ["--build-dir", "--report", "--conformance-tests", "--harness-model", "--judge-model", "--review"]);
39
+ const { positional, options } = parseArgs(process.argv.slice(2), ["--dry-run", "--start-over", "--from-scratch", "--from-scratch-chain"], USAGE, ["--build-dir", "--report", "--conformance-tests", "--harness-model", "--judge-model", "--review", "--mutation-testing"]);
35
40
  const { report, buildDir } = headlessOptions(options, true);
36
41
  const named = positional[0] ?? readProjectConfig(process.cwd()).module;
37
42
  // Functional specs named after the file: regenerated again though their spec did not change.
@@ -40,9 +45,10 @@ if (!named) {
40
45
  console.error(`${USAGE}\n\nNo file given, and ${CONFIG_FILE} names no module.`);
41
46
  process.exit(1);
42
47
  }
48
+ const scratch = options["from-scratch-chain"] !== undefined ? "chain" : options["from-scratch"] !== undefined ? "module" : undefined;
43
49
  // A dry run starts nothing, and from scratch deletes before it plans: the two do not go together.
44
- if (options["from-scratch"] !== undefined && options["dry-run"] !== undefined) {
45
- console.error("--from-scratch deletes the module's code before anything is planned: it cannot be a dry run.");
50
+ if (scratch !== undefined && options["dry-run"] !== undefined) {
51
+ console.error(`--from-scratch${scratch === "chain" ? "-chain" : ""} deletes the code before anything is planned: it cannot be a dry run.`);
46
52
  process.exit(1);
47
53
  }
48
54
  runLoop({
@@ -54,8 +60,8 @@ runLoop({
54
60
  startOver: options["start-over"] !== undefined,
55
61
  ask: (loop) => again.length > 0
56
62
  ? loop.regenerateAgain(named, again)
57
- : options["from-scratch"] !== undefined
58
- ? loop.fromScratch(named)
63
+ : scratch !== undefined
64
+ ? loop.fromScratch(named, { chain: scratch === "chain" })
59
65
  : loop.bringUp(named),
60
66
  }).catch((error) => {
61
67
  console.error(error instanceof Error ? error.message : error);
@@ -79,7 +79,8 @@ export function createLiveReviewer(opts) {
79
79
  pending.push(finding);
80
80
  all.push(finding);
81
81
  }
82
- if (violations.length === 0) {
82
+ // No verdict - its turn stopped before it gave one - clears nothing: the scope is looked at again next pass.
83
+ if (captured !== undefined && violations.length === 0) {
83
84
  cleared.push(scope);
84
85
  }
85
86
  else if (captured?.question) {
@@ -22,6 +22,9 @@ const emptyTotals = () => ({
22
22
  llm_calls: 0,
23
23
  agent_turns: 0,
24
24
  compactions: 0,
25
+ provider_retries: 0,
26
+ provider_stalls: 0,
27
+ turns_stopped: 0,
25
28
  model_seconds: 0,
26
29
  });
27
30
  function addUsage(totals, usage) {
@@ -43,8 +46,14 @@ function addEvent(totals, event, tokens) {
43
46
  }
44
47
  else if (event.kind === "turn")
45
48
  totals.agent_turns += 1;
46
- else
49
+ else if (event.kind === "compaction")
47
50
  totals.compactions += 1;
51
+ else if (event.kind === "provider_retry")
52
+ totals.provider_retries += 1;
53
+ else if (event.kind === "provider_stall")
54
+ totals.provider_stalls += 1;
55
+ else
56
+ totals.turns_stopped += 1;
48
57
  }
49
58
  function sumTotals(a, b) {
50
59
  const sum = emptyTotals();
@@ -181,6 +190,32 @@ export function startRunReport(options) {
181
190
  list,
182
191
  };
183
192
  };
193
+ /** The spec gaps the pulses' agents met, in the order the pulses started: questions a person would want to decide. */
194
+ const specGapsOf = (jobs) => jobs.flatMap((job) => {
195
+ const details = job.details;
196
+ return (details?.specGaps ?? []).map((gap) => ({
197
+ module: job.module ?? null,
198
+ pulse: job.pulse ?? null,
199
+ pulse_id: job.id,
200
+ landed: job.status === "succeeded" && details?.landed === true,
201
+ question: gap.question,
202
+ assumption: gap.assumption,
203
+ }));
204
+ });
205
+ /** Each request the provider failed and was waited out or stalled on, and each turn turri ended itself: why, and where. */
206
+ const turnIncidentsOf = () => events
207
+ .filter((event) => event.kind === "provider_retry" || event.kind === "provider_stall" || event.kind === "stopped")
208
+ .map((event) => ({
209
+ kind: event.kind,
210
+ pulse_id: event.job ?? null,
211
+ role: event.role ?? null,
212
+ model: event.model ?? null,
213
+ ...(event.kind === "stopped"
214
+ ? { reason: event.reason ?? null }
215
+ : event.kind === "provider_stall"
216
+ ? { silent_seconds: Math.round((event.waitMs ?? 0) / 1000) }
217
+ : { error: event.error ?? null, attempt: event.attempt ?? null, of: event.of ?? null, wait_seconds: Math.round((event.waitMs ?? 0) / 100) / 10 }),
218
+ }));
184
219
  const functionalitiesOf = (counts) => {
185
220
  if (counts === undefined)
186
221
  return null;
@@ -228,6 +263,7 @@ export function startRunReport(options) {
228
263
  build_dir: options.buildDir !== undefined ? resolve(options.buildDir) : null,
229
264
  conformance_tests: options.conformanceTests,
230
265
  review: options.review ?? null,
266
+ mutation_testing: options.mutationTesting ?? null,
231
267
  models: {
232
268
  ...Object.fromEntries(Object.entries(options.models).map(([role, choice]) => [role, { model: choice.model ?? null, thinking: choice.thinking ?? null }])),
233
269
  observed: Object.fromEntries([...new Set(events.map((event) => event.role ?? "unknown"))].sort().map((role) => [role, [...new Set(events.filter((event) => (event.role ?? "unknown") === role).map((event) => event.model ?? "unknown"))].sort()])),
@@ -245,6 +281,8 @@ export function startRunReport(options) {
245
281
  usage: usageOf(jobs),
246
282
  pulses: pulsesOf(jobs, now),
247
283
  functionalities: functionalitiesOf(attempt(sources.completion)),
284
+ spec_gaps: specGapsOf(jobs),
285
+ turn_incidents: turnIncidentsOf(),
248
286
  ...(exitParts ?? {}),
249
287
  logs: {
250
288
  jobs_dir: fromProject(join(projectRoot, ".turri", "jobs")),
@@ -158,13 +158,15 @@ an agent has to decide to go and read.
158
158
  | `import-modules.md`, `requires-modules.md` | the two ways modules build on each other |
159
159
  | `exported-concepts.md`, `required-concepts.md` | which concepts cross module boundaries |
160
160
  | `integrations.md` (+ standalone, embedded, embedded testing) | specs for REST API integrations, deployed standalone or embedded in an existing codebase |
161
+ | `turri-regeneration.md` | how turri regenerates a spec change - as a spec diff, wherever it sits, in the chain's tip - so a spec is placed by what it means, never to spare regeneration |
161
162
  | `stdlib.md` | the standard library: when to import which template, and every template with what it is and where it is, read from `stdlib/` |
162
163
 
163
164
  The ones that shape a spec most:
164
165
 
165
166
  - **One functionality is at most ~200 lines of code.** A bigger one is split before it is written
166
167
  (`analyze-if-func-spec-too-complex`, `break-down-func-spec`).
167
- - **Functional specs are in build order.** Each is rendered on top of the ones before it.
168
+ - **Functional specs are in build order.** Each is rendered on top of the ones before it - which is
169
+ what a spec may assume, not what a change costs: a spec inserted anywhere is regenerated alone.
168
170
  - **They state facts, with a concrete subject.** "A :User: can add a :Task:" - not "Implement
169
171
  adding tasks", not "The system should…".
170
172
  - **Nothing a test cannot check.** No `robust`, `seamless`, `as appropriate`; state the checkable
package/docs/config.md CHANGED
@@ -84,7 +84,7 @@ runs:
84
84
  | --- | --- |
85
85
  | now | `harness-model` and `models.chat` - the conversation switches to it; `parallel-jobs` - a pulse waiting for a slot starts if there is one now; `allow-to-stop-jobs` |
86
86
  | your next message | `rules-off` - for the conversation; a skill's agents from the next skill run |
87
- | the next pulse - one running keeps what it started with | `coding-model`, `judge-model`, every other `models.<role>`, `review`, `turn-limit`, `compact-at`, `agent-env`, `toolchains` |
87
+ | the next pulse - one running keeps what it started with | `coding-model`, `judge-model`, every other `models.<role>`, `review`, `mutation-testing`, `turn-limit`, `compact-at`, `agent-env`, `toolchains` |
88
88
  | the next time the work is planned | `conformance-tests`, `conformance-budget`, `max-specs-per-pulse`, `max-lines-per-pulse` |
89
89
  | the next test run - the running pulse's too | the testing scripts, `testing-scripts-run-on` |
90
90
  | the next pulse that lands - the running one too | `release-after-pulse` |
@@ -128,6 +128,7 @@ models: # each agent role's model, thinking and tur
128
128
  | `conformance-tests` | `all` (or `true`): conformance tests for every functional spec of every module with test reqs, written once each module's code is built, before anything is built on it. `chosen`: for the functional specs chosen - every one with acceptance tests, and those the chooser picks as each code pulse ends, from what that pulse regenerated. `module`: the same, but the chooser is asked once, when the whole module is regenerated, and plans the conformance pulses too. Under both, the choice is made inside the pulse, before anything is built on the module, and the pulse's report says what was chosen and why; those the person asks for with `conform` are written too; once chosen, a functional spec keeps them, and they are rewritten when it changes - see [who chooses, and when](regenerating.md#conformance-tests-in-the-work-loop). `false`: none written, and none of the existing ones run - until the conversation asks with `conform` | `false` |
129
129
  | `conformance-budget` | under `conformance-tests: chosen` or `module`: how many of a module's functional specs may be chosen for conformance tests, beside those with acceptance tests - a count (`2`) or a share of its functional specs (`30%`, rounded up, at least one). Every choice for the module counts, whenever it was made; the chooser is told what is left, and can choose no more. Your own `conform` is not limited. A stack's `config.turri.<stack>.yaml` can set its own | no limit |
130
130
  | `review` | `true` or `false`: whether the code and its unit tests - and the conformance tests - are reviewed once they pass: two reviews at most, the second weighed by the arbiter; off, a job lands once its tests pass - see [regenerating the code](regenerating.md#the-code-and-its-unit-tests-are-reviewed) | `false` |
131
+ | `mutation-testing` | `true` or `false`: whether the coding agent and the reviewer have `can_it_fail` - one change put in the code for one run of the unit testing script, to see that a test catches it; on a copy of the code, or in place and put back after the run (see [regenerating the code](regenerating.md#checking-its-own-work)). `turri regenerate --mutation-testing false` for one run | `true` |
131
132
  | `rules-off` | a list of rule names - `integrations`, `concise-specs`, the files of `genome/rules/` without `.md` - left out of the conversation's prompt and every spec-writing agent's: a rule this project's own skills or AGENTS.md replace, such as one that says to probe a live API before any spec is written. The project's alone | none |
132
133
  | `allow-to-stop-jobs` | `true` or `false`: whether turri stops a running job the spec has moved on from - a functional spec it regenerates changed, or a file one links was edited - rolls it back and regenerates the spec as it now is. `false`: the job runs to its end and lands, and what changed since is regenerated on top of it by the next job - see [regenerating the code](regenerating.md). Your own `halt` stops a job either way | `true` |
133
134
  | `release-after-pulse` | `true` or `false`: whether every pulse that lands code releases it, in the chat, as its last stage - before the module's next pulse starts, whatever the chat is doing: an agent on the coding model looks for the project's release guidance as the chat does (what was passed to `release` this conversation, AGENTS.md, the project's skills) and, when it says to release after a build, does what it says - see [deploy](deploy.md#after-every-pulse). One release a pulse that lands; a release that fails is said in the pulse's report, and what it landed stays | `false` |
@@ -142,7 +143,7 @@ models: # each agent role's model, thinking and tur
142
143
  | `toolchains` | folders of this machine an agent's commands may read beside the system's, the `PATH`'s and those the toolchain variables point at - a toolchain installed somewhere unusual (`[/srv/zig]`). A stack's add to the project's. See [the OS sandbox](sandbox.md#the-os-sandbox) | none |
143
144
  | `turn-limit` | seconds each turn of an agent a job starts has, for every role without its own (`models:`); `0` for none. The config is the only place it is set. A turn past it ends at its next request to the model - see [regenerating the code](regenerating.md) | 120 |
144
145
  | `models` | each agent role's own model, thinking and turn limit - see [models per role](#models-per-role) | every role on `coding-model`, the conversation's side on `harness-model` |
145
- | `testing-scripts-run-on` | what the testing scripts run on - always on this machine, in your environment. `in-place`: the real build and tests folders, the script at its own path, from the project - so a script that finds a host codebase from its own path finds it. `copy`: a fresh copy of the code, staged in `plain_modules/.turri/scripts/`, with the script copied beside it; it gives the coding agent `can_it_fail` (see [the testing scripts](regenerating.md#the-testing-scripts)) | `in-place` |
146
+ | `testing-scripts-run-on` | what the testing scripts run on - always on this machine, in your environment. `in-place`: the real build and tests folders, the script at its own path, from the project - so a script that finds a host codebase from its own path finds it. `copy`: a fresh copy of the code, staged in `plain_modules/.turri/scripts/`, with the script copied beside it. `can_it_fail` works on either: on a copy it changes the copy, in place the code itself for the one run, put back after it (see [the testing scripts](regenerating.md#the-testing-scripts)) | `in-place` |
146
147
 
147
148
  Keys are written with dashes; underscores are read the same (`conformance_tests`). A key turri
148
149
  does not know is ignored - another tool's `config.yaml`, read while it is the old file, may carry several - and so is a value of the