@trama-dev/runtime 0.4.0 → 0.5.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.
package/dist/runner.js CHANGED
@@ -1,20 +1,25 @@
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
8
  import { PiAdapter } from "./pi-adapter.js";
9
- import { createContext } from "./context.js";
9
+ import { LATEST_LOG_PATH, appendLogEntry, createContext } from "./context.js";
10
10
  import { createAgent, stripCodeFences } from "./agent.js";
11
11
  import { createTools } from "./tools.js";
12
12
  import { createWorkspace } from "./workspace.js";
13
- import { guardPath } from "./path-guard.js";
13
+ import { guardPath, identityOf, projectAt, realRootOf, sameProjectAs, wayTo } from "./path-guard.js";
14
+ import { copyTree, entryAt, mergeTree, pathAsListed, readTree } from "./tree.js";
15
+ import { stageFile } from "./replace-file.js";
16
+ import { readProjectMeta } from "./meta.js";
17
+ import { describeJson, isJsonObject } from "./serializable.js";
14
18
  import { createAllowance, superviseChild } from "./child-process.js";
15
19
  import { removeTempDir, removeWithThisProcess, requireWatchdog, stopGroups, stopWithThisProcess } from "./stopping.js";
16
20
  import { createIPCServer, listen, closeServer } from "./ipc-server.js";
17
- import { JOURNAL_DIR, openJournal } from "./journal.js";
21
+ import { journalEntriesOf, openJournal } from "./journal.js";
22
+ import { messageOf } from "./errors.js";
18
23
  // --- Locating the runtime itself ---
19
24
  /** The installed @trama-dev/runtime package — this file lives in its dist/. */
20
25
  const RUNTIME_PACKAGE_DIR = dirname(dirname(fileURLToPath(import.meta.url)));
@@ -44,10 +49,14 @@ catch { /* not installed — programs simply cannot import it */ }
44
49
  * so program.ts can import it. Replaces any existing symlink whose target
45
50
  * differs (including user-managed ones). Only refuses to touch a real
46
51
  * directory/file to avoid destroying user content.
52
+ *
53
+ * The link points outside the project, and is meant to. Where it is put is
54
+ * inside it, like everything else the runtime writes: a project whose
55
+ * node_modules leads somewhere else is refused, not followed there.
47
56
  */
48
57
  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");
58
+ const linkDir = guardPath(projectDir, join("node_modules", "@trama-dev"));
59
+ // Not through the guard: it is the link itself that is looked at and replaced, not what it points at.
51
60
  const linkPath = join(linkDir, name);
52
61
  try {
53
62
  if (!lstatSync(linkPath).isSymbolicLink()) {
@@ -80,15 +89,14 @@ function ensureModulePackageJson(projectDir) {
80
89
  }
81
90
  catch (err) {
82
91
  throw new Error(`Malformed package.json at ${pkgPath}. ${advice}\n` +
83
- `Parse error: ${err instanceof Error ? err.message : err}`);
92
+ `Parse error: ${messageOf(err)}`);
84
93
  }
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}`);
94
+ if (!isJsonObject(pkg)) {
95
+ throw new Error(`Malformed package.json at ${pkgPath} — expected a JSON object but got ${describeJson(pkg)}. ${advice}`);
87
96
  }
88
- const pkgObj = pkg;
89
- if (pkgObj.type !== "module") {
90
- pkgObj.type = "module";
91
- writeFileSync(pkgPath, JSON.stringify(pkgObj, null, 2));
97
+ if (pkg.type !== "module") {
98
+ pkg.type = "module";
99
+ writeFileSync(pkgPath, JSON.stringify(pkg, null, 2));
92
100
  }
93
101
  }
94
102
  /** Make sure .gitignore excludes what trama generates, without disturbing existing entries. */
@@ -110,6 +118,7 @@ function ensureGitignore(projectDir) {
110
118
  * Idempotent — called before every run, so a freshly cloned project just works.
111
119
  */
112
120
  export function ensureProjectScaffold(projectDir) {
121
+ projectAt(projectDir);
113
122
  mkdirSync(guardPath(projectDir, "history"), { recursive: true });
114
123
  mkdirSync(guardPath(projectDir, "logs"), { recursive: true });
115
124
  ensureModulePackageJson(projectDir);
@@ -159,12 +168,17 @@ export function loadConfig() {
159
168
  }
160
169
  catch (err) {
161
170
  throw new Error(`Malformed config at ${configPath} — fix or delete it.\n` +
162
- `Parse error: ${err instanceof Error ? err.message : err}`);
171
+ `Parse error: ${messageOf(err)}`);
163
172
  }
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.`);
173
+ if (!isJsonObject(parsed)) {
174
+ throw new Error(`Malformed config at ${configPath} — expected a JSON object but got ${describeJson(parsed)}. Fix or delete it to proceed.`);
166
175
  }
