@trama-dev/runtime 0.3.1 → 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.
Files changed (47) 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 +0 -6
  5. package/dist/agent-backend.js +1 -21
  6. package/dist/agent.d.ts +16 -1
  7. package/dist/agent.js +108 -35
  8. package/dist/bridge-client.js +44 -14
  9. package/dist/child-process.d.ts +1 -20
  10. package/dist/child-process.js +11 -86
  11. package/dist/client.d.ts +2 -1
  12. package/dist/client.js +5 -15
  13. package/dist/context.d.ts +36 -7
  14. package/dist/context.js +83 -92
  15. package/dist/errors.d.ts +2 -0
  16. package/dist/errors.js +2 -0
  17. package/dist/index.d.ts +12 -1
  18. package/dist/index.js +93 -53
  19. package/dist/ipc-server.d.ts +12 -6
  20. package/dist/ipc-server.js +124 -136
  21. package/dist/journal-view.d.ts +9 -0
  22. package/dist/journal-view.js +139 -0
  23. package/dist/journal.d.ts +70 -0
  24. package/dist/journal.js +454 -0
  25. package/dist/meta.d.ts +18 -0
  26. package/dist/meta.js +29 -0
  27. package/dist/path-guard.d.ts +128 -19
  28. package/dist/path-guard.js +384 -68
  29. package/dist/pi-adapter.d.ts +7 -6
  30. package/dist/pi-adapter.js +15 -26
  31. package/dist/replace-file.d.ts +31 -0
  32. package/dist/replace-file.js +75 -0
  33. package/dist/runner-types.d.ts +2 -0
  34. package/dist/runner.d.ts +37 -37
  35. package/dist/runner.js +565 -239
  36. package/dist/serializable.d.ts +10 -4
  37. package/dist/serializable.js +56 -31
  38. package/dist/{watchdog.d.ts → stopping.d.ts} +15 -0
  39. package/dist/stopping.js +268 -0
  40. package/dist/tools.js +44 -13
  41. package/dist/tree.d.ts +234 -0
  42. package/dist/tree.js +1409 -0
  43. package/dist/types.d.ts +6 -3
  44. package/dist/workspace.d.ts +7 -0
  45. package/dist/workspace.js +93 -104
  46. package/package.json +2 -2
  47. package/dist/watchdog.js +0 -167
package/dist/runner.js CHANGED
@@ -1,19 +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 } 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
- import { randomBytes } from "crypto";
7
- import { rejectOnAbort } from "./agent-backend.js";
6
+ import { createHash, randomBytes } from "crypto";
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";
14
- import { createAllowance, stopGroups, superviseChild } from "./child-process.js";
15
- import { removeTempDir, removeWithThisProcess, requireWatchdog, stopWithThisProcess } from "./watchdog.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";
18
+ import { createAllowance, superviseChild } from "./child-process.js";
19
+ import { removeTempDir, removeWithThisProcess, requireWatchdog, stopGroups, stopWithThisProcess } from "./stopping.js";
16
20
  import { createIPCServer, listen, closeServer } from "./ipc-server.js";
21
+ import { journalEntriesOf, openJournal } from "./journal.js";
22
+ import { messageOf } from "./errors.js";
17
23
  // --- Locating the runtime itself ---
18
24
  /** The installed @trama-dev/runtime package — this file lives in its dist/. */
19
25
  const RUNTIME_PACKAGE_DIR = dirname(dirname(fileURLToPath(import.meta.url)));
@@ -43,10 +49,14 @@ catch { /* not installed — programs simply cannot import it */ }
43
49
  * so program.ts can import it. Replaces any existing symlink whose target
44
50
  * differs (including user-managed ones). Only refuses to touch a real
45
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.
46
56
  */
47
57
  function linkPackage(projectDir, name, target) {
48
- // The link deliberately points OUTSIDE the project — do not apply guardPath here.
49
- 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.
50
60
  const linkPath = join(linkDir, name);
51
61
  try {
52
62
  if (!lstatSync(linkPath).isSymbolicLink()) {
@@ -79,15 +89,14 @@ function ensureModulePackageJson(projectDir) {
79
89
  }
80
90
  catch (err) {
81
91
  throw new Error(`Malformed package.json at ${pkgPath}. ${advice}\n` +
82
- `Parse error: ${err instanceof Error ? err.message : err}`);
92
+ `Parse error: ${messageOf(err)}`);
83
93
  }
84
- if (typeof pkg !== "object" || pkg === null || Array.isArray(pkg)) {
85
- 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}`);
86
96
  }
87
- const pkgObj = pkg;
88
- if (pkgObj.type !== "module") {
89
- pkgObj.type = "module";
90
- writeFileSync(pkgPath, JSON.stringify(pkgObj, null, 2));
97
+ if (pkg.type !== "module") {
98
+ pkg.type = "module";
99
+ writeFileSync(pkgPath, JSON.stringify(pkg, null, 2));
91
100
  }
92
101
  }
93
102
  /** Make sure .gitignore excludes what trama generates, without disturbing existing entries. */
@@ -109,6 +118,7 @@ function ensureGitignore(projectDir) {
109
118
  * Idempotent — called before every run, so a freshly cloned project just works.
110
119
  */
111
120
  export function ensureProjectScaffold(projectDir) {
121
+ projectAt(projectDir);
112
122
  mkdirSync(guardPath(projectDir, "history"), { recursive: true });
113
123
  mkdirSync(guardPath(projectDir, "logs"), { recursive: true });
114
124
  ensureModulePackageJson(projectDir);
@@ -141,6 +151,7 @@ export function loadConfig() {
141
151
  maxRepairAttempts: 3,
142
152
  defaultTimeout: 300_000,
143
153
  defaultMaxIterations: 100,
154
+ journalRuns: 20,
144
155
  };
145
156
  let raw;
146
157
  try {
@@ -157,12 +168,17 @@ export function loadConfig() {
157
168
  }
158
169
  catch (err) {
159
170
  throw new Error(`Malformed config at ${configPath} — fix or delete it.\n` +
160
- `Parse error: ${err instanceof Error ? err.message : err}`);
171
+ `Parse error: ${messageOf(err)}`);
161
172
  }
162
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
163
- 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.`);
164
175
  }
