@trama-dev/runtime 0.4.0 → 0.6.0

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 (56) hide show
  1. package/README.md +4 -3
  2. package/dist/abort.d.ts +12 -0
  3. package/dist/abort.js +31 -0
  4. package/dist/agent-backend.d.ts +127 -7
  5. package/dist/agent-backend.js +38 -19
  6. package/dist/agent-host.d.ts +50 -0
  7. package/dist/agent-host.js +97 -0
  8. package/dist/agent-hosts.d.ts +14 -0
  9. package/dist/agent-hosts.js +321 -0
  10. package/dist/agent.d.ts +26 -3
  11. package/dist/agent.js +165 -43
  12. package/dist/bridge-client.d.ts +6 -0
  13. package/dist/bridge-client.js +69 -16
  14. package/dist/budget.d.ts +52 -0
  15. package/dist/budget.js +118 -0
  16. package/dist/child-process.d.ts +18 -0
  17. package/dist/child-process.js +38 -9
  18. package/dist/client.d.ts +2 -1
  19. package/dist/client.js +9 -19
  20. package/dist/context.d.ts +36 -7
  21. package/dist/context.js +83 -92
  22. package/dist/errors.d.ts +2 -0
  23. package/dist/errors.js +2 -0
  24. package/dist/index.d.ts +7 -2
  25. package/dist/index.js +254 -88
  26. package/dist/ipc-server.d.ts +14 -5
  27. package/dist/ipc-server.js +174 -144
  28. package/dist/journal-view.d.ts +2 -0
  29. package/dist/journal-view.js +52 -7
  30. package/dist/journal.d.ts +27 -9
  31. package/dist/journal.js +216 -79
  32. package/dist/meta.d.ts +18 -0
  33. package/dist/meta.js +29 -0
  34. package/dist/model-relay.d.ts +130 -0
  35. package/dist/model-relay.js +339 -0
  36. package/dist/path-guard.d.ts +128 -19
  37. package/dist/path-guard.js +384 -68
  38. package/dist/pi-adapter.d.ts +35 -9
  39. package/dist/pi-adapter.js +865 -66
  40. package/dist/replace-file.d.ts +31 -0
  41. package/dist/replace-file.js +75 -0
  42. package/dist/runner-types.d.ts +35 -0
  43. package/dist/runner.d.ts +202 -30
  44. package/dist/runner.js +949 -273
  45. package/dist/serializable.d.ts +10 -4
  46. package/dist/serializable.js +56 -31
  47. package/dist/stopping.d.ts +37 -3
  48. package/dist/stopping.js +167 -21
  49. package/dist/tools.d.ts +2 -1
  50. package/dist/tools.js +90 -21
  51. package/dist/tree.d.ts +241 -0
  52. package/dist/tree.js +1431 -0
  53. package/dist/types.d.ts +106 -15
  54. package/dist/workspace.d.ts +7 -0
  55. package/dist/workspace.js +93 -104
  56. package/package.json +1 -1
package/dist/runner.js CHANGED
@@ -1,20 +1,26 @@
1
1
  import { spawn } from "child_process";
2
- import { readFileSync, writeFileSync, appendFileSync, readdirSync, copyFileSync, mkdirSync, existsSync, statSync, symlinkSync, rmSync, lstatSync, readlinkSync, cpSync, mkdtempSync, openSync, closeSync, realpathSync, } from "fs";
3
- import { join, dirname, relative } from "path";
2
+ import { readFileSync, writeFileSync, appendFileSync, readdirSync, mkdirSync, existsSync, statSync, symlinkSync, rmSync, lstatSync, readlinkSync, mkdtempSync, openSync, closeSync, chmodSync, accessSync, constants, truncateSync, } from "fs";
3
+ import { basename, join, dirname, relative } from "path";
4
4
  import { homedir, tmpdir } from "os";
5
5
  import { fileURLToPath } from "url";
6
6
  import { createHash, randomBytes } from "crypto";
7
- import { rejectOnAbort } from "./agent-backend.js";
7
+ import { onAbort, rejectOnAbort } from "./abort.js";
8
+ import { checkedBudget, createMeter } from "./budget.js";
8
9
  import { PiAdapter } from "./pi-adapter.js";
9
- import { createContext } from "./context.js";
10
+ import { LATEST_LOG_PATH, appendLogEntry, createContext } from "./context.js";
10
11
  import { createAgent, stripCodeFences } from "./agent.js";
11
12
  import { createTools } from "./tools.js";
12
13
  import { createWorkspace } from "./workspace.js";
13
- import { guardPath } from "./path-guard.js";
14
- import { createAllowance, superviseChild } from "./child-process.js";
15
- import { removeTempDir, removeWithThisProcess, requireWatchdog, stopGroups, stopWithThisProcess } from "./stopping.js";
14
+ import { guardPath, identityOf, projectAt, realRootOf, sameProjectAs, wayTo } from "./path-guard.js";
15
+ import { copyTree, differences, entryAt, mergeTree, pathAsListed, readTree } from "./tree.js";
16
+ import { stageFile } from "./replace-file.js";
17
+ import { readProjectMeta } from "./meta.js";
18
+ import { describeJson, isJsonObject } from "./serializable.js";
19
+ import { checkedEnv, createAllowance, superviseChild } from "./child-process.js";
20
+ import { KILL_GRACE_MS, removeTempDir, removeWithThisProcess, requireWatchdog, stopGroups, stopWithThisProcess } from "./stopping.js";
16
21
  import { createIPCServer, listen, closeServer } from "./ipc-server.js";
17
- import { JOURNAL_DIR, openJournal } from "./journal.js";
22
+ import { journalEntriesOf, openJournal } from "./journal.js";
23
+ import { messageOf } from "./errors.js";
18
24
  // --- Locating the runtime itself ---
19
25
  /** The installed @trama-dev/runtime package — this file lives in its dist/. */
20
26
  const RUNTIME_PACKAGE_DIR = dirname(dirname(fileURLToPath(import.meta.url)));
@@ -44,10 +50,14 @@ catch { /* not installed — programs simply cannot import it */ }
44
50
  * so program.ts can import it. Replaces any existing symlink whose target
45
51
  * differs (including user-managed ones). Only refuses to touch a real
46
52
  * directory/file to avoid destroying user content.
53
+ *
54
+ * The link points outside the project, and is meant to. Where it is put is
55
+ * inside it, like everything else the runtime writes: a project whose
56
+ * node_modules leads somewhere else is refused, not followed there.
47
57
  */
