@trama-dev/runtime 0.1.4 → 0.2.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,169 +1,135 @@
1
- import { createServer } from "http";
2
1
  import { spawn } from "child_process";
3
- import { readFileSync, writeFileSync, appendFileSync, readdirSync, copyFileSync, mkdirSync, existsSync, symlinkSync, rmSync, lstatSync, readlinkSync, cpSync, mkdtempSync, openSync, closeSync, } from "fs";
4
- import { join, dirname } from "path";
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";
5
4
  import { homedir, tmpdir } from "os";
6
5
  import { fileURLToPath } from "url";
7
- import { StringDecoder } from "string_decoder";
6
+ import { randomBytes } from "crypto";
8
7
  import { PiAdapter } from "./pi-adapter.js";
9
8
  import { createContext } from "./context.js";
10
9
  import { createAgent } from "./agent.js";
11
- import { createTools, cappedBuffer } from "./tools.js";
10
+ import { createTools } from "./tools.js";
11
+ import { createWorkspace } from "./workspace.js";
12
12
  import { guardPath } from "./path-guard.js";
13
- import { assertSerializable } from "./serializable.js";
14
- // --- Module resolution for child processes ---
13
+ import { superviseChild } from "./child-process.js";
14
+ import { createIPCServer, listen, closeServer } from "./ipc-server.js";
15
+ // --- Locating the runtime itself ---
16
+ /** The installed @trama-dev/runtime package — this file lives in its dist/. */
17
+ 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"));
15
20
  /**
16
- * Find the node_modules directory that contains @trama-dev/runtime.
17
- * Works for both global install and monorepo development.
21
+ * The @trama-dev packages a program.ts can import, and where they are installed.
22
+ * The runtime always; the session layer when it is installed alongside (as it
23
+ * is with the CLI). The runtime never imports the session layer itself — it
24
+ * only makes it reachable from projects.
18
25
  */
