@trama-dev/runtime 0.2.1 → 0.3.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,22 +1,30 @@
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, renameSync, } from "fs";
3
- import { join, dirname, basename, resolve } from "path";
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";
4
4
  import { homedir, tmpdir } from "os";
5
5
  import { fileURLToPath } from "url";
6
6
  import { randomBytes } from "crypto";
7
7
  import { PiAdapter } from "./pi-adapter.js";
8
8
  import { createContext } from "./context.js";
9
- import { createAgent } from "./agent.js";
9
+ import { createAgent, stripCodeFences } from "./agent.js";
10
10
  import { createTools } from "./tools.js";
11
11
  import { createWorkspace } from "./workspace.js";
12
12
  import { guardPath } from "./path-guard.js";
13
- import { superviseChild } from "./child-process.js";
13
+ import { createAllowance, stopGroups, superviseChild } from "./child-process.js";
14
+ import { openBridge } from "./bridge-client.js";
15
+ import { removeTempDir, removeWithThisProcess, stopWithThisProcess } from "./lifetime.js";
14
16
  import { createIPCServer, listen, closeServer } from "./ipc-server.js";
15
17
  // --- Locating the runtime itself ---
16
18
  /** The installed @trama-dev/runtime package — this file lives in its dist/. */
17
19
  const RUNTIME_PACKAGE_DIR = dirname(dirname(fileURLToPath(import.meta.url)));
