@turri-dev/cli 0.1.3-next.f74e98a → 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.
Files changed (46) hide show
  1. package/README.md +22 -1
  2. package/dist/ask.js +34 -15
  3. package/dist/cli-options.js +12 -6
  4. package/dist/config-edit.js +1 -0
  5. package/dist/config.js +5 -2
  6. package/dist/extension.js +86 -25
  7. package/dist/genome.js +1 -1
  8. package/dist/init-config.js +5 -0
  9. package/dist/loop-cli.js +13 -1
  10. package/dist/loop-tools.js +31 -12
  11. package/dist/pi-launch.js +5 -0
  12. package/dist/pi.js +48 -19
  13. package/dist/question-dialog.js +9 -3
  14. package/dist/questioning.js +1 -1
  15. package/dist/regenerate/activity.js +14 -0
  16. package/dist/regenerate/conform.js +5 -5
  17. package/dist/regenerate/conformance-agents.js +28 -8
  18. package/dist/regenerate/conformance.js +24 -10
  19. package/dist/regenerate/list-arguments.js +121 -0
  20. package/dist/regenerate/loop.js +137 -18
  21. package/dist/regenerate/notes.js +66 -17
  22. package/dist/regenerate/prompt.js +3 -1
  23. package/dist/regenerate/regenerate.js +16 -10
  24. package/dist/regenerate/regression.js +2 -1
  25. package/dist/regenerate/requires.js +55 -2
  26. package/dist/regenerate/self-check.js +13 -6
  27. package/dist/regenerate/test-scripts.js +54 -10
  28. package/dist/regenerate/unit-review.js +12 -1
  29. package/dist/regenerate-cli.js +11 -5
  30. package/dist/release-tools.js +1 -1
  31. package/dist/resume-line.js +4 -0
  32. package/dist/review/live.js +2 -1
  33. package/dist/run-report.js +34 -1
  34. package/dist/spec-tools.js +10 -45
  35. package/docs/authoring-plain.md +9 -6
  36. package/docs/config.md +3 -2
  37. package/docs/headless.md +30 -3
  38. package/docs/installation.md +3 -0
  39. package/docs/regenerating.md +69 -20
  40. package/docs/skills-and-gates.md +5 -3
  41. package/docs/using.md +20 -9
  42. package/genome/skills/bud/SKILL.md +67 -36
  43. package/genome/skills/bud/references/intent.md +4 -0
  44. package/genome/skills/refactor-module/SKILL.md +24 -2
  45. package/package.json +3 -3
  46. package/genome/skills/bud/references/checklist.md +0 -44
@@ -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
+ }
@@ -16,7 +16,7 @@ import { modulesRoot } from "./paths.js";
16
16
  import { budgetFor, choosingWhen, configForSpec, conformanceSwitchedOn } from "../config.js";
17
17
  import { describeSpecChange } from "./prompt.js";
18
18
  import { resolveTemplateDirs } from "./paths.js";
19
- import { builtTips, copyRequiredCode, newlyRequired, resolveRequiresChain, startFromScratch } from "./requires.js";
19
+ import { builtTips, copyRequiredCode, importingModules, isImportModule, newlyRequired, resolveRequiresChain, startFromScratch } from "./requires.js";
20
20
  import { withTryItLine } from "./delivery.js";
21
21
  import { describeSpecDiff, renderSpecDiff, specFilesOf } from "./regenerate.js";
22
22
  import { locateDiffLines } from "./diff-view.js";
@@ -85,6 +85,23 @@ function chainsFor(plainFile) {
85
85
  const tips = builtTips(plainFile);
86
86
  return tips.length > 0 ? tips : [resolveRequiresChain(plainFile, [], undefined, { allowNoFunctionalities: true })];
87
87
  }