167
- const merged = { ...defaults, ...parsed };
176
+ // null is how JSON says a field is not there.
177
+ const given = Object.fromEntries(Object.entries(parsed).filter(([, value]) => value !== null));
178
+ return checkedConfig({ ...defaults, ...given }, "config");
179
+ }
180
+ /** A config that holds what the runtime can work with — or an error naming what does not, and where it came from. */
181
+ function checkedConfig(merged, source) {
168
182
  const s = (v) => typeof v === "string" && v.length > 0;
169
183
  const pint = (v) => Number.isInteger(v) && v > 0;
170
184
  const checks = [
@@ -177,19 +191,21 @@ export function loadConfig() {
177
191
  ];
178
192
  for (const [ok, msg] of checks) {
179
193
  if (!ok)
180
- throw new Error(`Invalid config: ${msg}`);
194
+ throw new Error(`Invalid ${source}: ${msg}`);
181
195
  }
182
196
  return merged;
183
197
  }
184
198
  /** The global config, with the model/provider a project was created with taking precedence. */
185
- export function loadProjectConfig(projectDir) {
199
+ export function loadProjectConfig(projectDir, meta = readProjectMeta(projectDir)) {
186
200
  const config = loadConfig();
187
- const meta = JSON.parse(readFileSync(guardPath(projectDir, "meta.json"), "utf-8"));
188
- if (meta.model)
201
+ // null is how JSON says a field is not there. Anything else a project says
202
+ // is taken, and held to what the global config is held to — an empty or
203
+ // mistyped name is an error here, not a quiet return to another model.
204
+ if (meta.model != null)
189
205
  config.model = meta.model;
190
- if (meta.provider)
206
+ if (meta.provider != null)
191
207
  config.provider = meta.provider;
192
- return config;
208
+ return checkedConfig(config, `meta.json in ${projectDir}`);
193
209
  }
194
210
  /**
195
211
  * What does the LLM work for a project. The only place that picks a backend:
@@ -203,134 +219,114 @@ export function createBackend(config) {
203
219
  }
204
220
  export function loadState(projectDir) {
205
221
  const statePath = guardPath(projectDir, "state.json");
206
- if (!existsSync(statePath))
207
- return {};
208
- const raw = readFileSync(statePath, "utf-8");
209
- const fail = (reason) => {
222
+ let raw;
223
+ try {
224
+ raw = readFileSync(statePath, "utf-8");
225
+ }
226
+ catch (err) {
227
+ if (err.code === "ENOENT")
228
+ return {};
229
+ throw err;
230
+ }
231
+ function fail(reason) {
210
232
  throw new Error(`Corrupt state.json in ${projectDir} — cannot safely continue.\n${reason}\n` +
211
233
  `Back up or delete state.json to reset state.`);
212
- };
234
+ }
213
235
  let parsed;
214
236
  try {
215
237
  parsed = JSON.parse(raw);
216
238
  }
217
239
  catch (err) {
218
- fail(`Parse error: ${err instanceof Error ? err.message : err}`);
240
+ fail(`Parse error: ${messageOf(err)}`);
219
241
  }
220
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
221
- fail(`Expected a JSON object but got ${Array.isArray(parsed) ? "array" : typeof parsed}.`);
242
+ if (!isJsonObject(parsed)) {
243
+ fail(`Expected a JSON object but got ${describeJson(parsed)}.`);
222
244
  }
223
245
  return parsed;
224
246
  }
225
247
  // --- 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
248
  /** The index.jsonl field that carries the detail for each kind of versioned change. */
231
249
  const HISTORY_DETAIL_FIELD = { create: "prompt", update: "prompt", repair: "error" };
232
250
  /**
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.)
251
+ * Add a version to a project's history: its text as history/NNNN.ts, and a
252
+ * line in index.jsonl saying why (after `notes`, lines that belong with it).
253
+ * Either all of it is written or none of it. Returns how to take it back, for
254
+ * a caller whose own next step may still fail.
237
255
  */
238
- export function copyToHistory(projectDir, reason, detail) {
256
+ function recordVersion(projectDir, source, reason, detail, notes = []) {
239
257
  const historyDir = guardPath(projectDir, "history");
258
+ const indexPath = guardPath(projectDir, join("history", "index.jsonl"));
240
259
  const versions = readdirSync(historyDir)
241
260
  .filter(f => /^\d+\.ts$/.test(f))
242
- .map(f => parseInt(f, 10));
261
+ .map(f => parseInt(f, 10))
262
+ .filter(n => Number.isSafeInteger(n) && n < Number.MAX_SAFE_INTEGER);
243
263
  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)));
264
+ const snapshot = guardPath(projectDir, join("history", `${String(version).padStart(4, "0")}.ts`));
246
265
  const entry = { version, reason, timestamp: new Date().toISOString() };
247
266
  const detailField = HISTORY_DETAIL_FIELD[reason];
248
267
  if (detailField && detail)
249
268
  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);