18
- /** tsx executes program.ts. Resolved through the module system, so any install layout works. */
19
- const TSX_CLI = fileURLToPath(import.meta.resolve("tsx/cli"));
20
+ /**
21
+ * tsx lets node run program.ts. Resolved through the module system, so any
22
+ * install layout works. It is loaded into the program's own node process
23
+ * rather than run as the `tsx` command, which puts a process of its own in
24
+ * front of the program: one that kills the program some 60 ms after a SIGTERM
25
+ * it has not acted on, and reports its death by signal as an exit code.
26
+ */
27
+ const TSX_LOADER = import.meta.resolve("tsx");
20
28
  /**
21
29
  * The @trama-dev packages a program.ts can import, and where they are installed.
22
30
  * The runtime always; the session layer when it is installed alongside (as it
@@ -180,6 +188,13 @@ export function loadProjectConfig(projectDir) {
180
188
  config.provider = meta.provider;
181
189
  return config;
182
190
  }
191
+ /**
192
+ * What does the LLM work for a project. The only place that picks a backend:
193
+ * everything else is handed one and does not know which it is.
194
+ */
195
+ export function createBackend(config) {
196
+ return new PiAdapter(config);
197
+ }
183
198
  export function loadState(projectDir) {
184
199
  const statePath = guardPath(projectDir, "state.json");
185
200
  if (!existsSync(statePath))
@@ -212,9 +227,7 @@ const HISTORY_DETAIL_FIELD = { create: "prompt", update: "prompt", repair: "erro
212
227
  * Save the current program.ts as the next version: copy it to history/NNNN.ts
213
228
  * and record why in index.jsonl.
214
229
  *
215
- * Repairs made while validating a create or update are NOT versions of their
216
- * own — they are noted in index.jsonl only (reason "create-repair" /
217
- * "update-repair"), and the validated program becomes the create/update version.
230
+ * (See installValidatedProgram for how a create or update is recorded.)
218
231
  */
219
232
  export function copyToHistory(projectDir, reason, detail) {
220
233
  const historyDir = guardPath(projectDir, "history");
@@ -259,130 +272,104 @@ export function snapshotDir(dir, prefix = "") {
259
272
  }
260
273
  const sameStat = (a, b) => a.size === b.size && a.mtimeMs === b.mtimeMs;
261
274
  /**
262
- * Commit workspace changes from a temp workspace back to the real workspace,
263
- * using a three-way check to avoid overwriting concurrent updates by other participants.
275
+ * Merge what a run did to a staged copy back into the real directory, with a
276
+ * three-way check so that nothing changed in the real directory meanwhile —
277
+ * by the user, or by another run of the same project — is overwritten.
264
278
  *
265
- * @param tempDir - temp workspace after the run (source of changes)
266
- * @param realDir - real shared workspace (destination)
267
- * @param tempBefore - temp workspace snapshot before the run (detects what the run changed)
268
- * @param realSeed - real workspace snapshot at seed time (detects concurrent changes)
279
+ * @param stagedDir - the copy after the run (source of changes)
280
+ * @param realDir - the real directory (destination)
281
+ * @param stagedBefore - snapshot of the copy before the run (detects what the run changed)
282
+ * @param realSeed - snapshot of the real directory when the copy was taken (detects concurrent changes)
269
283
  *
270
- * For each file the run created or modified in the temp workspace:
271
- * - New file: copied unless that path has meanwhile appeared in the real workspace.
272
- * - Modified file: copied only if the real workspace's copy still matches realSeed.
273
- * If it doesn't, another participant changed or removed it concurrently — skip.
274
- * Best-effort: anything that cannot be committed safely is skipped, never thrown.
284
+ * For each file the run touched in the copy:
285
+ * - Created: copied, unless that path has meanwhile appeared in the real directory.
286
+ * - Modified: copied only if the real file still matches realSeed.
287
+ * - Deleted: deleted only if the real file still matches realSeed.
288
+ * Best-effort: anything that cannot be merged safely is skipped, never thrown.
275
289
  */
276
- export function commitWorkspaceChanges(tempDir, realDir, tempBefore, realSeed) {
277
- for (const [relPath, afterStat] of snapshotDir(tempDir)) {
278
- const beforeStat = tempBefore.get(relPath);
279
- if (beforeStat && sameStat(beforeStat, afterStat))
290
+ export function commitStagedChanges(stagedDir, realDir, stagedBefore, realSeed) {
291
+ const stagedAfter = snapshotDir(stagedDir);
292
+ /** The real file as it is now — but only if nobody has touched it since the copy was taken. */
293
+ const untouchedSinceSeed = (relPath, dstPath) => {
294
+ const seedStat = realSeed.get(relPath);
295
+ const realNow = statSync(dstPath, { throwIfNoEntry: false });
296
+ return seedStat === undefined || (realNow !== undefined && sameStat(realNow, seedStat));
297
+ };
298
+ for (const relPath of new Set([...stagedBefore.keys(), ...stagedAfter.keys()])) {
299
+ const beforeStat = stagedBefore.get(relPath);
300
+ const afterStat = stagedAfter.get(relPath);
301
+ if (beforeStat && afterStat && sameStat(beforeStat, afterStat))
280
302
  continue; // the run didn't touch it
281
303
  try {
282
- // A concurrent participant could have placed a symlink at this path or in
283
- // a parent directory, pointing outside the workspace — guardPath throws.
304
+ // A symlink placed at this path, or in a parent directory, could point
305
+ // outside the real directory — guardPath throws.
284
306
  const dstPath = guardPath(realDir, relPath);
285
- const realNow = statSync(dstPath, { throwIfNoEntry: false });
286
- if (beforeStat) {
287
- const seedStat = realSeed.get(relPath);
288
- if (seedStat && (!realNow || !sameStat(realNow, seedStat)))
307
+ if (!afterStat) {
308
+ if (untouchedSinceSeed(relPath, dstPath))
309
+ rmSync(dstPath, { force: true });
310
+ }
311
+ else if (beforeStat) {
312
+ if (!untouchedSinceSeed(relPath, dstPath))
289
313
  continue; // changed or removed concurrently
314
+ copyFileSync(join(stagedDir, relPath), dstPath);
290
315
  }
291
- else if (realNow) {
292
- continue; // someone else created the same path first — keep theirs
316
+ else {
317
+ if (statSync(dstPath, { throwIfNoEntry: false }))
318
+ continue; // someone else created it first — keep theirs
319
+ mkdirSync(dirname(dstPath), { recursive: true });
320
+ copyFileSync(join(stagedDir, relPath), dstPath);
293
321
  }
294
- mkdirSync(dirname(dstPath), { recursive: true });
295
- copyFileSync(join(tempDir, relPath), dstPath);
296
322
  }
297
323
  catch {
298
- // Escapes the workspace, path-shape conflict, permissions — skip
324
+ // Escapes the directory, path-shape conflict, permissions — skip
299
325
  }
300
326
  }
301
327
  }
302
- /**
303
- * Run fn against a directory that can be put back exactly as it was: if fn
304
- * returns keep:false or throws, the directory is rolled back. Returns fn's value.
305
- *
306
- * The snapshot is a hidden copy next to the directory, on the same file
307
- * system, so rolling back is two renames — move the directory aside, move the
308
- * snapshot into its place — and at no point does the content exist nowhere.
309
- * (If the process is killed outright, the snapshot is left behind beside the
310
- * directory: it is the pre-change state.)
311
- */
312
- export async function withSnapshot(dir, fn) {
313
- const target = resolve(dir);
314
- const snap = mkdtempSync(join(dirname(target), `.${basename(target)}.trama-snapshot-`));
315
- let rolledBack = false;
316
- const rollBack = () => {
317
- const discarded = `${snap}.discarded`;
318
- renameSync(target, discarded);
319
- renameSync(snap, target);
320
- rolledBack = true;
321
- removeTempDir(discarded);
322
- };
323
- try {
324
- cpSync(target, snap, { recursive: true });
325
- let result;
326
- try {
327
- result = await fn();
328
- }
329
- catch (err) {
330
- rollBack();
331
- throw err;
332
- }
333
- if (!result.keep)
334
- rollBack();
335
- return result.value;
336
- }
337
- finally {
338
- if (!rolledBack)
339
- removeTempDir(snap);
340
- }
341
- }
342
- /** Remove a temp directory. Best-effort: failing to clean up must never change a run's outcome. */
343
- function removeTempDir(dir) {
344
- try {
345
- rmSync(dir, { recursive: true, force: true });
346
- }
347
- catch { /* left for the OS to reap */ }
348
- }
349
- /** Run fn in a temp directory, clean up afterwards regardless of outcome. */
328
+ /** Run fn in a temp directory, clean up afterwards regardless of outcome — including this process being stopped. */
350
329
  export async function withTempDir(prefix, fn) {
351
330
  const dir = mkdtempSync(join(tmpdir(), prefix));
331
+ const settled = removeWithThisProcess(dir);
352
332
  try {
353
333
  return await fn(dir);
354
334
  }
355
335
  finally {
356
336
  removeTempDir(dir);
337
+ settled();
357
338
  }
358
339
  }
340
+ /** Copy a directory's contents into an existing one, keeping symlinks as they are written. */
341
+ function copyDirInto(srcDir, dstDir) {
342
+ // realpath: a project directory may itself be a symlink.
343
+ cpSync(realpathSync(srcDir), dstDir, { recursive: true, verbatimSymlinks: true });
344
+ }
359
345
  /**
360
- * Run fn against a private copy of the shared workspace, so its writes stay
361
- * invisible to other participants unless fn asks to commit them — in which
362
- * case what it created or changed is merged back (see commitWorkspaceChanges).
363
- * Outside a session there is no workspace and fn simply runs.
346
+ * Run fn against a private copy of a directory. What fn does there stays
347
+ * invisible to the real directory unless fn asks to commit it — then it is
348
+ * merged back (see commitStagedChanges). If fn fails, or this process is
349
+ * stopped half-way, the real directory was never touched.
364
350
  */
365
- async function withStagedWorkspace(workspaceDir, fn) {
366
- if (!workspaceDir)
367
- return (await fn(undefined)).value;
368
- const realSeed = snapshotDir(workspaceDir);
369
- return withTempDir("trama-repair-ws-", async (stagedDir) => {
370
- cpSync(workspaceDir, stagedDir, { recursive: true });
351
+ async function withStagedCopy(realDir, fn) {
352
+ const realSeed = snapshotDir(realDir);
353
+ return withTempDir("trama-staged-", async (stagedDir) => {
354
+ copyDirInto(realDir, stagedDir);
371
355
  const stagedBefore = snapshotDir(stagedDir);
372
356
  const { commit, value } = await fn(stagedDir);
373
357
  if (commit)
374
- commitWorkspaceChanges(stagedDir, workspaceDir, stagedBefore, realSeed);
358
+ commitStagedChanges(stagedDir, realDir, stagedBefore, realSeed);
375
359
  return value;
376
360
  });
377
361
  }
378
- const formatError = (r) => `program.ts exited with code ${r.exitCode}\nstdout: ${r.stdout}\nstderr: ${r.stderr}`;
362
+ /** The end of a long output — where the error is — with a note of how much was dropped. */
363
+ function tail(text, max = 20_000) {
364
+ return text.length <= max ? text : `[… ${text.length - max} earlier characters omitted]\n${text.slice(-max)}`;
365
+ }
366
+ const describeFailure = (r) => `program.ts exited with code ${r.exitCode}\nstdout: ${tail(r.stdout)}\nstderr: ${tail(r.stderr)}`;
379
367
  /**
380
368
  * Hand the program its starting state through a private temp file rather than
381
369
  * env vars — no OS size limit, and mode 0600 in an unpredictable directory
382
- * keeps it from other local users. Returns the directory to remove afterwards.
370
+ * keeps it (and the bridge secret in it) from other local users.
383
371
  */
384
- function writeInitFile(payload) {
385
- const dir = mkdtempSync(join(tmpdir(), "trama-init-"));
372
+ function writeInitFile(dir, payload) {
386
373
  const file = join(dir, "init.json");
387
374
  const fd = openSync(file, "w", 0o600);
388
375
  try {
@@ -391,7 +378,7 @@ function writeInitFile(payload) {
391
378
  finally {
392
379
  closeSync(fd);
393
380
  }
394
- return { dir, file };
381
+ return file;
395
382
  }
396
383
  function toChildResult(exit) {
397
384
  const { stdout, stderr } = exit;
@@ -402,14 +389,37 @@ function toChildResult(exit) {
402
389
  return { exitCode: 0, stdout, stderr };
403
390
  return { exitCode: exit.code ?? 1, stdout, stderr };
404
391
  }
392
+ /**
393
+ * Decide how a finished run ended. A terminal signal the program completed
394
+ * takes precedence over its exit code: a program that called ctx.done() and
395
+ * then crashed is done. Returns null for a failure (non-zero exit, no signal).
396
+ */
397
+ function settle(projectDir, child, terminalSignal) {
398
+ // Read state first: if the program left state.json corrupt, say so now
399
+ // rather than report an outcome (or start a repair) on top of it.
400
+ const state = loadState(projectDir);
401
+ if (terminalSignal)
402
+ return terminalSignal;
403
+ if (child.exitCode !== 0)
404
+ return null;
405
+ // Natural success without done() or yield(): if this run was the resumption
406
+ // of an earlier yield, that yield is now over — don't let its marker make
407
+ // the next run look resumed.
408
+ if (state.__trama_yield != null) {
409
+ delete state.__trama_yield;
410
+ writeFileSync(guardPath(projectDir, "state.json"), JSON.stringify(state, null, 2));
411
+ }
412
+ return { status: "done" };
413
+ }
405
414
  /**
406
415
  * Run program.ts once in the given directory: scaffold, start the IPC server,
407
- * spawn the program, wait for it, and tear everything down.
408
- * Reports how the program ended — does NOT throw on non-zero exit. Throws only
409
- * when the run could not happen at all (bad project, server or spawn failure).
416
+ * spawn the program, wait for it, tear everything down, and say how it ended.
417
+ * The program's output is echoed as it runs. A program that fails is a result,
418
+ * not an exception — this throws only when the run could not happen at all
419
+ * (bad project, server or spawn failure) or left state.json unreadable.
410
420
  */
411
421
  async function runProgramOnce(options) {
412
- const { projectDir, adapter, timeout, maxIterations, argsOverride, streamOutput, stopOnReady, workspaceDir } = options;
422
+ const { projectDir, backend, timeout, maxIterations, argsOverride, stopOnReady, workspaceDir } = options;
413
423
  ensureProjectScaffold(projectDir);
414
424
  // Cancels in-flight LLM calls, fetches and observes once the run is over.
415
425
  const runEnded = new AbortController();
@@ -427,96 +437,101 @@ async function runProgramOnce(options) {
427
437
  // Truncate logs only after preflight succeeds — preserves the prior run's
428
438
  // diagnostics if scaffolding, state loading, or context creation fails.
429
439
  writeFileSync(guardPath(projectDir, join("logs", "latest.jsonl")), "");
440
+ // The program's own time. It stops while a run the program started is in flight.
441
+ const allowance = createAllowance(timeout);
430
442
  const tools = createTools(projectDir, runEnded.signal);
431
443
  // Known only to this run's program, through its init file.
432
444
  const token = randomBytes(32).toString("hex");
433
445
  const server = createIPCServer({
434
446
  token,
435
447
  ctx,
436
- agent: createAgent(adapter, runEnded.signal),
448
+ agent: createAgent(backend, projectDir, runEnded.signal),
437
449
  tools,
438
450
  workspace: workspaceDir ? createWorkspace(workspaceDir, runEnded.signal) : null,
439
451
  // The first terminal signal wins; ctx itself rejects a conflicting second one.
440
452
  onTerminalSignal: result => { terminalSignal ??= result; },
453
+ holdClock: () => allowance.hold(),
441
454
  });
442
- let initDir;
455
+ // The program leads a process group of its own, so that everything it starts is in it.
456
+ let programGroup;
457
+ // If this process is stopped while the program is running, the program is stopped with it.
458
+ let programSettled = () => { };
443
459
  try {
444
- const port = await listen(server);
445
- const init = writeInitFile({
446
- token,
447
- input: ctx.input,
448
- state: ctx.state,
449
- iteration: ctx.iteration,
450
- maxIterations: ctx.maxIterations,
451
- workspace: workspaceDir ?? null,
452
- resumed: ctx.resumed,
453
- yieldReason: ctx.yieldReason,
460
+ const child = await withTempDir("trama-init-", async (initDir) => {
461
+ const port = await listen(server);
462
+ const initFile = writeInitFile(initDir, {
463
+ token,
464
+ input: ctx.input,
465
+ state: ctx.state,
466
+ iteration: ctx.iteration,
467
+ maxIterations: ctx.maxIterations,
468
+ inSession: workspaceDir !== undefined,
469
+ resumed: ctx.resumed,
470
+ yieldReason: ctx.yieldReason,
471
+ });
472
+ const program = spawn(process.execPath, ["--import", TSX_LOADER, guardPath(projectDir, "program.ts")], {
473
+ cwd: projectDir,
474
+ env: { ...process.env, TRAMA_PORT: String(port), TRAMA_INIT: initFile },
475
+ stdio: ["ignore", "pipe", "pipe"],
476
+ detached: true,
477
+ });
478
+ programGroup = program.pid;
479
+ if (programGroup)
480
+ programSettled = stopWithThisProcess(programGroup);
481
+ return toChildResult(await superviseChild(program, {
482
+ timeout: allowance,
483
+ stopSignal: stopOnReady ? readyStop.signal : undefined,
484
+ sinks: {
485
+ stdout: chunk => { process.stdout.write(chunk); },
486
+ stderr: chunk => { process.stderr.write(chunk); },
487
+ },
488
+ }));
454
489
  });
455
- initDir = init.dir;
456
- const child = spawn(process.execPath, [TSX_CLI, guardPath(projectDir, "program.ts")], {
457
- cwd: projectDir,
458
- env: { ...process.env, TRAMA_PORT: String(port), TRAMA_INIT: init.file },
459
- stdio: ["ignore", "pipe", "pipe"],
460
- detached: true,
461
- });
462
- const exit = await superviseChild(child, {
463
- timeout,
464
- stopSignal: stopOnReady ? readyStop.signal : undefined,
465
- sinks: streamOutput ? {
466
- stdout: chunk => { process.stdout.write(chunk); },
467
- stderr: chunk => { process.stderr.write(chunk); },
468
- } : undefined,
469
- });
470
- return { child: toChildResult(exit), terminalSignal };
490
+ return { outcome: settle(projectDir, child, terminalSignal), failure: describeFailure(child) };
471
491
  }
472
492
  finally {
473
- // The program is gone (or never started): cancel what it left in flight,
474
- // kill shells it left running in the background, and drop its connections.
493
+ // The program is gone (or never started). Nothing it started outlives its
494
+ // run: cancel the calls it left in flight, and stop what is left of its
495
+ // process group and of its shell commands. Only once they are gone is the
496
+ // run over — whoever called will merge or delete what they were writing to.
475
497
  if (readyTimer)
476
498
  clearTimeout(readyTimer);
477
499
  runEnded.abort();
478
- tools.killActiveShells();
500
+ await Promise.all([stopGroups(programGroup ? [programGroup] : []), tools.stopActiveShells()]);
501
+ programSettled();
479
502
  server.closeAllConnections();
480
503
  await closeServer(server).catch(() => { });
481
- if (initDir)
482
- removeTempDir(initDir);
483
504
  }
484
505
  }
506
+ /** The instructions a request for a fix is made under. (Exported so the tests' stand-in LLM can tell one from any other call.) */
507
+ export const REPAIR_SYSTEM_PROMPT = "You are a TypeScript repair tool.";
508
+ const repairPrompt = (input) => `Fix this program so it runs.\n\n` +
509
+ `Runtime types:\n${RUNTIME_TYPES}\n\n` +
510
+ `Broken program:\n${input.programSource}\n\n` +
511
+ `Error:\n${input.error}\n\n` +
512
+ `Output ONLY the fixed program. No explanation.`;
485
513
  /**
486
- * Decide how a finished run ended. A terminal signal the program persisted
487
- * takes precedence over its exit code: a program that called ctx.done() and
488
- * then crashed is done. Returns null for a failure (non-zero exit, no signal).
489
- */
490
- function settle(projectDir, run) {
491
- // Read state first: if the program left state.json corrupt, say so now
492
- // rather than report an outcome (or start a repair) on top of it.
493
- const state = loadState(projectDir);
494
- if (run.terminalSignal)
495
- return run.terminalSignal;
496
- if (run.child.exitCode !== 0)
497
- return null;
498
- // Natural success without done() or yield(): if this run was the resumption
499
- // of an earlier yield, that yield is now over — don't let its marker make
500
- // the next run look resumed.
501
- if (state.__trama_yield != null) {
502
- delete state.__trama_yield;
503
- writeFileSync(guardPath(projectDir, "state.json"), JSON.stringify(state, null, 2));
504
- }
505
- return { status: "done" };
506
- }
507
- /**
508
- * Ask the LLM for a fix. The repair agent has tools, so it works in a
509
- * throwaway copy of the project — whatever it reads is real, whatever it
510
- * writes is discarded; only the program text it returns is used. Bounded by
511
- * its own timeout. Returns null (and records why) if no fix came back.
514
+ * Ask the LLM for a fix. The agent has tools, so it works in a throwaway copy
515
+ * of the project that holds the program it is asked to fix — whatever it reads
516
+ * is real, whatever it writes is discarded; only the program text it returns
517
+ * is used. Bounded by its own timeout.
518
+ * Returns null (and records why) if no usable fix came back.
512
519
  */
513
520
  async function requestRepair(options, input, repairErrors) {
514
521
  return withTempDir("trama-repair-", async (tempDir) => {
515
- cpSync(options.projectDir, tempDir, { recursive: true });
522
+ copyDirInto(options.projectDir, tempDir);
523
+ writeFileSync(guardPath(tempDir, "program.ts"), input.programSource);
516
524
  const controller = new AbortController();
517
525
  const timer = setTimeout(() => controller.abort(), options.timeout);
518
526
  try {
519
- return await options.adapter.withCwd(tempDir).repair({ ...input, runtimeTypes: RUNTIME_TYPES }, controller.signal);
527
+ const fixed = stripCodeFences(await options.backend.ask(repairPrompt(input), {
528
+ cwd: tempDir, system: REPAIR_SYSTEM_PROMPT, signal: controller.signal,
529
+ }));
530
+ if (fixed.trim() === "")
531
+ throw new Error("The repair returned an empty program.");
532
+ if (fixed === input.programSource)
533
+ throw new Error("The repair returned the program unchanged.");
534
+ return fixed;
520
535
  }
521
536
  catch (err) {
522
537
  repairErrors.push(err instanceof Error ? err.message : String(err));
@@ -528,94 +543,144 @@ async function requestRepair(options, input, repairErrors) {
528
543
  });
529
544
  }
530
545
  /**
531
- * Run a proposed fix. If it fails too, the project is rolled back to how it
532
- * was before the fix and its workspace writes are dropped; if it succeeds,
533
- * they are merged into the shared workspace.
546
+ * Try a proposed fix.
547
+ *
548
+ * The project is the program's own, so the fix runs on a private copy of it.
549
+ * Only if it works does anything reach the real one — the fix becomes
550
+ * program.ts, and what the run wrote is merged back. A fix that fails, or a
551
+ * runner that is stopped half-way, leaves the project exactly as it was,
552
+ * because it was never touched: its state is only ever written by code that
553
+ * is, or becomes, its program.
554
+ *
555
+ * The shared workspace is not copied. It is how the participants of a session
556
+ * talk to each other, and a program that is being fixed still has to be heard
557
+ * and answered — a fix that wrote its requests where nobody could see them
558
+ * would wait for replies forever. So what a fix writes there is written,
559
+ * whether or not the fix works: like anything a run wrote before it failed.
534
560
  */
535
- async function applyRepair(options, fixed) {
561
+ async function tryFix(options, fixed) {
536
562
  const { projectDir } = options;
537
- return withStagedWorkspace(options.workspaceDir, async (stagedWorkspace) => {
538
- const value = await withSnapshot(projectDir, async () => {
539
- writeFileSync(guardPath(projectDir, "program.ts"), fixed);
540
- const run = await runProgramOnce({ ...options, streamOutput: true, workspaceDir: stagedWorkspace });
541
- const outcome = settle(projectDir, run);
542
- return { keep: outcome !== null, value: { outcome, error: formatError(run.child) } };
543
- });
544
- return { commit: value.outcome !== null, value };
563
+ const run = await withStagedCopy(projectDir, async (stagedProject) => {
564
+ writeFileSync(guardPath(stagedProject, "program.ts"), fixed);
565
+ // If the copy cannot be run at all, or is left unusable, this fix did not work either.
566
+ const trial = await runProgramOnce({ ...options, projectDir: stagedProject }).catch((err) => ({
567
+ outcome: null,
568
+ failure: `The repaired program could not be run: ${err instanceof Error ? err.message : err}`,
569
+ }));
570
+ return { commit: trial.outcome !== null, value: trial };
545
571
  });
572
+ // The merge above carries over what the run changed; the fix itself was
573
+ // written before the run started, so it is installed explicitly.
574
+ if (run.outcome)
575
+ writeFileSync(guardPath(projectDir, "program.ts"), fixed);
576
+ return run;
546
577
  }
547
578
  /**
548
- * Run a program to an outcome. If it crashes, ask the LLM to repair it and run
549
- * the fix — up to maxRepairAttempts times. A fix that also fails leaves no
550
- * trace: the project and the shared workspace are as they were before it ran.
579
+ * Run a program to an outcome. If it crashes, ask the LLM to repair it and try
580
+ * the fix — up to maxRepairAttempts times.
551
581
  */
552
582
  async function executeProgram(options) {
553
583
  const { projectDir, maxRepairAttempts } = options;
554
- const firstRun = await runProgramOnce({ ...options, streamOutput: true });
555
- const outcome = settle(projectDir, firstRun);
556
- if (outcome)
557
- return outcome;
558
- let lastError = formatError(firstRun.child);
559
- if (maxRepairAttempts === 0) {
560
- return { status: "failed", reason: `Program failed (repair disabled): ${lastError}` };
561
- }
562
- // Each attempt builds on the previous one's source, even though a failed
563
- // attempt is rolled back out of the real project.
584
+ const failed = (reason) => ({ result: { status: "failed", reason } });
585
+ const firstRun = await runProgramOnce(options);
586
+ if (firstRun.outcome)
587
+ return { result: firstRun.outcome };
588
+ let lastError = firstRun.failure;
589
+ if (maxRepairAttempts === 0)
590
+ return failed(`Program failed (repair disabled): ${lastError}`);
591
+ // Each attempt builds on the previous one's source, though a fix that failed never reached the project.
564
592
  let currentSource = readFileSync(guardPath(projectDir, "program.ts"), "utf-8");
565
593
  const repairErrors = [];
566
594
  const repairDetails = () => repairErrors.length > 0
567
595
  ? `\nRepair errors:\n${repairErrors.map((e, i) => ` [${i + 1}] ${e}`).join("\n")}` : "";
568
596
  for (let attempt = 0; attempt < maxRepairAttempts; attempt++) {
569
597
  const fixed = await requestRepair(options, { programSource: currentSource, error: lastError }, repairErrors);
570
- if (!fixed) {
571
- return { status: "failed", reason: `Failed after ${attempt + 1} repair attempt(s): ${lastError}${repairDetails()}` };
572
- }
598
+ if (!fixed)
599
+ return failed(`Failed after ${attempt + 1} repair attempt(s): ${lastError}${repairDetails()}`);
573
600
  currentSource = fixed;
574
- const applied = await applyRepair(options, fixed);
575
- if (applied.outcome) {
576
- try {
577
- // lastError is still the failure this repair fixed.
578
- options.onRepair?.(attempt, maxRepairAttempts, lastError);
579
- }
580
- catch (bookkeepingErr) {
581
- console.warn(`[trama] repair bookkeeping failed: ${bookkeepingErr instanceof Error ? bookkeepingErr.message : bookkeepingErr}`);
582
- }
583
- return applied.outcome;
584
- }
585
- lastError = applied.error;
601
+ const run = await tryFix(options, fixed);
602
+ if (run.outcome)
603
+ return { result: run.outcome, repair: { attempt, error: lastError } };
604
+ lastError = run.failure;
586
605
  }
587
- return { status: "failed", reason: `Failed after ${maxRepairAttempts} repair attempts: ${lastError}${repairDetails()}` };
606
+ return failed(`Failed after ${maxRepairAttempts} repair attempts: ${lastError}${repairDetails()}`);
588
607
  }
589
- // --- Smoke run (used by create and update) ---
590
- const SMOKE_READY_GRACE_MS = 2_000;
608
+ // --- Validating a candidate program (used by create and update) ---
609
+ const VALIDATION_READY_GRACE_MS = 2_000;
591
610
  /**
592
- * Validate a freshly generated program.ts by running it (with repair) in a
593
- * throwaway copy of the project, so the validation run's file side effects
594
- * don't persist. On success the validated — possibly repaired — program is
595
- * copied back. Throws if it cannot be made to run.
611
+ * Validate a candidate program.ts for a project without touching the project:
612
+ * run it (with repair) in a throwaway copy. Returns the program that worked —
613
+ * the candidate itself, or a repaired version of it, with the failure that was
614
+ * repaired. Throws if it cannot be made to run.
615
+ *
616
+ * Only the project's own files are shielded. What the program does beyond
617
+ * them — network calls, shell commands, other projects it runs — is real.
596
618
  */
597
- export async function smokeRunAndRepair(projectDir, adapter, reason, options) {
598
- await withTempDir("trama-smoke-", async (smokeDir) => {
599
- cpSync(projectDir, smokeDir, { recursive: true });
600
- const result = await executeProgram({
601
- projectDir: smokeDir,
602
- adapter: adapter.withCwd(smokeDir),
603
- maxRepairAttempts: options.maxRepairAttempts,
604
- timeout: options.timeout,
605
- maxIterations: options.maxIterations,
606
- stopOnReady: { graceMs: SMOKE_READY_GRACE_MS },
607
- onRepair(_attempt, _max, error) {
608
- appendHistoryIndex(projectDir, { reason: `${reason}-repair`, timestamp: new Date().toISOString(), error });
609
- },
619
+ export async function validateProgram(projectDir, backend, candidate, options) {
620
+ return withTempDir("trama-validate-", async (trialDir) => {
621
+ copyDirInto(projectDir, trialDir);
622
+ const programPath = guardPath(trialDir, "program.ts");
623
+ writeFileSync(programPath, candidate);
624
+ const { result, repair } = await executeProgram({
625
+ ...options,
626
+ projectDir: trialDir,
627
+ backend,
628
+ stopOnReady: { graceMs: VALIDATION_READY_GRACE_MS },
610
629
  });
611
630
  if (result.status === "failed") {
612
631
  throw new Error(`Program failed: ${result.reason}`);
613
632
  }
614
- copyFileSync(guardPath(smokeDir, "program.ts"), guardPath(projectDir, "program.ts"));
633
+ return { source: readFileSync(programPath, "utf-8"), repairedError: repair?.error };
615
634
  });
616
635
  }
636
+ /**
637
+ * Make a validated program the project's program.ts and record it as a new
638
+ * version. A repair made while validating is not a version of its own — it is
639
+ * noted in the history index only.
640
+ */
641
+ export function installValidatedProgram(projectDir, validated, reason, prompt) {
642
+ writeFileSync(guardPath(projectDir, "program.ts"), validated.source);
643
+ if (validated.repairedError) {
644
+ appendHistoryIndex(projectDir, {
645
+ reason: `${reason}-repair`, timestamp: new Date().toISOString(), error: validated.repairedError,
646
+ });
647
+ }
648
+ copyToHistory(projectDir, reason, prompt);
649
+ }
617
650
  // --- Core execution ---
651
+ /**
652
+ * A run started from inside a program — a session participant, typically — is
653
+ * under a timeout of its own. Tell the runner of the program it was started
654
+ * from, so that program's clock stops while this run lasts and it is not
655
+ * killed for the time its participant was entitled to take.
656
+ *
657
+ * Returns what ends the hold. Best-effort: if that runner cannot be reached
658
+ * its program's run is over, and this one is about to be stopped with it.
659
+ *
660
+ * This exists only because the runner of a participant lives inside the
661
+ * program that spawned it, where that program's own runner cannot see it. It
662
+ * goes away once starting a run is itself a call on the bridge.
663
+ */
664
+ function holdParentClock() {
665
+ const { TRAMA_PORT: port, TRAMA_INIT: initPath } = process.env;
666
+ if (port && initPath) {
667
+ try {
668
+ return openBridge(port, initPath).hold("/clock/hold");
669
+ }
670
+ catch { /* not held */ }
671
+ }
672
+ return () => { };
673
+ }
618
674
  export async function runProgram(options) {
675
+ const releaseParentClock = holdParentClock();
676
+ try {
677
+ return await runProject(options);
678
+ }
679
+ finally {
680
+ releaseParentClock();
681
+ }
682
+ }
683
+ async function runProject(options) {
619
684
  const { projectDir } = options;
620
685
  if (!existsSync(join(projectDir, "meta.json"))) {
621
686
  throw new Error(`Project not found at ${projectDir}. ` +
@@ -630,20 +695,26 @@ export async function runProgram(options) {
630
695
  if (!Number.isInteger(maxRepairAttempts) || maxRepairAttempts < 0) {
631
696
  throw new Error(`Invalid maxRepairAttempts: ${maxRepairAttempts}. Must be a non-negative integer.`);
632
697
  }
633
- return executeProgram({
698
+ const { result, repair } = await executeProgram({
634
699
  projectDir,
635
- adapter: new PiAdapter(config, projectDir),
700
+ backend: createBackend(config),
636
701
  maxRepairAttempts,
637
702
  timeout,
638
703
  maxIterations: config.defaultMaxIterations,
639
704
  argsOverride: options.args,
640
705
  workspaceDir: options.workspaceDir,
641
- onRepair(attempt, max, error) {
642
- // Runs after the repaired program's own run, so this lands at the end of its log.
643
- const entry = { ts: Date.now(), message: `Repair attempt ${attempt + 1}/${max}`, data: { error } };
644
- appendFileSync(guardPath(projectDir, join("logs", "latest.jsonl")), JSON.stringify(entry) + "\n");
645
- console.log(`[trama] Repair attempt ${attempt + 1}/${max}`);
646
- copyToHistory(projectDir, "repair", error);
647
- },
648
706
  });
707
+ if (repair) {
708
+ // The program is fixed and has run; failing to write this down must not turn that into an error.
709
+ try {
710
+ const entry = { ts: Date.now(), message: `Repair attempt ${repair.attempt + 1}/${maxRepairAttempts}`, data: { error: repair.error } };
711
+ appendFileSync(guardPath(projectDir, join("logs", "latest.jsonl")), JSON.stringify(entry) + "\n");
712
+ console.log(`[trama] Repair attempt ${repair.attempt + 1}/${maxRepairAttempts}`);
713
+ copyToHistory(projectDir, "repair", repair.error);
714
+ }
715
+ catch (err) {
716
+ console.warn(`[trama] repair bookkeeping failed: ${err instanceof Error ? err.message : err}`);
717
+ }
718
+ }
719
+ return result;
649
720
  }