165
- 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) {
166
182
  const s = (v) => typeof v === "string" && v.length > 0;
167
183
  const pint = (v) => Number.isInteger(v) && v > 0;
168
184
  const checks = [
@@ -171,22 +187,25 @@ export function loadConfig() {
171
187
  [Number.isInteger(merged.maxRepairAttempts) && merged.maxRepairAttempts >= 0, `"maxRepairAttempts" must be a non-negative integer (got ${merged.maxRepairAttempts})`],
172
188
  [Number.isFinite(merged.defaultTimeout) && merged.defaultTimeout > 0, `"defaultTimeout" must be a positive number (got ${merged.defaultTimeout})`],
173
189
  [pint(merged.defaultMaxIterations), `"defaultMaxIterations" must be a positive integer (got ${merged.defaultMaxIterations})`],
190
+ [Number.isInteger(merged.journalRuns) && merged.journalRuns >= 0, `"journalRuns" must be a non-negative integer (got ${merged.journalRuns})`],
174
191
  ];
175
192
  for (const [ok, msg] of checks) {
176
193
  if (!ok)
177
- throw new Error(`Invalid config: ${msg}`);
194
+ throw new Error(`Invalid ${source}: ${msg}`);
178
195
  }
179
196
  return merged;
180
197
  }
181
198
  /** The global config, with the model/provider a project was created with taking precedence. */
182
- export function loadProjectConfig(projectDir) {
199
+ export function loadProjectConfig(projectDir, meta = readProjectMeta(projectDir)) {
183
200
  const config = loadConfig();
184
- const meta = JSON.parse(readFileSync(guardPath(projectDir, "meta.json"), "utf-8"));
185
- 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)
186
205
  config.model = meta.model;
187
- if (meta.provider)
206
+ if (meta.provider != null)
188
207
  config.provider = meta.provider;
189
- return config;
208
+ return checkedConfig(config, `meta.json in ${projectDir}`);
190
209
  }
191
210
  /**
192
211
  * What does the LLM work for a project. The only place that picks a backend:
@@ -200,134 +219,114 @@ export function createBackend(config) {
200
219
  }
201
220
  export function loadState(projectDir) {
202
221
  const statePath = guardPath(projectDir, "state.json");
203
- if (!existsSync(statePath))
204
- return {};
205
- const raw = readFileSync(statePath, "utf-8");
206
- 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) {
207
232
  throw new Error(`Corrupt state.json in ${projectDir} — cannot safely continue.\n${reason}\n` +
208
233
  `Back up or delete state.json to reset state.`);
209
- };
234
+ }
210
235
  let parsed;
211
236
  try {
212
237
  parsed = JSON.parse(raw);
213
238
  }
214
239
  catch (err) {
215
- fail(`Parse error: ${err instanceof Error ? err.message : err}`);
240
+ fail(`Parse error: ${messageOf(err)}`);
216
241
  }
217
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
218
- 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)}.`);
219
244
  }
220
245
  return parsed;
221
246
  }
222
247
  // --- History management ---
223
- /** Append one metadata line to history/index.jsonl. */
224
- function appendHistoryIndex(projectDir, entry) {
225
- appendFileSync(guardPath(projectDir, join("history", "index.jsonl")), JSON.stringify(entry) + "\n");
226
- }
227
248
  /** The index.jsonl field that carries the detail for each kind of versioned change. */
228
249
  const HISTORY_DETAIL_FIELD = { create: "prompt", update: "prompt", repair: "error" };
229
250
  /**
230
- * Save the current program.ts as the next version: copy it to history/NNNN.ts
231
- * and record why in index.jsonl.
232
- *
233
- * (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.
234
255
  */
235
- export function copyToHistory(projectDir, reason, detail) {
256
+ function recordVersion(projectDir, source, reason, detail, notes = []) {
236
257
  const historyDir = guardPath(projectDir, "history");
258
+ const indexPath = guardPath(projectDir, join("history", "index.jsonl"));
237
259
  const versions = readdirSync(historyDir)
238
260
  .filter(f => /^\d+\.ts$/.test(f))
239
- .map(f => parseInt(f, 10));
261
+ .map(f => parseInt(f, 10))
262
+ .filter(n => Number.isSafeInteger(n) && n < Number.MAX_SAFE_INTEGER);
240
263
  const version = versions.reduce((a, b) => Math.max(a, b), 0) + 1;
241
- const fileName = `${String(version).padStart(4, "0")}.ts`;
242
- copyFileSync(guardPath(projectDir, "program.ts"), guardPath(projectDir, join("history", fileName)));
264
+ const snapshot = guardPath(projectDir, join("history", `${String(version).padStart(4, "0")}.ts`));
243
265
  const entry = { version, reason, timestamp: new Date().toISOString() };
244
266
  const detailField = HISTORY_DETAIL_FIELD[reason];
245
267
  if (detailField && detail)
246
268
  entry[detailField] = detail;
247
- appendHistoryIndex(projectDir, entry);
248
- }
249
- /** Record all files in a directory with their size and mtime for change detection. */
250
- export function snapshotDir(dir, prefix = "") {
251
- const result = new Map();
252
- let entries;
253
- try {
254
- entries = readdirSync(dir, { withFileTypes: true });
255
- }
256
- catch {
257
- return result;
258
- }
259
- for (const entry of entries) {
260
- const relPath = prefix ? `${prefix}/${entry.name}` : entry.name;
261
- const fullPath = join(dir, entry.name);
262
- if (entry.isDirectory()) {
263
- for (const [k, v] of snapshotDir(fullPath, relPath))
264
- 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);
265
293
  }
266
- 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)
267
301
  try {
268
- const st = statSync(fullPath);
269
- result.set(relPath, { size: st.size, mtimeMs: st.mtimeMs });
302
+ rmSync(snapshot, { force: true });
270
303
  }
271
- catch { /* skip */ }
272
- }
273
- }
274
- return result;
275
- }
276
- const sameStat = (a, b) => a.size === b.size && a.mtimeMs === b.mtimeMs;
277
- /**
278
- * Merge what a run did to a staged copy back into the real directory, with a
279
- * three-way check so that nothing changed in the real directory meanwhile —
280
- * by the user, or by another run of the same project — is overwritten.
281
- *
282
- * @param stagedDir - the copy after the run (source of changes)
283
- * @param realDir - the real directory (destination)
284
- * @param stagedBefore - snapshot of the copy before the run (detects what the run changed)
285
- * @param realSeed - snapshot of the real directory when the copy was taken (detects concurrent changes)
286
- *
287
- * For each file the run touched in the copy:
288
- * - Created: copied, unless that path has meanwhile appeared in the real directory.
289
- * - Modified: copied only if the real file still matches realSeed.
290
- * - Deleted: deleted only if the real file still matches realSeed.
291
- * Best-effort: anything that cannot be merged safely is skipped, never thrown.
292
- */
293
- export function commitStagedChanges(stagedDir, realDir, stagedBefore, realSeed) {
294
- const stagedAfter = snapshotDir(stagedDir);
295
- /** The real file as it is now — but only if nobody has touched it since the copy was taken. */
296
- const untouchedSinceSeed = (relPath, dstPath) => {
297
- const seedStat = realSeed.get(relPath);
298
- const realNow = statSync(dstPath, { throwIfNoEntry: false });
299
- return seedStat === undefined || (realNow !== undefined && sameStat(realNow, seedStat));
304
+ catch { /* best-effort */ }
300
305
  };
301
- for (const relPath of new Set([...stagedBefore.keys(), ...stagedAfter.keys()])) {
302
- const beforeStat = stagedBefore.get(relPath);
303
- const afterStat = stagedAfter.get(relPath);
304
- if (beforeStat && afterStat && sameStat(beforeStat, afterStat))
305
- 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;
306
310
  try {
307
- // A symlink placed at this path, or in a parent directory, could point
308
- // outside the real directory — guardPath throws.
309
- const dstPath = guardPath(realDir, relPath);
310
- if (!afterStat) {
311
- if (untouchedSinceSeed(relPath, dstPath))
312
- rmSync(dstPath, { force: true });
313
- }
314
- else if (beforeStat) {
315
- if (!untouchedSinceSeed(relPath, dstPath))
316
- continue; // changed or removed concurrently
317
- copyFileSync(join(stagedDir, relPath), dstPath);
318
- }
319
- else {
320
- if (statSync(dstPath, { throwIfNoEntry: false }))
321
- continue; // someone else created it first — keep theirs
322
- mkdirSync(dirname(dstPath), { recursive: true });
323
- copyFileSync(join(stagedDir, relPath), dstPath);
324
- }
311
+ writeFileSync(fd, source);
325
312
  }
326
- catch {
327
- // Escapes the directory, path-shape conflict, permissions — skip
313
+ finally {
314
+ closeSync(fd);
328
315
  }
316
+ appendFileSync(indexPath, lines);
317
+ appended = true;
329
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);
330
328
  }
329
+ // --- Staging: run against a copy, merge back what worked (see tree.ts) ---
331
330
  /** Run fn in a temp directory, clean up afterwards regardless of outcome — including this process being stopped. */
332
331
  export async function withTempDir(prefix, fn) {
333
332
  const dir = mkdtempSync(join(tmpdir(), prefix));
@@ -340,27 +339,72 @@ export async function withTempDir(prefix, fn) {
340
339
  settled();
341
340
  }
342
341
  }
343
- /** Copy a directory's contents into an existing one, keeping symlinks as they are written. */
344
- function copyDirInto(srcDir, dstDir) {
345
- // realpath: a project directory may itself be a symlink.
346
- cpSync(realpathSync(srcDir), dstDir, { recursive: true, verbatimSymlinks: true });
342
+ /**
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.
345
+ */
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;
347
364
  }
348
365
  /**
349
- * Run fn against a private copy of a directory. What fn does there stays
350
- * invisible to the real directory unless fn asks to commit it — then it is
351
- * merged back (see commitStagedChanges). If fn fails, or this process is
352
- * 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.
353
387
  */
354
- async function withStagedCopy(realDir, fn) {
355
- const realSeed = snapshotDir(realDir);
356
- return withTempDir("trama-staged-", async (stagedDir) => {
357
- copyDirInto(realDir, stagedDir);
358
- const stagedBefore = snapshotDir(stagedDir);
359
- const { commit, value } = await fn(stagedDir);
360
- if (commit)
361
- commitStagedChanges(stagedDir, realDir, stagedBefore, realSeed);
362
- 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);
363
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 };
364
408
  }
365
409
  /** The end of a long output — where the error is — with a note of how much was dropped. */
366
410
  function tail(text, max = 20_000) {
@@ -394,6 +438,18 @@ function labelled(label, write) {
394
438
  flush,
395
439
  };
396
440
  }
441
+ /** How much of each of a program's output streams goes into the journal. */
442
+ const MAX_JOURNALLED_OUTPUT = 64 * 1024;
443
+ /** What identifies a program text without quoting it. */
444
+ function fingerprint(programPath) {
445
+ try {
446
+ const source = readFileSync(programPath);
447
+ return { sha256: createHash("sha256").update(source).digest("hex"), bytes: source.length };
448
+ }
449
+ catch {
450
+ return null; // no program to speak of; the attempt will say so itself
451
+ }
452
+ }
397
453
  const describeFailure = (r) => `program.ts exited with code ${r.exitCode}\nstdout: ${tail(r.stdout)}\nstderr: ${tail(r.stderr)}`;
398
454
  /**
399
455
  * Hand the program its starting state through a private temp file rather than
@@ -425,12 +481,12 @@ function toChildResult(exit) {
425
481
  * takes precedence over its exit code: a program that called ctx.done() and
426
482
  * then crashed is done. Returns null for a failure (non-zero exit, no signal).
427
483
  */
428
- function settle(projectDir, child, terminalSignal) {
484
+ function settle(projectDir, child, ended) {
429
485
  // Read state first: if the program left state.json corrupt, say so now
430
486
  // rather than report an outcome (or start a repair) on top of it.
431
487
  const state = loadState(projectDir);
432
- if (terminalSignal)
433
- return terminalSignal;
488
+ if (ended)
489
+ return ended;
434
490
  if (child.exitCode !== 0)
435
491
  return null;
436
492
  // Natural success without done() or yield(): if this run was the resumption
@@ -450,9 +506,8 @@ function settle(projectDir, child, terminalSignal) {
450
506
  * (bad project, server or spawn failure) or left state.json unreadable.
451
507
  */
452
508
  async function runProgramOnce(options) {
453
- const { projectDir, backend, timeout, maxIterations, argsOverride, validating, workspaceDir, label, signal } = options;
454
- if (signal?.aborted)
455
- return { outcome: null, failure: "The run was stopped before its program started." };
509
+ const { projectDir, backend, timeout, maxIterations, argsOverride, validating, workspaceDir, label, signal, journal } = options;
510
+ const attempt = options.attempt ?? 0;
456
511
  requireWatchdog();
457
512
  ensureProjectScaffold(projectDir);
458
513
  // Cancels in-flight LLM calls, fetches and observes once the run is over.
@@ -460,8 +515,10 @@ async function runProgramOnce(options) {
460
515
  // Ends a validation: the program has shown what it had to, and is asked to stop.
461
516
  const validated = new AbortController();
462
517
  let readyTimer = null;
463
- let terminalSignal = null;
464
- 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, {
465
522
  maxIterations,
466
523
  argsOverride,
467
524
  onReady: validating && (() => {
@@ -469,9 +526,17 @@ async function runProgramOnce(options) {
469
526
  }),
470
527
  print: line => console.log(tagged(label, line)),
471
528
  });
529
+ journal.note("attempt", {
530
+ attempt,
531
+ // Where it runs — a copy of the project, when a fix is being tried or a candidate validated.
532
+ dir: projectDir,
533
+ program: fingerprint(guardPath(projectDir, "program.ts")),
534
+ iteration: ctx.iteration,
535
+ resumed: ctx.resumed,
536
+ });
472
537
  // Truncate logs only after preflight succeeds — preserves the prior run's
473
538
  // diagnostics if scaffolding, state loading, or context creation fails.
474
- writeFileSync(guardPath(projectDir, join("logs", "latest.jsonl")), "");
539
+ writeFileSync(guardPath(projectDir, LATEST_LOG_PATH), "");
475
540
  // The program's own time. It stops while a run the program asked for is in flight.
476
541
  const allowance = createAllowance(timeout);
477
542
  // Set when a validation ended because the program asked for another to be run.
@@ -479,6 +544,14 @@ async function runProgramOnce(options) {
479
544
  // Runs the program has asked for and that are still going. They belong to this run.
480
545
  const nestedRuns = new Set();
481
546
  const workspaces = new Map();
547
+ const workspaceAt = (dir) => {
548
+ let workspace = workspaces.get(dir);
549
+ if (!workspace)
550
+ workspaces.set(dir, workspace = createWorkspace(dir, runEnded.signal));
551
+ return workspace;
552
+ };
553
+ // The workspace of the session this run is part of, if it is part of one.
554
+ const sessionWorkspace = workspaceDir ? workspaceAt(workspaceDir) : null;
482
555
  const tools = createTools(projectDir, runEnded.signal);
483
556
  // Known only to this run's program, through its init file.
484
557
  const token = randomBytes(32).toString("hex");
@@ -487,14 +560,10 @@ async function runProgramOnce(options) {
487
560
  ctx,
488
561
  agent: createAgent(backend, projectDir, runEnded.signal),
489
562
  tools,
490
- workspace: workspaceDir ? createWorkspace(workspaceDir, runEnded.signal) : null,
491
- workspaceAt: (dir) => {
492
- let workspace = workspaces.get(dir);
493
- if (!workspace)
494
- workspaces.set(dir, workspace = createWorkspace(dir, runEnded.signal));
495
- return workspace;
496
- },
497
- run: (request, stop) => {
563
+ workspace: sessionWorkspace,
564
+ workspaceAt,
565
+ journal,
566
+ run: (request, stop, seq) => {
498
567
  if (validating) {
499
568
  // As far as a validation goes. The call is left unanswered — an answer
500
569
  // would only send the program on to do more — until the program,
@@ -507,15 +576,20 @@ async function runProgramOnce(options) {
507
576
  // the run it asked for lasts, which has a timeout of its own. That run
508
577
  // is stopped when this one ends, or when the program no longer wants it.
509
578
  const release = allowance.hold();
510
- const nested = runProgram({ ...request, signal: AbortSignal.any([runEnded.signal, stop]) }, options.depth + 1).finally(() => {
579
+ const nested = runProgram({ ...request, signal: AbortSignal.any([runEnded.signal, stop]) }, {
580
+ depth: options.depth + 1,
581
+ // The two journals point at each other: this one says which run the call started…
582
+ started: (run, path) => { if (run)
583
+ journal.note("child", { seq, run, journal: path }); },
584
+ // …and that run's journal says which call started it.
585
+ parent: { run: journal.run, journal: journal.path, seq },
586
+ }).finally(() => {
511
587
  release();
512
588
  nestedRuns.delete(nested);
513
589
  });
514
590
  nestedRuns.add(nested);
515
591
  return nested;
516
592
  },
517
- // The first terminal signal wins; ctx itself rejects a conflicting second one.
518
- onTerminalSignal: result => { terminalSignal ??= result; },
519
593
  });
520
594
  // A participant's output is shown under its name. It is not its parent's
521
595
  // output: the runner writes it out itself, wherever in the tree it runs.
@@ -538,17 +612,17 @@ async function runProgramOnce(options) {
538
612
  if (programGroup)
539
613
  void stopGroups([programGroup]);
540
614
  };
541
- signal?.addEventListener("abort", stopProgram, { once: true });
615
+ const offStop = onAbort(signal, stopProgram);
542
616
  try {
543
- const child = await withTempDir("trama-init-", async (initDir) => {
617
+ const { child, exited } = await withTempDir("trama-init-", async (initDir) => {
544
618
  const port = await listen(server);
545
619
  const initFile = writeInitFile(initDir, {
546
620
  token,
547
621
  input: ctx.input,
548
- state: ctx.state,
622
+ state,
549
623
  iteration: ctx.iteration,
550
624
  maxIterations: ctx.maxIterations,
551
- inSession: workspaceDir !== undefined,
625
+ inSession: sessionWorkspace !== null,
552
626
  resumed: ctx.resumed,
553
627
  yieldReason: ctx.yieldReason,
554
628
  });
@@ -572,16 +646,45 @@ async function runProgramOnce(options) {
572
646
  },
573
647
  });
574
648
  programOver = true;
575
- // A validation that reached a hand-off in time was decided there.
576
- if (handedOff && !exit.timedOut) {
649
+ // A validation that reached a hand-off in time was decided there: how the
650
+ // program goes down, cut off in mid-flow, says nothing about it.
651
+ const passedAtHandOff = handedOff && !exit.timedOut;
652
+ if (passedAtHandOff)
577
653
  console.log(tagged(label, "[trama] validated up to where it starts another program"));
578
- return { exitCode: 0, stdout: exit.stdout, stderr: exit.stderr };
579
- }
580
- return toChildResult(exit);
654
+ return {
655
+ child: passedAtHandOff ? { exitCode: 0, stdout: exit.stdout, stderr: exit.stderr } : toChildResult(exit),
656
+ // How the program's process ended, for the record.
657
+ exited: {
658
+ code: exit.code,
659
+ signal: exit.signal,
660
+ ...(exit.timedOut ? { timedOut: true } : {}),
661
+ // Stopped by the runner at the end of a validation: at a hand-off, or once it had been ready a while.
662
+ ...(exit.stopped ? { validated: handedOff ? "hand-off" : "ready" } : {}),
663
+ },
664
+ };
581
665
  });
582
- // A program that was stopped did not finish, whatever its exit code says —
583
- // unless it had already said it was done.
584
- const outcome = stopped && !terminalSignal ? null : settle(projectDir, child, terminalSignal);
666
+ // How the attempt ended goes on record whatever comes of it — also when
667
+ // what the program left behind cannot be made sense of.
668
+ const noteExit = (verdict) => journal.note("exit", {
669
+ attempt,
670
+ ...exited,
671
+ ...(stopped ? { stopped: true } : {}),
672
+ // What the program printed is part of what it did. The end of it, where a failure shows.
673
+ stdout: tail(child.stdout, MAX_JOURNALLED_OUTPUT),
674
+ stderr: tail(child.stderr, MAX_JOURNALLED_OUTPUT),
675
+ ...verdict,
676
+ });
677
+ let outcome;
678
+ try {
679
+ // A program that was stopped did not finish, whatever its exit code
680
+ // says — unless it had already said it was done.
681
+ outcome = stopped && !ctx.ended ? null : settle(projectDir, child, ctx.ended);
682
+ }
683
+ catch (err) {
684
+ noteExit({ error: messageOf(err) });
685
+ throw err;
686
+ }
687
+ noteExit({ outcome });
585
688
  return { outcome, failure: describeFailure(child) };
586
689
  }
587
690
  finally {
@@ -590,7 +693,7 @@ async function runProgramOnce(options) {
590
693
  // them — and stop what is left of its process group and of its shell
591
694
  // commands. Only once they are gone is the run over: whoever called will
592
695
  // merge or delete what they were writing to.
593
- signal?.removeEventListener("abort", stopProgram);
696
+ offStop();
594
697
  out?.flush();
595
698
  err?.flush();
596
699
  if (readyTimer)
@@ -603,7 +706,7 @@ async function runProgramOnce(options) {
603
706
  ]);
604
707
  programSettled();
605
708
  server.closeAllConnections();
606
- await closeServer(server).catch(() => { });
709
+ await closeServer(server);
607
710
  }
608
711
  }
609
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.) */
@@ -618,29 +721,31 @@ const repairPrompt = (input) => `Fix this program so it runs.\n\n` +
618
721
  * of the project that holds the program it is asked to fix — whatever it reads
619
722
  * is real, whatever it writes is discarded; only the program text it returns
620
723
  * is used. Bounded by its own timeout.
621
- * Returns null (and records why) if no usable fix came back.
724
+ * Returns the fixed program, or why no usable one came back.
622
725
  */
623
- async function requestRepair(options, input, repairErrors) {
624
- return withTempDir("trama-repair-", async (tempDir) => {
625
- copyDirInto(options.projectDir, tempDir);
626
- writeFileSync(guardPath(tempDir, "program.ts"), input.programSource);
726
+ async function requestRepair(options, input) {
727
+ options.journal.note("fix-request", { error: input.error });
728
+ return withTempDir("trama-repair-", async (privateDir) => {
627
729
  const timedOut = new AbortController();
628
730
  const limit = createAllowance(options.timeout);
629
- limit.start(() => timedOut.abort());
630
731
  const signal = options.signal ? AbortSignal.any([timedOut.signal, options.signal]) : timedOut.signal;
631
732
  try {
733
+ const { copy } = copyProjectWith(options.projectDir, privateDir, input.programSource);
734
+ limit.start(() => timedOut.abort());
632
735
  const fixed = stripCodeFences(await options.backend.ask(repairPrompt(input), {
633
- cwd: tempDir, system: REPAIR_SYSTEM_PROMPT, signal,
736
+ cwd: copy, system: REPAIR_SYSTEM_PROMPT, signal,
634
737
  }));
635
738
  if (fixed.trim() === "")
636
739
  throw new Error("The repair returned an empty program.");
637
740
  if (fixed === input.programSource)
638
741
  throw new Error("The repair returned the program unchanged.");
639
- return fixed;
742
+ options.journal.note("fix", { ok: true, source: fixed });
743
+ return { fixed };
640
744
  }
641
745
  catch (err) {
642
- repairErrors.push(err instanceof Error ? err.message : String(err));
643
- return null;
746
+ const error = messageOf(err);
747
+ options.journal.note("fix", { ok: false, error });
748
+ return { error };
644
749
  }
645
750
  finally {
646
751
  limit.cancel();
@@ -652,10 +757,10 @@ async function requestRepair(options, input, repairErrors) {
652
757
  *
653
758
  * The project is the program's own, so the fix runs on a private copy of it.
654
759
  * Only if it works does anything reach the real one — the fix becomes
655
- * program.ts, and what the run wrote is merged back. A fix that fails, or a
656
- * runner that is stopped half-way, leaves the project exactly as it was,
657
- * because it was never touched: its state is only ever written by code that
658
- * 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.
659
764
  *
660
765
  * The shared workspace is not copied. It is how the participants of a session
661
766
  * talk to each other, and a program that is being fixed still has to be heard
@@ -663,22 +768,101 @@ async function requestRepair(options, input, repairErrors) {
663
768
  * would wait for replies forever. So what a fix writes there is written,
664
769
  * whether or not the fix works: like anything a run wrote before it failed.
665
770
  */
666
- async function tryFix(options, fixed) {
771
+ async function tryFix(options, fixed, attempt) {
667
772
  const { projectDir } = options;
668
- const run = await withStagedCopy(projectDir, async (stagedProject) => {
669
- 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();
670
792
  // If the copy cannot be run at all, or is left unusable, this fix did not work either.
671
- const trial = await runProgramOnce({ ...options, projectDir: stagedProject }).catch((err) => ({
793
+ const trial = await runProgramOnce({ ...options, projectDir: stagedProject, attempt }).catch((err) => ({
672
794
  outcome: null,
673
- 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)}`,
674
796
  }));
675
- 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;
676
865
  });
677
- // The merge above carries over what the run changed; the fix itself was
678
- // written before the run started, so it is installed explicitly.
679
- if (run.outcome)
680
- writeFileSync(guardPath(projectDir, "program.ts"), fixed);
681
- return run;
682
866
  }
683
867
  /**
684
868
  * Run a program to an outcome. If it crashes, ask the LLM to repair it and try
@@ -694,6 +878,7 @@ async function executeProgram(options) {
694
878
  const wasStopped = () => failed("The run was stopped before it finished.");
695
879
  if (stopped())
696
880
  return wasStopped();
881
+ const stillTheProject = sameProjectAs(projectDir);
697
882
  const firstRun = await runProgramOnce(options);
698
883
  if (firstRun.outcome)
699
884
  return { result: firstRun.outcome };
@@ -702,32 +887,62 @@ async function executeProgram(options) {
702
887
  let lastError = firstRun.failure;
703
888
  if (maxRepairAttempts === 0)
704
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}`);
705
897
  // Each attempt builds on the previous one's source, though a fix that failed never reached the project.
706
- let currentSource = readFileSync(guardPath(projectDir, "program.ts"), "utf-8");
707
- const repairErrors = [];
708
- const repairDetails = () => repairErrors.length > 0
709
- ? `\nRepair errors:\n${repairErrors.map((e, i) => ` [${i + 1}] ${e}`).join("\n")}` : "";
710
- for (let attempt = 0; attempt < maxRepairAttempts; attempt++) {
711
- const fixed = await requestRepair(options, { programSource: currentSource, error: lastError }, repairErrors);
898
+ let currentSource = programIn(projectDir);
899
+ if (currentSource === null)
900
+ return failed(`Program failed (there is no program.ts to repair): ${lastError}`);
901
+ // The program as it was is attempt 0; each fix is the next.
902
+ for (let attempt = 1; attempt <= maxRepairAttempts; attempt++) {
903
+ stillTheProject();
904
+ const fix = await requestRepair(options, { programSource: currentSource, error: lastError });
712
905
  if (stopped())
713
906
  return wasStopped();
714
- if (!fixed)
715
- return failed(`Failed after ${attempt + 1} repair attempt(s): ${lastError}${repairDetails()}`);
716
- currentSource = fixed;
717
- const run = await tryFix(options, fixed);
907
+ stillTheProject();
908
+ // Without a fix there is nothing more to try: asking again would be asking the same thing.
909
+ if ("error" in fix) {
910
+ return failed(`Failed after ${attempt} repair attempt(s): ${lastError}\nNo fix came back: ${fix.error}`);
911
+ }
912
+ currentSource = fix.fixed;
913
+ const run = await tryFix(options, fix.fixed, attempt);
718
914
  if (run.outcome)
719
915
  return { result: run.outcome, repair: { attempt, error: lastError } };
720
916
  if (stopped())
721
917
  return wasStopped();
722
918
  lastError = run.failure;
723
919
  }
724
- return failed(`Failed after ${maxRepairAttempts} repair attempts: ${lastError}${repairDetails()}`);
920
+ return failed(`Failed after ${maxRepairAttempts} repair attempts: ${lastError}`);
921
+ }
922
+ /**
923
+ * Carry out a run under its journal. However it goes, the journal's last
924
+ * record says so: the run's result, or why it could not be carried out.
925
+ */
926
+ async function journalled(journal, run) {
927
+ try {
928
+ const execution = await run();
929
+ journal.note("end", { result: execution.result });
930
+ return execution;
931
+ }
932
+ catch (err) {
933
+ journal.note("end", { error: messageOf(err) });
934
+ throw err;
935
+ }
936
+ finally {
937
+ journal.close();
938
+ }
725
939
  }
726
940
  // --- Validating a candidate program (used by create and update) ---
727
941
  const VALIDATION_READY_GRACE_MS = 2_000;
728
942
  /**
729
- * Validate a candidate program.ts for a project without touching the project:
730
- * run it (with repair) in a throwaway copy. Returns the program that worked —
943
+ * Validate a candidate program.ts for a project without touching what the
944
+ * project holds: run it (with repair) in a throwaway copy. The one thing left
945
+ * in the project is the journal of the validation. Returns the program that worked —
731
946
  * the candidate itself, or a repaired version of it, with the failure that was
732
947
  * repaired. Throws if it cannot be made to run.
733
948
  *
@@ -737,22 +952,108 @@ const VALIDATION_READY_GRACE_MS = 2_000;
737
952
  * first.
738
953
  */
739
954
  export async function validateProgram(projectDir, backend, candidate, options) {
740
- return withTempDir("trama-validate-", async (trialDir) => {
741
- copyDirInto(projectDir, trialDir);
742
- const programPath = guardPath(trialDir, "program.ts");
743
- writeFileSync(programPath, candidate);
744
- const { result, repair } = await executeProgram({
745
- ...options,
955
+ const { journalRuns = 0, signal, ...limits } = options;
956
+ // Recorded with the project, though run in a copy of it.
957
+ const journal = openJournal(projectDir, journalRuns, { purpose: "validate", ...limits });
958
+ const { result, repair, left } = await journalled(journal, () => withTempDir("trama-validate-", async (privateDir) => {
959
+ const { copy: trialDir } = copyProjectWith(projectDir, privateDir, candidate);
960
+ const execution = await executeProgram({
961
+ ...limits,
746
962
  projectDir: trialDir,
747
963
  backend,
748
964
  depth: 0,
749
965
  validating: { readyGraceMs: VALIDATION_READY_GRACE_MS },
966
+ signal,
967
+ journal,
750
968
  });
751
- if (result.status === "failed") {
752
- throw new Error(`Program failed: ${result.reason}`);
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 };
753
976
  }
754
- return { source: readFileSync(programPath, "utf-8"), repairedError: repair?.error };
755
- });
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
+ }
981
+ }));
982
+ if (result.status === "failed")
983
+ throw new Error(`Program failed: ${result.reason}`);
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);
756
1057
  }
757
1058
  /**
758
1059
  * Make a validated program the project's program.ts and record it as a new
@@ -760,13 +1061,24 @@ export async function validateProgram(projectDir, backend, candidate, options) {
760
1061
  * noted in the history index only.
761
1062
  */
762
1063
  export function installValidatedProgram(projectDir, validated, reason, prompt) {
763
- writeFileSync(guardPath(projectDir, "program.ts"), validated.source);
764
- if (validated.repairedError) {
765
- appendHistoryIndex(projectDir, {
766
- reason: `${reason}-repair`, timestamp: new Date().toISOString(), error: validated.repairedError,
767
- });
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;
768
1081
  }
769
- copyToHistory(projectDir, reason, prompt);
770
1082
  }
771
1083
  // --- Core execution ---
772
1084
  /** How deep programs may run programs, and how many runs one runner carries at a time. */
@@ -776,12 +1088,12 @@ let runsInFlight = 0;
776
1088
  /**
777
1089
  * Run a project, in this process: this is what a runner does.
778
1090
  *
779
- * `depth` is how many runs deep this one is — 0 unless a program asked for it
780
- * (see the "/run/program" call), in which case it is one more than that
781
- * program's own. One runner carries the whole tree, so it is also where the
1091
+ * `askedFor` is set when a program asked for the run (see the "/run/program"
1092
+ * call). One runner carries the whole tree of runs, so it is also where the
782
1093
  * tree is kept from growing without bound.
783
1094
  */
784
- export async function runProgram(options, depth = 0) {
1095
+ export async function runProgram(options, askedFor) {
1096
+ const depth = askedFor?.depth ?? 0;
785
1097
  if (depth > MAX_RUN_DEPTH) {
786
1098
  throw new Error(`Not running ${options.projectDir}: programs are running programs more than ${MAX_RUN_DEPTH} deep. ` +
787
1099
  `A program that runs itself, or two that run each other, never ends.`);
@@ -791,13 +1103,13 @@ export async function runProgram(options, depth = 0) {
791
1103
  }
792
1104
  runsInFlight += 1;
793
1105
  try {
794
- return await runProject(options, depth);
1106
+ return await runProject(options, depth, askedFor);
795
1107
  }
796
1108
  finally {
797
1109
  runsInFlight -= 1;
798
1110
  }
799
1111
  }
800
- async function runProject(options, depth) {
1112
+ async function runProject(options, depth, askedFor) {
801
1113
  const { projectDir } = options;
802
1114
  if (!existsSync(join(projectDir, "meta.json"))) {
803
1115
  throw new Error(`Project not found at ${projectDir}. ` +
@@ -812,7 +1124,19 @@ async function runProject(options, depth) {
812
1124
  if (!Number.isInteger(maxRepairAttempts) || maxRepairAttempts < 0) {
813
1125
  throw new Error(`Invalid maxRepairAttempts: ${maxRepairAttempts}. Must be a non-negative integer.`);
814
1126
  }
815
- const { result, repair } = await executeProgram({
1127
+ const journal = openJournal(projectDir, config.journalRuns, {
1128
+ purpose: "run",
1129
+ label: options.label,
1130
+ depth,
1131
+ parent: askedFor?.parent,
1132
+ workspace: options.workspaceDir,
1133
+ timeout,
1134
+ maxRepairAttempts,
1135
+ args: options.args, // last: it is the one field of unknown size
1136
+ });
1137
+ askedFor?.started(journal.run, journal.path);
1138
+ const stillTheProject = sameProjectAs(projectDir);
1139
+ const { result, repair } = await journalled(journal, () => executeProgram({
816
1140
  projectDir,
817
1141
  backend: createBackend(config),
818
1142
  maxRepairAttempts,
@@ -823,17 +1147,19 @@ async function runProject(options, depth) {
823
1147
  depth,
824
1148
  label: options.label,
825
1149
  signal: options.signal,
826
- });
1150
+ journal,
1151
+ }));
827
1152
  if (repair) {
828
1153
  // The program is fixed and has run; failing to write this down must not turn that into an error.
829
1154
  try {
830
- const entry = { ts: Date.now(), message: `Repair attempt ${repair.attempt + 1}/${maxRepairAttempts}`, data: { error: repair.error } };
831
- appendFileSync(guardPath(projectDir, join("logs", "latest.jsonl")), JSON.stringify(entry) + "\n");
832
- console.log(tagged(options.label, `[trama] Repair attempt ${repair.attempt + 1}/${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}`));
833
1159
  copyToHistory(projectDir, "repair", repair.error);
834
1160
  }
835
1161
  catch (err) {
836
- 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)}`));
837
1163
  }
838
1164
  }
839
1165
  return result;