88
+ /**
89
+ * The modules a .plain file is built as: itself - or, an import module, the modules importing it whose code is started.
90
+ * An import module is no codebase; one no started module imports has nothing to build yet - its reqs are built with the
91
+ * first module that imports it.
92
+ */
93
+ function codebasesOf(plainFile) {
94
+ if (!isImportModule(plainFile))
95
+ return [plainFile];
96
+ return importingModules(plainFile).filter((file) => {
97
+ try {
98
+ return builtTips(file).length > 0 || started(resolveRequiresChain(file, [], undefined, { allowNoFunctionalities: true }).at(-1));
99
+ }
100
+ catch {
101
+ return false;
102
+ }
103
+ });
104
+ }
88
105
  /** How many functional specs of its own a codebase has built - none when it was only started from the code below it. */
89
106
  function ownBuilt(entry) {
90
107
  return (readRecord(entry.buildDir)?.[FUNCTIONAL_REQUIREMENTS] ?? []).length;
@@ -361,6 +378,8 @@ export function createWorkLoop(options) {
361
378
  const waiting = (why) => ({ module: entry.moduleName, why: `waiting for ${entry.moduleName}: ${why}` });
362
379
  if (below.running !== undefined)
363
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");
364
383
  const spec = chainSpec(below.chain);
365
384
  if (codeWork(builtOf(below), spec.tree).length > 0)
366
385
  return waiting("the code it is built on is not built yet");
@@ -469,6 +488,11 @@ export function createWorkLoop(options) {
469
488
  /** A dry run's first jobs, by codebase: what each would start. */
470
489
  const firsts = new Map();
471
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
+ }
472
496
  const tip = tipEntry(state);
473
497
  if (options.dryRun === true) {
474
498
  firsts.set(tip.buildDir, { spec: planned.track === "conformance" ? spec : { ...spec, tree: planned.step.tree }, planned });
@@ -573,7 +597,14 @@ export function createWorkLoop(options) {
573
597
  }
574
598
  return {
575
599
  report: released !== undefined ? `${report}\n\n${released}` : report,
576
- 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
+ },
577
608
  };
578
609
  },
579
610
  });
@@ -756,16 +787,37 @@ export function createWorkLoop(options) {
756
787
  }
757
788
  return states;
758
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
+ };
759
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
+ }
760
807
  const now = active();
761
808
  looking = now;
762
809
  for (const key of order) {
763
810
  const state = modules.get(key);
764
- // 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.
765
813
  if (now.has(state) || state.running !== undefined)
766
814
  await look(state);
767
- else
815
+ else {
768
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
+ }
769
821
  }
770
822
  };
771
823
  const look = async (state) => {
@@ -776,6 +828,12 @@ export function createWorkLoop(options) {
776
828
  }
777
829
  catch (error) {
778
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
+ }
779
837
  return;
780
838
  }
781
839
  const specKey = keyOf(spec);
@@ -828,6 +886,11 @@ export function createWorkLoop(options) {
828
886
  return;
829
887
  }
830
888
  hashResources(state, spec);
889
+ if (state.held !== undefined) {
890
+ state.why = state.held.why;
891
+ state.waitsFor = undefined;
892
+ return;
893
+ }
831
894
  if (state.halted !== undefined) {
832
895
  if (state.halted.specKey === specKey) {
833
896
  state.why = state.halted.why;
@@ -988,13 +1051,18 @@ export function createWorkLoop(options) {
988
1051
  return state;
989
1052
  };
990
1053
  const loop = {
991
- async bringUp(plainFile, request = {}) {
992
- const file = resolve(options.cwd, plainFile);
993
- asked.set(file, { ...asked.get(file), ...request });
994
- const states = withParseCache(() => chainsFor(file).flatMap((chain) => toBuild(chain).map((entry) => track(chain.slice(0, chain.indexOf(entry) + 1), file, request))));
995
- // Asked again, a halted codebase is tried again.
996
- for (const state of states)
1054
+ async bringUp(plainFile, given = {}) {
1055
+ const { specChange, ...request } = given;
1056
+ const files = codebasesOf(resolve(options.cwd, plainFile));
1057
+ for (const file of files)
1058
+ asked.set(file, { ...asked.get(file), ...request });
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)))));
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) {
997
1062
  state.halted = undefined;
1063
+ if (specChange !== true)
1064
+ state.held = undefined;
1065
+ }
998
1066
  await tick();
999
1067
  return [...new Set(states)].map(statusOf);