269
+ const lines = Buffer.from([...notes, entry].map(line => JSON.stringify(line) + "\n").join(""));
270
+ const sizeBefore = statSync(indexPath, { throwIfNoEntry: false })?.size;
271
+ let wroteSnapshot = false;
272
+ let appended = false;
273
+ // Takes back what was written here and nothing else. Another run of the
274
+ // project may be recording a version of its own at the same moment: if the
275
+ // index no longer ends with these lines alone, they are left in it, and the
276
+ // version file with them — a version on record that was never installed,
277
+ // rather than someone else's record cut out of the history.
278
+ const undo = () => {
279
+ try {
280
+ const index = readFileSync(indexPath);
281
+ const start = sizeBefore ?? 0;
282
+ const sinceThen = index.subarray(Math.min(start, index.length));
283
+ // What was appended is the end of the index — whole, or as far as a failed write got.
284
+ const cutTo = index.subarray(-lines.length).equals(lines) ? index.length - lines.length
285
+ : lines.subarray(0, sinceThen.length).equals(sinceThen) ? start
286
+ : null;
287
+ if (cutTo === null)
288
+ return;
289
+ if (cutTo === 0 && sizeBefore === undefined)
290
+ rmSync(indexPath, { force: true });
291
+ else if (cutTo < index.length)
292
+ truncateSync(indexPath, cutTo);
268
293
  }
269
- else if (entry.isFile()) {
294
+ catch (err) {
295
+ // The index cannot be looked at. If the lines went into it, they stay,
296
+ // and the version file with them; if they never did, there is only the file.
297
+ if (appended && err.code !== "ENOENT")
298
+ return;
299
+ }
300
+ if (wroteSnapshot)
270
301
  try {
271
- const st = statSync(fullPath);
272
- result.set(relPath, { size: st.size, mtimeMs: st.mtimeMs });
302
+ rmSync(snapshot, { force: true });
273
303
  }
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));
304
+ catch { /* best-effort */ }
303
305
  };
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
306
+ try {
307
+ // Never over a version file that is already there: that one is someone else's.
308
+ const fd = openSync(snapshot, "wx");
309
+ wroteSnapshot = true;
309
310
  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
- }
311
+ writeFileSync(fd, source);
328
312
  }
329
- catch {
330
- // Escapes the directory, path-shape conflict, permissions — skip
313
+ finally {
314
+ closeSync(fd);
331
315
  }
316
+ appendFileSync(indexPath, lines);
317
+ appended = true;
332
318
  }
319
+ catch (err) {
320
+ undo();
321
+ throw err;
322
+ }
323
+ return undo;
324
+ }
325
+ /** Save the current program.ts as the next version of the project, and record why. */
326
+ export function copyToHistory(projectDir, reason, detail) {
327
+ recordVersion(projectDir, readFileSync(guardPath(projectDir, "program.ts")), reason, detail);
333
328
  }
329
+ // --- Staging: run against a copy, merge back what worked (see tree.ts) ---
334
330
  /** Run fn in a temp directory, clean up afterwards regardless of outcome — including this process being stopped. */
335
331
  export async function withTempDir(prefix, fn) {
336
332
  const dir = mkdtempSync(join(tmpdir(), prefix));
@@ -344,35 +340,71 @@ export async function withTempDir(prefix, fn) {
344
340
  }
345
341
  }
346
342
  /**
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.
343
+ * Do something in a directory of a copy that may be closed to it: a copy is
344
+ * the runner's to open. The directory is left allowing what it allowed.
350
345
  */
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,
358
- });
346
+ function inDirOfCopy(dir, what) {
347
+ const allows = statSync(dir).mode;
348
+ if ((allows & 0o700) === 0o700)
349
+ return what();
350
+ chmodSync(dir, (allows & 0o7777) | 0o700);
351
+ try {
352
+ return what();
353
+ }
354
+ finally {
355
+ chmodSync(dir, allows & 0o7777);
356
+ }
357
+ }
358
+ /** The directory a file at `place` is made in — or, if that is still to be made, the one it is made in. */
359
+ function whereMade(place) {
360
+ let dir = dirname(place);
361
+ while (!existsSync(dir))
362
+ dir = dirname(dir);
363
+ return dir;
359
364
  }
