@trama-dev/runtime 0.3.1 → 0.4.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/child-process.d.ts +1 -20
- package/dist/child-process.js +2 -77
- package/dist/index.d.ts +8 -0
- package/dist/index.js +9 -0
- package/dist/ipc-server.d.ts +8 -2
- package/dist/ipc-server.js +36 -15
- package/dist/journal-view.d.ts +9 -0
- package/dist/journal-view.js +131 -0
- package/dist/journal.d.ts +60 -0
- package/dist/journal.js +322 -0
- package/dist/runner-types.d.ts +2 -0
- package/dist/runner.d.ts +20 -6
- package/dist/runner.js +176 -63
- package/dist/{watchdog.d.ts → stopping.d.ts} +12 -0
- package/dist/stopping.js +230 -0
- package/dist/tools.js +4 -3
- package/package.json +2 -2
- package/dist/watchdog.js +0 -167
package/dist/runner.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { spawn } from "child_process";
|
|
2
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";
|
|
3
|
+
import { join, dirname, relative } from "path";
|
|
4
4
|
import { homedir, tmpdir } from "os";
|
|
5
5
|
import { fileURLToPath } from "url";
|
|
6
|
-
import { randomBytes } from "crypto";
|
|
6
|
+
import { createHash, randomBytes } from "crypto";
|
|
7
7
|
import { rejectOnAbort } from "./agent-backend.js";
|
|
8
8
|
import { PiAdapter } from "./pi-adapter.js";
|
|
9
9
|
import { createContext } from "./context.js";
|
|
@@ -11,9 +11,10 @@ import { createAgent, stripCodeFences } from "./agent.js";
|
|
|
11
11
|
import { createTools } from "./tools.js";
|
|
12
12
|
import { createWorkspace } from "./workspace.js";
|
|
13
13
|
import { guardPath } from "./path-guard.js";
|
|
14
|
-
import { createAllowance,
|
|
15
|
-
import { removeTempDir, removeWithThisProcess, requireWatchdog, stopWithThisProcess } from "./
|
|
14
|
+
import { createAllowance, superviseChild } from "./child-process.js";
|
|
15
|
+
import { removeTempDir, removeWithThisProcess, requireWatchdog, stopGroups, stopWithThisProcess } from "./stopping.js";
|
|
16
16
|
import { createIPCServer, listen, closeServer } from "./ipc-server.js";
|
|
17
|
+
import { JOURNAL_DIR, openJournal } from "./journal.js";
|
|
17
18
|
// --- Locating the runtime itself ---
|
|
18
19
|
/** The installed @trama-dev/runtime package — this file lives in its dist/. */
|
|
19
20
|
const RUNTIME_PACKAGE_DIR = dirname(dirname(fileURLToPath(import.meta.url)));
|
|
@@ -141,6 +142,7 @@ export function loadConfig() {
|
|
|
141
142
|
maxRepairAttempts: 3,
|
|
142
143
|
defaultTimeout: 300_000,
|
|
143
144
|
defaultMaxIterations: 100,
|
|
145
|
+
journalRuns: 20,
|
|
144
146
|
};
|
|
145
147
|
let raw;
|
|
146
148
|
try {
|
|
@@ -171,6 +173,7 @@ export function loadConfig() {
|
|
|
171
173
|
[Number.isInteger(merged.maxRepairAttempts) && merged.maxRepairAttempts >= 0, `"maxRepairAttempts" must be a non-negative integer (got ${merged.maxRepairAttempts})`],
|
|
172
174
|
[Number.isFinite(merged.defaultTimeout) && merged.defaultTimeout > 0, `"defaultTimeout" must be a positive number (got ${merged.defaultTimeout})`],
|
|
173
175
|
[pint(merged.defaultMaxIterations), `"defaultMaxIterations" must be a positive integer (got ${merged.defaultMaxIterations})`],
|
|
176
|
+
[Number.isInteger(merged.journalRuns) && merged.journalRuns >= 0, `"journalRuns" must be a non-negative integer (got ${merged.journalRuns})`],
|
|
174
177
|
];
|
|
175
178
|
for (const [ok, msg] of checks) {
|
|
176
179
|
if (!ok)
|
|
@@ -340,10 +343,19 @@ export async function withTempDir(prefix, fn) {
|
|
|
340
343
|
settled();
|
|
341
344
|
}
|
|
342
345
|
}
|
|
343
|
-
/**
|
|
346
|
+
/**
|
|
347
|
+
* Copy a directory's contents into an existing one, keeping symlinks as they
|
|
348
|
+
* are written. A project's journals stay behind: they are the record of its
|
|
349
|
+
* runs, not part of what a run works on, and a copy is where a run is tried.
|
|
350
|
+
*/
|
|
344
351
|
function copyDirInto(srcDir, dstDir) {
|
|
345
352
|
// realpath: a project directory may itself be a symlink.
|
|
346
|
-
|
|
353
|
+
const source = realpathSync(srcDir);
|
|
354
|
+
cpSync(source, dstDir, {
|
|
355
|
+
recursive: true,
|
|
356
|
+
verbatimSymlinks: true,
|
|
357
|
+
filter: path => relative(source, path) !== JOURNAL_DIR,
|
|
358
|
+
});
|
|
347
359
|
}
|
|
348
360
|
/**
|
|
349
361
|
* Run fn against a private copy of a directory. What fn does there stays
|
|
@@ -394,6 +406,18 @@ function labelled(label, write) {
|
|
|
394
406
|
flush,
|
|
395
407
|
};
|
|
396
408
|
}
|
|
409
|
+
/** How much of each of a program's output streams goes into the journal. */
|
|
410
|
+
const MAX_JOURNALLED_OUTPUT = 64 * 1024;
|
|
411
|
+
/** What identifies a program text without quoting it. */
|
|
412
|
+
function fingerprint(programPath) {
|
|
413
|
+
try {
|
|
414
|
+
const source = readFileSync(programPath);
|
|
415
|
+
return { sha256: createHash("sha256").update(source).digest("hex"), bytes: source.length };
|
|
416
|
+
}
|
|
417
|
+
catch {
|
|
418
|
+
return null; // no program to speak of; the attempt will say so itself
|
|
419
|
+
}
|
|
420
|
+
}
|
|
397
421
|
const describeFailure = (r) => `program.ts exited with code ${r.exitCode}\nstdout: ${tail(r.stdout)}\nstderr: ${tail(r.stderr)}`;
|
|
398
422
|
/**
|
|
399
423
|
* Hand the program its starting state through a private temp file rather than
|
|
@@ -450,7 +474,8 @@ function settle(projectDir, child, terminalSignal) {
|
|
|
450
474
|
* (bad project, server or spawn failure) or left state.json unreadable.
|
|
451
475
|
*/
|
|
452
476
|
async function runProgramOnce(options) {
|
|
453
|
-
const { projectDir, backend, timeout, maxIterations, argsOverride, validating, workspaceDir, label, signal } = options;
|
|
477
|
+
const { projectDir, backend, timeout, maxIterations, argsOverride, validating, workspaceDir, label, signal, journal } = options;
|
|
478
|
+
const attempt = options.attempt ?? 0;
|
|
454
479
|
if (signal?.aborted)
|
|
455
480
|
return { outcome: null, failure: "The run was stopped before its program started." };
|
|
456
481
|
requireWatchdog();
|
|
@@ -469,6 +494,14 @@ async function runProgramOnce(options) {
|
|
|
469
494
|
}),
|
|
470
495
|
print: line => console.log(tagged(label, line)),
|
|
471
496
|
});
|
|
497
|
+
journal.note("attempt", {
|
|
498
|
+
attempt,
|
|
499
|
+
// Where it runs — a copy of the project, when a fix is being tried or a candidate validated.
|
|
500
|
+
dir: projectDir,
|
|
501
|
+
program: fingerprint(guardPath(projectDir, "program.ts")),
|
|
502
|
+
iteration: ctx.iteration,
|
|
503
|
+
resumed: ctx.resumed,
|
|
504
|
+
});
|
|
472
505
|
// Truncate logs only after preflight succeeds — preserves the prior run's
|
|
473
506
|
// diagnostics if scaffolding, state loading, or context creation fails.
|
|
474
507
|
writeFileSync(guardPath(projectDir, join("logs", "latest.jsonl")), "");
|
|
@@ -479,6 +512,14 @@ async function runProgramOnce(options) {
|
|
|
479
512
|
// Runs the program has asked for and that are still going. They belong to this run.
|
|
480
513
|
const nestedRuns = new Set();
|
|
481
514
|
const workspaces = new Map();
|
|
515
|
+
const workspaceAt = (dir) => {
|
|
516
|
+
let workspace = workspaces.get(dir);
|
|
517
|
+
if (!workspace)
|
|
518
|
+
workspaces.set(dir, workspace = createWorkspace(dir, runEnded.signal));
|
|
519
|
+
return workspace;
|
|
520
|
+
};
|
|
521
|
+
// The workspace of the session this run is part of, if it is part of one.
|
|
522
|
+
const sessionWorkspace = workspaceDir ? workspaceAt(workspaceDir) : null;
|
|
482
523
|
const tools = createTools(projectDir, runEnded.signal);
|
|
483
524
|
// Known only to this run's program, through its init file.
|
|
484
525
|
const token = randomBytes(32).toString("hex");
|
|
@@ -487,14 +528,10 @@ async function runProgramOnce(options) {
|
|
|
487
528
|
ctx,
|
|
488
529
|
agent: createAgent(backend, projectDir, runEnded.signal),
|
|
489
530
|
tools,
|
|
490
|
-
workspace:
|
|
491
|
-
workspaceAt
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
workspaces.set(dir, workspace = createWorkspace(dir, runEnded.signal));
|
|
495
|
-
return workspace;
|
|
496
|
-
},
|
|
497
|
-
run: (request, stop) => {
|
|
531
|
+
workspace: sessionWorkspace,
|
|
532
|
+
workspaceAt,
|
|
533
|
+
journal,
|
|
534
|
+
run: (request, stop, seq) => {
|
|
498
535
|
if (validating) {
|
|
499
536
|
// As far as a validation goes. The call is left unanswered — an answer
|
|
500
537
|
// would only send the program on to do more — until the program,
|
|
@@ -507,7 +544,14 @@ async function runProgramOnce(options) {
|
|
|
507
544
|
// the run it asked for lasts, which has a timeout of its own. That run
|
|
508
545
|
// is stopped when this one ends, or when the program no longer wants it.
|
|
509
546
|
const release = allowance.hold();
|
|
510
|
-
const nested = runProgram({ ...request, signal: AbortSignal.any([runEnded.signal, stop]) },
|
|
547
|
+
const nested = runProgram({ ...request, signal: AbortSignal.any([runEnded.signal, stop]) }, {
|
|
548
|
+
depth: options.depth + 1,
|
|
549
|
+
// The two journals point at each other: this one says which run the call started…
|
|
550
|
+
started: (run, path) => { if (run)
|
|
551
|
+
journal.note("child", { seq, run, journal: path }); },
|
|
552
|
+
// …and that run's journal says which call started it.
|
|
553
|
+
parent: { run: journal.run, journal: journal.path, seq },
|
|
554
|
+
}).finally(() => {
|
|
511
555
|
release();
|
|
512
556
|
nestedRuns.delete(nested);
|
|
513
557
|
});
|
|
@@ -540,7 +584,7 @@ async function runProgramOnce(options) {
|
|
|
540
584
|
};
|
|
541
585
|
signal?.addEventListener("abort", stopProgram, { once: true });
|
|
542
586
|
try {
|
|
543
|
-
const child = await withTempDir("trama-init-", async (initDir) => {
|
|
587
|
+
const { child, exited } = await withTempDir("trama-init-", async (initDir) => {
|
|
544
588
|
const port = await listen(server);
|
|
545
589
|
const initFile = writeInitFile(initDir, {
|
|
546
590
|
token,
|
|
@@ -548,7 +592,7 @@ async function runProgramOnce(options) {
|
|
|
548
592
|
state: ctx.state,
|
|
549
593
|
iteration: ctx.iteration,
|
|
550
594
|
maxIterations: ctx.maxIterations,
|
|
551
|
-
inSession:
|
|
595
|
+
inSession: sessionWorkspace !== null,
|
|
552
596
|
resumed: ctx.resumed,
|
|
553
597
|
yieldReason: ctx.yieldReason,
|
|
554
598
|
});
|
|
@@ -572,16 +616,45 @@ async function runProgramOnce(options) {
|
|
|
572
616
|
},
|
|
573
617
|
});
|
|
574
618
|
programOver = true;
|
|
575
|
-
// A validation that reached a hand-off in time was decided there
|
|
576
|
-
|
|
619
|
+
// A validation that reached a hand-off in time was decided there: how the
|
|
620
|
+
// program goes down, cut off in mid-flow, says nothing about it.
|
|
621
|
+
const passedAtHandOff = handedOff && !exit.timedOut;
|
|
622
|
+
if (passedAtHandOff)
|
|
577
623
|
console.log(tagged(label, "[trama] validated up to where it starts another program"));
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
624
|
+
return {
|
|
625
|
+
child: passedAtHandOff ? { exitCode: 0, stdout: exit.stdout, stderr: exit.stderr } : toChildResult(exit),
|
|
626
|
+
// How the program's process ended, for the record.
|
|
627
|
+
exited: {
|
|
628
|
+
code: exit.code,
|
|
629
|
+
signal: exit.signal,
|
|
630
|
+
...(exit.timedOut ? { timedOut: true } : {}),
|
|
631
|
+
// Stopped by the runner at the end of a validation: at a hand-off, or once it had been ready a while.
|
|
632
|
+
...(exit.stopped ? { validated: handedOff ? "hand-off" : "ready" } : {}),
|
|
633
|
+
},
|
|
634
|
+
};
|
|
581
635
|
});
|
|
582
|
-
//
|
|
583
|
-
//
|
|
584
|
-
const
|
|
636
|
+
// How the attempt ended goes on record whatever comes of it — also when
|
|
637
|
+
// what the program left behind cannot be made sense of.
|
|
638
|
+
const noteExit = (verdict) => journal.note("exit", {
|
|
639
|
+
attempt,
|
|
640
|
+
...exited,
|
|
641
|
+
...(stopped ? { stopped: true } : {}),
|
|
642
|
+
// What the program printed is part of what it did. The end of it, where a failure shows.
|
|
643
|
+
stdout: tail(child.stdout, MAX_JOURNALLED_OUTPUT),
|
|
644
|
+
stderr: tail(child.stderr, MAX_JOURNALLED_OUTPUT),
|
|
645
|
+
...verdict,
|
|
646
|
+
});
|
|
647
|
+
let outcome;
|
|
648
|
+
try {
|
|
649
|
+
// A program that was stopped did not finish, whatever its exit code
|
|
650
|
+
// says — unless it had already said it was done.
|
|
651
|
+
outcome = stopped && !terminalSignal ? null : settle(projectDir, child, terminalSignal);
|
|
652
|
+
}
|
|
653
|
+
catch (err) {
|
|
654
|
+
noteExit({ error: err instanceof Error ? err.message : String(err) });
|
|
655
|
+
throw err;
|
|
656
|
+
}
|
|
657
|
+
noteExit({ outcome });
|
|
585
658
|
return { outcome, failure: describeFailure(child) };
|
|
586
659
|
}
|
|
587
660
|
finally {
|
|
@@ -618,9 +691,10 @@ const repairPrompt = (input) => `Fix this program so it runs.\n\n` +
|
|
|
618
691
|
* of the project that holds the program it is asked to fix — whatever it reads
|
|
619
692
|
* is real, whatever it writes is discarded; only the program text it returns
|
|
620
693
|
* is used. Bounded by its own timeout.
|
|
621
|
-
* Returns
|
|
694
|
+
* Returns the fixed program, or why no usable one came back.
|
|
622
695
|
*/
|
|
623
|
-
async function requestRepair(options, input
|
|
696
|
+
async function requestRepair(options, input) {
|
|
697
|
+
options.journal.note("fix-request", { error: input.error });
|
|
624
698
|
return withTempDir("trama-repair-", async (tempDir) => {
|
|
625
699
|
copyDirInto(options.projectDir, tempDir);
|
|
626
700
|
writeFileSync(guardPath(tempDir, "program.ts"), input.programSource);
|
|
@@ -636,11 +710,13 @@ async function requestRepair(options, input, repairErrors) {
|
|
|
636
710
|
throw new Error("The repair returned an empty program.");
|
|
637
711
|
if (fixed === input.programSource)
|
|
638
712
|
throw new Error("The repair returned the program unchanged.");
|
|
639
|
-
|
|
713
|
+
options.journal.note("fix", { ok: true, source: fixed });
|
|
714
|
+
return { fixed };
|
|
640
715
|
}
|
|
641
716
|
catch (err) {
|
|
642
|
-
|
|
643
|
-
|
|
717
|
+
const error = err instanceof Error ? err.message : String(err);
|
|
718
|
+
options.journal.note("fix", { ok: false, error });
|
|
719
|
+
return { error };
|
|
644
720
|
}
|
|
645
721
|
finally {
|
|
646
722
|
limit.cancel();
|
|
@@ -663,12 +739,12 @@ async function requestRepair(options, input, repairErrors) {
|
|
|
663
739
|
* would wait for replies forever. So what a fix writes there is written,
|
|
664
740
|
* whether or not the fix works: like anything a run wrote before it failed.
|
|
665
741
|
*/
|
|
666
|
-
async function tryFix(options, fixed) {
|
|
742
|
+
async function tryFix(options, fixed, attempt) {
|
|
667
743
|
const { projectDir } = options;
|
|
668
744
|
const run = await withStagedCopy(projectDir, async (stagedProject) => {
|
|
669
745
|
writeFileSync(guardPath(stagedProject, "program.ts"), fixed);
|
|
670
746
|
// If the copy cannot be run at all, or is left unusable, this fix did not work either.
|
|
671
|
-
const trial = await runProgramOnce({ ...options, projectDir: stagedProject }).catch((err) => ({
|
|
747
|
+
const trial = await runProgramOnce({ ...options, projectDir: stagedProject, attempt }).catch((err) => ({
|
|
672
748
|
outcome: null,
|
|
673
749
|
failure: `The repaired program could not be run: ${err instanceof Error ? err.message : err}`,
|
|
674
750
|
}));
|
|
@@ -704,30 +780,49 @@ async function executeProgram(options) {
|
|
|
704
780
|
return failed(`Program failed (repair disabled): ${lastError}`);
|
|
705
781
|
// Each attempt builds on the previous one's source, though a fix that failed never reached the project.
|
|
706
782
|
let currentSource = readFileSync(guardPath(projectDir, "program.ts"), "utf-8");
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
for (let attempt = 0; attempt < maxRepairAttempts; attempt++) {
|
|
711
|
-
const fixed = await requestRepair(options, { programSource: currentSource, error: lastError }, repairErrors);
|
|
783
|
+
// The program as it was is attempt 0; each fix is the next.
|
|
784
|
+
for (let attempt = 1; attempt <= maxRepairAttempts; attempt++) {
|
|
785
|
+
const fix = await requestRepair(options, { programSource: currentSource, error: lastError });
|
|
712
786
|
if (stopped())
|
|
713
787
|
return wasStopped();
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
788
|
+
// Without a fix there is nothing more to try: asking again would be asking the same thing.
|
|
789
|
+
if ("error" in fix) {
|
|
790
|
+
return failed(`Failed after ${attempt} repair attempt(s): ${lastError}\nNo fix came back: ${fix.error}`);
|
|
791
|
+
}
|
|
792
|
+
currentSource = fix.fixed;
|
|
793
|
+
const run = await tryFix(options, fix.fixed, attempt);
|
|
718
794
|
if (run.outcome)
|
|
719
795
|
return { result: run.outcome, repair: { attempt, error: lastError } };
|
|
720
796
|
if (stopped())
|
|
721
797
|
return wasStopped();
|
|
722
798
|
lastError = run.failure;
|
|
723
799
|
}
|
|
724
|
-
return failed(`Failed after ${maxRepairAttempts} repair attempts: ${lastError}
|
|
800
|
+
return failed(`Failed after ${maxRepairAttempts} repair attempts: ${lastError}`);
|
|
801
|
+
}
|
|
802
|
+
/**
|
|
803
|
+
* Carry out a run under its journal. However it goes, the journal's last
|
|
804
|
+
* record says so: the run's result, or why it could not be carried out.
|
|
805
|
+
*/
|
|
806
|
+
async function journalled(journal, run) {
|
|
807
|
+
try {
|
|
808
|
+
const execution = await run();
|
|
809
|
+
journal.note("end", { result: execution.result });
|
|
810
|
+
return execution;
|
|
811
|
+
}
|
|
812
|
+
catch (err) {
|
|
813
|
+
journal.note("end", { error: err instanceof Error ? err.message : String(err) });
|
|
814
|
+
throw err;
|
|
815
|
+
}
|
|
816
|
+
finally {
|
|
817
|
+
journal.close();
|
|
818
|
+
}
|
|
725
819
|
}
|
|
726
820
|
// --- Validating a candidate program (used by create and update) ---
|
|
727
821
|
const VALIDATION_READY_GRACE_MS = 2_000;
|
|
728
822
|
/**
|
|
729
|
-
* Validate a candidate program.ts for a project without touching the
|
|
730
|
-
* run it (with repair) in a throwaway copy.
|
|
823
|
+
* Validate a candidate program.ts for a project without touching what the
|
|
824
|
+
* project holds: run it (with repair) in a throwaway copy. The one thing left
|
|
825
|
+
* in the project is the journal of the validation. Returns the program that worked —
|
|
731
826
|
* the candidate itself, or a repaired version of it, with the failure that was
|
|
732
827
|
* repaired. Throws if it cannot be made to run.
|
|
733
828
|
*
|
|
@@ -737,22 +832,28 @@ const VALIDATION_READY_GRACE_MS = 2_000;
|
|
|
737
832
|
* first.
|
|
738
833
|
*/
|
|
739
834
|
export async function validateProgram(projectDir, backend, candidate, options) {
|
|
740
|
-
|
|
835
|
+
const { journalRuns = 0, ...limits } = options;
|
|
836
|
+
// Recorded with the project, though run in a copy of it.
|
|
837
|
+
const journal = openJournal(projectDir, journalRuns, { purpose: "validate", ...limits });
|
|
838
|
+
const { result, repair, worked } = await journalled(journal, () => withTempDir("trama-validate-", async (trialDir) => {
|
|
741
839
|
copyDirInto(projectDir, trialDir);
|
|
742
840
|
const programPath = guardPath(trialDir, "program.ts");
|
|
743
841
|
writeFileSync(programPath, candidate);
|
|
744
|
-
const
|
|
745
|
-
...
|
|
842
|
+
const execution = await executeProgram({
|
|
843
|
+
...limits,
|
|
746
844
|
projectDir: trialDir,
|
|
747
845
|
backend,
|
|
748
846
|
depth: 0,
|
|
749
847
|
validating: { readyGraceMs: VALIDATION_READY_GRACE_MS },
|
|
848
|
+
journal,
|
|
750
849
|
});
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
}
|
|
754
|
-
|
|
755
|
-
|
|
850
|
+
// The program that worked — the candidate, or what a repair made of it. None, if nothing did.
|
|
851
|
+
const worked = execution.result.status === "failed" ? null : readFileSync(programPath, "utf-8");
|
|
852
|
+
return { ...execution, worked };
|
|
853
|
+
}));
|
|
854
|
+
if (worked === null)
|
|
855
|
+
throw new Error(`Program failed: ${result.reason}`);
|
|
856
|
+
return { source: worked, repairedError: repair?.error };
|
|
756
857
|
}
|
|
757
858
|
/**
|
|
758
859
|
* Make a validated program the project's program.ts and record it as a new
|
|
@@ -776,12 +877,12 @@ let runsInFlight = 0;
|
|
|
776
877
|
/**
|
|
777
878
|
* Run a project, in this process: this is what a runner does.
|
|
778
879
|
*
|
|
779
|
-
* `
|
|
780
|
-
*
|
|
781
|
-
* program's own. One runner carries the whole tree, so it is also where the
|
|
880
|
+
* `askedFor` is set when a program asked for the run (see the "/run/program"
|
|
881
|
+
* call). One runner carries the whole tree of runs, so it is also where the
|
|
782
882
|
* tree is kept from growing without bound.
|
|
783
883
|
*/
|
|
784
|
-
export async function runProgram(options,
|
|
884
|
+
export async function runProgram(options, askedFor) {
|
|
885
|
+
const depth = askedFor?.depth ?? 0;
|
|
785
886
|
if (depth > MAX_RUN_DEPTH) {
|
|
786
887
|
throw new Error(`Not running ${options.projectDir}: programs are running programs more than ${MAX_RUN_DEPTH} deep. ` +
|
|
787
888
|
`A program that runs itself, or two that run each other, never ends.`);
|
|
@@ -791,13 +892,13 @@ export async function runProgram(options, depth = 0) {
|
|
|
791
892
|
}
|
|
792
893
|
runsInFlight += 1;
|
|
793
894
|
try {
|
|
794
|
-
return await runProject(options, depth);
|
|
895
|
+
return await runProject(options, depth, askedFor);
|
|
795
896
|
}
|
|
796
897
|
finally {
|
|
797
898
|
runsInFlight -= 1;
|
|
798
899
|
}
|
|
799
900
|
}
|
|
800
|
-
async function runProject(options, depth) {
|
|
901
|
+
async function runProject(options, depth, askedFor) {
|
|
801
902
|
const { projectDir } = options;
|
|
802
903
|
if (!existsSync(join(projectDir, "meta.json"))) {
|
|
803
904
|
throw new Error(`Project not found at ${projectDir}. ` +
|
|
@@ -812,7 +913,18 @@ async function runProject(options, depth) {
|
|
|
812
913
|
if (!Number.isInteger(maxRepairAttempts) || maxRepairAttempts < 0) {
|
|
813
914
|
throw new Error(`Invalid maxRepairAttempts: ${maxRepairAttempts}. Must be a non-negative integer.`);
|
|
814
915
|
}
|
|
815
|
-
const
|
|
916
|
+
const journal = openJournal(projectDir, config.journalRuns, {
|
|
917
|
+
purpose: "run",
|
|
918
|
+
label: options.label,
|
|
919
|
+
depth,
|
|
920
|
+
parent: askedFor?.parent,
|
|
921
|
+
workspace: options.workspaceDir,
|
|
922
|
+
timeout,
|
|
923
|
+
maxRepairAttempts,
|
|
924
|
+
args: options.args, // last: it is the one field of unknown size
|
|
925
|
+
});
|
|
926
|
+
askedFor?.started(journal.run, journal.path);
|
|
927
|
+
const { result, repair } = await journalled(journal, () => executeProgram({
|
|
816
928
|
projectDir,
|
|
817
929
|
backend: createBackend(config),
|
|
818
930
|
maxRepairAttempts,
|
|
@@ -823,13 +935,14 @@ async function runProject(options, depth) {
|
|
|
823
935
|
depth,
|
|
824
936
|
label: options.label,
|
|
825
937
|
signal: options.signal,
|
|
826
|
-
|
|
938
|
+
journal,
|
|
939
|
+
}));
|
|
827
940
|
if (repair) {
|
|
828
941
|
// The program is fixed and has run; failing to write this down must not turn that into an error.
|
|
829
942
|
try {
|
|
830
|
-
const entry = { ts: Date.now(), message: `Repair attempt ${repair.attempt
|
|
943
|
+
const entry = { ts: Date.now(), message: `Repair attempt ${repair.attempt}/${maxRepairAttempts}`, data: { error: repair.error } };
|
|
831
944
|
appendFileSync(guardPath(projectDir, join("logs", "latest.jsonl")), JSON.stringify(entry) + "\n");
|
|
832
|
-
console.log(tagged(options.label, `[trama] Repair attempt ${repair.attempt
|
|
945
|
+
console.log(tagged(options.label, `[trama] Repair attempt ${repair.attempt}/${maxRepairAttempts}`));
|
|
833
946
|
copyToHistory(projectDir, "repair", repair.error);
|
|
834
947
|
}
|
|
835
948
|
catch (err) {
|
|
@@ -1,3 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Send a signal to a whole process group. Children spawned with `detached: true`
|
|
3
|
+
* lead their own group, so this also reaches whatever they started in the background.
|
|
4
|
+
* Signal 0 only probes. Returns false if the group no longer exists.
|
|
5
|
+
*/
|
|
6
|
+
export declare function signalGroup(pgid: number, signal: NodeJS.Signals | 0): boolean;
|
|
1
7
|
/**
|
|
2
8
|
* Make sure there is a watchdog before anything is started that would need
|
|
3
9
|
* one. Throws if one cannot be started: running without it would mean leaving
|
|
@@ -17,3 +23,9 @@ export declare function stopWithThisProcess(pgid: number): () => void;
|
|
|
17
23
|
export declare function removeWithThisProcess(dir: string): () => void;
|
|
18
24
|
/** Remove a temp directory. Best-effort: failing to clean up must never change a run's outcome. */
|
|
19
25
|
export declare function removeTempDir(dir: string): void;
|
|
26
|
+
/**
|
|
27
|
+
* Stop process groups for good: SIGTERM now, SIGKILL after the grace period to
|
|
28
|
+
* whichever are still there. Resolves when none is left — so that what follows
|
|
29
|
+
* (merging a directory they were writing to, deleting it) finds them gone.
|
|
30
|
+
*/
|
|
31
|
+
export declare function stopGroups(pgids: number[]): Promise<void>;
|