1000
1068
  },
@@ -1062,7 +1130,7 @@ export function createWorkLoop(options) {
1062
1130
  report.scheduled = (state.scheduled ?? []).map((group) => ({ frids: group.specs.map((touched) => touched.frid), unbuilt: group.unbuilt }));
1063
1131
  if (state.running !== undefined)
1064
1132
  report.running = { jobId: state.running.jobId, title: state.running.planned.title };
1065
- const halted = state.halted?.why ?? state.conformanceHalted?.why;
1133
+ const halted = state.held?.why ?? state.halted?.why ?? state.conformanceHalted?.why;
1066
1134
  if (halted !== undefined)
1067
1135
  report.why = halted;
1068
1136
  if (state.startOver !== undefined)
@@ -1149,6 +1217,7 @@ export function createWorkLoop(options) {
1149
1217
  }
1150
1218
  state.conformanceHalted = undefined;
1151
1219
  state.halted = undefined;
1220
+ state.held = undefined;
1152
1221
  }
1153
1222
  await tick();
1154
1223
  return [...new Set(states)].map((state) => {
@@ -1178,19 +1247,67 @@ export function createWorkLoop(options) {
1178
1247
  startAgain(entry, `it now requires ${requires.join(", ")}, which its code was not built on`);
1179
1248
  return loop.bringUp(plainFile, request);
1180
1249
  },
1181
- async fromScratch(plainFile, request = {}) {
1250
+ async fromScratch(plainFile, { chain, ...request } = {}) {
1182
1251
  const file = resolve(options.cwd, plainFile);
1183
- // Where its code lives: the tips its module is built in, or - none built yet - its own codebase.
1184
- 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()];
1185
1257
  for (const entry of codebases) {
1186
1258
  if (modules.get(entry.buildDir)?.running !== undefined)
1187
1259
  throw new Error(`${entry.moduleName} has a pulse running: halt it, or ask again once it is done.`);
1188
1260
  }
1261
+ const why = chain === true ? "asked to be regenerated from scratch, with its whole chain" : "asked to be regenerated from scratch";
1189
1262
  for (const entry of codebases)
1190
1263
  if (started(entry))
1191
- startAgain(entry, "asked to be regenerated from scratch");
1264
+ startAgain(entry, why);
1192
1265
  return loop.bringUp(plainFile, request);
1193
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
+ },
1194
1311
  status() {
1195
1312
  return order.map((key) => statusOf(modules.get(key)));
1196
1313
  },
@@ -1405,7 +1522,7 @@ export function describeModules(statuses, options = {}) {
1405
1522
  ` Ask the user whether to start ${codebases.join(", ")} over, and say why: ${codebases.join(", ")} was built without ` +
1406
1523
  `${requires.join(", ")}, so no change to its code can bring ${requires.join(", ")} in - its code and conformance ` +
1407
1524
  "tests are taken out, kept in its history, and built again from the bottom of the chain. Only if they agree, " +
1408
- `call regenerate with ${basename(status.plainFile)} and from_scratch.`,
1525
+ `call regenerate with ${basename(status.plainFile)} and from_scratch: "module".`,
1409
1526
  ];
1410
1527
  };
1411
1528
  return statuses
@@ -1459,7 +1576,7 @@ const defaultConformanceRunner = async (job, onDelta) => {
1459
1576
  writeTestsRecord(result.conformanceDir, job.planned.step.tree);
1460
1577
  recordHistory(job.buildDir, `conformance tests: ${job.planned.title}`);
1461
1578
  }
1462
- return { landed: result.passed, report: describeSpecDiffConformance(result) };
1579
+ return { landed: result.passed, report: describeSpecDiffConformance(result), ...(result.specGaps !== undefined ? { specGaps: result.specGaps } : {}) };
1463
1580
  };
1464
1581
  /** A job as a spec diff render, landed on its unit tests: conformance is a track of its own. */
1465
1582
  const defaultRunner = async (job, onDelta) => {
@@ -1475,7 +1592,9 @@ const defaultRunner = async (job, onDelta) => {
1475
1592
  onDelta,
1476
1593
  });