19
- function findRuntimeNodeModules() {
20
- let dir = dirname(fileURLToPath(import.meta.url));
21
- while (dir !== dirname(dir)) {
22
- const candidate = join(dir, "node_modules");
23
- if (existsSync(join(candidate, "@trama-dev", "runtime"))) {
24
- return candidate;
25
- }
26
- dir = dirname(dir);
27
- }
28
- throw new Error("Could not locate node_modules containing @trama-dev/runtime");
26
+ const IMPORTABLE_PACKAGES = { runtime: RUNTIME_PACKAGE_DIR };
27
+ try {
28
+ // Resolves to <package>/dist/index.js
29
+ IMPORTABLE_PACKAGES.session = dirname(dirname(fileURLToPath(import.meta.resolve("@trama-dev/session"))));
29
30
  }
30
- const TRAMA_NODE_MODULES = findRuntimeNodeModules();
31
- const TSX_CLI = join(TRAMA_NODE_MODULES, "tsx", "dist", "cli.mjs");
32
- export const PI_VERSION = JSON.parse(readFileSync(join(TRAMA_NODE_MODULES, "@mariozechner", "pi-coding-agent", "package.json"), "utf-8")).version;
31
+ catch { /* not installed — programs simply cannot import it */ }
32
+ // --- Project scaffolding ---
33
33
  /**
34
- * Ensure the project directory has a node_modules symlink to @trama-dev/runtime.
35
- * Replaces any existing symlink whose target differs (including user-managed ones).
36
- * Only refuses to touch a real directory/file to avoid destroying user content.
34
+ * Point the project's node_modules/@trama-dev/<name> at an installed package,
35
+ * so program.ts can import it. Replaces any existing symlink whose target
36
+ * differs (including user-managed ones). Only refuses to touch a real
37
+ * directory/file to avoid destroying user content.
37
38
  */
38
- function ensureRuntimeLink(projectDir) {
39
- // node_modules/@trama-dev/runtime is deliberately a symlink pointing OUTSIDE
40
- // the project (to the global trama install). Do not apply guardPath here.
39
+ function linkPackage(projectDir, name, target) {
40
+ // The link deliberately points OUTSIDE the project — do not apply guardPath here.
41
41
  const linkDir = join(projectDir, "node_modules", "@trama-dev");
42
- const linkPath = join(linkDir, "runtime");
43
- const target = join(TRAMA_NODE_MODULES, "@trama-dev", "runtime");
42
+ const linkPath = join(linkDir, name);
44
43
  try {
45
- const stat = lstatSync(linkPath);
46
- if (stat.isSymbolicLink()) {
47
- // Symlink exists — replace if target doesn't match
48
- if (readlinkSync(linkPath) === target)
49
- return;
50
- rmSync(linkPath);
51
- }
52
- else {
53
- // Real directory/file — not ours, refuse to destroy it
44
+ if (!lstatSync(linkPath).isSymbolicLink()) {
54
45
  throw new Error(`${linkPath} exists and is not a symlink. ` +
55
46
  `trama needs this path for module resolution. ` +
56
47
  `Remove it manually or rename it to proceed.`);
57
48
  }
49
+ if (readlinkSync(linkPath) === target)
50
+ return;
51
+ rmSync(linkPath);
58
52
  }
59
53
  catch (err) {
60
54
  if (err.code !== "ENOENT")
61
55
  throw err;
62
- // ENOENT — path doesn't exist, proceed to create
63
56
  }
64
57
  mkdirSync(linkDir, { recursive: true });
65
58
  symlinkSync(target, linkPath, "dir");
66
59
  }
67
- /**
68
- * Ensure project has ESM package.json and .gitignore.
69
- * If package.json exists but lacks "type": "module", patches it in.
70
- */
71
- export function ensureProjectScaffold(projectDir) {
60
+ /** Make sure package.json exists and declares an ES module (program.ts uses top-level await). */
61
+ function ensureModulePackageJson(projectDir) {
72
62
  const pkgPath = guardPath(projectDir, "package.json");
73
- if (existsSync(pkgPath)) {
74
- let pkg;
75
- try {
76
- pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
77
- }
78
- catch (err) {
79
- throw new Error(`Malformed package.json at ${pkgPath}. ` +
80
- `trama will not overwrite it automatically; fix or remove it and try again.\n` +
81
- `Parse error: ${err instanceof Error ? err.message : err}`);
82
- }
83
- if (typeof pkg !== "object" || pkg === null || Array.isArray(pkg)) {
84
- throw new Error(`Malformed package.json at ${pkgPath} — expected a JSON object but got ${Array.isArray(pkg) ? "an array" : typeof pkg}. trama will not overwrite it automatically; fix or remove it and try again.`);
85
- }
86
- const pkgObj = pkg;
87
- if (pkgObj.type !== "module") {
88
- pkgObj.type = "module";
89
- writeFileSync(pkgPath, JSON.stringify(pkgObj, null, 2));
90
- }
91
- }
92
- else {
63
+ if (!existsSync(pkgPath)) {
93
64
  writeFileSync(pkgPath, JSON.stringify({ type: "module" }, null, 2));
65
+ return;
94
66
  }
95
- const giPath = guardPath(projectDir, ".gitignore");
96
- const requiredEntries = ["node_modules/", "state.json", "logs/", "history/"];
97
- if (existsSync(giPath)) {
98
- const existing = readFileSync(giPath, "utf-8");
99
- const missing = requiredEntries.filter(e => !existing.split("\n").some(line => line.trim() === e));
100
- if (missing.length > 0) {
101
- const suffix = existing.endsWith("\n") ? "" : "\n";
102
- writeFileSync(giPath, existing + suffix + missing.join("\n") + "\n");
103
- }
67
+ const advice = "trama will not overwrite it automatically; fix or remove it and try again.";
68
+ let pkg;
69
+ try {
70
+ pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
104
71
  }
105
- else {
106
- writeFileSync(giPath, requiredEntries.join("\n") + "\n");
72
+ catch (err) {
73
+ throw new Error(`Malformed package.json at ${pkgPath}. ${advice}\n` +
74
+ `Parse error: ${err instanceof Error ? err.message : err}`);
75
+ }
76
+ if (typeof pkg !== "object" || pkg === null || Array.isArray(pkg)) {
77
+ throw new Error(`Malformed package.json at ${pkgPath} — expected a JSON object but got ${Array.isArray(pkg) ? "an array" : typeof pkg}. ${advice}`);
78
+ }
79
+ const pkgObj = pkg;
80
+ if (pkgObj.type !== "module") {
81
+ pkgObj.type = "module";
82
+ writeFileSync(pkgPath, JSON.stringify(pkgObj, null, 2));
107
83
  }
108
84
  }
109
- // --- Runtime type definitions (included in system prompts) ---
85
+ /** Make sure .gitignore excludes what trama generates, without disturbing existing entries. */
86
+ function ensureGitignore(projectDir) {
87
+ const giPath = guardPath(projectDir, ".gitignore");
88
+ const required = ["node_modules/", "state.json", "logs/", "history/"];
89
+ const existing = existsSync(giPath) ? readFileSync(giPath, "utf-8") : "";
90
+ const present = new Set(existing.split("\n").map(line => line.trim()));
91
+ const missing = required.filter(entry => !present.has(entry));
92
+ if (missing.length === 0)
93
+ return;
94
+ const separator = existing === "" || existing.endsWith("\n") ? "" : "\n";
95
+ writeFileSync(giPath, existing + separator + missing.join("\n") + "\n");
96
+ }
110
97
  /**
111
- * Simplified API reference for LLM system prompts.
112
- * NOT the canonical type definitions (those live in types.ts).
113
- * Kept as a readable string rather than auto-generated, because the LLM
114
- * needs a concise reference, not the full implementation types.
115
- * If types.ts changes, review whether this summary needs updating.
98
+ * Everything a project directory needs around program.ts before it can run:
99
+ * history/ and logs/, an ESM package.json, .gitignore entries, and links to the
100
+ * @trama-dev packages it can import.
101
+ * Idempotent — called before every run, so a freshly cloned project just works.
116
102
  */
117
- export const RUNTIME_TYPES = `// @trama-dev/runtime - Complete API
118
-
119
- export interface Ctx {
120
- input: { prompt: string; args: Record<string, unknown> };
121
- state: Record<string, unknown>;
122
- iteration: number;
123
- maxIterations: number;
124
- log(message: string, data?: Record<string, unknown>): Promise<void>;
125
- ready(data?: Record<string, unknown>): Promise<void>;
126
- checkpoint(): Promise<void>;
127
- done(result?: Record<string, unknown>): Promise<void>;
128
- }
129
-
130
- export interface Agent {
131
- instruct(prompt: string, options?: { system?: string }): Promise<string>;
132
- /** @deprecated Use instruct() instead */
133
- ask(prompt: string, options?: { system?: string }): Promise<string>;
134
- generate<T>(input: {
135
- prompt: string;
136
- schema: Record<string, string>;
137
- system?: string;
138
- }): Promise<T>;
139
- }
140
-
141
- export interface ShellResult {
142
- exitCode: number;
143
- stdout: string;
144
- stderr: string;
145
- }
146
-
147
- export interface Tools {
148
- read(path: string): Promise<string>;
149
- write(path: string, content: string): Promise<void>;
150
- shell(command: string, options?: { cwd?: string; timeout?: number }): Promise<ShellResult>;
151
- fetch(url: string, options?: {
152
- method?: string;
153
- headers?: Record<string, string>;
154
- body?: string;
155
- }): Promise<{ status: number; body: string; headers: Record<string, string> }>;
103
+ export function ensureProjectScaffold(projectDir) {
104
+ mkdirSync(guardPath(projectDir, "history"), { recursive: true });
105
+ mkdirSync(guardPath(projectDir, "logs"), { recursive: true });
106
+ ensureModulePackageJson(projectDir);
107
+ ensureGitignore(projectDir);
108
+ for (const [name, target] of Object.entries(IMPORTABLE_PACKAGES))
109
+ linkPackage(projectDir, name, target);
156
110
  }
157
-
158
- export declare const ctx: Ctx;
159
- export declare const agent: Agent;
160
- export declare const tools: Tools;`;
111
+ // --- The API reference shown to the LLM ---
112
+ /**
113
+ * The program-facing API, as shown to the LLM when it writes or repairs a
114
+ * program. This is the declaration file generated from types.ts, so the prompt
115
+ * cannot drift from the real API — doc comments included.
116
+ */
117
+ export const RUNTIME_TYPES = [
118
+ "// @trama-dev/runtime - Complete API",
119
+ readFileSync(new URL("./types.d.ts", import.meta.url), "utf-8").trim(),
120
+ [
121
+ "export declare const ctx: Ctx;",
122
+ "export declare const agent: Agent;",
123
+ "export declare const tools: Tools;",
124
+ "export declare const workspace: Workspace;",
125
+ ].join("\n"),
126
+ ].join("\n\n");
161
127
  // --- Config & state loaders ---
162
128
  export function loadConfig() {
163
129
  const configPath = join(homedir(), ".trama", "config.json");
164
130
  const defaults = {
165
131
  provider: "anthropic",
166
- model: "claude-opus-4-6",
132
+ model: "claude-opus-5-5",
167
133
  maxRepairAttempts: 3,
168
134
  defaultTimeout: 300_000,
169
135
  defaultMaxIterations: 100,
@@ -204,6 +170,16 @@ export function loadConfig() {
204
170
  }
205
171
  return merged;
206
172
  }
173
+ /** The global config, with the model/provider a project was created with taking precedence. */
174
+ export function loadProjectConfig(projectDir) {
175
+ const config = loadConfig();
176
+ const meta = JSON.parse(readFileSync(guardPath(projectDir, "meta.json"), "utf-8"));
177
+ if (meta.model)
178
+ config.model = meta.model;
179
+ if (meta.provider)
180
+ config.provider = meta.provider;
181
+ return config;
182
+ }
207
183
  export function loadState(projectDir) {
208
184
  const statePath = guardPath(projectDir, "state.json");
209
185
  if (!existsSync(statePath))
@@ -225,330 +201,150 @@ export function loadState(projectDir) {
225
201
  }
226
202
  return parsed;
227
203
  }
228
- // --- IPC Server ---
229
- const MAX_IPC_BODY = 50 * 1024 * 1024; // 50 MB
230
- /** Validate required fields in IPC request body. Returns error message or null. */
231
- function validateIPC(data, fields) {
232
- for (const [name, type] of Object.entries(fields)) {
233
- const val = data[name];
234
- if (type === "object") {
235
- if (typeof val !== "object" || val === null || Array.isArray(val)) {
236
- return `Missing or invalid field: ${name} (expected object)`;
237
- }
238
- }
239
- else if (typeof val !== type) {
240
- return `Missing or invalid field: ${name} (expected ${type})`;
241
- }
242
- }
243
- return null;
204
+ // --- History management ---
205
+ /** Append one metadata line to history/index.jsonl. */
206
+ function appendHistoryIndex(projectDir, entry) {
207
+ appendFileSync(guardPath(projectDir, join("history", "index.jsonl")), JSON.stringify(entry) + "\n");
244
208
  }
245
- function createIPCServer(ctx, agentImpl, toolsImpl) {
246
- return createServer((req, res) => {
247
- if (req.method !== "POST") {
248
- res.writeHead(405);
249
- res.end("Method not allowed");
250
- return;
209
+ /** The index.jsonl field that carries the detail for each kind of versioned change. */
210
+ const HISTORY_DETAIL_FIELD = { create: "prompt", update: "prompt", repair: "error" };
211
+ /**
212
+ * Save the current program.ts as the next version: copy it to history/NNNN.ts
213
+ * and record why in index.jsonl.
214
+ *
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.
218
+ */
219
+ export function copyToHistory(projectDir, reason, detail) {
220
+ const historyDir = guardPath(projectDir, "history");
221
+ const versions = readdirSync(historyDir)
222
+ .filter(f => /^\d+\.ts$/.test(f))
223
+ .map(f => parseInt(f, 10));
224
+ const version = versions.reduce((a, b) => Math.max(a, b), 0) + 1;
225
+ const fileName = `${String(version).padStart(4, "0")}.ts`;
226
+ copyFileSync(guardPath(projectDir, "program.ts"), guardPath(projectDir, join("history", fileName)));
227
+ const entry = { version, reason, timestamp: new Date().toISOString() };
228
+ const detailField = HISTORY_DETAIL_FIELD[reason];
229
+ if (detailField && detail)
230
+ entry[detailField] = detail;
231
+ appendHistoryIndex(projectDir, entry);
232
+ }
233
+ /** Record all files in a directory with their size and mtime for change detection. */
234
+ export function snapshotDir(dir, prefix = "") {
235
+ const result = new Map();
236
+ let entries;
237
+ try {
238
+ entries = readdirSync(dir, { withFileTypes: true });
239
+ }
240
+ catch {
241
+ return result;
242
+ }
243
+ for (const entry of entries) {
244
+ const relPath = prefix ? `${prefix}/${entry.name}` : entry.name;
245
+ const fullPath = join(dir, entry.name);
246
+ if (entry.isDirectory()) {
247
+ for (const [k, v] of snapshotDir(fullPath, relPath))
248
+ result.set(k, v);
251
249
  }
252
- const chunks = [];
253
- let byteCount = 0;
254
- let overflow = false;
255
- req.on("data", (chunk) => {
256
- if (overflow)
257
- return;
258
- chunks.push(chunk);
259
- byteCount += chunk.length;
260
- if (byteCount > MAX_IPC_BODY) {
261
- overflow = true;
262
- res.writeHead(413);
263
- res.end("IPC request body exceeds 50MB limit");
264
- req.destroy();
265
- }
266
- });
267
- req.on("end", async () => {
268
- if (overflow)
269
- return;
250
+ else if (entry.isFile()) {
270
251
  try {
271
- const data = JSON.parse(Buffer.concat(chunks).toString("utf-8"));
272
- let result;
273
- // Per-endpoint field validation
274
- const validationRules = {
275
- "/agent/ask": { prompt: "string" },
276
- "/agent/generate": { prompt: "string", schema: "object" },
277
- "/tools/read": { path: "string" },
278
- "/tools/write": { path: "string", content: "string" },
279
- "/tools/shell": { command: "string" },
280
- "/tools/fetch": { url: "string" },
281
- "/ctx/checkpoint": { state: "object" },
282
- "/ctx/log": { message: "string" },
283
- "/ctx/done": { state: "object" },
284
- };
285
- const rules = req.url ? validationRules[req.url] : undefined;
286
- if (rules) {
287
- const validationError = validateIPC(data, rules);
288
- if (validationError) {
289
- res.writeHead(400);
290
- res.end(validationError);
291
- return;
292
- }
293
- }
294
- switch (req.url) {
295
- case "/agent/ask":
296
- result = await agentImpl.ask(data.prompt, { system: data.system });
297
- res.writeHead(200, { "Content-Type": "application/json" });
298
- res.end(JSON.stringify({ result }));
299
- break;
300
- case "/agent/generate":
301
- result = await agentImpl.generate(data);
302
- res.writeHead(200, { "Content-Type": "application/json" });
303
- res.end(JSON.stringify({ result }));
304
- break;
305
- case "/tools/read":
306
- result = await toolsImpl.read(data.path);
307
- res.writeHead(200, { "Content-Type": "application/json" });
308
- res.end(JSON.stringify({ result }));
309
- break;
310
- case "/tools/write":
311
- await toolsImpl.write(data.path, data.content);
312
- res.writeHead(200, { "Content-Type": "application/json" });
313
- res.end(JSON.stringify({ result: null }));
314
- break;
315
- case "/tools/shell":
316
- result = await toolsImpl.shell(data.command, { cwd: data.cwd, timeout: data.timeout });
317
- res.writeHead(200, { "Content-Type": "application/json" });
318
- res.end(JSON.stringify({ result }));
319
- break;
320
- case "/tools/fetch":
321
- result = await toolsImpl.fetch(data.url, {
322
- method: data.method, headers: data.headers, body: data.body,
323
- });
324
- res.writeHead(200, { "Content-Type": "application/json" });
325
- res.end(JSON.stringify({ result }));
326
- break;
327
- case "/ctx/checkpoint":
328
- assertSerializable(data.state, "ctx.state");
329
- ctx.state = data.state;
330
- await ctx.checkpoint();
331
- res.writeHead(200, { "Content-Type": "application/json" });
332
- res.end(JSON.stringify({ result: null }));
333
- break;
334
- case "/ctx/log":
335
- await ctx.log(data.message, data.data);
336
- res.writeHead(200, { "Content-Type": "application/json" });
337
- res.end(JSON.stringify({ result: null }));
338
- break;
339
- case "/ctx/ready":
340
- if (data.data !== undefined && (typeof data.data !== "object" || data.data === null || Array.isArray(data.data))) {
341
- res.writeHead(400);
342
- res.end("Invalid field: data (expected object or undefined)");
343
- break;
344
- }
345
- await ctx.ready(data.data);
346
- res.writeHead(200, { "Content-Type": "application/json" });
347
- res.end(JSON.stringify({ result: null }));
348
- break;
349
- case "/ctx/done":
350
- assertSerializable(data.state, "ctx.state");
351
- ctx.state = data.state;
352
- await ctx.done(data.result);
353
- res.writeHead(200, { "Content-Type": "application/json" });
354
- res.end(JSON.stringify({ result: null }));
355
- break;
356
- default:
357
- res.writeHead(404);
358
- res.end("Not found");
359
- }
360
- }
361
- catch (err) {
362
- if (!res.headersSent)
363
- res.writeHead(500);
364
- res.end(String(err));
365
- }
366
- });
367
- });
368
- }
369
- function startServer(server) {
370
- return new Promise((resolve, reject) => {
371
- server.listen(0, "127.0.0.1", () => {
372
- const addr = server.address();
373
- if (addr && typeof addr === "object") {
374
- resolve(addr.port);
375
- }
376
- else {
377
- reject(new Error("Failed to get server port"));
378
- }
379
- });
380
- server.on("error", reject);
381
- });
382
- }
383
- function closeServer(server) {
384
- return new Promise((resolve, reject) => {
385
- server.close(err => {
386
- if (!err || err.code === "ERR_SERVER_NOT_RUNNING") {
387
- resolve();
388
- }
389
- else {
390
- reject(err);
252
+ const st = statSync(fullPath);
253
+ result.set(relPath, { size: st.size, mtimeMs: st.mtimeMs });
391
254
  }
392
- });
393
- });
394
- }
395
- /** Abort in-flight operations, kill orphan shells, drop HTTP connections, then close. */
396
- function forceCloseServer(server, toolsImpl, abortController) {
397
- abortController?.abort();
398
- toolsImpl.killActiveShells();
399
- server.closeAllConnections();
400
- return closeServer(server);
255
+ catch { /* skip */ }
256
+ }
257
+ }
258
+ return result;
401
259
  }
402
- // --- Child process management ---
260
+ const sameStat = (a, b) => a.size === b.size && a.mtimeMs === b.mtimeMs;
403
261
  /**
404
- * Collect stdout/stderr as strings and wait for exit.
405
- * Enforces wall-clock timeout via explicit setTimeout + kill.
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.
264
+ *
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)
269
+ *
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.
406
275
  */
407
- function waitForChild(child, options) {
408
- const { timeout, sinks, stopSignal } = options;
409
- return new Promise((resolve, reject) => {
410
- const out = cappedBuffer();
411
- const err = cappedBuffer();
412
- const outDecoder = new StringDecoder("utf-8");
413
- const errDecoder = new StringDecoder("utf-8");
414
- let timedOut = false;
415
- let exited = false;
416
- let stopRequested = false;
417
- let killFallbackTimer = null;
418
- const killChild = (sig) => {
419
- if (child.pid) {
420
- try {
421
- process.kill(-child.pid, sig);
422
- }
423
- catch { /* already gone */ }
424
- }
425
- else {
426
- child.kill(sig);
427
- }
428
- };
429
- const scheduleKill = (reason) => {
430
- if (exited)
431
- return;
432
- if (reason === "timeout") {
433
- timedOut = true;
434
- }
435
- else if (stopRequested || timedOut) {
436
- return;
437
- }
438
- else {
439
- stopRequested = true;
440
- }
441
- killChild("SIGTERM");
442
- if (killFallbackTimer)
443
- clearTimeout(killFallbackTimer);
444
- killFallbackTimer = setTimeout(() => {
445
- if (!exited)
446
- killChild("SIGKILL");
447
- }, 5000);
448
- killFallbackTimer.unref?.();
449
- };
450
- const onStopRequest = () => scheduleKill("stop-request");
451
- stopSignal?.addEventListener("abort", onStopRequest, { once: true });
452
- child.stdout?.on("data", (chunk) => {
453
- const text = outDecoder.write(chunk);
454
- out.append(text);
455
- sinks?.stdout?.(text);
456
- });
457
- child.stderr?.on("data", (chunk) => {
458
- const text = errDecoder.write(chunk);
459
- err.append(text);
460
- sinks?.stderr?.(text);
461
- });
462
- const timer = setTimeout(() => {
463
- scheduleKill("timeout");
464
- }, timeout);
465
- child.on("error", (err) => {
466
- clearTimeout(timer);
467
- if (killFallbackTimer)
468
- clearTimeout(killFallbackTimer);
469
- stopSignal?.removeEventListener("abort", onStopRequest);
470
- reject(err);
471
- });
472
- child.on("close", (code, signal) => {
473
- exited = true;
474
- clearTimeout(timer);
475
- if (killFallbackTimer)
476
- clearTimeout(killFallbackTimer);
477
- stopSignal?.removeEventListener("abort", onStopRequest);
478
- const outFlush = outDecoder.end();
479
- const errFlush = errDecoder.end();
480
- if (outFlush) {
481
- out.append(outFlush);
482
- sinks?.stdout?.(outFlush);
483
- }
484
- if (errFlush) {
485
- err.append(errFlush);
486
- sinks?.stderr?.(errFlush);
487
- }
488
- if (timedOut) {
489
- resolve({ exitCode: 1, stdout: out.value, stderr: err.value + "\n[trama] program killed: timeout" });
490
- }
491
- else if (stopRequested && (code === 0 || signal === "SIGTERM")) {
492
- resolve({ exitCode: 0, stdout: out.value, stderr: err.value });
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))
280
+ continue; // the run didn't touch it
281
+ 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.
284
+ 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)))
289
+ continue; // changed or removed concurrently
493
290
  }
494
- else {
495
- resolve({ exitCode: code ?? 1, stdout: out.value, stderr: err.value });
291
+ else if (realNow) {
292
+ continue; // someone else created the same path first — keep theirs
496
293
  }
497
- });
498
- });
294
+ mkdirSync(dirname(dstPath), { recursive: true });
295
+ copyFileSync(join(tempDir, relPath), dstPath);
296
+ }
297
+ catch {
298
+ // Escapes the workspace, path-shape conflict, permissions — skip
299
+ }
300
+ }
499
301
  }
500
- // --- History management ---
501
302
  /**
502
- * Copy current program.ts to history/NNNN.ts and append to index.jsonl.
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.
503
305
  *
504
- * WARNING: Do NOT use this for create-time repair attempts.
505
- * Create-time repairs go to index.jsonl only (reason: "create-repair").
506
- */
507
- export function copyToHistory(projectDir, reason, detail) {
508
- const historyDir = guardPath(projectDir, "history");
509
- const existing = readdirSync(historyDir).filter(f => /^\d+\.ts$/.test(f));
510
- const nums = existing.map(f => parseInt(f.replace(".ts", ""), 10));
511
- const nextNum = nums.length > 0 ? nums.reduce((a, b) => Math.max(a, b), 0) + 1 : 1;
512
- const next = String(nextNum).padStart(Math.max(4, String(nextNum).length), "0");
513
- const srcPath = guardPath(projectDir, "program.ts");
514
- const dstPath = guardPath(projectDir, join("history", `${next}.ts`));
515
- copyFileSync(srcPath, dstPath);
516
- const entry = { version: nextNum, reason, timestamp: new Date().toISOString() };
517
- if (reason === "repair" && detail)
518
- entry.error = detail;
519
- if (reason === "update" && detail)
520
- entry.prompt = detail;
521
- const indexPath = guardPath(projectDir, join("history", "index.jsonl"));
522
- appendFileSync(indexPath, JSON.stringify(entry) + "\n");
523
- }
524
- // --- Helpers ---
525
- /**
526
- * Snapshot a directory, run fn, restore from snapshot if fn returns false
527
- * or if fn throws. Always cleans up the snapshot. Returns whatever fn returns.
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.)
528
311
  */
529
312
  export async function withSnapshot(dir, fn) {
530
- const snap = mkdtempSync(join(tmpdir(), "trama-snapshot-"));
531
- const restore = () => {
532
- rmSync(dir, { recursive: true, force: true });
533
- cpSync(snap, dir, { recursive: true });
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);
534
322
  };
535
323
  try {
536
- cpSync(dir, snap, { recursive: true });
324
+ cpSync(target, snap, { recursive: true });
537
325
  let result;
538
326
  try {
539
327
  result = await fn();
540
328
  }
541
329
  catch (err) {
542
- restore();
330
+ rollBack();
543
331
  throw err;
544
332
  }
545
333
  if (!result.keep)
546
- restore();
334
+ rollBack();
547
335
  return result.value;
548
336
  }
549
337
  finally {
550
- rmSync(snap, { recursive: true, force: true });
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 });
551
346
  }
347
+ catch { /* left for the OS to reap */ }
552
348
  }
553
349
  /** Run fn in a temp directory, clean up afterwards regardless of outcome. */
554
350
  export async function withTempDir(prefix, fn) {
@@ -557,300 +353,265 @@ export async function withTempDir(prefix, fn) {
557
353
  return await fn(dir);
558
354
  }
559
355
  finally {
560
- rmSync(dir, { recursive: true, force: true });
356
+ removeTempDir(dir);
561
357
  }
562
358
  }
563
359
  /**
564
- * Attempt a single repair call with its own timeout and cancellation.
565
- * Returns true if repair succeeded, false if it failed (error is appended to repairErrors).
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.
364
+ */
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 });
371
+ const stagedBefore = snapshotDir(stagedDir);
372
+ const { commit, value } = await fn(stagedDir);
373
+ if (commit)
374
+ commitWorkspaceChanges(stagedDir, workspaceDir, stagedBefore, realSeed);
375
+ return value;
376
+ });
377
+ }
378
+ const formatError = (r) => `program.ts exited with code ${r.exitCode}\nstdout: ${r.stdout}\nstderr: ${r.stderr}`;
379
+ /**
380
+ * Hand the program its starting state through a private temp file rather than
381
+ * 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.
566
383
  */