360
365
  /**
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.
366
+ * Make, in `privateDir`, a copy of a project to try a program in: what the
367
+ * project is and holds (see copyTree), with `program` as its program.ts.
368
+ * Returns where the copy is, and what the project was when it was copied.
369
+ *
370
+ * The copy allows what the project allows, to everybody: so it is made in a
371
+ * directory that is this runner's alone, and is nobody else's to come to. It
372
+ * has the project's name there.
373
+ *
374
+ * The project's journals are not carried over: they are the record of its
375
+ * runs, not part of what a run works on, and a copy is where a run is tried.
376
+ *
377
+ * In everything else the copy is as the project is, so that what a program
378
+ * can do in the one it can do in the other: what a run did in a copy is
379
+ * merged back into the project, and must not have been possible only there.
380
+ * The one exception is the program: the one to be tried, in the place of
381
+ * the project's. It allows what the project's allows — and its owner to
382
+ * replace it — and is put there whatever the directory it goes in allows:
383
+ * a copy is where programs are tried and replaced, and whether the project's
384
+ * own may be is said of the project, where one is to take its place (see
385
+ * whyNotReplaceable). A project with a directory where its program should be
386
+ * has no place for one, and is not copied to try one in.
365
387
  */
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;
388
+ function copyProjectWith(projectDir, privateDir, program) {
389
+ const root = projectAt(projectDir);
390
+ const copyDir = join(realRootOf(privateDir), basename(root) || "project");
391
+ mkdirSync(copyDir);
392
+ const journals = journalEntriesOf(root);
393
+ const theCopy = identityOf(copyDir);
394
+ const held = copyTree(root, copyDir, (at, entry) => {
395
+ if (entry.kind === "other")
396
+ return false;
397
+ if (entry.id === theCopy) {
398
+ throw new Error(`A copy of ${root} cannot be made inside it, at ${at}. (Is the temp directory in the project?)`);
399
+ }
400
+ return journals.has(entry.id);
375
401
  });
402
+ const place = guardPath(copyDir, "program.ts");
403
+ const had = statSync(place, { throwIfNoEntry: false });
404
+ if (had?.isDirectory())
405
+ throw new Error(`No program can be tried in a copy of ${root}: its program.ts is a directory.`);
406
+ inDirOfCopy(whereMade(place), () => stageFile(copyDir, "program.ts", program, had && (had.mode | 0o200)).commit());
407
+ return { copy: copyDir, held };
376
408
  }
377
409
  /** The end of a long output — where the error is — with a note of how much was dropped. */