48
58
  function linkPackage(projectDir, name, target) {
49
- // The link deliberately points OUTSIDE the project — do not apply guardPath here.
50
- const linkDir = join(projectDir, "node_modules", "@trama-dev");
59
+ const linkDir = guardPath(projectDir, join("node_modules", "@trama-dev"));
60
+ // Not through the guard: it is the link itself that is looked at and replaced, not what it points at.
51
61
  const linkPath = join(linkDir, name);
52
62
  try {
53
63
  if (!lstatSync(linkPath).isSymbolicLink()) {
@@ -80,15 +90,14 @@ function ensureModulePackageJson(projectDir) {
80
90
  }
81
91
  catch (err) {
82
92
  throw new Error(`Malformed package.json at ${pkgPath}. ${advice}\n` +
83
- `Parse error: ${err instanceof Error ? err.message : err}`);
93
+ `Parse error: ${messageOf(err)}`);
84
94
  }
85
- if (typeof pkg !== "object" || pkg === null || Array.isArray(pkg)) {
86
- throw new Error(`Malformed package.json at ${pkgPath} — expected a JSON object but got ${Array.isArray(pkg) ? "an array" : typeof pkg}. ${advice}`);
95
+ if (!isJsonObject(pkg)) {
96
+ throw new Error(`Malformed package.json at ${pkgPath} — expected a JSON object but got ${describeJson(pkg)}. ${advice}`);
87
97
  }
88
- const pkgObj = pkg;
89
- if (pkgObj.type !== "module") {
90
- pkgObj.type = "module";
91
- writeFileSync(pkgPath, JSON.stringify(pkgObj, null, 2));
98
+ if (pkg.type !== "module") {
99
+ pkg.type = "module";
100
+ writeFileSync(pkgPath, JSON.stringify(pkg, null, 2));
92
101
  }
93
102
  }
94
103
  /** Make sure .gitignore excludes what trama generates, without disturbing existing entries. */
@@ -110,6 +119,7 @@ function ensureGitignore(projectDir) {
110
119
  * Idempotent — called before every run, so a freshly cloned project just works.
111
120
  */
112
121
  export function ensureProjectScaffold(projectDir) {
122
+ projectAt(projectDir);
113
123
  mkdirSync(guardPath(projectDir, "history"), { recursive: true });
114
124
  mkdirSync(guardPath(projectDir, "logs"), { recursive: true });
115
125
  ensureModulePackageJson(projectDir);
@@ -143,6 +153,7 @@ export function loadConfig() {
143
153
  defaultTimeout: 300_000,
144
154
  defaultMaxIterations: 100,
145
155
  journalRuns: 20,
156
+ agentChanges: "keep",
146
157
  };
147
158
  let raw;
148
159
  try {
@@ -159,12 +170,17 @@ export function loadConfig() {
159
170
  }
160
171
  catch (err) {
161
172
  throw new Error(`Malformed config at ${configPath} — fix or delete it.\n` +
162
- `Parse error: ${err instanceof Error ? err.message : err}`);
173
+ `Parse error: ${messageOf(err)}`);
163
174
  }
164
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
165
- throw new Error(`Malformed config at ${configPath} — expected a JSON object but got ${Array.isArray(parsed) ? "an array" : typeof parsed}. Fix or delete it to proceed.`);
175
+ if (!isJsonObject(parsed)) {
176
+ throw new Error(`Malformed config at ${configPath} — expected a JSON object but got ${describeJson(parsed)}. Fix or delete it to proceed.`);
166
177
  }
167
- const merged = { ...defaults, ...parsed };
178
+ // null is how JSON says a field is not there.
179
+ const given = Object.fromEntries(Object.entries(parsed).filter(([, value]) => value !== null));
180
+ return checkedConfig({ ...defaults, ...given }, "config");
181
+ }
182
+ /** A config that holds what the runtime can work with — or an error naming what does not, and where it came from. */
183
+ function checkedConfig(merged, source) {
168
184
  const s = (v) => typeof v === "string" && v.length > 0;
169
185
  const pint = (v) => Number.isInteger(v) && v > 0;
170
186
  const checks = [
@@ -174,163 +190,259 @@ export function loadConfig() {
174
190
  [Number.isFinite(merged.defaultTimeout) && merged.defaultTimeout > 0, `"defaultTimeout" must be a positive number (got ${merged.defaultTimeout})`],
175
191
  [pint(merged.defaultMaxIterations), `"defaultMaxIterations" must be a positive integer (got ${merged.defaultMaxIterations})`],
176
192
  [Number.isInteger(merged.journalRuns) && merged.journalRuns >= 0, `"journalRuns" must be a non-negative integer (got ${merged.journalRuns})`],
193
+ [merged.agentChanges === "keep" || merged.agentChanges === "discard", `"agentChanges" must be "keep" or "discard" (got ${JSON.stringify(merged.agentChanges)})`],
177
194
  ];
178
195
  for (const [ok, msg] of checks) {
179
196
  if (!ok)
180
- throw new Error(`Invalid config: ${msg}`);
197
+ throw new Error(`Invalid ${source}: ${msg}`);
198
+ }
199
+ if (merged.budget === undefined)
200
+ return merged;
201
+ try {
202
+ return { ...merged, budget: checkedBudget(merged.budget, `"budget"`) };
203
+ }
204
+ catch (err) {
205
+ throw new Error(`Invalid ${source}: ${messageOf(err)}`);
181
206
  }
182
- return merged;
183
207
  }
184
208
  /** The global config, with the model/provider a project was created with taking precedence. */
185
- export function loadProjectConfig(projectDir) {
209
+ export function loadProjectConfig(projectDir, meta = readProjectMeta(projectDir)) {
186
210
  const config = loadConfig();
187
- const meta = JSON.parse(readFileSync(guardPath(projectDir, "meta.json"), "utf-8"));
188
- if (meta.model)
211
+ // null is how JSON says a field is not there. Anything else a project says
212
+ // is taken, and held to what the global config is held to — an empty or
213
+ // mistyped name is an error here, not a quiet return to another model.
214
+ if (meta.model != null)
189
215
  config.model = meta.model;
190
- if (meta.provider)
216
+ if (meta.provider != null)
191
217
  config.provider = meta.provider;
192
- return config;
218
+ return checkedConfig(config, `meta.json in ${projectDir}`);
193
219
  }
194
220
  /**
195
221
  * What does the LLM work for a project. The only place that picks a backend:
196
222
  * everything else is handed one and does not know which it is.
223
+ *
224
+ * It is also where what is asked of a model is counted, and held to a
225
+ * budget (`meter`): every call passes here, whoever makes it. A call that
226
+ * comes when the budget is spent is refused; one under way is stopped where
227
+ * its agent would ask the model again — what the model was asked before
228
+ * that is used, and what it was answering is let finish. `spent` is told
229
+ * why, the first time either happens.
197
230
  */
198
- export function createBackend(config) {
199
- const backend = new PiAdapter(config);
200
- // The interface promises that a cancelled call rejects, and a run's end
201
- // waits on that. Every backend is held to it here, rather than trusted with it.
202
- return { ask: (prompt, call) => rejectOnAbort(backend.ask(prompt, call), call.signal) };
231
+ export function createBackend(config, meter = createMeter(), spent = () => { }, env) {
232
+ // (`env`: the variables of the run whose calls these are — its agents' too, as they are its program's and its commands'.)
233
+ const backend = new PiAdapter(config, env);
234
+ // The calls that were cancelled.
235
+ const cutOff = new Set();
236
+ // Why a call was first refused, or stopped, for the budget.
237
+ let refused;
238
+ const overBudget = (why) => {
239
+ if (refused === undefined)
240
+ spent(why);
241
+ refused ??= why;
242
+ return new Error(why);
243
+ };
244
+ return {
245
+ spent: () => meter.spent(),
246
+ refused: () => refused,
247
+ counts: () => meter.capped(),
248
+ // The interface promises that a cancelled call rejects, and a run's end
249
+ // waits on that. Every backend is held to it here, rather than trusted with it.
250
+ async ask(prompt, call) {
251
+ let account;
252
+ try {
253
+ account = meter.admit();
254
+ }
255
+ catch (err) {
256
+ throw overBudget(messageOf(err));
257
+ }
258
+ // Stops the call where the budget is reached while it is under way.
259
+ const over = new AbortController();
260
+ let why;
261
+ const signal = call.signal ? AbortSignal.any([call.signal, over.signal]) : over.signal;
262
+ const work = backend.ask(prompt, {
263
+ ...call,
264
+ signal,
265
+ sofar(usage, answered) {
266
+ const reached = account.sofar(usage);
267
+ call.sofar?.(usage, answered);
268
+ // A call that is over keeps what it ended with — its answer, or its own failure: what would be
269
+ // asked beside it is not asked, and that is all. (It is a request refused for the budget all the
270
+ // same, and said as one.)
271
+ if (answered) {
272
+ const spent = why ?? reached;
273
+ if (spent === undefined)
274
+ return true;
275
+ overBudget(spent);
276
+ return false;
277
+ }
278
+ // (Once it is to stop, it is to stop — whatever is said of it after.)
279
+ why ??= reached;
280
+ if (why === undefined)
281
+ return true;
282
+ over.abort();
283
+ return false;
284
+ },
285
+ // (What the call has used is counted from when it is known: nothing is stopped for it here — a reply that
286
+ // has come is not taken back — but whatever is asked next, by this call or another, is asked against it.)
287
+ had(usage) {
288
+ account.sofar(usage);
289
+ call.had?.(usage);
290
+ },
291
+ used(usage) {
292
+ account.sofar(usage);
293
+ call.used?.(usage);
294
+ },
295
+ });
296
+ const off = onAbort(signal, () => { cutOff.add(work); });
297
+ // What the call used is counted as its own until the backend has let go of it — which
298
+ // is when it has said the last of it — however long ago whoever asked was answered.
299
+ const settled = () => {
300
+ off();
301
+ account.close();
302
+ };
303
+ work.then(settled, settled);
304
+ try {
305
+ return await rejectOnAbort(work, signal);
306
+ }
307
+ catch (err) {
308
+ // (Stopped by whoever asked, it was stopped by them, whatever the budget had come to.)
309
+ throw why !== undefined && !call.signal?.aborted ? overBudget(why) : err;
310
+ }
311
+ },
312
+ close: () => backend.close(),
313
+ async letGo() {
314
+ let giveUp;
315
+ await Promise.race([
316
+ Promise.allSettled(cutOff),
317
+ new Promise(resolve => { giveUp = setTimeout(resolve, KILL_GRACE_MS); }),
318
+ ]);
319
+ clearTimeout(giveUp);
320
+ },
321
+ };
203
322
  }
323
+ /** The budgets of which it has been said that they are spent. */
324
+ const saidSpent = new WeakSet();
325
+ /**
326
+ * Say that a budget is spent, once for the budget — whoever comes up against
327
+ * it first: the run's own backend, or the backend of a project being made
328
+ * for the run's program, of which there may be many.
329
+ */
330
+ export const saysOnce = (meter, say) => (why) => {
331
+ if (saidSpent.has(meter))
332
+ return;
333
+ saidSpent.add(meter);
334
+ say(why);
335
+ };
204
336
  export function loadState(projectDir) {
205
337
  const statePath = guardPath(projectDir, "state.json");
206
- if (!existsSync(statePath))
207
- return {};
208
- const raw = readFileSync(statePath, "utf-8");
209
- const fail = (reason) => {
338
+ let raw;
339
+ try {
340
+ raw = readFileSync(statePath, "utf-8");
341
+ }
342
+ catch (err) {
343
+ if (err.code === "ENOENT")
344
+ return {};
345
+ throw err;
346
+ }
347
+ function fail(reason) {
210
348
  throw new Error(`Corrupt state.json in ${projectDir} — cannot safely continue.\n${reason}\n` +
211
349
  `Back up or delete state.json to reset state.`);
212
- };
350
+ }
213
351
  let parsed;
214
352
  try {
215
353
  parsed = JSON.parse(raw);
216
354
  }
217
355
  catch (err) {
218
- fail(`Parse error: ${err instanceof Error ? err.message : err}`);
356
+ fail(`Parse error: ${messageOf(err)}`);
219
357
  }
220
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
221
- fail(`Expected a JSON object but got ${Array.isArray(parsed) ? "array" : typeof parsed}.`);
358
+ if (!isJsonObject(parsed)) {
359
+ fail(`Expected a JSON object but got ${describeJson(parsed)}.`);
222
360
  }
223
361
  return parsed;
224
362
  }
225
363
  // --- History management ---
226
- /** Append one metadata line to history/index.jsonl. */
227
- function appendHistoryIndex(projectDir, entry) {
228
- appendFileSync(guardPath(projectDir, join("history", "index.jsonl")), JSON.stringify(entry) + "\n");
229
- }
230
364
  /** The index.jsonl field that carries the detail for each kind of versioned change. */
231
365
  const HISTORY_DETAIL_FIELD = { create: "prompt", update: "prompt", repair: "error" };
232
366
  /**
233
- * Save the current program.ts as the next version: copy it to history/NNNN.ts
234
- * and record why in index.jsonl.
235
- *
236
- * (See installValidatedProgram for how a create or update is recorded.)
367
+ * Add a version to a project's history: its text as history/NNNN.ts, and a
368
+ * line in index.jsonl saying why (after `notes`, lines that belong with it).
369
+ * Either all of it is written or none of it. Returns how to take it back, for
370
+ * a caller whose own next step may still fail.
237
371
  */
238
- export function copyToHistory(projectDir, reason, detail) {
372
+ function recordVersion(projectDir, source, reason, detail, notes = []) {
239
373
  const historyDir = guardPath(projectDir, "history");
374
+ const indexPath = guardPath(projectDir, join("history", "index.jsonl"));
240
375
  const versions = readdirSync(historyDir)
241
376
  .filter(f => /^\d+\.ts$/.test(f))
242
- .map(f => parseInt(f, 10));
377
+ .map(f => parseInt(f, 10))
378
+ .filter(n => Number.isSafeInteger(n) && n < Number.MAX_SAFE_INTEGER);
243
379
  const version = versions.reduce((a, b) => Math.max(a, b), 0) + 1;
244
- const fileName = `${String(version).padStart(4, "0")}.ts`;
245
- copyFileSync(guardPath(projectDir, "program.ts"), guardPath(projectDir, join("history", fileName)));
380
+ const snapshot = guardPath(projectDir, join("history", `${String(version).padStart(4, "0")}.ts`));
246
381
  const entry = { version, reason, timestamp: new Date().toISOString() };
247
382
  const detailField = HISTORY_DETAIL_FIELD[reason];
248
383
  if (detailField && detail)
249
384
  entry[detailField] = detail;
250
- appendHistoryIndex(projectDir, entry);
251
- }
252
- /** Record all files in a directory with their size and mtime for change detection. */
253
- export function snapshotDir(dir, prefix = "") {
254
- const result = new Map();
255
- let entries;
256
- try {
257
- entries = readdirSync(dir, { withFileTypes: true });
258
- }
259
- catch {
260
- return result;
261
- }
262
- for (const entry of entries) {
263
- const relPath = prefix ? `${prefix}/${entry.name}` : entry.name;
264
- const fullPath = join(dir, entry.name);
265
- if (entry.isDirectory()) {
266
- for (const [k, v] of snapshotDir(fullPath, relPath))
267
- result.set(k, v);
385
+ const lines = Buffer.from([...notes, entry].map(line => JSON.stringify(line) + "\n").join(""));
386
+ const sizeBefore = statSync(indexPath, { throwIfNoEntry: false })?.size;
387
+ let wroteSnapshot = false;
388
+ let appended = false;
389
+ // Takes back what was written here and nothing else. Another run of the
390
+ // project may be recording a version of its own at the same moment: if the
391
+ // index no longer ends with these lines alone, they are left in it, and the
392
+ // version file with them — a version on record that was never installed,
393
+ // rather than someone else's record cut out of the history.
394
+ const undo = () => {
395
+ try {
396
+ const index = readFileSync(indexPath);
397
+ const start = sizeBefore ?? 0;
398
+ const sinceThen = index.subarray(Math.min(start, index.length));
399
+ // What was appended is the end of the index — whole, or as far as a failed write got.
400
+ const cutTo = index.subarray(-lines.length).equals(lines) ? index.length - lines.length
401
+ : lines.subarray(0, sinceThen.length).equals(sinceThen) ? start
402
+ : null;
403
+ if (cutTo === null)
404
+ return;
405
+ if (cutTo === 0 && sizeBefore === undefined)
406
+ rmSync(indexPath, { force: true });
407
+ else if (cutTo < index.length)
408
+ truncateSync(indexPath, cutTo);
268
409
  }
269
- else if (entry.isFile()) {
410
+ catch (err) {
411
+ // The index cannot be looked at. If the lines went into it, they stay,
412
+ // and the version file with them; if they never did, there is only the file.
413
+ if (appended && err.code !== "ENOENT")
414
+ return;
415
+ }
416
+ if (wroteSnapshot)
270
417
  try {
271
- const st = statSync(fullPath);
272
- result.set(relPath, { size: st.size, mtimeMs: st.mtimeMs });
418
+ rmSync(snapshot, { force: true });
273
419
  }
274
- catch { /* skip */ }
275
- }
276
- }
277
- return result;
278
- }
279
- const sameStat = (a, b) => a.size === b.size && a.mtimeMs === b.mtimeMs;
280
- /**
281
- * Merge what a run did to a staged copy back into the real directory, with a
282
- * three-way check so that nothing changed in the real directory meanwhile —
283
- * by the user, or by another run of the same project — is overwritten.
284
- *
285
- * @param stagedDir - the copy after the run (source of changes)
286
- * @param realDir - the real directory (destination)
287
- * @param stagedBefore - snapshot of the copy before the run (detects what the run changed)
288
- * @param realSeed - snapshot of the real directory when the copy was taken (detects concurrent changes)
289
- *
290
- * For each file the run touched in the copy:
291
- * - Created: copied, unless that path has meanwhile appeared in the real directory.
292
- * - Modified: copied only if the real file still matches realSeed.
293
- * - Deleted: deleted only if the real file still matches realSeed.
294
- * Best-effort: anything that cannot be merged safely is skipped, never thrown.
295
- */
296
- export function commitStagedChanges(stagedDir, realDir, stagedBefore, realSeed) {
297
- const stagedAfter = snapshotDir(stagedDir);
298
- /** The real file as it is now — but only if nobody has touched it since the copy was taken. */
299
- const untouchedSinceSeed = (relPath, dstPath) => {
300
- const seedStat = realSeed.get(relPath);
301
- const realNow = statSync(dstPath, { throwIfNoEntry: false });
302
- return seedStat === undefined || (realNow !== undefined && sameStat(realNow, seedStat));
420
+ catch { /* best-effort */ }
303
421
  };
304
- for (const relPath of new Set([...stagedBefore.keys(), ...stagedAfter.keys()])) {
305
- const beforeStat = stagedBefore.get(relPath);
306
- const afterStat = stagedAfter.get(relPath);
307
- if (beforeStat && afterStat && sameStat(beforeStat, afterStat))
308
- continue; // the run didn't touch it
422
+ try {
423
+ // Never over a version file that is already there: that one is someone else's.
424
+ const fd = openSync(snapshot, "wx");
425
+ wroteSnapshot = true;
309
426
  try {
310
- // A symlink placed at this path, or in a parent directory, could point
311
- // outside the real directory — guardPath throws.
312
- const dstPath = guardPath(realDir, relPath);
313
- if (!afterStat) {
314
- if (untouchedSinceSeed(relPath, dstPath))
315
- rmSync(dstPath, { force: true });
316
- }
317
- else if (beforeStat) {
318
- if (!untouchedSinceSeed(relPath, dstPath))
319
- continue; // changed or removed concurrently
320
- copyFileSync(join(stagedDir, relPath), dstPath);
321
- }
322
- else {
323
- if (statSync(dstPath, { throwIfNoEntry: false }))
324
- continue; // someone else created it first — keep theirs
325
- mkdirSync(dirname(dstPath), { recursive: true });
326
- copyFileSync(join(stagedDir, relPath), dstPath);
327
- }
427
+ writeFileSync(fd, source);
328
428
  }
329
- catch {
330
- // Escapes the directory, path-shape conflict, permissions — skip
429
+ finally {
430
+ closeSync(fd);
331
431
  }
432
+ appendFileSync(indexPath, lines);
433
+ appended = true;
434
+ }
435
+ catch (err) {
436
+ undo();
437
+ throw err;
332
438
  }
439
+ return undo;
440
+ }
441
+ /** Save the current program.ts as the next version of the project, and record why. */
442
+ export function copyToHistory(projectDir, reason, detail) {
443
+ recordVersion(projectDir, readFileSync(guardPath(projectDir, "program.ts")), reason, detail);
333
444
  }
445
+ // --- Staging: run against a copy, merge back what worked (see tree.ts) ---
334
446
  /** Run fn in a temp directory, clean up afterwards regardless of outcome — including this process being stopped. */
335
447
  export async function withTempDir(prefix, fn) {
336
448
  const dir = mkdtempSync(join(tmpdir(), prefix));
@@ -344,42 +456,167 @@ export async function withTempDir(prefix, fn) {
344
456
  }
345
457
  }
346
458
  /**
347
- * Copy a directory's contents into an existing one, keeping symlinks as they
348
- * are written. A project's journals stay behind: they are the record of its
349
- * runs, not part of what a run works on, and a copy is where a run is tried.
459
+ * Do something in a directory of a copy that may be closed to it: a copy is
460
+ * the runner's to open. The directory is left allowing what it allowed.
461
+ */
462
+ function inDirOfCopy(dir, what) {
463
+ const allows = statSync(dir).mode;
464
+ if ((allows & 0o700) === 0o700)
465
+ return what();
466
+ chmodSync(dir, (allows & 0o7777) | 0o700);
467
+ try {
468
+ return what();
469
+ }
470
+ finally {
471
+ chmodSync(dir, allows & 0o7777);
472
+ }
473
+ }
474
+ /** The directory a file at `place` is made in — or, if that is still to be made, the one it is made in. */
475
+ function whereMade(place) {
476
+ let dir = dirname(place);
477
+ while (!existsSync(dir))
478
+ dir = dirname(dir);
479
+ return dir;
480
+ }
481
+ /**
482
+ * Put a program where a copy of a project has its program.ts — whatever the
483
+ * directory it goes in allows: a copy is where programs are tried and
484
+ * replaced. The new file allows what `mode` says or, where that is not said,
485
+ * what the one it takes the place of allows — and its owner to replace it.
486
+ * Throws where a directory is in the place of the program: `root` is the
487
+ * project the copy is of, for saying so.
488
+ */
489
+ function putProgram(copyDir, root, program, mode) {
490
+ const place = guardPath(copyDir, "program.ts");
491
+ const had = statSync(place, { throwIfNoEntry: false });
492
+ if (had?.isDirectory())
493
+ throw new Error(`No program can be tried in a copy of ${root}: its program.ts is a directory.`);
494
+ inDirOfCopy(whereMade(place), () => stageFile(copyDir, "program.ts", program, mode ?? (had && (had.mode | 0o200))).commit());
495
+ }
496
+ /**
497
+ * All that makes a directory's program.ts lead to its program, as the
498
+ * directory stands: the name, each link and each directory on the way, the
499
+ * file — each by what it is (see Entry), which is asked of the place,
500
+ * whatever its directory lists or allows.
350
501
  */
351
- function copyDirInto(srcDir, dstDir) {
352
- // realpath: a project directory may itself be a symlink.
353
- const source = realpathSync(srcDir);
354
- cpSync(source, dstDir, {
355
- recursive: true,
356
- verbatimSymlinks: true,
357
- filter: path => relative(source, path) !== JOURNAL_DIR,
502
+ const programParts = (dir) => wayTo(dir, "program.ts").flatMap((place) => {
503
+ const entry = entryAt(place);
504
+ return entry && entry.kind !== "other" ? [entry.id] : [];
505
+ });
506
+ function standAmong(root, privateDir) {
507
+ const among = dirname(root);
508
+ let names;
509
+ try {
510
+ names = readdirSync(among);
511
+ }
512
+ catch {
513
+ return { among, names: [] };
514
+ }
515
+ const put = names.filter((name) => {
516
+ const beside = join(among, name);
517
+ // (Not the directory all this is made in, where that is beside the project: it would stand beside itself.)
518
+ if (beside === privateDir)
519
+ return false;
520
+ try {
521
+ symlinkSync(beside, join(privateDir, name));
522
+ return true;
523
+ }
524
+ catch {
525
+ return false;
526
+ }
358
527
  });
528
+ return { among, names: put };
529
+ }
530
+ /**
531
+ * What was done beside a copy that is not thereby done beside its project:
532
+ * each name made there, and each of those put there (see standAmong) that is
533
+ * gone, or is something else now — another link among them. Told as what did
534
+ * not arrive is told: the path — from the project — and why.
535
+ */
536
+ function strandedBeside(copy, beside) {
537
+ const dir = dirname(realRootOf(copy));
538
+ const put = new Set(beside.names);
539
+ const stranded = [];
540
+ /** Whether a name put there is still the link that was put there. */
541
+ const asPut = (name) => {
542
+ try {
543
+ return readlinkSync(join(dir, name)) === join(beside.among, name);
544
+ }
545
+ catch {
546
+ return false;
547
+ }
548
+ };
549
+ try {
550
+ for (const name of readdirSync(dir)) {
551
+ if (name === basename(copy) || put.has(name))
552
+ continue;
553
+ stranded.push({ path: `../${name}`, why: "it was made beside the copy that was worked in, and goes with it: beside the project there is no such thing" });
554
+ }
555
+ for (const name of beside.names) {
556
+ if (asPut(name))
557
+ continue;
558
+ stranded.push({ path: `../${name}`, why: "it was removed, or something else put there, beside the copy that was worked in: beside the project it is as it was" });
559
+ }
560
+ }
561
+ catch { /* what cannot be looked at has nothing told of it */ }
562
+ return stranded.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
359
563
  }
360
564
  /**
361
- * Run fn against a private copy of a directory. What fn does there stays
362
- * invisible to the real directory unless fn asks to commit it — then it is
363
- * merged back (see commitStagedChanges). If fn fails, or this process is
364
- * stopped half-way, the real directory was never touched.
565
+ * Make, in `privateDir`, a copy of a project — to try a program in, or for an
566
+ * agent to look at and work in: what the project is and holds (see copyTree),
567
+ * with `program` as its program.ts where one is given. Returns where the
568
+ * copy is, what the project was when it was copied, and the names put beside
569
+ * the copy for what is beside the project.
570
+ *
571
+ * The copy allows what the project allows, to everybody: so it is made in a
572
+ * directory that is this runner's alone, and is nobody else's to come to. It
573
+ * has the project's name there, and what is beside the project beside it (see
574
+ * standAmong) — nothing else is to be in that directory. Where what is
575
+ * copied is itself a copy of a project — as where a candidate is validated
576
+ * in the project as an agent prepared it — `among` names the project: what
577
+ * is beside the copy is what is beside that, and nothing an agent made
578
+ * beside its own.
579
+ *
580
+ * The project's journals are not carried over: they are the record of its
581
+ * runs, not part of what a run works on, and a copy is where a run is tried.
582
+ *
583
+ * In everything else the copy is as the project is, so that what a program
584
+ * can do in the one it can do in the other: what a run did in a copy is
585
+ * merged back into the project, and must not have been possible only there.
586
+ * The one exception is the program: the one to be tried, in the place of
587
+ * the project's. It allows what the project's allows — and its owner to
588
+ * replace it — and is put there whatever the directory it goes in allows:
589
+ * a copy is where programs are tried and replaced, and whether the project's
590
+ * own may be is said of the project, where one is to take its place (see
591
+ * whyNotReplaceable). A project with a directory where its program should be
592
+ * has no place for one, and is not copied to try one in.
365
593
  */
366
- async function withStagedCopy(realDir, fn) {
367
- const realSeed = snapshotDir(realDir);
368
- return withTempDir("trama-staged-", async (stagedDir) => {
369
- copyDirInto(realDir, stagedDir);
370
- const stagedBefore = snapshotDir(stagedDir);
371
- const { commit, value } = await fn(stagedDir);
372
- if (commit)
373
- commitStagedChanges(stagedDir, realDir, stagedBefore, realSeed);
374
- return value;
594
+ export function copyProjectWith(projectDir, privateDir, program, among = projectDir) {
595
+ const root = projectAt(projectDir);
596
+ const itsOwn = realRootOf(privateDir);
597
+ const copyDir = join(itsOwn, basename(root) || "project");
598
+ mkdirSync(copyDir);
599
+ const beside = standAmong(projectAt(among), itsOwn);
600
+ const journals = journalEntriesOf(root);
601
+ const theCopy = identityOf(copyDir);
602
+ const held = copyTree(root, copyDir, (at, entry) => {
603
+ if (entry.kind === "other")
604
+ return false;
605
+ if (entry.id === theCopy) {
606
+ throw new Error(`A copy of ${root} cannot be made inside it, at ${at}. (Is the temp directory in the project?)`);
607
+ }
608
+ return journals.has(entry.id);
375
609
  });
610
+ if (program !== undefined)
611
+ putProgram(copyDir, root, program);
612
+ return { copy: copyDir, held, beside };
376
613
  }
377
614
  /** The end of a long output — where the error is — with a note of how much was dropped. */
378
615
  function tail(text, max = 20_000) {
379
616
  return text.length <= max ? text : `[… ${text.length - max} earlier characters omitted]\n${text.slice(-max)}`;
380
617
  }
381
618
  /** A line as it is shown for a run: under the run's name, if it has one. */
382
- const tagged = (label, line) => label ? `[${label}] ${line}` : line;
619
+ export const tagged = (label, line) => label ? `[${label}] ${line}` : line;
383
620
  /** The longest stretch of output held back while waiting for its line to end. */
384
621
  const MAX_HELD_LINE = 64 * 1024;
385
622
  /** Put a label in front of each line written to a stream. `flush` writes out a last line that had no newline. */
@@ -449,12 +686,12 @@ function toChildResult(exit) {
449
686
  * takes precedence over its exit code: a program that called ctx.done() and
450
687
  * then crashed is done. Returns null for a failure (non-zero exit, no signal).
451
688
  */
452
- function settle(projectDir, child, terminalSignal) {
689
+ function settle(projectDir, child, ended) {
453
690
  // Read state first: if the program left state.json corrupt, say so now
454
691
  // rather than report an outcome (or start a repair) on top of it.
455
692
  const state = loadState(projectDir);
456
- if (terminalSignal)
457
- return terminalSignal;
693
+ if (ended)
694
+ return ended;
458
695
  if (child.exitCode !== 0)
459
696
  return null;
460
697
  // Natural success without done() or yield(): if this run was the resumption
@@ -476,8 +713,6 @@ function settle(projectDir, child, terminalSignal) {
476
713
  async function runProgramOnce(options) {
477
714
  const { projectDir, backend, timeout, maxIterations, argsOverride, validating, workspaceDir, label, signal, journal } = options;
478
715
  const attempt = options.attempt ?? 0;
479
- if (signal?.aborted)
480
- return { outcome: null, failure: "The run was stopped before its program started." };
481
716
  requireWatchdog();
482
717
  ensureProjectScaffold(projectDir);
483
718
  // Cancels in-flight LLM calls, fetches and observes once the run is over.
@@ -485,8 +720,10 @@ async function runProgramOnce(options) {
485
720
  // Ends a validation: the program has shown what it had to, and is asked to stop.
486
721
  const validated = new AbortController();
487
722
  let readyTimer = null;
488
- let terminalSignal = null;
489
- const ctx = createContext(projectDir, loadState(projectDir), {
723
+ // The state the program starts from. From here on it is the program's: the
724
+ // runner sees it again only as the program hands it over to be persisted.
725
+ const state = loadState(projectDir);
726
+ const ctx = createContext(projectDir, state, {
490
727
  maxIterations,
491
728
  argsOverride,
492
729
  onReady: validating && (() => {
@@ -504,10 +741,10 @@ async function runProgramOnce(options) {
504
741
  });
505
742
  // Truncate logs only after preflight succeeds — preserves the prior run's
506
743
  // diagnostics if scaffolding, state loading, or context creation fails.
507
- writeFileSync(guardPath(projectDir, join("logs", "latest.jsonl")), "");
744
+ writeFileSync(guardPath(projectDir, LATEST_LOG_PATH), "");
508
745
  // The program's own time. It stops while a run the program asked for is in flight.
509
746
  const allowance = createAllowance(timeout);
510
- // Set when a validation ended because the program asked for another to be run.
747
+ // Set when a validation ended because the program asked for another to be run, or for a project to be made or changed.
511
748
  let handedOff = false;
512
749
  // Runs the program has asked for and that are still going. They belong to this run.
513
750
  const nestedRuns = new Set();
@@ -520,9 +757,19 @@ async function runProgramOnce(options) {
520
757
  };
521
758
  // The workspace of the session this run is part of, if it is part of one.
522
759
  const sessionWorkspace = workspaceDir ? workspaceAt(workspaceDir) : null;
523
- const tools = createTools(projectDir, runEnded.signal);
760
+ const tools = createTools(projectDir, runEnded.signal, options.env);
761
+ // As far as a validation goes: the program asks its runner for what would be real — a run, a project
762
+ // made. The call is left unanswered — an answer would only send the program on to do more — until
763
+ // the program, which is being stopped, lets go of it.
764
+ const handOff = (what, stop) => {
765
+ handedOff = what;
766
+ validated.abort();
767
+ return rejectOnAbort(new Promise(() => { }), stop);
768
+ };
524
769
  // Known only to this run's program, through its init file.
525
770
  const token = randomBytes(32).toString("hex");
771
+ // Whether the program's process has ended. (Nothing is an answer to it after that, and it is no longer there to stop.)
772
+ let programOver = false;
526
773
  const server = createIPCServer({
527
774
  token,
528
775
  ctx,
@@ -531,35 +778,53 @@ async function runProgramOnce(options) {
531
778
  workspace: sessionWorkspace,
532
779
  workspaceAt,
533
780
  journal,
534
- run: (request, stop, seq) => {
535
- if (validating) {
536
- // As far as a validation goes. The call is left unanswered — an answer
537
- // would only send the program on to do more — until the program,
538
- // which is being stopped, lets go of it.
539
- handedOff = true;
540
- validated.abort();
541
- return rejectOnAbort(new Promise(() => { }), stop);
781
+ programOver: () => programOver,
782
+ make: (request, stop, seq) => {
783
+ if (validating)
784
+ return handOff("has a project made or changed", stop);
785
+ if (!options.making) {
786
+ throw new Error("This runner was not given a way to make projects: createProject and updateProject are carried out where a run is started by way of @trama-dev/runtime/runner.");
542
787
  }
788
+ // The run's own, as a run it asks for is: under its budget, with its variables, stopped when it
789
+ // ends or when the program no longer wants it, and not over before this is. (But the program's
790
+ // clock goes on: what it has made is its own work, with no timeout but the program's.)
791
+ const made = options.making(request, {
792
+ signal: AbortSignal.any([runEnded.signal, stop]),
793
+ above: options.meter,
794
+ label,
795
+ env: options.env,
796
+ parent: { run: journal.run, journal: journal.path, seq },
797
+ // (What it starts is a validation: of the program the project is made with.)
798
+ started: (run, path) => { if (run)
799
+ journal.note("child", { seq, run, journal: path, purpose: "validate" }); },
800
+ }).finally(() => { nestedRuns.delete(made); });
801
+ nestedRuns.add(made);
802
+ return made;
803
+ },
804
+ run: (request, stop, seq) => {
805
+ if (validating)
806
+ return handOff("starts another program", stop);
543
807
  // The program is waiting, not working: its clock stops for as long as
544
808
  // the run it asked for lasts, which has a timeout of its own. That run
545
809
  // is stopped when this one ends, or when the program no longer wants it.
546
810
  const release = allowance.hold();
547
- const nested = runProgram({ ...request, signal: AbortSignal.any([runEnded.signal, stop]) }, {
811
+ // What this run was started with, the run it asks for has too — and what it is given besides.
812
+ const env = options.env || request.env ? { ...options.env, ...request.env } : undefined;
813
+ const nested = runProgram({ ...request, env, signal: AbortSignal.any([runEnded.signal, stop]) }, {
548
814
  depth: options.depth + 1,
549
815
  // The two journals point at each other: this one says which run the call started…
550
816
  started: (run, path) => { if (run)
551
817
  journal.note("child", { seq, run, journal: path }); },
552
818
  // …and that run's journal says which call started it.
553
819
  parent: { run: journal.run, journal: journal.path, seq },
554
- }).finally(() => {
820
+ above: options.meter,
821
+ }, options.making).finally(() => {
555
822
  release();
556
823
  nestedRuns.delete(nested);
557
824
  });
558
825
  nestedRuns.add(nested);
559
826
  return nested;
560
827
  },
561
- // The first terminal signal wins; ctx itself rejects a conflicting second one.
562
- onTerminalSignal: result => { terminalSignal ??= result; },
563
828
  });
564
829
  // A participant's output is shown under its name. It is not its parent's
565
830
  // output: the runner writes it out itself, wherever in the tree it runs.
@@ -572,7 +837,6 @@ async function runProgramOnce(options) {
572
837
  // Asked to stop while its program had not ended. Everything it has in flight
573
838
  // goes at once — the runs it asked for among them, so that a tree of runs is
574
839
  // stopped together rather than one level after another.
575
- let programOver = false;
576
840
  let stopped = false;
577
841
  const stopProgram = () => {
578
842
  if (programOver)
@@ -582,14 +846,14 @@ async function runProgramOnce(options) {
582
846
  if (programGroup)
583
847
  void stopGroups([programGroup]);
584
848
  };
585
- signal?.addEventListener("abort", stopProgram, { once: true });
849
+ const offStop = onAbort(signal, stopProgram);
586
850
  try {
587
851
  const { child, exited } = await withTempDir("trama-init-", async (initDir) => {
588
852
  const port = await listen(server);
589
853
  const initFile = writeInitFile(initDir, {
590
854
  token,
591
855
  input: ctx.input,
592
- state: ctx.state,
856
+ state,
593
857
  iteration: ctx.iteration,
594
858
  maxIterations: ctx.maxIterations,
595
859
  inSession: sessionWorkspace !== null,
@@ -598,7 +862,7 @@ async function runProgramOnce(options) {
598
862
  });
599
863
  const program = spawn(process.execPath, ["--import", TSX_LOADER, guardPath(projectDir, "program.ts")], {
600
864
  cwd: projectDir,
601
- env: { ...process.env, TRAMA_PORT: String(port), TRAMA_INIT: initFile },
865
+ env: { ...process.env, ...options.env, TRAMA_PORT: String(port), TRAMA_INIT: initFile },
602
866
  stdio: ["ignore", "pipe", "pipe"],
603
867
  detached: true,
604
868
  });
@@ -620,7 +884,7 @@ async function runProgramOnce(options) {
620
884
  // program goes down, cut off in mid-flow, says nothing about it.
621
885
  const passedAtHandOff = handedOff && !exit.timedOut;
622
886
  if (passedAtHandOff)
623
- console.log(tagged(label, "[trama] validated up to where it starts another program"));
887
+ console.log(tagged(label, `[trama] validated up to where it ${handedOff}`));
624
888
  return {
625
889
  child: passedAtHandOff ? { exitCode: 0, stdout: exit.stdout, stderr: exit.stderr } : toChildResult(exit),
626
890
  // How the program's process ended, for the record.
@@ -648,10 +912,10 @@ async function runProgramOnce(options) {
648
912
  try {
649
913
  // A program that was stopped did not finish, whatever its exit code
650
914
  // says — unless it had already said it was done.
651
- outcome = stopped && !terminalSignal ? null : settle(projectDir, child, terminalSignal);
915
+ outcome = stopped && !ctx.ended ? null : settle(projectDir, child, ctx.ended);
652
916
  }
653
917
  catch (err) {
654
- noteExit({ error: err instanceof Error ? err.message : String(err) });
918
+ noteExit({ error: messageOf(err) });
655
919
  throw err;
656
920
  }
657
921
  noteExit({ outcome });
@@ -663,7 +927,7 @@ async function runProgramOnce(options) {
663
927
  // them — and stop what is left of its process group and of its shell
664
928
  // commands. Only once they are gone is the run over: whoever called will
665
929
  // merge or delete what they were writing to.
666
- signal?.removeEventListener("abort", stopProgram);
930
+ offStop();
667
931
  out?.flush();
668
932
  err?.flush();
669
933
  if (readyTimer)
@@ -676,62 +940,146 @@ async function runProgramOnce(options) {
676
940
  ]);
677
941
  programSettled();
678
942
  server.closeAllConnections();
679
- await closeServer(server).catch(() => { });
943
+ await closeServer(server);
680
944
  }
681
945
  }
682
946
  /** The instructions a request for a fix is made under. (Exported so the tests' stand-in LLM can tell one from any other call.) */
683
947
  export const REPAIR_SYSTEM_PROMPT = "You are a TypeScript repair tool.";
684
948
  const repairPrompt = (input) => `Fix this program so it runs.\n\n` +
685
- `Runtime types:\n${RUNTIME_TYPES}\n\n` +
949
+ `You are working in a copy of the project's directory, where the program is program.ts. ` +
950
+ (input.kept
951
+ ? `If what is wrong is in the project and not in the program — a package that is not installed, a file the program needs that is missing or wrong — put it right here: ` +
952
+ `what you change in this directory is kept, with the program you answer with, if that program then runs. If it does not, none of it is.\n`
953
+ : `Nothing you change in this directory is kept: the program you answer with is all that is taken from you.\n`) +
954
+ (input.journal ? `The record of the run that failed — each call the program made, and what came back — is at ${input.journal}, a line of JSON for each.\n` : "") +
955
+ `\nRuntime types:\n${RUNTIME_TYPES}\n\n` +
686
956
  `Broken program:\n${input.programSource}\n\n` +
687
957
  `Error:\n${input.error}\n\n` +
688
- `Output ONLY the fixed program. No explanation.`;
958
+ `Output ONLY the fixed program${input.kept ? ": the whole of it, also where it is the project that needed fixing" : ""}. No explanation.`;
959
+ /**
960
+ * A question to ask of a copy an agent has worked in: whether what is at its
961
+ * path is still the directory that was read (`was`). An agent can move its
962
+ * copy away and leave a link there, or nothing: what is done next is done in
963
+ * the copy, not in what a link leads to, nor in a directory made anew.
964
+ */
965
+ const sameCopyAs = (copy, was) => () => {
966
+ const there = entryAt(copy), itself = was.get(".");
967
+ if (!(there?.kind === "dir" && itself?.kind === "dir" && there.id === itself.id)) {
968
+ throw new Error("the copy that was worked in is no longer where it was made: it was moved away, or something else put in its place");
969
+ }
970
+ };
971
+ function fixIn(copy) {
972
+ const root = realRootOf(copy);
973
+ return {
974
+ root,
975
+ name: pathAsListed(copy, join(root, "program.ts")) ?? "program.ts",
976
+ allowed: statSync(guardPath(copy, "program.ts")).mode,
977
+ parts: programParts(copy),
978
+ };
979
+ }
980
+ /** Make a copy of a project to ask for a fix in, or to try one in: with `program` as its program. */
981
+ function stageProject(projectDir, privateDir, program) {
982
+ const { copy, held, beside } = copyProjectWith(projectDir, privateDir, program);
983
+ const place = guardPath(copy, "program.ts");
984
+ const before = readTree(copy);
985
+ const fix = fixIn(copy);
986
+ return {
987
+ copy, held, beside, before, intact: sameCopyAs(copy, before), fix,
988
+ program: { parts: fix.parts, place, listed: pathAsListed(copy, place), allowed: fix.allowed },
989
+ };
990
+ }
991
+ /** How many of the paths an agent changed are written down, or shown. */
992
+ const MAX_PATHS_NOTED = 200;
993
+ const MAX_PATHS_SHOWN = 10;
994
+ export const shownPaths = (paths) => paths.slice(0, MAX_PATHS_SHOWN).join(", ") + (paths.length > MAX_PATHS_SHOWN ? ", …" : "");
689
995
  /**
690
- * Ask the LLM for a fix. The agent has tools, so it works in a throwaway copy
691
- * of the project that holds the program it is asked to fix — whatever it reads
692
- * is real, whatever it writes is discarded; only the program text it returns
693
- * is used. Bounded by its own timeout.
694
- * Returns the fixed program, or why no usable one came back.
996
+ * Ask the LLM for a fix. The agent has tools, so it works in a copy of the
997
+ * project that holds the program it is asked to fix. What it reads there is
998
+ * as the project has it. Bounded by its own timeout.
999
+ *
1000
+ * What it changes there is part of the fix — the copy is the one the fix is
1001
+ * then tried in, and what was done in it reaches the project with the fix or
1002
+ * not at all (see tryFix) — unless that is not to be (`agentChanges`), or
1003
+ * the run is a validation: of a validation nothing is kept but the program,
1004
+ * so a fix that leaned on what its agent did beside it would be installed
1005
+ * without it. There the fix is the program alone, and the agent is told so.
1006
+ *
1007
+ * The program is the text it returns, whatever it did to program.ts: where
1008
+ * its work is kept, that text is put where program.ts leads as it left it,
1009
+ * allowing what the program allowed.
1010
+ *
1011
+ * Returns the fixed program — with the copy it is to be tried in, where that
1012
+ * is this one; or with why it cannot be tried in this one, where the agent
1013
+ * left it with no place for a program, not to be read, or moved it away: the
1014
+ * fix is then the program alone, as where nothing else is kept — or why no
1015
+ * usable fix came back.
695
1016
  */
696
- async function requestRepair(options, input) {
1017
+ async function requestRepair(options, input, privateDir) {
697
1018
  options.journal.note("fix-request", { error: input.error });
698
- return withTempDir("trama-repair-", async (tempDir) => {
699
- copyDirInto(options.projectDir, tempDir);
700
- writeFileSync(guardPath(tempDir, "program.ts"), input.programSource);
701
- const timedOut = new AbortController();
702
- const limit = createAllowance(options.timeout);
1019
+ const timedOut = new AbortController();
1020
+ const limit = createAllowance(options.timeout);
1021
+ const signal = options.signal ? AbortSignal.any([timedOut.signal, options.signal]) : timedOut.signal;
1022
+ try {
1023
+ const kept = options.agentChanges !== "discard" && !options.validating;
1024
+ const staged = stageProject(options.projectDir, privateDir, input.programSource);
703
1025
  limit.start(() => timedOut.abort());
704
- const signal = options.signal ? AbortSignal.any([timedOut.signal, options.signal]) : timedOut.signal;
705
- try {
706
- const fixed = stripCodeFences(await options.backend.ask(repairPrompt(input), {
707
- cwd: tempDir, system: REPAIR_SYSTEM_PROMPT, signal,
708
- }));
709
- if (fixed.trim() === "")
710
- throw new Error("The repair returned an empty program.");
1026
+ const fixed = stripCodeFences(await options.backend.ask(repairPrompt({ ...input, journal: options.journal.path, kept }), {
1027
+ cwd: staged.copy, system: REPAIR_SYSTEM_PROMPT, signal,
1028
+ used: (usage) => options.journal.used("fix", usage),
1029
+ }));
1030
+ if (fixed.trim() === "")
1031
+ throw new Error("The repair returned an empty program.");
1032
+ if (!kept) {
711
1033
  if (fixed === input.programSource)
712
1034
  throw new Error("The repair returned the program unchanged.");
713
1035
  options.journal.note("fix", { ok: true, source: fixed });
714
1036
  return { fixed };
715
1037
  }
1038
+ let changed = [], unusable;
1039
+ try {
1040
+ staged.intact();
1041
+ putProgram(staged.copy, options.projectDir, fixed, staged.program.allowed);
1042
+ staged.fix = fixIn(staged.copy);
1043
+ staged.changed = changed = differences(staged.before, readTree(staged.copy, true)).filter((path) => path !== staged.program.listed);
1044
+ }
716
1045
  catch (err) {
717
- const error = err instanceof Error ? err.message : String(err);
718
- options.journal.note("fix", { ok: false, error });
719
- return { error };
1046
+ unusable = messageOf(err);
720
1047
  }
721
- finally {
722
- limit.cancel();
1048
+ // A fix is the program, or the project, or both. One that is neither is the failure over again.
1049
+ if (fixed === input.programSource && changed.length === 0) {
1050
+ throw new Error(`The repair returned the program unchanged${unusable === undefined ? ", and changed nothing else in the project" : ""}.`);
723
1051
  }
724
- });
1052
+ options.journal.note("fix", {
1053
+ ok: true,
1054
+ ...(changed.length > 0 ? { changed: changed.slice(0, MAX_PATHS_NOTED) } : {}),
1055
+ ...(changed.length > MAX_PATHS_NOTED ? { changedInAll: changed.length } : {}),
1056
+ alone: unusable,
1057
+ source: fixed,
1058
+ });
1059
+ return unusable === undefined ? { fixed, staged } : { fixed, unusable };
1060
+ }
1061
+ catch (err) {
1062
+ const error = messageOf(err);
1063
+ options.journal.note("fix", { ok: false, error });
1064
+ return { error };
1065
+ }
1066
+ finally {
1067
+ limit.cancel();
1068
+ }
725
1069
  }
726
1070
  /**
727
- * Try a proposed fix.
1071
+ * Try a proposed fix, in a copy of the project that has it for its program.
728
1072
  *
729
- * The project is the program's own, so the fix runs on a private copy of it.
730
- * Only if it works does anything reach the real one — the fix becomes
731
- * program.ts, and what the run wrote is merged back. A fix that fails, or a
732
- * runner that is stopped half-way, leaves the project exactly as it was,
733
- * because it was never touched: its state is only ever written by code that
734
- * is, or becomes, its program.
1073
+ * The project is the program's own, so the fix runs on a private copy of it:
1074
+ * the one the agent worked in when it was asked for the fix, with what the
1075
+ * agent did there — or one made for the trial, where what the agent did is
1076
+ * not kept. Only if it works does anything reach the real one — the
1077
+ * fix becomes program.ts, and what was done in the copy is merged back: by
1078
+ * the agent, and by the run. A fix that fails, or a runner that is stopped
1079
+ * while one is tried, leaves the project exactly as it was, because it was
1080
+ * never touched: its state is only ever written by code that is, or
1081
+ * becomes, its program — and its other files, besides, by an agent whose fix
1082
+ * then ran.
735
1083
  *
736
1084
  * The shared workspace is not copied. It is how the participants of a session
737
1085
  * talk to each other, and a program that is being fixed still has to be heard
@@ -739,22 +1087,96 @@ async function requestRepair(options, input) {
739
1087
  * would wait for replies forever. So what a fix writes there is written,
740
1088
  * whether or not the fix works: like anything a run wrote before it failed.
741
1089
  */
742
- async function tryFix(options, fixed, attempt) {
1090
+ async function tryFix(options, staged, fixed, attempt) {
743
1091
  const { projectDir } = options;
744
- const run = await withStagedCopy(projectDir, async (stagedProject) => {
745
- writeFileSync(guardPath(stagedProject, "program.ts"), fixed);
746
- // If the copy cannot be run at all, or is left unusable, this fix did not work either.
747
- const trial = await runProgramOnce({ ...options, projectDir: stagedProject, attempt }).catch((err) => ({
1092
+ const { copy: stagedProject, held, before } = staged;
1093
+ const itsPlace = staged.program.listed;
1094
+ // The fix in the copy, as the copy has it: under which name, what it allows there, and all that makes program.ts lead to it.
1095
+ const { root: copyRoot, name: itsName, allowed, parts: was } = staged.fix;
1096
+ const programIs = () => programParts(stagedProject);
1097
+ // If the copy cannot be run at all, or is left unusable, this fix did not work either.
1098
+ const trial = await runProgramOnce({ ...options, projectDir: stagedProject, attempt }).catch((err) => ({
1099
+ outcome: null,
1100
+ failure: `The repaired program could not be run: ${messageOf(err)}`,
1101
+ }));
1102
+ if (trial.outcome === null)
1103
+ return trial;
1104
+ // The fix worked, and becomes the project's program — as it ran, first,
1105
+ // and in one move; only then is what its run did merged in. What the run
1106
+ // did to its own file is among that: a program may rewrite itself, give
1107
+ // itself other permissions, make program.ts lead elsewhere, and here as
1108
+ // in any run what it made of itself is what it is. (So a runner stopped
1109
+ // between the two leaves the fix beside the state it started from: the
1110
+ // program that would do the same again, not the one it turns into.)
1111
+ //
1112
+ // The project is to have a program afterwards. One that removed itself —
1113
+ // the system finds nothing at program.ts, however a link left there words
1114
+ // the way to it — is still the fix that ran: a file of its name is put
1115
+ // back where the run ended (the name itself, not what the link leads to).
1116
+ // A run that left something there that cannot be read as a program has
1117
+ // not left a project that has one, and was no fix.
1118
+ let is;
1119
+ try {
1120
+ if (statSync(join(copyRoot, itsName), { throwIfNoEntry: false })) {
1121
+ programIn(stagedProject);
1122
+ }
1123
+ else {
1124
+ inDirOfCopy(copyRoot, () => {
1125
+ rmSync(join(copyRoot, itsName), { force: true });
1126
+ stageFile(stagedProject, itsName, fixed, allowed).commit();
1127
+ });
1128
+ }
1129
+ is = programIs();
1130
+ }
1131
+ catch (err) {
1132
+ return {
748
1133
  outcome: null,
749
- failure: `The repaired program could not be run: ${err instanceof Error ? err.message : err}`,
750
- }));
751
- return { commit: trial.outcome !== null, value: trial };
752
- });
753
- // The merge above carries over what the run changed; the fix itself was
754
- // written before the run started, so it is installed explicitly.
755
- if (run.outcome)
756
- writeFileSync(guardPath(projectDir, "program.ts"), fixed);
757
- return run;
1134
+ failure: `The repaired program ran, but left no program.ts that can be read: ${messageOf(err)}`,
1135
+ };
1136
+ }
1137
+ // If it cannot be put in place, that is an error, and it is thrown from
1138
+ // here with nothing of the run in the project: a state the old program
1139
+ // did not write, beside the old program, is worse than either. Nor is it
1140
+ // put into another directory that is at the project's path by now: the
1141
+ // project is the directory that was copied, which the copy knows by what
1142
+ // it is.
1143
+ const projectRoot = realRootOf(projectDir);
1144
+ const copied = held.get("."), there = entryAt(projectRoot);
1145
+ if (there && copied?.kind === "dir" && !(there.kind === "dir" && there.id === copied.id)) {
1146
+ throw new Error(`The program cannot be replaced: what is at ${projectRoot} is not the project the fix was tried on.`);
1147
+ }
1148
+ const program = stageProgram(projectDir, fixed);
1149
+ program.commit();
1150
+ // The project now holds, where its program was, what the copy held there before the run — and the merge is
1151
+ // told so: that is what the place is taken to have held when the copy was made. (If that is still the
1152
+ // place program.ts leads to: where somebody has pointed it elsewhere meanwhile, the seed knows nothing new.)
1153
+ const installed = entryAt(program.destination);
1154
+ const samePlace = relative(projectRoot, program.destination) === relative(copyRoot, staged.program.place);
1155
+ if (itsPlace !== undefined && installed && samePlace)
1156
+ held.set(itsPlace, installed);
1157
+ // What the agent and the run made of the program is one thing, with what it was: the name, and what the
1158
+ // name leads through and to. If part of that does not arrive — or a part that was left alone is not, in the
1159
+ // project, as it was — none of it is carried over: a link without what it leads to, or the file gone from where
1160
+ // the project's program.ts still leads, would be a project with no program. The project then keeps the fix as it ran.
1161
+ // (What it was before the agent worked is named too: that is the file the reading the merge compares with has
1162
+ // at the program's place, and by it that place is known for a part where the run removed what was there.)
1163
+ const unmerged = [
1164
+ ...mergeTree(stagedProject, projectDir, before, held, [[...new Set([...staged.program.parts, ...was, ...is])]]),
1165
+ // (Of a program that is only being validated nothing is told here: the copy it is validated in goes, with all of this.)
1166
+ ...(options.validating ? [] : strandedBeside(stagedProject, staged.beside)),
1167
+ ];
1168
+ // What the agent changed beside the program is said: it is in the project now, but for what is told of below.
1169
+ if (staged.changed?.length) {
1170
+ console.log(tagged(options.label, `[trama] the agent asked for the fix changed ${staged.changed.length} path(s) beside the program: ${shownPaths(staged.changed)}`));
1171
+ }
1172
+ if (unmerged.length > 0) {
1173
+ // The run is done and its program installed; what was done that is not in the project is said, not passed over.
1174
+ options.journal.note("unmerged", { attempt, files: unmerged });
1175
+ console.warn(tagged(options.label, `[trama] ${unmerged.length} change(s) the repair made did not reach the project:`));
1176
+ for (const { path, why } of unmerged)
1177
+ console.warn(tagged(options.label, `[trama] ${path} — ${why}`));
1178
+ }
1179
+ return trial;
758
1180
  }
759
1181
  /**
760
1182
  * Run a program to an outcome. If it crashes, ask the LLM to repair it and try
@@ -770,6 +1192,7 @@ async function executeProgram(options) {
770
1192
  const wasStopped = () => failed("The run was stopped before it finished.");
771
1193
  if (stopped())
772
1194
  return wasStopped();
1195
+ const stillTheProject = sameProjectAs(projectDir);
773
1196
  const firstRun = await runProgramOnce(options);
774
1197
  if (firstRun.outcome)
775
1198
  return { result: firstRun.outcome };
@@ -778,43 +1201,89 @@ async function executeProgram(options) {
778
1201
  let lastError = firstRun.failure;
779
1202
  if (maxRepairAttempts === 0)
780
1203
  return failed(`Program failed (repair disabled): ${lastError}`);
1204
+ // What is said and done from here on is said and done of the project the run was started on. (Not what was
1205
+ // said just now: where nothing more is to be done, how the program failed is all there is to say.)
1206
+ stillTheProject();
1207
+ // A fix is worth asking for, and trying, only where it could become the program.
1208
+ const refusal = whyNotReplaceable(projectDir);
1209
+ if (refusal)
1210
+ return failed(`Program failed, and no repair was tried. ${refusal}\n${lastError}`);
781
1211
  // Each attempt builds on the previous one's source, though a fix that failed never reached the project.
782
- let currentSource = readFileSync(guardPath(projectDir, "program.ts"), "utf-8");
1212
+ let currentSource = programIn(projectDir);
1213
+ if (currentSource === null)
1214
+ return failed(`Program failed (there is no program.ts to repair): ${lastError}`);
783
1215
  // The program as it was is attempt 0; each fix is the next.
784
1216
  for (let attempt = 1; attempt <= maxRepairAttempts; attempt++) {
785
- const fix = await requestRepair(options, { programSource: currentSource, error: lastError });
786
- if (stopped())
1217
+ stillTheProject();
1218
+ // A fix is asked of a model: where no more may be, none is asked for, and nothing is got ready for one.
1219
+ const spent = options.backend.spent?.();
1220
+ if (spent !== undefined) {
1221
+ return failed(`${attempt === 1 ? "Program failed, and no repair was tried" : `Failed after ${attempt - 1} repair attempt(s), and no further repair was tried`}. ${spent}\n${lastError}`);
1222
+ }
1223
+ const source = currentSource, error = lastError;
1224
+ // One copy of the project for the attempt: the fix is asked for in it, and tried in it.
1225
+ const tried = await withTempDir("trama-repair-", async (privateDir) => {
1226
+ const fix = await requestRepair(options, { programSource: source, error }, privateDir);
1227
+ if (stopped())
1228
+ return null;
1229
+ stillTheProject();
1230
+ if ("error" in fix)
1231
+ return fix;
1232
+ const { fixed, staged, unusable } = fix;
1233
+ if (unusable !== undefined) {
1234
+ console.warn(tagged(options.label, `[trama] the fix is tried by itself, and nothing else its agent did is kept: the copy the agent worked in cannot be used (${unusable})`));
1235
+ }
1236
+ // Where what the agent changed is not kept, the fix is tried in a copy the agent was never in.
1237
+ const run = staged
1238
+ ? await tryFix(options, staged, fixed, attempt)
1239
+ : await withTempDir("trama-staged-", (apart) => tryFix(options, stageProject(projectDir, apart, fixed), fixed, attempt));
1240
+ return { fixed, run };
1241
+ });
1242
+ if (tried === null)
787
1243
  return wasStopped();
788
1244
  // Without a fix there is nothing more to try: asking again would be asking the same thing.
789
- if ("error" in fix) {
790
- return failed(`Failed after ${attempt} repair attempt(s): ${lastError}\nNo fix came back: ${fix.error}`);
1245
+ if ("error" in tried) {
1246
+ return failed(`Failed after ${attempt} repair attempt(s): ${lastError}\nNo fix came back: ${tried.error}`);
791
1247
  }
792
- currentSource = fix.fixed;
793
- const run = await tryFix(options, fix.fixed, attempt);
794
- if (run.outcome)
795
- return { result: run.outcome, repair: { attempt, error: lastError } };
1248
+ currentSource = tried.fixed;
1249
+ if (tried.run.outcome)
1250
+ return { result: tried.run.outcome, repair: { attempt, error: lastError } };
796
1251
  if (stopped())
797
1252
  return wasStopped();
798
- lastError = run.failure;
1253
+ lastError = tried.run.failure;
799
1254
  }
800
1255
  return failed(`Failed after ${maxRepairAttempts} repair attempts: ${lastError}`);
801
1256
  }
802
1257
  /**
803
1258
  * Carry out a run under its journal. However it goes, the journal's last
804
- * record says so: the run's result, or why it could not be carried out.
1259
+ * record says so: the run's result, or why it could not be carried out —
1260
+ * after the agent calls that were cut off on the way have said what they
1261
+ * used. (A run that is not recorded, and whose backend holds what calls use
1262
+ * to nothing, has nothing to wait for.) Where the budget the backend counts
1263
+ * in is spent by then — or a call was refused or stopped for it on the way —
1264
+ * the record before the last says that.
805
1265
  */
806
- async function journalled(journal, run) {
1266
+ async function journalled(journal, backend, run) {
1267
+ let end = {};
807
1268
  try {
808
- const execution = await run();
809
- journal.note("end", { result: execution.result });
1269
+ const execution = await run(backend);
1270
+ end = { result: execution.result };
810
1271
  return execution;
811
1272
  }
812
1273
  catch (err) {
813
- journal.note("end", { error: err instanceof Error ? err.message : String(err) });
1274
+ end = { error: messageOf(err) };
814
1275
  throw err;
815
1276
  }
816
1277
  finally {
1278
+ if (journal.run || backend.counts?.())
1279
+ await backend.letGo();
1280
+ const spent = backend.spent?.() ?? backend.refused?.();
1281
+ if (spent !== undefined)
1282
+ journal.note("budget", { spent });
1283
+ journal.note("end", end);
817
1284
  journal.close();
1285
+ // Nothing a run started outlives it: nor what served its agent calls.
1286
+ await backend.close?.();
818
1287
  }
819
1288
  }
820
1289
  // --- Validating a candidate program (used by create and update) ---
@@ -826,34 +1295,216 @@ const VALIDATION_READY_GRACE_MS = 2_000;
826
1295
  * the candidate itself, or a repaired version of it, with the failure that was
827
1296
  * repaired. Throws if it cannot be made to run.
828
1297
  *
1298
+ * `as` names a directory that is the project as it is to be once the
1299
+ * program is in it — the copy the agent that wrote the program worked in,
1300
+ * with what it made there (see Prepared). The copy the program is run in is
1301
+ * then a copy of that, which is no more touched than the project is, and it
1302
+ * stands among what the project stands among.
1303
+ *
1304
+ * A repair made here is of the program alone (see requestRepair): the copy a
1305
+ * candidate runs in goes whole, with whatever was done in it.
1306
+ *
1307
+ * Where the agent left its copy so that no copy can be made of it — a file
1308
+ * nobody may read, say — the candidate is validated in the project as it is,
1309
+ * as it would be were nothing of the agent's kept: and `alone` says why,
1310
+ * for then nothing of the agent's is to be kept. (A caller that knows of such
1311
+ * a reason beforehand gives it as `alone`, with no `as`.) That is said when
1312
+ * it is found, whatever then comes of the candidate.
1313
+ *
829
1314
  * Only the project's own files are shielded. What the program does beyond
830
1315
  * them — network calls, shell commands, agent calls — is real. A run it asks
831
1316
  * its runner for is not started: the validation ends where it asks for the
832
1317
  * first.
833
1318
  */
834
1319
  export async function validateProgram(projectDir, backend, candidate, options) {
835
- const { journalRuns = 0, ...limits } = options;
836
- // Recorded with the project, though run in a copy of it.
837
- const journal = openJournal(projectDir, journalRuns, { purpose: "validate", ...limits });
838
- const { result, repair, worked } = await journalled(journal, () => withTempDir("trama-validate-", async (trialDir) => {
839
- copyDirInto(projectDir, trialDir);
840
- const programPath = guardPath(trialDir, "program.ts");
841
- writeFileSync(programPath, candidate);
1320
+ const { journalRuns = 0, signal, as = projectDir, timeout, maxRepairAttempts, maxIterations, label, env, askedFor } = options;
1321
+ // (What is written down, and handed on, is what a validation is known to take: nothing else that came with it.)
1322
+ const limits = { timeout, maxRepairAttempts, maxIterations };
1323
+ // Recorded with the project, though run in a copy of it. `budget` is for the record: the backend is what holds to it.
1324
+ const journal = openJournal(projectDir, journalRuns, {
1325
+ purpose: "validate", label, parent: askedFor?.parent, ...limits, budget: options.budget, env: env && Object.keys(env),
1326
+ });
1327
+ askedFor?.started(journal.run, journal.path);
1328
+ // What writing the candidate used is on record with its validation: it happened in no run, and has no journal of its own.
1329
+ for (const usage of options.wrote ?? [])
1330
+ journal.used("generate", usage);
1331
+ let alone;
1332
+ const byItself = (why) => {
1333
+ alone = why;
1334
+ console.warn(tagged(label, `[trama] the program is validated by itself, and nothing else its agent did is kept: the copy the agent worked in cannot be used (${why})`));
1335
+ };
1336
+ if (options.alone !== undefined)
1337
+ byItself(options.alone);
1338
+ const validatedIn = (prepared) => withTempDir("trama-validate-", async (privateDir) => {
1339
+ let trialDir;
1340
+ try {
1341
+ trialDir = copyProjectWith(prepared, privateDir, candidate, projectDir).copy;
1342
+ }
1343
+ catch (err) {
1344
+ if (prepared === projectDir)
1345
+ throw err;
1346
+ byItself(messageOf(err));
1347
+ return null;
1348
+ }
842
1349
  const execution = await executeProgram({
843
1350
  ...limits,
844
1351
  projectDir: trialDir,
845
1352
  backend,
846
1353
  depth: 0,
847
1354
  validating: { readyGraceMs: VALIDATION_READY_GRACE_MS },
1355
+ label,
1356
+ env,
1357
+ signal,
848
1358
  journal,
849
1359
  });
850
- // The program that worked — the candidate, or what a repair made of it. None, if nothing did.
851
- const worked = execution.result.status === "failed" ? null : readFileSync(programPath, "utf-8");
852
- return { ...execution, worked };
853
- }));
854
- if (worked === null)
1360
+ // Of a run that failed nothing is installed, and why it failed is what there is to say: what it left is not looked at.
1361
+ if (execution.result.status === "failed")
1362
+ return { ...execution, left: candidate };
1363
+ // The program as its run left it: the candidate, or what a repair or the program itself
1364
+ // made of it. (One that removed itself is still the candidate that ran.)
1365
+ try {
1366
+ return { ...execution, left: programIn(trialDir) ?? candidate };
1367
+ }
1368
+ catch (err) {
1369
+ const reason = `The program ran, but left no program.ts that can be read: ${messageOf(err)}`;
1370
+ return { ...execution, result: { status: "failed", reason }, left: candidate };
1371
+ }
1372
+ });
1373
+ const { result, repair, left } = await journalled(journal, backend, async () => (await validatedIn(as)) ?? (await validatedIn(projectDir)));
1374
+ if (result.status === "failed")
855
1375
  throw new Error(`Program failed: ${result.reason}`);
856
- return { source: worked, repairedError: repair?.error };
1376
+ return { source: left, repairedError: repair?.error, ...(alone === undefined ? {} : { alone }) };
1377
+ }
1378
+ export function prepareProject(projectDir, privateDir) {
1379
+ const { copy, held, beside } = copyProjectWith(projectDir, privateDir);
1380
+ const before = readTree(copy);
1381
+ const intact = sameCopyAs(copy, before);
1382
+ const root = realRootOf(copy);
1383
+ const name = join(root, "program.ts");
1384
+ /** The paths of the copy that are its program's, as it stands: the name, and what it leads through and to — but for directories, which hold other things too. */
1385
+ const programAt = () => [name, ...wayTo(copy, "program.ts")]
1386
+ .flatMap((place) => (entryAt(place)?.kind === "dir" ? [] : pathAsListed(copy, place) ?? []));
1387
+ /**
1388
+ * The way from the name to the program, as it stands: each place on it, and
1389
+ * what kind of thing is there — but that a file, or nothing yet, is all one:
1390
+ * either is a place a program can be put. (What a link says is not asked:
1391
+ * where it leads is the places that follow.)
1392
+ */
1393
+ const way = () => [name, ...wayTo(copy, "program.ts")].map((place) => {
1394
+ const there = entryAt(place);
1395
+ return `${relative(root, place)} ${there === undefined || there.kind === "file" ? "" : there.kind}`;
1396
+ }).join("\n");
1397
+ // What the name was, the way from it, and the program's places: before the agent worked, and as the agent left them.
1398
+ const nameWas = entryAt(name);
1399
+ const wayWas = way();
1400
+ const places = programAt();
1401
+ return {
1402
+ copy,
1403
+ ready() {
1404
+ intact();
1405
+ places.push(...programAt());
1406
+ const nameIs = entryAt(name);
1407
+ const asItWas = nameIs?.kind === "link" ? nameWas?.kind === "link" && nameWas.text === nameIs.text : nameWas?.kind !== "link";
1408
+ if (!asItWas) {
1409
+ inDirOfCopy(root, () => {
1410
+ rmSync(name, { force: true });
1411
+ if (nameWas?.kind === "link")
1412
+ symlinkSync(nameWas.text, name);
1413
+ });
1414
+ }
1415
+ if (way() !== wayWas)
1416
+ throw new Error("program.ts does not lead, in the copy that was worked in, where it led before: a program validated there would not be the program where it is installed");
1417
+ },
1418
+ keep() {
1419
+ intact();
1420
+ // (With what is closed opened for the reading: a copy was made of this one to validate in, but not of all
1421
+ // of it — what is left out of a copy, a directory of journals, was not looked into.)
1422
+ const after = readTree(copy, true);
1423
+ // At the program's places — where they were, where the agent left them, and where they are now that the
1424
+ // name is as it was (which a directory may list in other letters than it did) — the copy is taken to have
1425
+ // been as it is: nothing was done there that is to arrive.
1426
+ for (const path of [...places, ...programAt()]) {
1427
+ const there = after.get(path);
1428
+ if (there)
1429
+ before.set(path, there);
1430
+ else
1431
+ before.delete(path);
1432
+ }
1433
+ return { changed: differences(before, after), unmerged: [...mergeTree(copy, projectDir, before, held), ...strandedBeside(copy, beside)] };
1434
+ },
1435
+ };
1436
+ }
1437
+ /** A project's program text — null if it has none. Throws if what is in its place is no file. */
1438
+ function programIn(projectDir) {
1439
+ // (What the guard lets through is a file, a directory, or nothing yet: reading it waits on nothing.)
1440
+ const place = guardPath(projectDir, "program.ts");
1441
+ try {
1442
+ return readFileSync(place, "utf-8");
1443
+ }
1444
+ catch (err) {
1445
+ const code = err.code;
1446
+ if (code === "ENOENT")
1447
+ return null;
1448
+ if (code === "EISDIR")
1449
+ throw new Error(`${place} is a directory, not a program.`);
1450
+ throw err;
1451
+ }
1452
+ }
1453
+ /**
1454
+ * Why a project's program cannot be given a successor — or null if it can.
1455
+ *
1456
+ * A program is replaced by a new file taking its place, which the system
1457
+ * allows whatever the old file's permissions say. So the old file is asked: a
1458
+ * program its owner has made read-only is not replaced. A directory in its
1459
+ * place is no program, and no file takes the place of one. And the new file
1460
+ * has to be made beside it, in a directory that is there or can be made.
1461
+ *
1462
+ * This is the rule stageProgram enforces. It is also asked before work whose
1463
+ * only use is a new program — an update, a repair — is begun.
1464
+ */
1465
+ export function whyNotReplaceable(projectDir) {
1466
+ // A program is a project's: where no project is, none is put.
1467
+ let place;
1468
+ let there;
1469
+ try {
1470
+ projectAt(projectDir);
1471
+ place = guardPath(projectDir, "program.ts");
1472
+ there = statSync(place, { throwIfNoEntry: false });
1473
+ }
1474
+ catch (err) {
1475
+ return `The program cannot be replaced: ${messageOf(err)}`;
1476
+ }
1477
+ const allows = (path, what) => {
1478
+ try {
1479
+ accessSync(path, what);
1480
+ return true;
1481
+ }
1482
+ catch {
1483
+ return false;
1484
+ }
1485
+ };
1486
+ if (there?.isDirectory())
1487
+ return `The program cannot be replaced: ${place} is a directory.`;
1488
+ if (there && !allows(place, constants.W_OK))
1489
+ return `The program cannot be replaced: ${place} is read-only.`;
1490
+ const dir = whereMade(place);
1491
+ if (!allows(dir, constants.W_OK | constants.X_OK))
1492
+ return `The program cannot be replaced: nothing can be created in ${dir}.`;
1493
+ return null;
1494
+ }
1495
+ /**
1496
+ * Get a program ready to become a project's program.ts: written beside the
1497
+ * one that is there, to take its place in one move — so program.ts is never
1498
+ * half a program, whatever happens in the middle of writing it.
1499
+ *
1500
+ * It is a new file that takes the place: the old one's permissions are carried
1501
+ * over, but not a second hard link to it, or its owner.
1502
+ */
1503
+ function stageProgram(projectDir, source) {
1504
+ const refusal = whyNotReplaceable(projectDir);
1505
+ if (refusal)
1506
+ throw Object.assign(new Error(refusal), { code: "EACCES" });
1507
+ return stageFile(projectDir, "program.ts", source);
857
1508
  }
858
1509
  /**
859
1510
  * Make a validated program the project's program.ts and record it as a new
@@ -861,13 +1512,24 @@ export async function validateProgram(projectDir, backend, candidate, options) {
861
1512
  * noted in the history index only.
862
1513
  */
863
1514
  export function installValidatedProgram(projectDir, validated, reason, prompt) {
864
- writeFileSync(guardPath(projectDir, "program.ts"), validated.source);
865
- if (validated.repairedError) {
866
- appendHistoryIndex(projectDir, {
867
- reason: `${reason}-repair`, timestamp: new Date().toISOString(), error: validated.repairedError,
868
- });
1515
+ // Three steps, ordered so that a failure at any of them leaves the project
1516
+ // as it was: the new program is written beside the old one (nothing else is
1517
+ // touched if even that cannot be done), the version is recorded, and only
1518
+ // then does the new program take the old one's place — in one move, so
1519
+ // program.ts is never half-written, and never a program that is not on record.
1520
+ const program = stageProgram(projectDir, validated.source);
1521
+ let unrecord = () => { };
1522
+ try {
1523
+ unrecord = recordVersion(projectDir, validated.source, reason, prompt, validated.repairedError
1524
+ ? [{ reason: `${reason}-repair`, timestamp: new Date().toISOString(), error: validated.repairedError }]
1525
+ : []);
1526
+ program.commit();
1527
+ }
1528
+ catch (err) {
1529
+ unrecord();
1530
+ program.discard();
1531
+ throw err;
869
1532
  }
870
- copyToHistory(projectDir, reason, prompt);
871
1533
  }
872
1534
  // --- Core execution ---
873
1535
  /** How deep programs may run programs, and how many runs one runner carries at a time. */
@@ -881,7 +1543,7 @@ let runsInFlight = 0;
881
1543
  * call). One runner carries the whole tree of runs, so it is also where the
882
1544
  * tree is kept from growing without bound.
883
1545
  */
884
- export async function runProgram(options, askedFor) {
1546
+ export async function runProgram(options, askedFor, making) {
885
1547
  const depth = askedFor?.depth ?? 0;
886
1548
  if (depth > MAX_RUN_DEPTH) {
887
1549
  throw new Error(`Not running ${options.projectDir}: programs are running programs more than ${MAX_RUN_DEPTH} deep. ` +
@@ -892,13 +1554,13 @@ export async function runProgram(options, askedFor) {
892
1554
  }
893
1555
  runsInFlight += 1;
894
1556
  try {
895
- return await runProject(options, depth, askedFor);
1557
+ return await runProject(options, depth, askedFor, making);
896
1558
  }
897
1559
  finally {
898
1560
  runsInFlight -= 1;
899
1561
  }
900
1562
  }
901
- async function runProject(options, depth, askedFor) {
1563
+ async function runProject(options, depth, askedFor, making) {
902
1564
  const { projectDir } = options;
903
1565
  if (!existsSync(join(projectDir, "meta.json"))) {
904
1566
  throw new Error(`Project not found at ${projectDir}. ` +
@@ -913,6 +1575,10 @@ async function runProject(options, depth, askedFor) {
913
1575
  if (!Number.isInteger(maxRepairAttempts) || maxRepairAttempts < 0) {
914
1576
  throw new Error(`Invalid maxRepairAttempts: ${maxRepairAttempts}. Must be a non-negative integer.`);
915
1577
  }
1578
+ const env = options.env == null ? undefined : checkedEnv(options.env);
1579
+ // Its own budget — the config's, for a run nobody's program asked for and that was given none — under the budgets above it.
1580
+ const budget = options.budget != null ? checkedBudget(options.budget) : askedFor ? undefined : config.budget;
1581
+ const meter = createMeter(budget, askedFor?.above);
916
1582
  const journal = openJournal(projectDir, config.journalRuns, {
917
1583
  purpose: "run",
918
1584
  label: options.label,
@@ -921,12 +1587,19 @@ async function runProject(options, depth, askedFor) {
921
1587
  workspace: options.workspaceDir,
922
1588
  timeout,
923
1589
  maxRepairAttempts,
1590
+ budget,
1591
+ // (The names: what the variables hold is not for a journal.)
1592
+ env: env && Object.keys(env),
924
1593
  args: options.args, // last: it is the one field of unknown size
925
1594
  });
926
1595
  askedFor?.started(journal.run, journal.path);
927
- const { result, repair } = await journalled(journal, () => executeProgram({
1596
+ const stillTheProject = sameProjectAs(projectDir);
1597
+ const outOfBudget = (why) => console.warn(tagged(options.label, `[trama] ${why}`));
1598
+ const { result, repair } = await journalled(journal, createBackend(config, meter, saysOnce(meter, outOfBudget), env), (backend) => executeProgram({
928
1599
  projectDir,
929
- backend: createBackend(config),
1600
+ backend,
1601
+ meter,
1602
+ making,
930
1603
  maxRepairAttempts,
931
1604
  timeout,
932
1605
  maxIterations: config.defaultMaxIterations,
@@ -934,19 +1607,22 @@ async function runProject(options, depth, askedFor) {
934
1607
  workspaceDir: options.workspaceDir,
935
1608
  depth,
936
1609
  label: options.label,
1610
+ env,
1611
+ agentChanges: config.agentChanges,
937
1612
  signal: options.signal,
938
1613
  journal,
939
1614
  }));
940
1615
  if (repair) {
941
1616
  // The program is fixed and has run; failing to write this down must not turn that into an error.
942
1617
  try {
943
- const entry = { ts: Date.now(), message: `Repair attempt ${repair.attempt}/${maxRepairAttempts}`, data: { error: repair.error } };
944
- appendFileSync(guardPath(projectDir, join("logs", "latest.jsonl")), JSON.stringify(entry) + "\n");
945
- console.log(tagged(options.label, `[trama] Repair attempt ${repair.attempt}/${maxRepairAttempts}`));
1618
+ stillTheProject();
1619
+ const message = `Repair attempt ${repair.attempt}/${maxRepairAttempts}`;
1620
+ appendLogEntry(guardPath(projectDir, LATEST_LOG_PATH), message, { error: repair.error });
1621
+ console.log(tagged(options.label, `[trama] ${message}`));
946
1622
  copyToHistory(projectDir, "repair", repair.error);
947
1623
  }
948
1624
  catch (err) {
949
- console.warn(tagged(options.label, `[trama] repair bookkeeping failed: ${err instanceof Error ? err.message : err}`));
1625
+ console.warn(tagged(options.label, `[trama] repair bookkeeping failed: ${messageOf(err)}`));
950
1626
  }
951
1627
  }
952
1628
  return result;