@turri-dev/cli 0.1.3-next.e5599c1 → 0.1.3

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/config.js CHANGED
@@ -189,8 +189,9 @@ export const ROLE_THINKING = {
189
189
  diagnosis: "medium",
190
190
  };
191
191
  /** The roles on the conversation's side: without their own entry they take the chat's model, not `default`. */
192
- // The release is not: it follows steps - a script, a start command - and runs on the coding model, thinking low.
193
- const CHAT_SIDE = ["chat", "chooser", "planner", "diagnosis"];
192
+ // The release is not: it follows steps - a script, a start command - and runs on the coding model, thinking low. Nor
193
+ // is the diagnosis: a post-mortem of a job that failed, read by the person - it runs on the coding model, thinking medium.
194
+ const CHAT_SIDE = ["chat", "chooser", "planner"];
194
195
  function isThinkingLevel(value) {
195
196
  return typeof value === "string" && THINKING_LEVELS.includes(value);
196
197
  }
package/dist/extension.js CHANGED
@@ -9,7 +9,7 @@ import { allocateImageId, Box, getCapabilities, getPngDimensions, isKeyRelease,
9
9
  import { defineTool } from "@earendil-works/pi-coding-agent";
10
10
  import { Type } from "typebox";
11
11
  import { CODING_MODEL_ENV } from "./chat-models.js";
12
- import { AGENT_ROLES, CONFIG_FILE, configForSpec, hasProjectConfig, LEGACY_CONFIG_FILE, projectConfigFile, stackConfigFileIn, stackOf, stacksOf, withStack, modelSpec, projectModels, readProjectConfig, roleModel, splitModelSpec } from "./config.js";
12
+ import { AGENT_ROLES, CONFIG_FILE, configForSpec, hasProjectConfig, LEGACY_CONFIG_FILE, projectConfigFile, stackConfigFileIn, stackOf, stacksOf, withStack, modelOnly, modelSpec, projectModels, readProjectConfig, roleModel, splitModelSpec } from "./config.js";
13
13
  import { skillRunDir } from "./regenerate/paths.js";
14
14
  import { sweepOrphanedGroups } from "./regenerate/shell.js";
15
15
  import { readScript, scriptAgainstMachine, stackOnMachine, toolchainsBlock } from "./stack.js";
@@ -90,15 +90,23 @@ aside) {
90
90
  // The question, with what the asker gives to read for it - a brief to confirm - above it; what it said of its work
91
91
  // before asking is kept in its record, never put in the dialog.
92
92
  // A dialog of turri's own: a long brief scrolls above the question, and the options always show (question-dialog.ts).
93
- const dialog = (question, context, options) => ctx.ui.custom((tui, theme, _keybindings, done) => new QuestionDialog({
94
- question,
95
- ...(context !== undefined ? { context } : {}),
96
- ...(options !== undefined ? { options } : {}),
97
- rows: () => tui.terminal.rows,
98
- style: { accent: (text) => theme.fg("accent", text), muted: (text) => theme.fg("muted", text), bold: (text) => theme.bold(text) },
99
- done,
100
- requestRender: () => tui.requestRender(),
101
- }));
93
+ const dialog = (question, context, options) => ctx.ui.custom((tui, theme, _keybindings, done) => {
94
+ const shown = new QuestionDialog({
95
+ question,
96
+ ...(context !== undefined ? { context } : {}),
97
+ ...(options !== undefined ? { options } : {}),
98
+ rows: () => tui.terminal.rows,
99
+ style: { accent: (text) => theme.fg("accent", text), muted: (text) => theme.fg("muted", text), bold: (text) => theme.bold(text) },
100
+ done: (answer) => {
101
+ if (questionShown === shown)
102
+ questionShown = undefined;
103
+ done(answer);
104
+ },
105
+ requestRender: () => tui.requestRender(),
106
+ });
107
+ questionShown = shown;
108
+ return shown;
109
+ });
102
110
  const asking = (asked) => runAsk(asked, {
103
111
  select: (title, options, context) => dialog(title, context, options),
104
112
  input: (title, context) => dialog(title, context),
@@ -117,6 +125,12 @@ aside) {
117
125
  }
118
126
  /** The side panel, as a question open in the chat reaches it: set once the extension has its panel. */
119
127
  let questionPeek;
128
+ /**
129
+ * The question open in the chat now, if any. The side panel gives the keys back to it: pi would give them to what had the
130
+ * focus when the panel first opened, and a panel kept beside the chat outlives that question - the keys would go to a
131
+ * dialog already answered, and nothing would take them.
132
+ */
133
+ let questionShown;
120
134
  /** A widget with nothing to draw: below the editor, it takes no line. */
121
135
  const PEEK_KEY_WIDGET = "turri-peek-key";
122
136
  /**
@@ -186,7 +200,8 @@ export default function (pi) {
186
200
  projectDir: cwd,
187
201
  harnessDir: PACKAGE_ROOT,
188
202
  jobLog,
189
- model: modelSpec(projectModels(readProjectConfig(cwd)).harness),
203
+ // The coding model the job ran on - its model alone: the diagnosis thinks as its role has it.
204
+ model: modelSpec(modelOnly(job.model ?? modelSpec(projectModels(readProjectConfig(cwd)).coding))),
190
205
  });
191
206
  return diagnosis !== undefined ? describeDiagnosis(diagnosis) : undefined;
192
207
  },
@@ -1507,6 +1522,7 @@ function registerJobTools(pi, jobs, cwd) {
1507
1522
  }
1508
1523
  needsLooking.delete(jobs);
1509
1524
  if (panel !== undefined) {
1525
+ panel.keepChatFocus();
1510
1526
  panel.handle?.setHidden(false);
1511
1527
  panel.keys = true;
1512
1528
  panel.handle?.focus();
@@ -1514,7 +1530,21 @@ function registerJobTools(pi, jobs, cwd) {
1514
1530
  }
1515
1531
  // Not awaited: the panel lives on while the jobs it shows run.
1516
1532
  void ctx.ui.custom((tui, theme, _keybindings, done) => {
1517
- const close = () => done(undefined);
1533
+ // What the chat shows when the panel takes the keys - its editor, or a pi dialog - for when it gives them back.
1534
+ const focusedNow = () => tui.getFocusedComponent?.() ?? null;
1535
+ let chatFocus = focusedNow();
1536
+ const keepChatFocus = () => {
1537
+ const focused = focusedNow();
1538
+ if (focused !== null && focused !== component && !(focused instanceof QuestionDialog))
1539
+ chatFocus = focused;
1540
+ };
1541
+ // The keys back to the chat: to the question open there now, else to what it showed - never to a question answered
1542
+ // while the panel was open.
1543
+ const giveBack = () => entry.handle?.unfocus({ target: questionShown ?? chatFocus });
1544
+ const close = () => {
1545
+ giveBack();
1546
+ done(undefined);
1547
+ };
1518
1548
  panelTerminal = tui.terminal;
1519
1549
  let component;
1520
1550
  // Beside the chat: the chat drawn narrower, on the left, and a click on either side giving it the keys - undone
@@ -1547,10 +1577,11 @@ function registerJobTools(pi, jobs, cwd) {
1547
1577
  // Beside the chat, back to it: the chat has the keys, the panel stays.
1548
1578
  const toChat = () => {
1549
1579
  entry.keys = false;
1550
- entry.handle?.unfocus();
1580
+ giveBack();
1551
1581
  tui.requestRender();
1552
1582
  };
1553
1583
  const toPanel = () => {
1584
+ keepChatFocus();
1554
1585
  entry.keys = true;
1555
1586
  entry.handle?.focus();
1556
1587
  tui.requestRender();
@@ -1603,7 +1634,7 @@ function registerJobTools(pi, jobs, cwd) {
1603
1634
  return focused !== null && focused !== component;
1604
1635
  },
1605
1636
  });
1606
- const entry = { view, close, keys: true };
1637
+ const entry = { view, close, keepChatFocus, keys: true };
1607
1638
  panel = entry;
1608
1639
  layOut();
1609
1640
  // Every key goes to the panel while it shows, whatever has the focus: a question the chat model asks in the
package/dist/loop-cli.js CHANGED
@@ -69,7 +69,7 @@ async function runLoopReporting(options) {
69
69
  const registry = createJobRegistry({
70
70
  retries: 1,
71
71
  diagnose: async (job, failures, jobLog) => {
72
- const diagnosis = await diagnoseFailure({ job, failures, projectDir, harnessDir: PACKAGE_ROOT, jobLog, model: modelSpec(projectModels(project).harness) ?? model });
72
+ const diagnosis = await diagnoseFailure({ job, failures, projectDir, harnessDir: PACKAGE_ROOT, jobLog, model: modelSpec(modelOnly(job.model ?? model)) });
73
73
  return diagnosis !== undefined ? describeDiagnosis(diagnosis) : undefined;
74
74
  },
75
75
  onChange: (job) => {
package/dist/pi-launch.js CHANGED
@@ -11,6 +11,7 @@ import { fileURLToPath, pathToFileURL } from "node:url";
11
11
  import { main, SettingsManager } from "@earendil-works/pi-coding-agent";
12
12
  import { ProcessTerminal } from "@earendil-works/pi-tui";
13
13
  import "./terminal-images.js";
14
+ import { resumeLine } from "./resume-line.js";
14
15
  /**
15
16
  * pi, started the way its own CLI starts it, for `turri`.
16
17
  *
@@ -31,6 +32,10 @@ const setTitle = ProcessTerminal.prototype.setTitle;
31
32
  ProcessTerminal.prototype.setTitle = function (title) {
32
33
  setTitle.call(this, title.replace(/^π(?= |$)/, "🪼 turri"));
33
34
  };
35
+ // What pi prints on the way out to resume the session names pi - its APP_NAME, a constant - which may not be on the
36
+ // PATH at all: turri takes the same flags, so it is turri the line names.
37
+ const write = process.stdout.write.bind(process.stdout);
38
+ process.stdout.write = ((chunk, ...rest) => write(typeof chunk === "string" ? resumeLine(chunk) : chunk, ...rest));
34
39
  // pi's own keys stand: a new line is shift+enter or ctrl+j. turri's side panel is on ctrl+h (job-panel.ts PANEL_KEY).
35
40
  // What pi's CLI does before main: the process title, pi's environment markers, the HTTP
36
41
  // dispatcher. Not exported, so loaded from the file - beside pi's entry point, wherever npm put it.
@@ -58,18 +58,23 @@ export class QuestionDialog {
58
58
  const choices = this.options.options ?? [];
59
59
  const body = this.input !== undefined
60
60
  ? this.input.render(inner)
61
- : choices.map((choice, index) => (index === this.selected ? style.accent(`› ${choice}`) : ` ${choice}`));
61
+ : // A long option wraps, its lines under its first, rather than cut off where the person cannot read it.
62
+ choices.flatMap((choice, index) => wrapTextWithAnsi(choice, Math.max(1, inner - 2)).map((line, at) => {
63
+ const shown = `${at === 0 && index === this.selected ? "›" : " "} ${line}`;
64
+ return index === this.selected ? style.accent(shown) : shown;
65
+ }));
62
66
  const hint = this.input !== undefined
63
67
  ? "enter answers · esc dismisses"
64
68
  : "↑↓ choose · enter picks · esc dismisses";
65
69
  // The brief gets what the question, the options and the hints leave of the screen.
66
- const fixed = question.length + body.length + 4;
70
+ const fixed = question.length + body.length + 5;
67
71
  const room = Math.max(3, this.options.rows() - KEPT_ABOVE - fixed);
68
72
  const scrolls = brief.length > room;
69
73
  this.window = scrolls ? room - 1 : brief.length;
70
74
  this.maxScroll = scrolls ? brief.length - this.window : 0;
71
75
  this.scroll = Math.min(this.scroll, this.maxScroll);
72
- const lines = [];
76
+ // Set apart from what is drawn above it - the job panel's hints.
77
+ const lines = [""];
73
78
  if (brief.length > 0) {
74
79
  lines.push(...brief.slice(this.scroll, this.scroll + this.window).map(pad));
75
80
  if (scrolls) {
@@ -43,7 +43,7 @@ export function questioningQuestion(phases) {
43
43
  return {
44
44
  question: `How many questions should I ask you in ${named}?`,
45
45
  options: QUESTIONING_LEVELS.map((level) => level.option),
46
- context: `Light, medium and thorough cap each of ${named} at 3, 5 and 10 questions - broader with fewer, so every level ` +
46
+ context: `Light, medium and thorough cap ${phases.length === 1 ? named : `each of ${named}`} at 3, 5 and 10 questions - broader with fewer, so every level ` +
47
47
  "covers the same ground, only in less or more depth. What the questions leave open, turri decides itself and " +
48
48
  "says what it chose. With best judgement, turri asks as much as it judges each phase needs. Each phase still " +
49
49
  "ends with your confirmation of its summary.",
@@ -183,6 +183,8 @@ export function describeToolCall(name, args) {
183
183
  return `± my_diff`;
184
184
  case "update_notes":
185
185
  return `✐ update_notes`;
186
+ case "report_spec_gap":
187
+ return `? spec gap: ${text("question") ?? ""}`.trimEnd();
186
188
  case "copy_resource":
187
189
  return `⎘ copy_resource ${path ?? text("to") ?? ""}`.trimEnd();
188
190
  case "can_it_fail":
@@ -7,7 +7,7 @@ import { abandonWork, startWork } from "./lineage.js";
7
7
  import { ensureRegressionPasses } from "./regression.js";
8
8
  import { modulesRoot, projectDirOf } from "./paths.js";
9
9
  import { applySpecDiff, snapshotSpec, specGapsText } from "./regenerate.js";
10
- import { linesAddedSince, readNotes } from "./notes.js";
10
+ import { gapMark, gapsSince } from "./notes.js";
11
11
  import { sectionsOf } from "./state.js";
12
12
  import { describeStop } from "./stop-report.js";
13
13
  import { missingTestLabels } from "./test-kinds.js";
@@ -41,8 +41,8 @@ export async function renderSpecDiffConformance(options) {
41
41
  // state, not to what an interrupted run left half-written. The tests and the whole suite are
42
42
  // one unit, landed whole or undone whole.
43
43
  const unit = startWork([buildDir, conformanceDir], moduleName);
44
- // The notes as its agents find them: a spec gap they add is told with the result.
45
- const notesBefore = { code: readNotes(buildDir), tests: readNotes(conformanceDir) };
44
+ // The spec gaps its agents report from here on are told with the result.
45
+ const gapsFrom = gapMark();
46
46
  const conformance = await renderConformanceTests({
47
47
  plainFile: tip.plainFile,
48
48
  frid: lastFrid,
@@ -58,8 +58,8 @@ export async function renderSpecDiffConformance(options) {
58
58
  });
59
59
  // What the codebase now has conformance tests for, as their labels say.
60
60
  const tested = () => frids.filter((frid) => missingTestLabels(conformanceDir, frid, []).length === 0);
61
- // Read before a rollback takes the notes back: a gap is the person's to decide, whether the tests passed or not.
62
- const base = { moduleName, buildDir, conformanceDir, diff: applied, conformance, specGaps: [...linesAddedSince(notesBefore.code, buildDir, "gaps"), ...linesAddedSince(notesBefore.tests, conformanceDir, "gaps")] };
61
+ // A gap is the person's to decide, whether the tests passed or not.
62
+ const base = { moduleName, buildDir, conformanceDir, diff: applied, conformance, specGaps: gapsSince(gapsFrom, [buildDir, conformanceDir]) };
63
63
  if (!conformance.passed) {
64
64
  abandonWork(unit, moduleName, notLandedWhy("for the spec change", conformance.unlabelled));
65
65
  return { ...base, tested: tested(), passed: false, stoppedAt: "conformance" };
@@ -7,6 +7,7 @@ import { confinedTools } from "./confine.js";
7
7
  import { ensureInModulesScratch, modulesScratchDir } from "./paths.js";
8
8
  import { workspaceBlock } from "./workspace.js";
9
9
  import { reportActivity } from "./activity.js";
10
+ import { runTiming, withTestingScripts } from "./test-scripts.js";
10
11
  import { createWebTools, WEB_TOOLS } from "./web.js";
11
12
  import { diffFiles, digestFiles } from "./codebase.js";
12
13
  import { ERROR_CAUSE_RULES, fixMethod, INTEGRITY_RULES, specPrimer } from "./prompt.js";
@@ -377,9 +378,17 @@ export function explorePrompt(buildDir, spec, scope, testingScripts, question, p
377
378
  ...(testingScripts !== undefined && testingScripts.length > 0
378
379
  ? [
379
380
  "",
380
- "This is the project's conformance testing script, which the harness runs to decide whether the",
381
- "tests pass - read it for what it builds or installs before the tests run, and so what the tests can depend on:",
382
- ...testingScripts.flatMap((script) => ["", `<script path="${script.path}" run-as="${script.runs}">`, script.content.trimEnd(), "</script>"]),
381
+ ...(testingScripts.some((script) => script.prepare === true)
382
+ ? [
383
+ "These are the project's prepare script, which the harness runs on the build first, and its conformance testing",
384
+ "script, which runs only once the prepare script passes and decides whether the tests pass - read both for what",
385
+ "they build or install before the tests run, and so what the tests can depend on:",
386
+ ]
387
+ : [
388
+ "This is the project's conformance testing script, which the harness runs to decide whether the",
389
+ "tests pass - read it for what it builds or installs before the tests run, and so what the tests can depend on:",
390
+ ]),
391
+ ...testingScripts.flatMap((script) => ["", `<script${script.prepare === true ? ' kind="prepare environment"' : ""} path="${script.path}" run-as="${script.runs}">`, script.content.trimEnd(), "</script>"]),
383
392
  ]
384
393
  : []),
385
394
  ...(previous !== undefined && question === undefined
@@ -703,7 +712,7 @@ export function unfoundedEvidence(evidence, opened) {
703
712
  "opened, the testing script, or the failing run - each with where. What <how to invoke it> says is not evidence: it " +
704
713
  "may be wrong, so check it against the testing script and the files.");
705
714
  }
706
- const inPrompt = (source) => /^(the )?(conformance )?testing script$|^(the )?failing run$/i.test(source.trim());
715
+ const inPrompt = (source) => /^(the )?(conformance )?testing script$|^(the )?prepare script$|^(the )?failing run$/i.test(source.trim());
707
716
  const unread = given.filter((item) => !inPrompt(item.source) && !opened(item.source.trim()));
708
717
  if (unread.length > 0) {
709
718
  return (`Your evidence cites ${unread.map((item) => item.source.trim()).join(", ")}, which you did not open. Open each file you cite ` +
@@ -734,7 +743,7 @@ export async function judgeFailure(options) {
734
743
  description: "For code: the conformance testing script's own words for what it needs the build to have - the file, entry point or module the run failed on - copied exactly from the script",
735
744
  })),
736
745
  evidence: Type.Optional(Type.Array(Type.Object({
737
- source: Type.String({ description: "Where: the path of a file you opened, `testing script`, or `failing run`" }),
746
+ source: Type.String({ description: "Where: the path of a file you opened, `testing script`, `prepare script` where there is one, or `failing run`" }),
738
747
  shows: Type.String({ description: "What it shows, e.g. `the script runs node dist/cli.js` or `tsconfig.json emits src/cli.ts as dist/src/cli.js`" }),
739
748
  }), { description: "What you found yourself, each with where - never what <how to invoke it> claims unchecked" })),
740
749
  functionalities: Type.Optional(Type.Array(Type.Object({
@@ -882,6 +891,8 @@ export function judgePrompt(options) {
882
891
  " the tests set up themselves - a credential, a variable or a fixture a test sets, overrides or names wrong: that is",
883
892
  " tests; nor for a toolchain or package missing where the tests run: the agents install those. The run stops on it",
884
893
  ` once it has been judged so ${ENVIRONMENT_RAISES} times in a row; until then the tests are checked for whether they cause it.`,
894
+ " A run the time limit stopped is environment only when nothing hangs and it needs more time than a test run may",
895
+ " take - and then it stops at once.",
885
896
  "",
886
897
  "When the output does not show why the software failed - it answered with an error that names no cause, and",
887
898
  "logged nothing about it - the code is what is wrong first: it hides the cause, and nobody can fix what they",
@@ -897,6 +908,12 @@ export function judgePrompt(options) {
897
908
  "what is wrong. What it does with the tests, the tests have to fit; what it needs of the code - a file it runs or",
898
909
  "checks for, a command it builds with - the code has to provide. A verdict that the script is wrong is neither",
899
910
  "code nor tests: say which of the two has to change to get past it.",
911
+ ...(scripts.some((script) => script.prepare === true)
912
+ ? [
913
+ "The prepare script below it runs on the build before every run, and the conformance testing script only once it",
914
+ "passes: it binds the same way - neither agent can change it, and what it needs of the code the code provides.",
915
+ ]
916
+ : []),
900
917
  "",
901
918
  ]
902
919
  : []),
@@ -926,13 +943,41 @@ export function judgePrompt(options) {
926
943
  "",
927
944
  `<how to invoke it>\n${options.invocation.trim()}\n</how to invoke it>`,
928
945
  "",
929
- ...scripts.flatMap((script) => [`<conformance testing script path="${script.path}" run-as="${script.runs}">`, script.content.trimEnd(), "</conformance testing script>", ""]),
946
+ ...scripts.flatMap((script) => {
947
+ const tag = script.prepare === true ? "prepare script" : "conformance testing script";
948
+ return [`<${tag} path="${script.path}" run-as="${script.runs}">`, script.content.trimEnd(), `</${tag}>`, ""];
949
+ }),
950
+ ...(options.run.timedOut === true ? [...timedOutBlock(options.run), ""] : []),
930
951
  `<failing run exit="${options.run.exitCode}" command="${options.run.command}">`,
952
+ runTiming(options.run),
953
+ "",
931
954
  options.run.output.trimEnd(),
932
955
  "</failing run>",
933
956
  ...(options.escalation !== undefined ? ["", ...escalationBlock(options.escalation)] : []),
934
957
  ].join("\n");
935
958
  }
959
+ /**
960
+ * For the judge, of a run the time limit stopped: what kept it from finishing - something that hangs, the code's or a
961
+ * test's, or a suite that is only slow, which no agent can give more time.
962
+ */
963
+ export function timedOutBlock(run) {
964
+ const limit = Math.round(run.timeoutMs / 1000);
965
+ return [
966
+ "<timed out>",
967
+ `This run did not end on its own: the time limit stopped it at ${limit}s, and it counts as failed. Its output ends where it`,
968
+ "was stopped - the step running then, or the one after the last it printed, is what did not finish. Decide what kept it:",
969
+ "- code: the software hangs - it waits on input, keeps a server in the foreground, never exits, loops, or blocks on a",
970
+ " lock or a call that never answers - when the tests reach it as the specification says.",
971
+ "- tests: a test waits for something that never comes - a process it started and never stops, output it waits for that",
972
+ " the software never prints, a port or a file nobody makes, a sleep or a retry with no end.",
973
+ "- environment: nothing hangs - the output shows the run making steady progress right up to the limit (installing,",
974
+ " building, test after test passing) and it needs more time than a test run may take. No agent can give it that: the",
975
+ " run stops at once, and the person is told to raise the limit. Say from the output how far it got, and what took",
976
+ " the time.",
977
+ "Judge from the output and the files, never from the time alone.",
978
+ "</timed out>",
979
+ ];
980
+ }
936
981
  /** For the judge: the tests were fixed for this failure, and it did not go away - is it the code's? */
937
982
  function escalationBlock(escalation) {
938
983
  const changed = escalation.changed.length === 0 ? "changed no file" : `changed ${escalation.changed.slice(0, 8).join(", ")}${escalation.changed.length > 8 ? ` and ${escalation.changed.length - 8} more` : ""}`;
@@ -976,7 +1021,10 @@ export async function createCodeFixer(options) {
976
1021
  model: options.model,
977
1022
  label: `${options.label} coding agent`, role: "coding",
978
1023
  system: `${fence.note}\n\n${workspaceBlock({ dir: options.buildDir, hasMyDiff: options.toolNames.includes("my_diff") })}`,
979
- task: codeFixerTask(options),
1024
+ // What the conformance testing script needs of the build, the code provides: the fixer reads it, not only a judge's quote of it.
1025
+ task: options.testingScripts !== undefined
1026
+ ? withTestingScripts(codeFixerTask(options), options.testingScripts.scripts, ["conformance", "unit"], options.testingScripts.root)
1027
+ : codeFixerTask(options),
980
1028
  compaction: { instructions: CODER_COMPACTION },
981
1029
  ...(options.checkEnvironment !== undefined ? { checkEnvironment: options.checkEnvironment } : {}),
982
1030
  });
@@ -1029,6 +1077,8 @@ export function codeFixPrompt(options) {
1029
1077
  `<why the code>\n${options.reason.trim()}\n</why the code>`,
1030
1078
  "",
1031
1079
  `<failing run command="${options.run.command}">`,
1080
+ runTiming(options.run),
1081
+ "",
1032
1082
  options.run.output.trimEnd(),
1033
1083
  "</failing run>",
1034
1084
  "",
@@ -1062,6 +1112,8 @@ export function escalatedFixPrompt(options) {
1062
1112
  "</evidence>",
1063
1113
  "",
1064
1114
  `<failing run command="${options.run.command}">`,
1115
+ runTiming(options.run),
1116
+ "",
1065
1117
  options.run.output.trimEnd(),
1066
1118
  "</failing run>",
1067
1119
  "",
@@ -1099,6 +1151,8 @@ export function testsFixPrompt(options) {
1099
1151
  `<why the tests>\n${options.reason.trim()}\n</why the tests>`,
1100
1152
  "",
1101
1153
  "<failing run>",
1154
+ runTiming(options.run),
1155
+ "",
1102
1156
  options.run.output.trimEnd(),
1103
1157
  "</failing run>",
1104
1158
  "",
@@ -9,12 +9,12 @@ import { abandonWork, diffSinceSnapshot, moduleDirOf, recordHistory, startWork,
9
9
  import { createWorkLedger, describeAccounts, SUBMIT_WORK_NOTE, unanswered, unansweredPrompt } from "./submit-work.js";
10
10
  import { CONFORMANCE_COMPACTION } from "./compaction.js";
11
11
  import { NOTES_TURN, notesForSession, passedOutcome, readNotes, reflectOnReview, withNotes } from "./notes.js";
12
- import { labelsPrompt, labelsPromptFor, misplacedConformanceTests, misplacedTestsPrompt, missingTestLabels } from "./test-kinds.js";
12
+ import { acceptanceLabel, acceptanceText, labelsPrompt, labelsPromptFor, misplacedConformanceTests, misplacedTestsPrompt, missingTestLabels } from "./test-kinds.js";
13
13
  import { createScriptTool, findTestScripts, projectRootFor, requireTestScripts, runConformanceScript, runUnitScript, failureSignature, STUCK_ROUNDS, scriptFailure, staticChecksOnly, withTestingScripts, } from "./test-scripts.js";
14
14
  import { createWebTools, WEB_TOOLS } from "./web.js";
15
15
  import { createMyDiffTool } from "./self-check.js";
16
16
  import { createServiceTools } from "./services.js";
17
- import { missingToolchainError, toolchainError } from "./environment-error.js";
17
+ import { missingToolchainError, timeLimitError, toolchainError } from "./environment-error.js";
18
18
  import { workspaceBlock } from "./workspace.js";
19
19
  import { codeFixPrompt, conflictKey, escalatedFixPrompt, createCodeFixer, answerAsExplorer, createAskExplorerTool, exploreInvocation, judgeFailure, SPEC_CONFLICT_RAISES, ENVIRONMENT_RAISES, environmentCheckPrompt, createTestReviewer, testReviewRequest, reviewFeedbackPrompt, testsFixPrompt, sortedRefs, } from "./conformance-agents.js";
20
20
  import { resolveRequiresChain } from "./requires.js";
@@ -157,9 +157,11 @@ export async function renderConformanceTests(options) {
157
157
  // may read the code but writes only tests. An explorer reads the code first and writes down how the
158
158
  // software is invoked, which is what the tests are written against.
159
159
  const label = `${moduleName} ${options.diff !== undefined ? "spec change" : frid}`;
160
- const specContext = { moduleName, text: specText(specifications, moduleName, frids, required, options.change ?? options.diff, sectionModules(tree, moduleName)) };
161
160
  // For a spec change: the functionalities it touches, whose acceptance tests are labelled, checked and reviewed.
162
161
  const touched = forChange ? touchedFunctionalities(tree, frids, options.diff) : [];
162
+ // The acceptance tests the run's tests carry out: every functionality the change touches, or the one under test.
163
+ const carriedOut = forChange ? touched : [{ frid: frid, acceptanceTests: specifications[ACCEPTANCE_TESTS] ?? [] }];
164
+ const specContext = { moduleName, text: specText(specifications, moduleName, frids, required, carriedOut, options.change ?? options.diff, sectionModules(tree, moduleName)) };
163
165
  // Any functionality of the codebase - this module's, and those of the modules it requires. A
164
166
  // functionality's run may raise a spec conflict only with that functionality; a spec diff's, between any two.
165
167
  const own = (forChange ? frids : frids.slice(0, frids.indexOf(frid) + 1)).map((id) => ({ module: moduleName, frid: id }));
@@ -223,11 +225,15 @@ export async function renderConformanceTests(options) {
223
225
  };
224
226
  stage(`exploring the code for how it is invoked${options.model ? ` (${options.model})` : ""}`);
225
227
  // The explorer reads the conformance testing script too: it is how the tests are built and run, and so how they reach the software.
228
+ // The prepare script, where there is one, runs on the build before it - and only once it passes does the suite run.
226
229
  const testingScripts = [
230
+ ...(scripts.prepare !== undefined
231
+ ? [{ path: relative(root, scripts.prepare), runs: "<script> <copy of the build>, before every run of the conformance testing script", content: readFileSync(scripts.prepare, "utf8"), prepare: true }]
232
+ : []),
227
233
  { path: relative(root, scripts.conformance), runs: "<script> <copy of the build> <copy of the whole conformance suite>", content: readFileSync(scripts.conformance, "utf8") },
228
234
  ];
229
235
  // The acceptance tests the explorer's plan has to carry out, step by step.
230
- const toCarryOut = (forChange ? touched : [{ frid: frid, acceptanceTests: specifications[ACCEPTANCE_TESTS] ?? [] }])
236
+ const toCarryOut = carriedOut
231
237
  .map((item) => ({ module: moduleName, frid: item.frid, count: item.acceptanceTests.length }))
232
238
  .filter((item) => item.count > 0);
233
239
  let invocation = await exploreInvocation({ buildDir, spec: specContext, scope, testingScripts, acceptance: toCarryOut, label, model: options.model, onDelta: options.onDelta });
@@ -272,6 +278,7 @@ export async function renderConformanceTests(options) {
272
278
  cwd: conformanceDir,
273
279
  customTools: [
274
280
  notes.tool,
281
+ notes.gapTool,
275
282
  work.tool,
276
283
  ...createWebTools(),
277
284
  ...fence.tools,
@@ -285,7 +292,7 @@ export async function renderConformanceTests(options) {
285
292
  }),
286
293
  createCopyResourceTool({ resources: linkedResources, dir: conformanceDir }),
287
294
  ],
288
- tools: [...fence.names, "run_conformance_tests", "my_diff", "ask_explorer", "update_notes", "submit_work", "copy_resource", ...WEB_TOOLS],
295
+ tools: [...fence.names, "run_conformance_tests", "my_diff", "ask_explorer", "update_notes", "report_spec_gap", "submit_work", "copy_resource", ...WEB_TOOLS],
289
296
  model: options.model,
290
297
  label: `${label} conformance agent`,
291
298
  role: "conformance",
@@ -313,12 +320,14 @@ export async function renderConformanceTests(options) {
313
320
  // The unit tests, and the conformance suite - to reproduce the failure and check the fix, seeing only its output.
314
321
  tools: [
315
322
  fixerNotes.tool,
323
+ fixerNotes.gapTool,
316
324
  createScriptTool({ kind: "unit", script: scripts.unit, run: () => runUnitScript(buildDir, scripts.unit), runs: unitRuns }),
317
325
  fixerConformanceRuns.tool,
318
326
  ...fixerServices.tools,
319
327
  ],
320
- toolNames: ["run_unit_tests", "run_conformance_tests", ...fixerServices.names, "update_notes"],
328
+ toolNames: ["run_unit_tests", "run_conformance_tests", ...fixerServices.names, "update_notes", "report_spec_gap"],
321
329
  checkEnvironment: { run: () => runUnitScript(buildDir, scripts.unit), script: scripts.unit },
330
+ testingScripts: { scripts, root },
322
331
  });
323
332
  fixerConformanceRuns.newTurn();
324
333
  return ask(fixer, withNotes(text, buildDir), options.onDelta);
@@ -494,19 +503,6 @@ export async function renderConformanceTests(options) {
494
503
  idleFixes = 0;
495
504
  continue;
496
505
  }
497
- // A run out of time is not a question of test or code: the tests' environment is the conformance agent's.
498
- if (recheck.timedOut === true) {
499
- const moved = await unmoved();
500
- if (moved === "stuck")
501
- break;
502
- if (moved === "asked")
503
- continue;
504
- stage("the conformance run did not get to the tests - back to the conformance agent");
505
- const fixed = await changing(() => askConformance(scriptFailure(recheck, "conformance testing"), options.onDelta));
506
- response = fixed.result;
507
- recordAttempt(rounds, recheck, `not a question of code or tests (${recheck.timedOut === true ? "the time limit" : `exit ${recheck.exitCode}`})`, { who: "conformance agent", files: fixed.files });
508
- continue;
509
- }
510
506
  stage(`conformance tests failing - working out whether the code, the tests or the spec are wrong${judgeModel ? ` (${judgeModel})` : ""}`);
511
507
  // A fix that changed no file leaves the next run as this one: IDLE_FIXES of them in a row, and nothing will change.
512
508
  const idle = (files) => {
@@ -541,6 +537,14 @@ export async function renderConformanceTests(options) {
541
537
  onDelta: options.onDelta,
542
538
  });
543
539
  const reason = verdict.reason.split("\n")[0].slice(0, 160);
540
+ // Stopped by the time limit while it was still getting on: no agent can give it more time. The pulse stops now -
541
+ // rolled back, no retry - and the person is told how to raise the limit.
542
+ if (verdict.culprit === "environment" && recheck.timedOut === true) {
543
+ stage(`the conformance run needs more than the ${Math.round(recheck.timeoutMs / 1000)}s a test run may take - stopping`);
544
+ if (start !== undefined)
545
+ abandonWork(start, moduleName, "the conformance testing script needs more time than a test run may take");
546
+ throw timeLimitError(recheck, { moduleName, script: scripts.conformance, kind: "conformance", reason: verdict.reason });
547
+ }
544
548
  // The environment - what the run is given - is the person's to fix: once judged so twice in a row, the run stops.
545
549
  if (verdict.culprit === "environment") {
546
550
  environmentRaises += 1;
@@ -692,7 +696,7 @@ export async function renderConformanceTests(options) {
692
696
  buildDir,
693
697
  conformanceDir,
694
698
  spec: specContext,
695
- functionalities: forChange ? touched : [{ frid: frid, acceptanceTests: specifications[ACCEPTANCE_TESTS] ?? [] }],
699
+ functionalities: carriedOut,
696
700
  forChange,
697
701
  invocation,
698
702
  label,
@@ -952,9 +956,10 @@ export function failureLine(run) {
952
956
  }
953
957
  /**
954
958
  * The spec as the explorer, the judge and the coding agent are shown it - its functional specs
955
- * numbered with their ids, so a spec conflict can name them.
959
+ * numbered with their ids, so a spec conflict can name them, and the acceptance tests the run carries
960
+ * out labelled as their tests are, so a verdict can quote them.
956
961
  */
957
- function specText(specifications, moduleName, frids, required, diff, modules) {
962
+ function specText(specifications, moduleName, frids, required, acceptance, diff, modules) {
958
963
  // Every functionality in the codebase, each with its module: the required modules' first, then this one's.
959
964
  const numbered = (key, items) => key === FUNCTIONAL_REQUIREMENTS
960
965
  ? [
@@ -962,10 +967,14 @@ function specText(specifications, moduleName, frids, required, diff, modules) {
962
967
  ]
963
968
  : items;
964
969
  // Each section in its tag, as every agent is shown it (see specPrimer).
965
- const sections = [DEFINITIONS, NON_FUNCTIONAL_REQUIREMENTS, TEST_REQUIREMENTS, FUNCTIONAL_REQUIREMENTS, ACCEPTANCE_TESTS]
970
+ const sections = [DEFINITIONS, NON_FUNCTIONAL_REQUIREMENTS, TEST_REQUIREMENTS, FUNCTIONAL_REQUIREMENTS]
966
971
  .map((key) => [key, specifications[key] ?? []])
967
972
  .filter(([, items]) => items.length > 0)
968
- .map(([key, items]) => (key === FUNCTIONAL_REQUIREMENTS || key === ACCEPTANCE_TESTS ? section(key, numbered(key, items)) : moduleSection(key, items, moduleName, modules)));
973
+ .map(([key, items]) => (key === FUNCTIONAL_REQUIREMENTS ? section(key, numbered(key, items)) : moduleSection(key, items, moduleName, modules)));
974
+ // Not only the last functionality's: a spec change's run carries out the acceptance tests of every one it touches.
975
+ const tests = acceptance.flatMap((item) => item.acceptanceTests.map((test, index) => `${acceptanceLabel(item.frid, index + 1)}: ${acceptanceText(test)}`));
976
+ if (tests.length > 0)
977
+ sections.push(section(ACCEPTANCE_TESTS, tests));
969
978
  if (diff !== undefined)
970
979
  sections.push(specChangeBlock(diff));
971
980
  return sections.join("\n\n");
@@ -4,6 +4,7 @@ import { Type } from "typebox";
4
4
  import { ask, BEGIN, createExecutor } from "../pi.js";
5
5
  import { confinedTools } from "./confine.js";
6
6
  import { createWebTools, WEB_TOOLS } from "./web.js";
7
+ import { runTiming } from "./test-scripts.js";
7
8
  /**
8
9
  * A fresh look at a failure the coding agent keeps hitting.
9
10
  *
@@ -24,9 +25,12 @@ export function diagnosisText(diagnosis) {
24
25
  }
25
26
  function debugPrompt(input) {
26
27
  const script = input.script !== undefined && existsSync(input.script) ? readFileSync(input.script, "utf8") : undefined;
28
+ const timedOut = input.run?.timedOut === true;
27
29
  return [
28
- `The unit tests of the codebase in ${input.buildDir} have failed the same way ${input.times} times in a row. The coding agent`,
29
- "keeps changing things and the failure does not move: it has not seen the cause. You look at it with fresh eyes.",
30
+ timedOut
31
+ ? `The unit testing script of the codebase in ${input.buildDir} did not finish: the time limit stopped it. You look at it with fresh eyes.`
32
+ : `The unit tests of the codebase in ${input.buildDir} have failed the same way ${input.times} times in a row. The coding agent`,
33
+ ...(timedOut ? [] : ["keeps changing things and the failure does not move: it has not seen the cause. You look at it with fresh eyes."]),
30
34
  "",
31
35
  "Find the root cause - the one thing that makes this failure happen - and the change that fixes it. Read the failing",
32
36
  "run below, the tests it names, the code they exercise, the build files (pyproject.toml, package.json, go.mod, pom.xml,",
@@ -37,6 +41,21 @@ function debugPrompt(input) {
37
41
  "",
38
42
  "You change nothing - you only read. When you know, call submit_diagnosis: the root cause, with the evidence for it,",
39
43
  "and the fix - which files, and exactly what to change in them.",
44
+ ...(timedOut
45
+ ? [
46
+ "",
47
+ "<timed out>",
48
+ "The run's output ends where the time limit stopped it: the test running then, or the step after the last one it",
49
+ "printed, is what did not finish. Find what kept it:",
50
+ "- something hangs - a test or the code waits on input, keeps a server in the foreground, never exits, loops, blocks",
51
+ " on a lock or a network call that never answers: the root cause and the fix, as for any failure;",
52
+ "- nothing hangs - the output shows the run making steady progress right up to the limit (installing, building, test",
53
+ " after test passing) and it needs more time than a test run may take: set too_slow, and say in root_cause from the",
54
+ " output how far it got and what took the time. No agent can give it more time: the work stops, and the person is",
55
+ " told to raise the limit. Judge from the output and the files, never from the time alone.",
56
+ "</timed out>",
57
+ ]
58
+ : []),
40
59
  "",
41
60
  "<what the change is meant to do>",
42
61
  input.task.trim(),
@@ -44,6 +63,7 @@ function debugPrompt(input) {
44
63
  ...(script !== undefined ? ["", `<testing script path="${input.script}">`, script.trimEnd(), "</testing script>"] : []),
45
64
  "",
46
65
  "<failing run>",
66
+ ...(input.run !== undefined ? [runTiming(input.run), ""] : []),
47
67
  input.failure.trimEnd().slice(-8000),
48
68
  "</failing run>",
49
69
  ].join("\n");
@@ -58,10 +78,14 @@ export async function debugFailure(input) {
58
78
  parameters: Type.Object({
59
79
  root_cause: Type.String({ description: "The one thing that makes the failure happen, and the evidence for it: the lines of the run, the code, the docs" }),
60
80
  fix: Type.String({ description: "The change that fixes it: which files, and exactly what to change in them" }),
81
+ too_slow: Type.Optional(Type.Boolean({
82
+ description: "Only for a run the time limit stopped: true when nothing hangs - it was making progress up to the limit and needs more time than a test run may take",
83
+ })),
61
84
  }),
62
85
  async execute(_id, params) {
63
86
  const given = params;
64
- found = { rootCause: given.root_cause, fix: given.fix };
87
+ // Too slow is a verdict on a run the limit stopped, and on no other.
88
+ found = { rootCause: given.root_cause, fix: given.fix, ...(given.too_slow === true && input.run?.timedOut === true ? { tooSlow: true } : {}) };
65
89
  return { content: [{ type: "text", text: "Recorded." }], details: {}, terminate: true };
66
90
  },
67
91
  });