378
410
  function tail(text, max = 20_000) {
@@ -449,12 +481,12 @@ function toChildResult(exit) {
449
481
  * takes precedence over its exit code: a program that called ctx.done() and
450
482
  * then crashed is done. Returns null for a failure (non-zero exit, no signal).
451
483
  */
452
- function settle(projectDir, child, terminalSignal) {
484
+ function settle(projectDir, child, ended) {
453
485
  // Read state first: if the program left state.json corrupt, say so now
454
486
  // rather than report an outcome (or start a repair) on top of it.
455
487
  const state = loadState(projectDir);
456
- if (terminalSignal)
457
- return terminalSignal;
488
+ if (ended)
489
+ return ended;
458
490
  if (child.exitCode !== 0)
459
491
  return null;
460
492
  // Natural success without done() or yield(): if this run was the resumption
@@ -476,8 +508,6 @@ function settle(projectDir, child, terminalSignal) {
476
508
  async function runProgramOnce(options) {
477
509
  const { projectDir, backend, timeout, maxIterations, argsOverride, validating, workspaceDir, label, signal, journal } = options;
478
510
  const attempt = options.attempt ?? 0;
479
- if (signal?.aborted)
480
- return { outcome: null, failure: "The run was stopped before its program started." };
481
511
  requireWatchdog();
482
512
  ensureProjectScaffold(projectDir);
483
513
  // Cancels in-flight LLM calls, fetches and observes once the run is over.
@@ -485,8 +515,10 @@ async function runProgramOnce(options) {
485
515
  // Ends a validation: the program has shown what it had to, and is asked to stop.
486
516
  const validated = new AbortController();
487
517
  let readyTimer = null;
488
- let terminalSignal = null;
489
- const ctx = createContext(projectDir, loadState(projectDir), {
518
+ // The state the program starts from. From here on it is the program's: the
519
+ // runner sees it again only as the program hands it over to be persisted.
520
+ const state = loadState(projectDir);
521
+ const ctx = createContext(projectDir, state, {
490
522
  maxIterations,
491
523
  argsOverride,
492
524
  onReady: validating && (() => {
@@ -504,7 +536,7 @@ async function runProgramOnce(options) {
504
536
  });
505
537
  // Truncate logs only after preflight succeeds — preserves the prior run's
506
538
  // diagnostics if scaffolding, state loading, or context creation fails.
507
- writeFileSync(guardPath(projectDir, join("logs", "latest.jsonl")), "");
539
+ writeFileSync(guardPath(projectDir, LATEST_LOG_PATH), "");
508
540
  // The program's own time. It stops while a run the program asked for is in flight.
509
541
  const allowance = createAllowance(timeout);
510
542
  // Set when a validation ended because the program asked for another to be run.
@@ -558,8 +590,6 @@ async function runProgramOnce(options) {
558
590
  nestedRuns.add(nested);
559
591
  return nested;
560
592
  },
561
- // The first terminal signal wins; ctx itself rejects a conflicting second one.
562
- onTerminalSignal: result => { terminalSignal ??= result; },
563
593
  });
564
594
  // A participant's output is shown under its name. It is not its parent's
565
595
  // output: the runner writes it out itself, wherever in the tree it runs.
@@ -582,14 +612,14 @@ async function runProgramOnce(options) {
582
612
  if (programGroup)
583
613
  void stopGroups([programGroup]);
584
614
  };
585
- signal?.addEventListener("abort", stopProgram, { once: true });
615
+ const offStop = onAbort(signal, stopProgram);
586
616
  try {
587
617
  const { child, exited } = await withTempDir("trama-init-", async (initDir) => {
588
618
  const port = await listen(server);
589
619
  const initFile = writeInitFile(initDir, {
590
620
  token,
591
621
  input: ctx.input,
592
- state: ctx.state,
622
+ state,
593
623
  iteration: ctx.iteration,
594
624
  maxIterations: ctx.maxIterations,
595
625
  inSession: sessionWorkspace !== null,
@@ -648,10 +678,10 @@ async function runProgramOnce(options) {
648
678
  try {
649
679
  // A program that was stopped did not finish, whatever its exit code
650
680
  // says — unless it had already said it was done.
651
- outcome = stopped && !terminalSignal ? null : settle(projectDir, child, terminalSignal);
681
+ outcome = stopped && !ctx.ended ? null : settle(projectDir, child, ctx.ended);
652
682
  }
653
683
  catch (err) {
654
- noteExit({ error: err instanceof Error ? err.message : String(err) });
684
+ noteExit({ error: messageOf(err) });
655
685
  throw err;
656
686
  }
657
687
  noteExit({ outcome });
@@ -663,7 +693,7 @@ async function runProgramOnce(options) {
663
693
  // them — and stop what is left of its process group and of its shell
664
694
  // commands. Only once they are gone is the run over: whoever called will
665
695
  // merge or delete what they were writing to.
666
- signal?.removeEventListener("abort", stopProgram);
696
+ offStop();
667
697
  out?.flush();
668
698
  err?.flush();
669
699
  if (readyTimer)
@@ -676,7 +706,7 @@ async function runProgramOnce(options) {
676
706
  ]);
677
707
  programSettled();
678
708
  server.closeAllConnections();
679
- await closeServer(server).catch(() => { });
709
+ await closeServer(server);
680
710
  }
681
711
  }
682
712
  /** The instructions a request for a fix is made under. (Exported so the tests' stand-in LLM can tell one from any other call.) */
@@ -695,16 +725,15 @@ const repairPrompt = (input) => `Fix this program so it runs.\n\n` +
695
725
  */
696
726
  async function requestRepair(options, input) {
697
727
  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);
728
+ return withTempDir("trama-repair-", async (privateDir) => {
701
729
  const timedOut = new AbortController();
702
730
  const limit = createAllowance(options.timeout);
703
- limit.start(() => timedOut.abort());
704
731
  const signal = options.signal ? AbortSignal.any([timedOut.signal, options.signal]) : timedOut.signal;
705
732
  try {
733
+ const { copy } = copyProjectWith(options.projectDir, privateDir, input.programSource);
734
+ limit.start(() => timedOut.abort());
706
735
  const fixed = stripCodeFences(await options.backend.ask(repairPrompt(input), {
707
- cwd: tempDir, system: REPAIR_SYSTEM_PROMPT, signal,
736
+ cwd: copy, system: REPAIR_SYSTEM_PROMPT, signal,
708
737
  }));
709
738
  if (fixed.trim() === "")
710
739
  throw new Error("The repair returned an empty program.");
@@ -714,7 +743,7 @@ async function requestRepair(options, input) {
714
743
  return { fixed };
715
744
  }
716
745
  catch (err) {
717
- const error = err instanceof Error ? err.message : String(err);
746
+ const error = messageOf(err);
718
747
  options.journal.note("fix", { ok: false, error });
719
748
  return { error };
720
749
  }
@@ -728,10 +757,10 @@ async function requestRepair(options, input) {
728
757
  *
729
758
  * The project is the program's own, so the fix runs on a private copy of it.
730
759
  * 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.
760
+ * program.ts, and what its run did is merged back. A fix that fails, or a
761
+ * runner that is stopped while one is tried, leaves the project exactly as
762
+ * it was, because it was never touched: its state is only ever written by
763
+ * code that is, or becomes, its program.
735
764
  *
736
765
  * The shared workspace is not copied. It is how the participants of a session
737
766
  * talk to each other, and a program that is being fixed still has to be heard
@@ -741,20 +770,99 @@ async function requestRepair(options, input) {
741
770
  */
742
771
  async function tryFix(options, fixed, attempt) {
743
772
  const { projectDir } = options;
744
- const run = await withStagedCopy(projectDir, async (stagedProject) => {
745
- writeFileSync(guardPath(stagedProject, "program.ts"), fixed);
773
+ return withTempDir("trama-staged-", async (privateDir) => {
774
+ // What the project held when it was copied: what its places are compared with when the run's work is merged in.
775
+ const { copy: stagedProject, held } = copyProjectWith(projectDir, privateDir, fixed);
776
+ // Taken with the fix in place: what differs from this afterwards is what the run did.
777
+ const before = readTree(stagedProject);
778
+ // The fix in the copy, as the copy has it: under which name, at which place — which is the place of
779
+ // the project's program in the project — and what it allows there.
780
+ const fixAt = guardPath(stagedProject, "program.ts");
781
+ const copyRoot = realRootOf(stagedProject);
782
+ const itsName = pathAsListed(stagedProject, join(copyRoot, "program.ts")) ?? "program.ts";
783
+ const itsPlace = pathAsListed(stagedProject, fixAt);
784
+ const allowed = statSync(fixAt).mode;
785
+ // And all that makes program.ts lead to it, as the copy stands: the name, each link and each directory on
786
+ // the way, the file — each by what it is, which is asked of the place, whatever its directory lists or allows.
787
+ const programIs = () => wayTo(stagedProject, "program.ts").flatMap((place) => {
788
+ const entry = entryAt(place);
789
+ return entry && entry.kind !== "other" ? [entry.id] : [];
790
+ });
791
+ const was = programIs();
746
792
  // If the copy cannot be run at all, or is left unusable, this fix did not work either.
747
793
  const trial = await runProgramOnce({ ...options, projectDir: stagedProject, attempt }).catch((err) => ({
748
794
  outcome: null,
749
- failure: `The repaired program could not be run: ${err instanceof Error ? err.message : err}`,
795
+ failure: `The repaired program could not be run: ${messageOf(err)}`,
750
796
  }));
751
- return { commit: trial.outcome !== null, value: trial };
797
+ if (trial.outcome === null)
798
+ return trial;
799
+ // The fix worked, and becomes the project's program — as it ran, first,
800
+ // and in one move; only then is what its run did merged in. What the run
801
+ // did to its own file is among that: a program may rewrite itself, give
802
+ // itself other permissions, make program.ts lead elsewhere, and here as
803
+ // in any run what it made of itself is what it is. (So a runner stopped
804
+ // between the two leaves the fix beside the state it started from: the
805
+ // program that would do the same again, not the one it turns into.)
806
+ //
807
+ // The project is to have a program afterwards. One that removed itself —
808
+ // the system finds nothing at program.ts, however a link left there words
809
+ // the way to it — is still the fix that ran: a file of its name is put
810
+ // back where the run ended (the name itself, not what the link leads to).
811
+ // A run that left something there that cannot be read as a program has
812
+ // not left a project that has one, and was no fix.
813
+ let is;
814
+ try {
815
+ if (statSync(join(copyRoot, itsName), { throwIfNoEntry: false })) {
816
+ programIn(stagedProject);
817
+ }
818
+ else {
819
+ inDirOfCopy(copyRoot, () => {
820
+ rmSync(join(copyRoot, itsName), { force: true });
821
+ stageFile(stagedProject, itsName, fixed, allowed).commit();
822
+ });
823
+ }
824
+ is = programIs();
825
+ }
826
+ catch (err) {
827
+ return {
828
+ outcome: null,
829
+ failure: `The repaired program ran, but left no program.ts that can be read: ${messageOf(err)}`,
830
+ };
831
+ }
832
+ // If it cannot be put in place, that is an error, and it is thrown from
833
+ // here with nothing of the run in the project: a state the old program
834
+ // did not write, beside the old program, is worse than either. Nor is it
835
+ // put into another directory that is at the project's path by now: the
836
+ // project is the directory that was copied, which the copy knows by what
837
+ // it is.
838
+ const projectRoot = realRootOf(projectDir);
839
+ const copied = held.get("."), there = entryAt(projectRoot);
840
+ if (there && copied?.kind === "dir" && !(there.kind === "dir" && there.id === copied.id)) {
841
+ throw new Error(`The program cannot be replaced: what is at ${projectRoot} is not the project the fix was tried on.`);
842
+ }
843
+ const program = stageProgram(projectDir, fixed);
844
+ program.commit();
845
+ // The project now holds, where its program was, what the copy held there before the run — and the merge is
846
+ // told so: that is what the place is taken to have held when the copy was made. (If that is still the
847
+ // place program.ts leads to: where somebody has pointed it elsewhere meanwhile, the seed knows nothing new.)
848
+ const installed = entryAt(program.destination);
849
+ const samePlace = relative(projectRoot, program.destination) === relative(copyRoot, fixAt);
850
+ if (itsPlace !== undefined && installed && samePlace)
851
+ held.set(itsPlace, installed);
852
+ // What the run made of its program is one thing, with what it was: the name, and what the name leads through
853
+ // and to. If part of that does not arrive — or a part the run left alone is not, in the project, as it was —
854
+ // none of it is carried over: a link without what it leads to, or the file gone from where the project's
855
+ // program.ts still leads, would be a project with no program. The project then keeps the fix as it ran.
856
+ const unmerged = mergeTree(stagedProject, projectDir, before, held, [[...new Set([...was, ...is])]]);
857
+ if (unmerged.length > 0) {
858
+ // The run is done and its program installed; what it did that is not in the project is said, not passed over.
859
+ options.journal.note("unmerged", { attempt, files: unmerged });
860
+ console.warn(tagged(options.label, `[trama] ${unmerged.length} change(s) the repaired run made did not reach the project:`));
861
+ for (const { path, why } of unmerged)
862
+ console.warn(tagged(options.label, `[trama] ${path} — ${why}`));
863
+ }
864
+ return trial;
752
865
  });
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;
758
866
  }
759
867
  /**
760
868
  * Run a program to an outcome. If it crashes, ask the LLM to repair it and try
@@ -770,6 +878,7 @@ async function executeProgram(options) {
770
878
  const wasStopped = () => failed("The run was stopped before it finished.");
771
879
  if (stopped())
772
880
  return wasStopped();
881
+ const stillTheProject = sameProjectAs(projectDir);
773
882
  const firstRun = await runProgramOnce(options);
774
883
  if (firstRun.outcome)
775
884
  return { result: firstRun.outcome };
@@ -778,13 +887,24 @@ async function executeProgram(options) {
778
887
  let lastError = firstRun.failure;
779
888
  if (maxRepairAttempts === 0)
780
889
  return failed(`Program failed (repair disabled): ${lastError}`);
890
+ // What is said and done from here on is said and done of the project the run was started on. (Not what was
891
+ // said just now: where nothing more is to be done, how the program failed is all there is to say.)
892
+ stillTheProject();
893
+ // A fix is worth asking for, and trying, only where it could become the program.
894
+ const refusal = whyNotReplaceable(projectDir);
895
+ if (refusal)
896
+ return failed(`Program failed, and no repair was tried. ${refusal}\n${lastError}`);
781
897
  // 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");
898
+ let currentSource = programIn(projectDir);
899
+ if (currentSource === null)
900
+ return failed(`Program failed (there is no program.ts to repair): ${lastError}`);
783
901
  // The program as it was is attempt 0; each fix is the next.
784
902
  for (let attempt = 1; attempt <= maxRepairAttempts; attempt++) {
903
+ stillTheProject();
785
904
  const fix = await requestRepair(options, { programSource: currentSource, error: lastError });
786
905
  if (stopped())
787
906
  return wasStopped();
907
+ stillTheProject();
788
908
  // Without a fix there is nothing more to try: asking again would be asking the same thing.
789
909
  if ("error" in fix) {
790
910
  return failed(`Failed after ${attempt} repair attempt(s): ${lastError}\nNo fix came back: ${fix.error}`);
@@ -810,7 +930,7 @@ async function journalled(journal, run) {
810
930
  return execution;
811
931
  }
812
932
  catch (err) {
813
- journal.note("end", { error: err instanceof Error ? err.message : String(err) });
933
+ journal.note("end", { error: messageOf(err) });
814
934
  throw err;
815
935
  }
816
936
  finally {
@@ -832,28 +952,108 @@ const VALIDATION_READY_GRACE_MS = 2_000;
832
952
  * first.
833
953
  */
834
954
  export async function validateProgram(projectDir, backend, candidate, options) {
835
- const { journalRuns = 0, ...limits } = options;
955
+ const { journalRuns = 0, signal, ...limits } = options;
836
956
  // Recorded with the project, though run in a copy of it.
837
957
  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);
958
+ const { result, repair, left } = await journalled(journal, () => withTempDir("trama-validate-", async (privateDir) => {
959
+ const { copy: trialDir } = copyProjectWith(projectDir, privateDir, candidate);
842
960
  const execution = await executeProgram({
843
961
  ...limits,
844
962
  projectDir: trialDir,
845
963
  backend,
846
964
  depth: 0,
847
965
  validating: { readyGraceMs: VALIDATION_READY_GRACE_MS },
966
+ signal,
848
967
  journal,
849
968
  });
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 };
969
+ // 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.
970
+ if (execution.result.status === "failed")
971
+ return { ...execution, left: candidate };
972
+ // The program as its run left it: the candidate, or what a repair or the program itself
973
+ // made of it. (One that removed itself is still the candidate that ran.)
974
+ try {
975
+ return { ...execution, left: programIn(trialDir) ?? candidate };
976
+ }
977
+ catch (err) {
978
+ const reason = `The program ran, but left no program.ts that can be read: ${messageOf(err)}`;
979
+ return { ...execution, result: { status: "failed", reason }, left: candidate };
980
+ }
853
981
  }));
854
- if (worked === null)
982
+ if (result.status === "failed")
855
983
  throw new Error(`Program failed: ${result.reason}`);
856
- return { source: worked, repairedError: repair?.error };
984
+ return { source: left, repairedError: repair?.error };
985
+ }
986
+ /** A project's program text — null if it has none. Throws if what is in its place is no file. */
987
+ function programIn(projectDir) {
988
+ // (What the guard lets through is a file, a directory, or nothing yet: reading it waits on nothing.)
989
+ const place = guardPath(projectDir, "program.ts");
990
+ try {
991
+ return readFileSync(place, "utf-8");
992
+ }
993
+ catch (err) {
994
+ const code = err.code;
995
+ if (code === "ENOENT")
996
+ return null;
997
+ if (code === "EISDIR")
998
+ throw new Error(`${place} is a directory, not a program.`);
999
+ throw err;
1000
+ }
1001
+ }
1002
+ /**
1003
+ * Why a project's program cannot be given a successor — or null if it can.
1004
+ *
1005
+ * A program is replaced by a new file taking its place, which the system
1006
+ * allows whatever the old file's permissions say. So the old file is asked: a
1007
+ * program its owner has made read-only is not replaced. A directory in its
1008
+ * place is no program, and no file takes the place of one. And the new file
1009
+ * has to be made beside it, in a directory that is there or can be made.
1010
+ *
1011
+ * This is the rule stageProgram enforces. It is also asked before work whose
1012
+ * only use is a new program — an update, a repair — is begun.
1013
+ */
1014
+ export function whyNotReplaceable(projectDir) {
1015
+ // A program is a project's: where no project is, none is put.
1016
+ let place;
1017
+ let there;
1018
+ try {
1019
+ projectAt(projectDir);
1020
+ place = guardPath(projectDir, "program.ts");
1021
+ there = statSync(place, { throwIfNoEntry: false });
1022
+ }
1023
+ catch (err) {
1024
+ return `The program cannot be replaced: ${messageOf(err)}`;
1025
+ }
1026
+ const allows = (path, what) => {
1027
+ try {
1028
+ accessSync(path, what);
1029
+ return true;
1030
+ }
1031
+ catch {
1032
+ return false;
1033
+ }
1034
+ };
1035
+ if (there?.isDirectory())
1036
+ return `The program cannot be replaced: ${place} is a directory.`;
1037
+ if (there && !allows(place, constants.W_OK))
1038
+ return `The program cannot be replaced: ${place} is read-only.`;
1039
+ const dir = whereMade(place);
1040
+ if (!allows(dir, constants.W_OK | constants.X_OK))
1041
+ return `The program cannot be replaced: nothing can be created in ${dir}.`;
1042
+ return null;
1043
+ }
1044
+ /**
1045
+ * Get a program ready to become a project's program.ts: written beside the
1046
+ * one that is there, to take its place in one move — so program.ts is never
1047
+ * half a program, whatever happens in the middle of writing it.
1048
+ *
1049
+ * It is a new file that takes the place: the old one's permissions are carried
1050
+ * over, but not a second hard link to it, or its owner.
1051
+ */
1052
+ function stageProgram(projectDir, source) {
1053
+ const refusal = whyNotReplaceable(projectDir);
1054
+ if (refusal)
1055
+ throw Object.assign(new Error(refusal), { code: "EACCES" });
1056
+ return stageFile(projectDir, "program.ts", source);
857
1057
  }
858
1058
  /**
859
1059
  * Make a validated program the project's program.ts and record it as a new
@@ -861,13 +1061,24 @@ export async function validateProgram(projectDir, backend, candidate, options) {
861
1061
  * noted in the history index only.
862
1062
  */
863
1063
  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
- });
1064
+ // Three steps, ordered so that a failure at any of them leaves the project
1065
+ // as it was: the new program is written beside the old one (nothing else is
1066
+ // touched if even that cannot be done), the version is recorded, and only
1067
+ // then does the new program take the old one's place — in one move, so
1068
+ // program.ts is never half-written, and never a program that is not on record.
1069
+ const program = stageProgram(projectDir, validated.source);
1070
+ let unrecord = () => { };
1071
+ try {
1072
+ unrecord = recordVersion(projectDir, validated.source, reason, prompt, validated.repairedError
1073
+ ? [{ reason: `${reason}-repair`, timestamp: new Date().toISOString(), error: validated.repairedError }]
1074
+ : []);
1075
+ program.commit();
1076
+ }
1077
+ catch (err) {
1078
+ unrecord();
1079
+ program.discard();
1080
+ throw err;
869
1081
  }
870
- copyToHistory(projectDir, reason, prompt);
871
1082
  }
872
1083
  // --- Core execution ---
873
1084
  /** How deep programs may run programs, and how many runs one runner carries at a time. */
@@ -924,6 +1135,7 @@ async function runProject(options, depth, askedFor) {
924
1135
  args: options.args, // last: it is the one field of unknown size
925
1136
  });
926
1137
  askedFor?.started(journal.run, journal.path);
1138
+ const stillTheProject = sameProjectAs(projectDir);
927
1139
  const { result, repair } = await journalled(journal, () => executeProgram({
928
1140
  projectDir,
929
1141
  backend: createBackend(config),
@@ -940,13 +1152,14 @@ async function runProject(options, depth, askedFor) {
940
1152
  if (repair) {
941
1153
  // The program is fixed and has run; failing to write this down must not turn that into an error.
942
1154
  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}`));
1155
+ stillTheProject();
1156
+ const message = `Repair attempt ${repair.attempt}/${maxRepairAttempts}`;
1157
+ appendLogEntry(guardPath(projectDir, LATEST_LOG_PATH), message, { error: repair.error });
1158
+ console.log(tagged(options.label, `[trama] ${message}`));
946
1159
  copyToHistory(projectDir, "repair", repair.error);
947
1160
  }
948
1161
  catch (err) {
949
- console.warn(tagged(options.label, `[trama] repair bookkeeping failed: ${err instanceof Error ? err.message : err}`));
1162
+ console.warn(tagged(options.label, `[trama] repair bookkeeping failed: ${messageOf(err)}`));
950
1163
  }
951
1164
  }
952
1165
  return result;