567
- async function repairWithTimeout(adapter, input, timeout, repairErrors) {
568
- const controller = new AbortController();
569
- const timer = setTimeout(() => controller.abort(), timeout);
384
+ function writeInitFile(payload) {
385
+ const dir = mkdtempSync(join(tmpdir(), "trama-init-"));
386
+ const file = join(dir, "init.json");
387
+ const fd = openSync(file, "w", 0o600);
570
388
  try {
571
- return await adapter.repair(input, controller.signal);
572
- }
573
- catch (err) {
574
- repairErrors.push(err instanceof Error ? err.message : String(err));
575
- return null;
389
+ writeFileSync(fd, JSON.stringify(payload));
576
390
  }
577
391
  finally {
578
- clearTimeout(timer);
392
+ closeSync(fd);
579
393
  }
394
+ return { dir, file };
395
+ }
396
+ function toChildResult(exit) {
397
+ const { stdout, stderr } = exit;
398
+ if (exit.timedOut)
399
+ return { exitCode: 1, stdout, stderr: stderr + "\n[trama] program killed: timeout" };
400
+ // Stopped by us after ctx.ready() — going down on SIGTERM is the expected outcome.
401
+ if (exit.stopped && (exit.code === 0 || exit.signal === "SIGTERM"))
402
+ return { exitCode: 0, stdout, stderr };
403
+ return { exitCode: exit.code ?? 1, stdout, stderr };
580
404
  }
581
405
  /**
582
- * Run program.ts once in the given directory. Sets up scaffolding, IPC server,
583
- * writes init file, spawns child, waits for result, and cleans up.
584
- * Returns the child process result — does NOT throw on non-zero exit.
406
+ * 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).
585
410
  */
586
411
  async function runProgramOnce(options) {
587
- const { projectDir, adapter, timeout, maxIterations, argsOverride, streamOutput, stopOnReady } = options;
412
+ const { projectDir, adapter, timeout, maxIterations, argsOverride, streamOutput, stopOnReady, workspaceDir } = options;
588
413
  ensureProjectScaffold(projectDir);
589
- ensureRuntimeLink(projectDir);
590
- const abortController = new AbortController();
591
- const stopController = new AbortController();
592
- const { signal } = abortController;
593
- let readyStopScheduled = false;
594
- let readyStopTimer = null;
595
- // When set, the grace period is active — child exit should cancel the timer
596
- // so that the natural exit code flows through instead of being masked by SIGTERM.
597
- let graceActive = false;
414
+ // Cancels in-flight LLM calls, fetches and observes once the run is over.
415
+ const runEnded = new AbortController();
416
+ // Asks the program to stop once it has been ready for the grace period.
417
+ const readyStop = new AbortController();
418
+ let readyTimer = null;
419
+ let terminalSignal = null;
598
420
  const ctx = createContext(projectDir, loadState(projectDir), {
599
421
  maxIterations,
600
422
  argsOverride,
601
- onReady: stopOnReady ? () => {
602
- if (readyStopScheduled)
603
- return;
604
- readyStopScheduled = true;
605
- graceActive = true;
606
- readyStopTimer = setTimeout(() => {
607
- graceActive = false;
608
- stopController.abort();
609
- }, stopOnReady.graceMs);
610
- readyStopTimer.unref?.();
611
- } : undefined,
423
+ onReady: stopOnReady && (() => {
424
+ readyTimer ??= setTimeout(() => readyStop.abort(), stopOnReady.graceMs).unref();
425
+ }),
612
426
  });
613
- // Truncate logs only after preflight succeeds — preserves prior run's diagnostics
614
- // if scaffolding, state loading, or context creation fails.
427
+ // Truncate logs only after preflight succeeds — preserves the prior run's
428
+ // diagnostics if scaffolding, state loading, or context creation fails.
615
429
  writeFileSync(guardPath(projectDir, join("logs", "latest.jsonl")), "");
616
- const agentImpl = createAgent(adapter, signal);
617
- const toolsImpl = createTools(projectDir, signal);
618
- const server = createIPCServer(ctx, agentImpl, toolsImpl);
619
- // Infrastructure setup — errors here are NOT program bugs.
620
- let port;
621
- try {
622
- port = await startServer(server);
623
- }
624
- catch (infraError) {
625
- await forceCloseServer(server, toolsImpl, abortController);
626
- throw infraError;
627
- }
628
- // Write init data to a temp file instead of env vars to avoid OS size limits.
629
- // Use mkdtempSync for an unpredictable path and mode 0o600 to prevent local disclosure.
630
- const initDir = mkdtempSync(join(tmpdir(), "trama-init-"));
631
- const initFile = join(initDir, "init.json");
632
- const fd = openSync(initFile, "w", 0o600);
430
+ const tools = createTools(projectDir, runEnded.signal);
431
+ // Known only to this run's program, through its init file.
432
+ const token = randomBytes(32).toString("hex");
433
+ const server = createIPCServer({
434
+ token,
435
+ ctx,
436
+ agent: createAgent(adapter, runEnded.signal),
437
+ tools,
438
+ workspace: workspaceDir ? createWorkspace(workspaceDir, runEnded.signal) : null,
439
+ // The first terminal signal wins; ctx itself rejects a conflicting second one.
440
+ onTerminalSignal: result => { terminalSignal ??= result; },
441
+ });
442
+ let initDir;
633
443
  try {
634
- writeFileSync(fd, JSON.stringify({
444
+ const port = await listen(server);
445
+ const init = writeInitFile({
446
+ token,
635
447
  input: ctx.input,
636
448
  state: ctx.state,
637
449
  iteration: ctx.iteration,
638
450
  maxIterations: ctx.maxIterations,
639
- }));
640
- }
641
- finally {
642
- closeSync(fd);
643
- }
644
- let child;
645
- try {
646
- child = spawn(process.execPath, [TSX_CLI, guardPath(projectDir, "program.ts")], {
451
+ workspace: workspaceDir ?? null,
452
+ resumed: ctx.resumed,
453
+ yieldReason: ctx.yieldReason,
454
+ });
455
+ initDir = init.dir;
456
+ const child = spawn(process.execPath, [TSX_CLI, guardPath(projectDir, "program.ts")], {
647
457
  cwd: projectDir,
648
- env: {
649
- ...process.env,
650
- TRAMA_PORT: String(port),
651
- TRAMA_INIT: initFile,
652
- },
458
+ env: { ...process.env, TRAMA_PORT: String(port), TRAMA_INIT: init.file },
653
459
  stdio: ["ignore", "pipe", "pipe"],
654
460
  detached: true,
655
461
  });
656
- }
657
- catch (spawnError) {
658
- if (readyStopTimer)
659
- clearTimeout(readyStopTimer);
660
- await forceCloseServer(server, toolsImpl, abortController);
661
- try {
662
- rmSync(initDir, { recursive: true, force: true });
663
- }
664
- catch { /* best-effort */ }
665
- throw spawnError;
666
- }
667
- // If the child exits on its own during the grace period (before we send
668
- // SIGTERM), cancel the grace timer so the real exit code flows through
669
- // waitForChild instead of being masked by a subsequent SIGTERM.
670
- if (stopOnReady) {
671
- child.on("close", () => {
672
- if (graceActive && readyStopTimer) {
673
- clearTimeout(readyStopTimer);
674
- readyStopTimer = null;
675
- graceActive = false;
676
- }
677
- });
678
- }
679
- let result;
680
- try {
681
- result = await waitForChild(child, {
462
+ const exit = await superviseChild(child, {
682
463
  timeout,
683
- stopSignal: stopOnReady ? stopController.signal : undefined,
464
+ stopSignal: stopOnReady ? readyStop.signal : undefined,
684
465
  sinks: streamOutput ? {
685
466
  stdout: chunk => { process.stdout.write(chunk); },
686
467
  stderr: chunk => { process.stderr.write(chunk); },
687
468
  } : undefined,
688
469
  });
470
+ return { child: toChildResult(exit), terminalSignal };
689
471
  }
690
- catch (spawnError) {
691
- if (readyStopTimer)
692
- clearTimeout(readyStopTimer);
693
- await forceCloseServer(server, toolsImpl, abortController);
694
- try {
695
- rmSync(initDir, { recursive: true, force: true });
696
- }
697
- catch { /* best-effort */ }
698
- throw spawnError;
472
+ 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.
475
+ if (readyTimer)
476
+ clearTimeout(readyTimer);
477
+ runEnded.abort();
478
+ tools.killActiveShells();
479
+ server.closeAllConnections();
480
+ await closeServer(server).catch(() => { });
481
+ if (initDir)
482
+ removeTempDir(initDir);
699
483
  }
700
- if (readyStopTimer)
701
- clearTimeout(readyStopTimer);
702
- try {
703
- rmSync(initDir, { recursive: true, force: true });
704
- }
705
- catch { /* best-effort */ }
706
- // Always kill background shells — even on success, spawned background
707
- // processes would otherwise outlive the runner and leak.
708
- toolsImpl.killActiveShells();
709
- if (result.exitCode === 0) {
710
- abortController.abort(); // cancel any in-flight LLM/fetch requests
484
+ }
485
+ /**
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.
512
+ */
513
+ async function requestRepair(options, input, repairErrors) {
514
+ return withTempDir("trama-repair-", async (tempDir) => {
515
+ cpSync(options.projectDir, tempDir, { recursive: true });
516
+ const controller = new AbortController();
517
+ const timer = setTimeout(() => controller.abort(), options.timeout);
711
518
  try {
712
- await closeServer(server);
519
+ return await options.adapter.withCwd(tempDir).repair({ ...input, runtimeTypes: RUNTIME_TYPES }, controller.signal);
713
520
  }
714
- catch {
715
- await forceCloseServer(server, toolsImpl);
521
+ catch (err) {
522
+ repairErrors.push(err instanceof Error ? err.message : String(err));
523
+ return null;
716
524
  }
717
- }
718
- else {
719
- try {
720
- await forceCloseServer(server, toolsImpl, abortController);
525
+ finally {
526
+ clearTimeout(timer);
721
527
  }
722
- catch { /* best-effort */ }
723
- }
724
- return result;
528
+ });
725
529
  }
726
- const formatError = (r) => `program.ts exited with code ${r.exitCode}\nstdout: ${r.stdout}\nstderr: ${r.stderr}`;
727
- async function executeProgram(options) {
728
- const { projectDir, adapter, maxRepairAttempts, timeout, maxIterations } = options;
729
- mkdirSync(guardPath(projectDir, "history"), { recursive: true });
730
- mkdirSync(guardPath(projectDir, "logs"), { recursive: true });
731
- // Phase 1: Run in the real project directory.
732
- const result = await runProgramOnce({
733
- projectDir, adapter, timeout, maxIterations,
734
- argsOverride: options.argsOverride,
735
- streamOutput: true,
736
- stopOnReady: options.stopOnReady,
530
+ /**
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.
534
+ */
535
+ async function applyRepair(options, fixed) {
536
+ 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 };
737
545
  });
738
- if (result.exitCode === 0)
739
- return;
546
+ }
547
+ /**
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.
551
+ */
552
+ async function executeProgram(options) {
553
+ 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);
740
559
  if (maxRepairAttempts === 0) {
741
- throw new Error(`Program failed (repair disabled): ${formatError(result)}`);
560
+ return { status: "failed", reason: `Program failed (repair disabled): ${lastError}` };
742
561
  }
743
- // Phase 2: Repair loop — both LLM repair call and verification run
744
- // are fully isolated in temp dirs to prevent side effects on the real project.
745
- let lastError = formatError(result);
746
- const originalSource = readFileSync(guardPath(projectDir, "program.ts"), "utf-8");
747
- let currentSource = originalSource;
562
+ // Each attempt builds on the previous one's source, even though a failed
563
+ // attempt is rolled back out of the real project.
564
+ let currentSource = readFileSync(guardPath(projectDir, "program.ts"), "utf-8");
748
565
  const repairErrors = [];
749
566
  const repairDetails = () => repairErrors.length > 0
750
567
  ? `\nRepair errors:\n${repairErrors.map((e, i) => ` [${i + 1}] ${e}`).join("\n")}` : "";
751
568
  for (let attempt = 0; attempt < maxRepairAttempts; attempt++) {
752
- const repairResult = await withTempDir("trama-repair-", async (tempDir) => {
753
- cpSync(projectDir, tempDir, { recursive: true });
754
- const tempAdapter = adapter.withCwd(tempDir);
755
- const fixed = await repairWithTimeout(tempAdapter, { programSource: currentSource, error: lastError, runtimeTypes: RUNTIME_TYPES }, timeout, repairErrors);
756
- if (!fixed)
757
- return null;
758
- writeFileSync(guardPath(tempDir, "program.ts"), fixed);
759
- const verifyResult = await runProgramOnce({
760
- projectDir: tempDir, adapter: tempAdapter, timeout, maxIterations,
761
- argsOverride: options.argsOverride,
762
- stopOnReady: options.stopOnReady,
763
- });
764
- return { fixed, verifyResult };
765
- });
766
- if (!repairResult) {
767
- // Repair LLM call itself failed — don't re-run the same broken program.
768
- throw new Error(`Failed after ${attempt + 1} repair attempt(s): ${lastError}${repairDetails()}`);
569
+ 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()}` };
769
572
  }
770
- if (repairResult.verifyResult.exitCode === 0) {
771
- // Repair verified in isolation — now run in the real project for actual output.
772
- // Snapshot first so we can restore cleanly if the real run fails.
773
- const realResult = await withSnapshot(projectDir, async () => {
774
- writeFileSync(guardPath(projectDir, "program.ts"), repairResult.fixed);
775
- const r = await runProgramOnce({
776
- projectDir, adapter, timeout, maxIterations,
777
- argsOverride: options.argsOverride,
778
- streamOutput: true,
779
- stopOnReady: options.stopOnReady,
780
- });
781
- return { keep: r.exitCode === 0, value: r };
782
- });
783
- if (realResult.exitCode === 0) {
784
- // Bookkeeping is best-effort — program already succeeded and side effects
785
- // are committed. Don't mask success with a history/log write failure.
786
- try {
787
- options.onRepair?.(attempt, maxRepairAttempts, lastError);
788
- }
789
- catch (bookkeepingErr) {
790
- console.warn(`[trama] repair bookkeeping failed: ${bookkeepingErr instanceof Error ? bookkeepingErr.message : bookkeepingErr}`);
791
- }
792
- return;
573
+ 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}`);
793
582
  }
794
- // Passed in isolation but failed in real dir — project already restored by withSnapshot.
795
- currentSource = repairResult.fixed;
796
- lastError = formatError(realResult);
797
- continue;
583
+ return applied.outcome;
798
584
  }
799
- // Repair produced broken code — update context for next attempt.
800
- currentSource = repairResult.fixed;
801
- lastError = formatError(repairResult.verifyResult);
585
+ lastError = applied.error;
802
586
  }
803
- throw new Error(`Failed after ${maxRepairAttempts} repair attempts: ${lastError}${repairDetails()}`);
587
+ return { status: "failed", reason: `Failed after ${maxRepairAttempts} repair attempts: ${lastError}${repairDetails()}` };
804
588
  }
805
589
  // --- Smoke run (used by create and update) ---
806
- /** Copy new history entries from src to dst (appends only entries added after the shared prefix). */
807
- function propagateHistoryEntries(srcDir, dstDir) {
808
- const srcPath = guardPath(srcDir, join("history", "index.jsonl"));
809
- const dstPath = guardPath(dstDir, join("history", "index.jsonl"));
810
- if (!existsSync(srcPath))
811
- return;
812
- const srcHistory = readFileSync(srcPath, "utf-8");
813
- const dstHistory = existsSync(dstPath) ? readFileSync(dstPath, "utf-8") : "";
814
- if (!srcHistory.startsWith(dstHistory))
815
- return; // History diverged — cannot safely propagate
816
- const newEntries = srcHistory.slice(dstHistory.length);
817
- if (newEntries.length > 0) {
818
- mkdirSync(guardPath(dstDir, "history"), { recursive: true });
819
- appendFileSync(dstPath, newEntries);
820
- }
821
- }
822
- const DEFAULT_SMOKE_TIMEOUT = 30_000;
823
590
  const SMOKE_READY_GRACE_MS = 2_000;
824
- export function resolveSmokeTimeout(timeout) {
825
- return timeout ?? DEFAULT_SMOKE_TIMEOUT;
826
- }
591
+ /**
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.
596
+ */
827
597
  export async function smokeRunAndRepair(projectDir, adapter, reason, options) {
828
- const smokeTimeout = resolveSmokeTimeout(options?.timeout);
829
- // Run validation in a temp copy so side effects don't persist in the real project
830
598
  await withTempDir("trama-smoke-", async (smokeDir) => {
831
599
  cpSync(projectDir, smokeDir, { recursive: true });
832
- const smokeAdapter = adapter.withCwd(smokeDir);
833
- try {
834
- await executeProgram({
835
- projectDir: smokeDir,
836
- adapter: smokeAdapter,
837
- maxRepairAttempts: options?.maxRepairAttempts ?? 3,
838
- timeout: smokeTimeout,
839
- maxIterations: options?.maxIterations ?? 100,
840
- stopOnReady: {
841
- graceMs: SMOKE_READY_GRACE_MS,
842
- },
843
- onRepair(_attempt, _max, error) {
844
- appendFileSync(guardPath(smokeDir, join("history", "index.jsonl")), JSON.stringify({ reason: `${reason}-repair`, timestamp: new Date().toISOString(), error }) + "\n");
845
- },
846
- });
847
- // Smoke passed — copy back program.ts (may have been repaired)
848
- copyFileSync(guardPath(smokeDir, "program.ts"), guardPath(projectDir, "program.ts"));
849
- }
850
- finally {
851
- // Always propagate repair history, whether smoke passed or failed
852
- propagateHistoryEntries(smokeDir, projectDir);
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
+ },
610
+ });
611
+ if (result.status === "failed") {
612
+ throw new Error(`Program failed: ${result.reason}`);
853
613
  }
614
+ copyFileSync(guardPath(smokeDir, "program.ts"), guardPath(projectDir, "program.ts"));
854
615
  });
855
616
  }
856
617
  // --- Core execution ---
@@ -860,36 +621,27 @@ export async function runProgram(options) {
860
621
  throw new Error(`Project not found at ${projectDir}. ` +
861
622
  `Run \`trama list\` to see available projects.`);
862
623
  }
863
- const config = loadConfig();
864
- // Use per-project model/provider if saved, else fall back to global config
865
- const metaPath = guardPath(projectDir, "meta.json");
866
- const meta = JSON.parse(readFileSync(metaPath, "utf-8"));
867
- if (meta.model)
868
- config.model = meta.model;
869
- if (meta.provider)
870
- config.provider = meta.provider;
624
+ const config = loadProjectConfig(projectDir);
871
625
  const maxRepairAttempts = options.maxRepairAttempts ?? config.maxRepairAttempts;
872
626
  const timeout = options.timeout ?? config.defaultTimeout;
873
- const maxIterations = config.defaultMaxIterations;
874
627
  if (!Number.isFinite(timeout) || timeout <= 0) {
875
628
  throw new Error(`Invalid timeout: ${timeout}. Must be a positive number.`);
876
629
  }
877
630
  if (!Number.isInteger(maxRepairAttempts) || maxRepairAttempts < 0) {
878
631
  throw new Error(`Invalid maxRepairAttempts: ${maxRepairAttempts}. Must be a non-negative integer.`);
879
632
  }
880
- const adapter = new PiAdapter(config, projectDir);
881
- await executeProgram({
633
+ return executeProgram({
882
634
  projectDir,
883
- adapter,
635
+ adapter: new PiAdapter(config, projectDir),
884
636
  maxRepairAttempts,
885
637
  timeout,
886
- maxIterations,
638
+ maxIterations: config.defaultMaxIterations,
887
639
  argsOverride: options.args,
640
+ workspaceDir: options.workspaceDir,
888
641
  onRepair(attempt, max, error) {
889
- // Log repair attempts (appends to already-open logs file)
890
- const logsPath = guardPath(projectDir, join("logs", "latest.jsonl"));
642
+ // Runs after the repaired program's own run, so this lands at the end of its log.
891
643
  const entry = { ts: Date.now(), message: `Repair attempt ${attempt + 1}/${max}`, data: { error } };
892
- appendFileSync(logsPath, JSON.stringify(entry) + "\n");
644
+ appendFileSync(guardPath(projectDir, join("logs", "latest.jsonl")), JSON.stringify(entry) + "\n");
893
645
  console.log(`[trama] Repair attempt ${attempt + 1}/${max}`);
894
646
  copyToHistory(projectDir, "repair", error);
895
647
  },