1477
1594
  // Landed code can be tried.
1478
- 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
+ };
1479
1598
  };
1480
1599
  /** How a code pulse went, for its line in the notes: the rounds it took, its test runs, what the debugger found. */
1481
1600
  export function codeStory(result) {
@@ -1,5 +1,5 @@
1
1
  import { existsSync, readFileSync, rmSync, writeFileSync } from "node:fs";
2
- import { basename, dirname, join } from "node:path";
2
+ import { basename, dirname, join, resolve } from "node:path";
3
3
  import { defineTool } from "@earendil-works/pi-coding-agent";
4
4
  import { Type } from "typebox";
5
5
  import { reportActivity } from "./activity.js";
@@ -40,7 +40,6 @@ export const SECTIONS = {
40
40
  where: "Where things are",
41
41
  run: "How to build, run and test",
42
42
  assumptions: "Assumptions",
43
- gaps: "Spec gaps",
44
43
  pitfalls: "Pitfalls",
45
44
  pulses: "Pulses",
46
45
  };
@@ -53,8 +52,13 @@ export function notesPath(buildDir) {
53
52
  return join(buildDir, NOTES_FILE);
54
53
  }
55
54
  function empty() {
56
- return { where: [], run: [], assumptions: [], gaps: [], pitfalls: [], pulses: [] };
55
+ return { where: [], run: [], assumptions: [], pitfalls: [], pulses: [] };
57
56
  }
57
+ /**
58
+ * Sections the notes no longer have, their lines dropped as they are read: the spec gaps are the person's, reported
59
+ * with report_spec_gap - the choice made meanwhile is an assumption, which stays.
60
+ */
61
+ const DROPPED = new Set(["spec gaps"]);
58
62
  /** The notes, as lines per section. Lines under no known heading go to pitfalls, not lost. */
59
63
  export function parseNotes(text) {
60
64
  const notes = empty();
@@ -63,11 +67,12 @@ export function parseNotes(text) {
63
67
  const line = raw.trim();
64
68
  const heading = /^##\s+(.+)$/.exec(line);
65
69
  if (heading) {
66
- section = ORDER.find((key) => SECTIONS[key].toLowerCase() === heading[1].trim().toLowerCase()) ?? section;
70
+ const named = heading[1].trim().toLowerCase();
71
+ section = DROPPED.has(named) ? undefined : (ORDER.find((key) => SECTIONS[key].toLowerCase() === named) ?? section ?? "pitfalls");
67
72
  continue;
68
73
  }
69
74
  const item = /^[-*]\s+(.+)$/.exec(line);
70
- if (item)
75
+ if (item && section !== undefined)
71
76
  notes[section].push(item[1].trim());
72
77
  }
73
78
  return notes;
@@ -93,14 +98,14 @@ const GUIDANCE = [
93
98
  `- ${SECTIONS.where}: entry points, layout, where each functionality and its tests live.`,
94
99
  `- ${SECTIONS.run}: the commands that build, run and test it, and what had to be installed for them.`,
95
100
  `- ${SECTIONS.assumptions}: what you assumed where the specification is silent - a format, a default, a`,
96
- " choice it leaves open. Build on the assumptions already there; change or remove one the moment the code",
97
- " or the specification shows it wrong.",
98
- `- ${SECTIONS.gaps}: what the specification should say and does not - a behaviour you had to decide that the`,
99
- " person would want to decide, not a detail of how. Each is put to the person, to be written into the",
100
- " specification. One a line, as the question it leaves: \"What happens to a contact archived in HubSpot after it",
101
- " was synced?\"",
101
+ " choice it leaves open - and the tests that assert it, when any do: \"A Dash drains Pulses at 1/s - asserted in",
102
+ " predators.test.ts, The Dash\". One no test asserts is written down all the same. Build on the assumptions",
103
+ " already there; change or remove one the moment the code or the specification shows it wrong - and the tests",
104
+ " it names with it.",
102
105
  `- ${SECTIONS.pitfalls}: what went wrong and what fixed it, approaches that did not work.`,
103
106
  `- ${SECTIONS.pulses}: written by turri as each pulse ends - read them, never write them.`,
107
+ "A behaviour you had to decide that the person would want to decide - not a detail of how - is not a note: report",
108
+ "it with report_spec_gap, with the assumption you made meanwhile.",
104
109
  "Each line stands on its own, for someone who never saw your work. When and where it came from is added",
105
110
  "to it for you - do not write it. Where two lines disagree, the later one is right: change the older one",
106
111
  'rather than add a contradicting line. Leave a section with nothing new alone: "none" is not a note.',
@@ -232,7 +237,7 @@ export function createNotesTool(buildDir, onWrite, before = () => { }, source) {
232
237
  label: "Update notes",
233
238
  description: "Update the working notes on this codebase for the next agent - add a line, change one that is no longer " +
234
239
  "true, remove one that is wrong - in its sections: where things are, how to build, run and test, " +
235
- "assumptions made where the specification is silent, spec gaps the person should decide, and pitfalls. Never " +
240
+ "assumptions made where the specification is silent, and pitfalls. Never " +
236
241
  "requirements: the specification is never an assumption.",
237
242
  promptSnippet: "leave the next agent what you learned and assumed about this codebase",
238
243
  parameters: Type.Object({
@@ -283,7 +288,7 @@ export function sectionNamed(name) {
283
288
  /** How many times an agent that finishes without update_notes is asked to call it. */
284
289
  export const NOTES_ASKS = 3;
285
290
  /** The turn that asks for the notes: update_notes is the only tool it may use - the work it follows is done. */
286
- export const NOTES_TURN = { onlyTools: ["update_notes"] };
291
+ export const NOTES_TURN = { onlyTools: ["update_notes", "report_spec_gap"] };
287
292
  /** What the notes turn says first, once the harness's own run of `script` has passed on the work. */
288
293
  export function passedOutcome(script) {
289
294
  return (`The harness ran the project's ${script} on your work itself, and it passed: your work is done and accepted. ` +
@@ -327,10 +332,53 @@ export function recordPulse(buildDir, text, source) {
327
332
  // The notes are a help, not the work.
328
333
  }
329
334
  }
330
- /** The lines of a section added since `before` - a pulse's new spec gaps, say - without when and where they came from. */
331
- export function linesAddedSince(before, buildDir, section) {
332
- const known = new Set(before[section]);
333
- return readNotes(buildDir)[section].filter((line) => !known.has(line)).map((line) => line.replace(/^\[[^\]]*\]\s*/, ""));
335
+ /** Every spec gap reported in this process, with the codebase it was met in: a pulse reads those since it started. */
336
+ const reportedGaps = [];
337
+ /** Where the spec gaps stand now: what `gapsSince` reads from. */
338
+ export function gapMark() {
339
+ return reportedGaps.length;
340
+ }
341
+ /** The spec gaps reported in these codebases since `mark`. */
342
+ export function gapsSince(mark, dirs) {
343
+ const wanted = new Set(dirs.map((dir) => resolve(dir)));
344
+ return reportedGaps.slice(mark).filter((entry) => wanted.has(entry.dir)).map((entry) => entry.gap);
345
+ }
346
+ /**
347
+ * `report_spec_gap`: a behaviour the specification leaves open that the person would want to decide, put to them as
348
+ * the pulse ends - never into the notes, which are the next agent's. What the agent decided meanwhile goes into the
349
+ * notes' assumptions, so the code built on it is known for what it is until the specification settles it.
350
+ */
351
+ export function createSpecGapTool(buildDir, source) {
352
+ return defineTool({
353
+ name: "report_spec_gap",
354
+ label: "Report a spec gap",
355
+ description: "Report a spec gap: a behaviour the specification leaves open that the person would want to decide - not a detail " +
356
+ "of how. Decide it meanwhile and carry on: the person is asked once the work ends, and what they decide is " +
357
+ "written into the specification. The assumption you made is added to the notes' assumptions for you.",
358
+ promptSnippet: "tell the person about a behaviour the specification leaves open, and what you decided meanwhile",
359
+ parameters: Type.Object({
360
+ question: Type.String({ description: 'The question it leaves the person, one line: "What happens to a contact archived in HubSpot after it was synced?"' }),
361
+ assumption: Type.String({
362
+ description: "What you decided meanwhile, as its line in the notes' assumptions - with the tests that assert it, when any do: " +
363
+ '"An archived contact is left as synced - asserted in sync.test.ts, archived contacts".',
364
+ }),
365
+ }),
366
+ async execute(_id, params) {
367
+ const question = params.question.replace(/\s+/g, " ").trim();
368
+ const assumption = params.assumption.replace(/\s+/g, " ").trim();
369
+ if (question === "" || assumption === "")
370
+ throw new Error("Nothing reported - a spec gap needs both the question it leaves and the assumption you made meanwhile.");
371
+ // However many there are, spec gaps are put to the person - never a reason to stop the pulse.
372
+ reportedGaps.push({ dir: resolve(buildDir), gap: { question, assumption } });
373
+ const known = readNotes(buildDir).assumptions.some((line) => body(line) === assumption);
374
+ if (!known)
375
+ recordNote(buildDir, "assumptions", assumption, source ?? "spec gap");
376
+ return {
377
+ content: [{ type: "text", text: `Reported. The assumption is in the notes' assumptions${known ? " already" : " now"} - do not add it again.` }],
378
+ details: { question, assumption },
379
+ };
380
+ },
381
+ });
334
382
  }
335
383
  /** The notes, for an agent that reads them but leaves none - a judge. Empty when there are none. */
336
384
  export function notesToRead(buildDir) {
@@ -367,6 +415,7 @@ export function notesForSession(buildDir, source) {
367
415
  return true;
368
416
  };
369
417
  return {
418
+ gapTool: createSpecGapTool(buildDir, source),
370
419
  tool: createNotesTool(buildDir, (text) => {
371
420
  written = true;
372
421
  knownNotes.set(file, text);
@@ -278,8 +278,10 @@ function itemText(serialized) {
278
278
  return item;
279
279
  const { markdown, [ACCEPTANCE_TESTS]: tests } = (item ?? {});
280
280
  const lines = [markdown ?? JSON.stringify(item)];
281
+ // Each test is an item of the tree, its text in its markdown - as spec-steps.ts `itemText` reads it.
282
+ const testText = (test) => (typeof test === "string" ? test : (test?.markdown ?? JSON.stringify(test)));
281
283
  if (Array.isArray(tests) && tests.length > 0)
282
- lines.push(" <acceptance tests>", ...tests.map((test) => ` ${String(test)}`), " </acceptance tests>");
284
+ lines.push(" <acceptance tests>", ...tests.map((test) => ` ${testText(test).replace(/\n/g, "\n ")}`), " </acceptance tests>");
283
285
  return lines.join("\n");
284
286
  }
285
287
  const indent = (text, by) => text.split("\n").map((line) => `${by}${line}`).join("\n");
@@ -14,7 +14,7 @@ import { buildSpecDiffPrompt, describeSpecChange, reviewedSpec, sectionModules }
14
14
  import { abandonWork, recordHistory, startWork } from "./lineage.js";
15
15
  import { createWorkLedger, SUBMIT_WORK_NOTE } from "./submit-work.js";
16
16
  import { CODER_COMPACTION } from "./compaction.js";
17
- import { linesAddedSince, NOTES_TURN, notesForSession, passedOutcome, readNotes, recordNote, withNotes } from "./notes.js";
17
+ import { gapMark, gapsSince, NOTES_TURN, notesForSession, passedOutcome, recordNote, withNotes } from "./notes.js";
18
18
  import { createLoopWatch, createScriptTool, failureSignature, findTestScripts, projectRootFor, requireTestScripts, runUnitScript, STUCK_ROUNDS, withoutConformance, withTestingScripts, } from "./test-scripts.js";
19
19
  import { createWebTools, WEB_TOOLS } from "./web.js";
20
20
  import { createCanItFailTool, createMyDiffTool, selfCheckNote } from "./self-check.js";
@@ -268,8 +268,8 @@ export async function renderSpecDiff(options) {
268
268
  ...(options.cases !== undefined ? { cases: options.cases } : {}),
269
269
  });
270
270
  const digestsBefore = digestFiles(buildDir);
271
- // The notes as the agent finds them: what it adds - a spec gap above all - is told with the result.
272
- const notesBefore = readNotes(buildDir);
271
+ // The spec gaps its agents report from here on are told with the result.
272
+ const gapsFrom = gapMark();
273
273
  /** What the debugger found, each time it was asked: the pulse's line in the notes says it. */
274
274
  const diagnosed = [];
275
275
  const runs = [];
@@ -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 });
@@ -305,6 +307,7 @@ export async function renderSpecDiff(options) {
305
307
  cwd: buildDir,
306
308
  customTools: [
307
309
  notes.tool,
310
+ notes.gapTool,
308
311
  work.tool,
309
312
  ...createWebTools(),
310
313
  createScriptTool({ kind: "unit", script: scripts.unit, run: () => runUnitScript(buildDir, scripts.unit), runs, watch: loop }),
@@ -313,7 +316,7 @@ export async function renderSpecDiff(options) {
313
316
  ...fence.tools,
314
317
  createCopyResourceTool({ resources: linkedResources, dir: buildDir }),
315
318
  ],
316
- tools: [...fence.names, "run_unit_tests", ...selfChecks.map((tool) => tool.name), ...services.names, "update_notes", "submit_work", "copy_resource", ...WEB_TOOLS],
319
+ tools: [...fence.names, "run_unit_tests", ...selfChecks.map((tool) => tool.name), ...services.names, "update_notes", "report_spec_gap", "submit_work", "copy_resource", ...WEB_TOOLS],
317
320
  model: options.model,
318
321
  label: `${moduleName} spec change coding agent`,
319
322
  role: "coding",
@@ -498,7 +501,8 @@ export async function renderSpecDiff(options) {
498
501
  forChange: true,
499
502
  ...(options.cases !== undefined ? { cases: options.cases } : {}),
500
503
  label: `${moduleName} spec change`,
501
- ...(scripts.runOn === "copy" ? { unitScript: scripts.unit } : {}),
504
+ ...(mutationTesting ? { unitScript: scripts.unit } : {}),
505
+ testingScript: { path: relative(root, scripts.unit), content: readFileSync(scripts.unit, "utf8") },
502
506
  model: options.judgeModel ?? modelSpec(inheritModel(configForSpec(tip.plainFile).judgeModel, modelOnly(options.model))),
503
507
  send: async (next) => {
504
508
  response = await ask(executor, next, options.onDelta);
@@ -541,8 +545,8 @@ export async function renderSpecDiff(options) {
541
545
  testRemovals,
542
546
  files,
543
547
  ...(steering !== undefined && steering.steers > 0 ? { steered: [...steering.notes] } : {}),
544
- // Read before a rollback takes the notes back: a gap the agent met is the person's to decide, whether it landed or not.
545
- specGaps: linesAddedSince(notesBefore, buildDir, "gaps"),
548
+ // A gap the agent met is the person's to decide, whether it landed or not.
549
+ specGaps: gapsSince(gapsFrom, [buildDir]),
546
550
  diagnosed,
547
551
  };
548
552
  /** The change landed: what the code is built from is now the spec with the change in, committed with it. */
@@ -579,8 +583,10 @@ export function specGapsText(gaps) {
579
583
  return [];
580
584
  return [
581
585
  "",
582
- "Spec gaps its agents met - the spec does not say, so they decided. Put each to the user, and write the ones they decide into the spec:",
583
- ...gaps.map((gap) => `- ${gap}`),
586
+ "Spec gaps its agents met - the spec does not say, so they decided, each as an assumption in the codebase's notes. Put " +
587
+ "each to the user, and write the ones they decide into the spec - the pulse that builds it is told the assumption " +
588
+ "it replaces:",
589
+ ...gaps.map((gap) => `- ${gap.question} Meanwhile: ${gap.assumption}`),
584
590
  ];
585
591
  }
586
592
  /** What a rendered spec change did, for the agent and the person. */