@vimhead.dev/norn-cli 0.1.0-tip.37310387847.1 → 0.1.0-tip.43698584363.1

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.
@@ -155,7 +155,11 @@ norn runs inspect <run>
155
155
  norn runs metrics <run>
156
156
  ```
157
157
 
158
- Start returns `{ "run": ... }` with `id`, `name`, and `path`, after launching a detached executor. This is acceptance of the launch, not success of the task. `runs wait` returns when the run is no longer running or inspection reports it unhealthy. Its successful process exit does not mean the workflow completed; callers check `run.status`, `run.health`, and outcome/failure information.
158
+ Start returns `{ "run": ... }` with `id`, `name`, and `path` after the detached executor initializes its run storage and acknowledges readiness. Resume also waits for initialization. A fast workflow may already have completed or interrupted by the time the command returns; successful initialization is not task success. `runs wait` returns when the run is no longer running or inspection reports it unhealthy. Its successful process exit does not mean the workflow completed; callers check `run.status`, `run.health`, and outcome/failure information.
159
+
160
+ Executor startup is bounded to 60 seconds. An early exit or initialization timeout returns a nonzero exit with error code `EXECUTOR_STARTUP_FAILED`, `runId`, `runRoot`, and `diagnosticsPath`. That file retains executor stdout and stderr, separately for each start/resume attempt and outside checkpoint rollback. Startup failures before a manifest exists remain inspectable; metrics contain no workflow activity. An abandoned launch without an acknowledgment becomes unhealthy rather than waiting indefinitely.
161
+
162
+ IF startup fails before the initial checkpoint exists, THEN inspect `diagnosticsPath`, repair the cause, and start a new run. ELSE use the [saved checkpoints](recovery.md) for recovery. For example, fix a missing dependency and start again; do not wait indefinitely for a failed executor. A resume that fails during project loading preserves the prior gate or retry boundary, so it can be retried after repair.
159
163
 
160
164
  Run results expose `run.paths.project` and `run.paths.workspace` as absolute directories. `run.path` identifies the complete run storage directory, not the workspace. A completed capability's outputs are in `run.outcome.metadata`; file paths in `data` follow that workflow's declared convention. The [minimal example](../examples/minimal-workflow/README.md) returns a `greetingPath` relative to `run.paths.workspace`.
161
165
 
@@ -1 +1 @@
1
- {"version":"0.1.0-tip.37310387847.1"}
1
+ {"version":"0.1.0-tip.43698584363.1"}
@@ -27,6 +27,9 @@ process.env.PI_PACKAGE_DIR = await materializePiAssets({
27
27
  registerBunOAuthFlows();
28
28
  const { main } = await import("../cli.ts");
29
29
  await main(process.argv.slice(2), {
30
- kind: "embedded",
31
- bundle: documentationAssets,
30
+ documentationSource: {
31
+ kind: "embedded",
32
+ bundle: documentationAssets,
33
+ },
34
+ invocation: [process.execPath],
32
35
  });
@@ -1,11 +1,15 @@
1
1
  import { main as runPi } from "@earendil-works/pi-coding-agent";
2
- import {
3
- type DeletedNornRunInfo,
4
- type NornAnyWorkflowDeclaration,
5
- type NornRunInfo,
6
- } from "@vimhead.dev/norn";
2
+ import { type DeletedNornRunInfo, type NornRunInfo } from "@vimhead.dev/norn";
7
3
  import { isNodeError } from "@vimhead.dev/norn-core/errors";
8
- import { spawn } from "node:child_process";
4
+ import {
5
+ NornDetachedExecutor,
6
+ type NornExecutorArgv,
7
+ } from "./internal/detached-executor.ts";
8
+ import {
9
+ EXECUTOR_START_TIMEOUT_MS,
10
+ NornExecutorStartup,
11
+ NornExecutorStartupError,
12
+ } from "./internal/executor-startup.ts";
9
13
  import { createHash, randomUUID } from "node:crypto";
10
14
  import {
11
15
  chmod,
@@ -17,9 +21,8 @@ import {
17
21
  writeFile,
18
22
  } from "node:fs/promises";
19
23
  import { homedir } from "node:os";
20
- import { dirname, isAbsolute, join, resolve } from "node:path";
24
+ import { dirname, join, resolve } from "node:path";
21
25
  import { setTimeout as delay } from "node:timers/promises";
22
- import { fileURLToPath } from "node:url";
23
26
  import { Value } from "typebox/value";
24
27
  import {
25
28
  NORN_BUILD_INFO,
@@ -41,10 +44,11 @@ import {
41
44
  } from "./internal/errors.ts";
42
45
  import {
43
46
  clearRunResumeRequest,
44
- readRunLaunchRequest,
47
+ readOptionalRunLaunchRequest,
45
48
  readRunResumeRequest,
46
49
  writeRunLaunchRequest,
47
50
  writeRunResumeRequest,
51
+ type NornRunLaunchRequest,
48
52
  type NornRunResumeRequest,
49
53
  } from "./internal/launch-request.ts";
50
54
  import { readRunMetrics } from "./internal/metrics.ts";
@@ -144,7 +148,7 @@ const COMMANDS: readonly CliCommand[] = [
144
148
  output:
145
149
  "JSON object under documentation with storage, version, commit, assetDigest, and absolute paths. NORN_DOCS_CACHE_DIR overrides the binary cache directory.",
146
150
  examples: ["norn docs inspect"],
147
- execute: async (args, documentationSource) => {
151
+ execute: async (args, { documentationSource }) => {
148
152
  assertNoExtraArgs("docs inspect", args);
149
153
  writeJson({
150
154
  documentation: await resolveCliDocumentation(documentationSource),
@@ -160,18 +164,12 @@ const COMMANDS: readonly CliCommand[] = [
160
164
  output:
161
165
  "JSON object with introduction text under intro. Uses the same asset resolution and NORN_DOCS_CACHE_DIR override as docs inspect.",
162
166
  examples: ["norn docs intro"],
163
- execute: async (args, documentationSource) => {
167
+ execute: async (args, { documentationSource, invocation }) => {
164
168
  assertNoExtraArgs("docs intro", args);
165
169
  writeJson({
166
170
  intro: renderNornDocumentationIntro({
167
171
  documentation: await resolveCliDocumentation(documentationSource),
168
- invocation:
169
- documentationSource.kind === "embedded"
170
- ? [process.execPath]
171
- : [
172
- process.execPath,
173
- fileURLToPath(new URL("../bin/norn.mjs", import.meta.url)),
174
- ],
172
+ invocation,
175
173
  }),
176
174
  });
177
175
  },
@@ -266,9 +264,9 @@ const COMMANDS: readonly CliCommand[] = [
266
264
  examples: [
267
265
  'printf \'{"args":{"task":"Add tests"}}\' | norn runs start example.plan',
268
266
  ],
269
- execute: async (args) => {
267
+ execute: async (args, { invocation }) => {
270
268
  const workflowId = requiredArg("runs start", args, 0, "workflow id");
271
- await startRun(workflowId, args.slice(1));
269
+ await startRun({ workflowId, commandArgs: args.slice(1), invocation });
272
270
  },
273
271
  },
274
272
  {
@@ -284,9 +282,9 @@ const COMMANDS: readonly CliCommand[] = [
284
282
  examples: [
285
283
  'printf \'{"args":{"decision":"accept"}}\' | norn runs resume quiet-river-lantern',
286
284
  ],
287
- execute: async (args) => {
285
+ execute: async (args, { invocation }) => {
288
286
  const run = requiredArg("runs resume", args, 0, "run");
289
- await resumeRun(run, args.slice(1));
287
+ await resumeRun({ run, args: args.slice(1), invocation });
290
288
  },
291
289
  },
292
290
  {
@@ -590,21 +588,27 @@ const HUMAN_COMMAND_SUMMARIES: Readonly<Record<string, string>> = {
590
588
  help: "Show concise command help.",
591
589
  };
592
590
 
591
+ type NornCliContext = {
592
+ readonly documentationSource: NornDocumentationSource;
593
+ readonly invocation: NornExecutorArgv;
594
+ };
595
+
593
596
  export async function main(
594
597
  args: readonly string[],
595
- documentationSource: NornDocumentationSource,
598
+ context: NornCliContext,
596
599
  ): Promise<void> {
597
600
  if (args[0] === "pi") {
598
601
  await runPi([...args.slice(1)]);
599
602
  return;
600
603
  }
601
604
  try {
602
- await runCommand(args, documentationSource);
605
+ await runCommand(args, context);
603
606
  } catch (error) {
604
607
  writeJson({
605
608
  error: {
606
609
  code: errorCode(error),
607
610
  message: errorMessage(error),
611
+ ...(error instanceof NornExecutorStartupError ? error.details : {}),
608
612
  ...(error instanceof NornProjectLoadError
609
613
  ? { isComplete: error.isComplete, diagnostics: error.diagnostics }
610
614
  : {}),
@@ -616,7 +620,7 @@ export async function main(
616
620
 
617
621
  async function runCommand(
618
622
  args: readonly string[],
619
- documentationSource: NornDocumentationSource,
623
+ context: NornCliContext,
620
624
  ): Promise<void> {
621
625
  if (args.length === 0) {
622
626
  writeCliHelp([]);
@@ -633,7 +637,7 @@ async function runCommand(
633
637
  }
634
638
  const command = findCliCommand(args);
635
639
  if (!command) throw new Error(`Unknown norn command: ${args.join(" ")}`);
636
- await command.execute(args.slice(command.path.length), documentationSource);
640
+ await command.execute(args.slice(command.path.length), context);
637
641
  }
638
642
 
639
643
  type CliCommand = {
@@ -649,7 +653,7 @@ type CliCommand = {
649
653
  readonly hidden?: true;
650
654
  readonly execute: (
651
655
  args: readonly string[],
652
- documentationSource: NornDocumentationSource,
656
+ context: NornCliContext,
653
657
  ) => Promise<void> | void;
654
658
  };
655
659
 
@@ -1096,10 +1100,15 @@ async function inspectProject(): Promise<void> {
1096
1100
  writeJson({ project, isComplete, diagnostics });
1097
1101
  }
1098
1102
 
1099
- async function startRun(
1100
- workflowId: string,
1101
- commandArgs: readonly string[],
1102
- ): Promise<void> {
1103
+ async function startRun({
1104
+ workflowId,
1105
+ commandArgs,
1106
+ invocation,
1107
+ }: {
1108
+ readonly workflowId: string;
1109
+ readonly commandArgs: readonly string[];
1110
+ readonly invocation: NornExecutorArgv;
1111
+ }): Promise<void> {
1103
1112
  assertNoStructuredInputArgs("runs start", commandArgs);
1104
1113
  const project = await loadNornProject(process.cwd());
1105
1114
  const workflow = project.registry.workflowById(workflowId);
@@ -1115,7 +1124,7 @@ async function startRun(
1115
1124
  const runRoot = resolve(project.projectRoot, RUNS_ROOT, id);
1116
1125
  await mkdir(runRoot, { recursive: true });
1117
1126
  const createdAt = new Date().toISOString();
1118
- await writeRunLaunchRequest(runRoot, {
1127
+ const request: NornRunLaunchRequest = {
1119
1128
  version: 2,
1120
1129
  type: "run",
1121
1130
  id,
@@ -1124,21 +1133,24 @@ async function startRun(
1124
1133
  args,
1125
1134
  configOverride,
1126
1135
  createdAt,
1127
- });
1128
- await startDetachedExecuteRun(id, project.projectRoot);
1129
- writeJson({
1130
- run: startedRunInfo({
1131
- id,
1132
- name,
1133
- workflow,
1134
- runRoot,
1135
- projectRoot: project.projectRoot,
1136
- createdAt,
1137
- }),
1138
- });
1136
+ };
1137
+ await writeRunLaunchRequest(runRoot, request);
1138
+ await new NornDetachedExecutor({
1139
+ invocation,
1140
+ startupTimeoutMs: EXECUTOR_START_TIMEOUT_MS,
1141
+ }).start({ projectRoot: project.projectRoot, runRoot, request });
1142
+ writeJson({ run: await getRunInfo(runRoot) });
1139
1143
  }
1140
1144
 
1141
- async function resumeRun(run: string, args: readonly string[]): Promise<void> {
1145
+ async function resumeRun({
1146
+ run,
1147
+ args,
1148
+ invocation,
1149
+ }: {
1150
+ readonly run: string;
1151
+ readonly args: readonly string[];
1152
+ readonly invocation: NornExecutorArgv;
1153
+ }): Promise<void> {
1142
1154
  assertNoStructuredInputArgs("runs resume", args);
1143
1155
  const project = await loadNornProject(process.cwd());
1144
1156
  const runRoot = await resolveRunRoot(project.projectRoot, run);
@@ -1162,7 +1174,10 @@ async function resumeRun(run: string, args: readonly string[]): Promise<void> {
1162
1174
  await lease.release();
1163
1175
  }
1164
1176
  try {
1165
- await startDetachedExecuteRun(request.id, project.projectRoot);
1177
+ await new NornDetachedExecutor({
1178
+ invocation,
1179
+ startupTimeoutMs: EXECUTOR_START_TIMEOUT_MS,
1180
+ }).start({ projectRoot: project.projectRoot, runRoot, request });
1166
1181
  } catch (error) {
1167
1182
  await removeResumeRequest({ runRoot, request });
1168
1183
  throw error;
@@ -1299,6 +1314,8 @@ async function executeRun(runId: string): Promise<void> {
1299
1314
  const request =
1300
1315
  (await readOptionalRunLaunchRequest(runRoot)) ??
1301
1316
  (await readRunResumeRequest(runRoot));
1317
+ const startup = new NornExecutorStartup({ runRoot, request });
1318
+ let isExecutorReady = false;
1302
1319
  try {
1303
1320
  const agentDir = resolveNornAgentDirectory({
1304
1321
  home: homedir(),
@@ -1312,6 +1329,10 @@ async function executeRun(runId: string): Promise<void> {
1312
1329
  signal: abortController.signal,
1313
1330
  gateMode: "pause",
1314
1331
  config: project.projectConfig,
1332
+ onExecutorReady: async () => {
1333
+ await startup.acknowledge();
1334
+ isExecutorReady = true;
1335
+ },
1315
1336
  });
1316
1337
  engine.registerWorkflows(project.definitions);
1317
1338
  if (request.type === "run") {
@@ -1325,10 +1346,14 @@ async function executeRun(runId: string): Promise<void> {
1325
1346
  } else {
1326
1347
  await engine.resumeRequestedWorkflow({ runRoot, request });
1327
1348
  }
1349
+ } catch (error) {
1350
+ if (!isExecutorReady) await startup.fail(errorMessage(error));
1351
+ throw error;
1328
1352
  } finally {
1329
- if (request.type === "run")
1330
- await rm(join(runRoot, "launch-request.json"), { force: true });
1331
- else await removeResumeRequest({ runRoot, request });
1353
+ if (request.type === "run") {
1354
+ if (isExecutorReady)
1355
+ await rm(join(runRoot, "launch-request.json"), { force: true });
1356
+ } else await removeResumeRequest({ runRoot, request });
1332
1357
  }
1333
1358
  }
1334
1359
 
@@ -1414,68 +1439,6 @@ async function writeRunLogs(
1414
1439
  }
1415
1440
  }
1416
1441
 
1417
- async function startDetachedExecuteRun(
1418
- runId: string,
1419
- projectRoot: string,
1420
- ): Promise<void> {
1421
- const child = spawn(process.execPath, detachedExecuteRunArgs(runId), {
1422
- cwd: projectRoot,
1423
- detached: true,
1424
- stdio: "ignore",
1425
- });
1426
- await new Promise<void>((resolveSpawn, reject) => {
1427
- child.once("spawn", resolveSpawn);
1428
- child.once("error", reject);
1429
- });
1430
- child.unref();
1431
- }
1432
-
1433
- function detachedExecuteRunArgs(runId: string): readonly string[] {
1434
- if (NORN_BUILD_INFO.kind === "github-release-binary")
1435
- return ["execute-run", runId];
1436
- const scriptPath = process.argv[1];
1437
- return scriptPath &&
1438
- isAbsolute(scriptPath) &&
1439
- /\.(?:c?m?js|ts)$/.test(scriptPath)
1440
- ? [scriptPath, "execute-run", runId]
1441
- : ["execute-run", runId];
1442
- }
1443
-
1444
- function startedRunInfo(input: {
1445
- readonly projectRoot: string;
1446
- readonly id: string;
1447
- readonly name: string;
1448
- readonly workflow: NornAnyWorkflowDeclaration;
1449
- readonly runRoot: string;
1450
- readonly createdAt: string;
1451
- }): NornRunInfo {
1452
- return {
1453
- version: 2,
1454
- id: input.id,
1455
- name: input.name,
1456
- path: input.runRoot,
1457
- paths: {
1458
- project: input.projectRoot,
1459
- workspace: join(input.runRoot, "current", "workspace"),
1460
- },
1461
- entrypointWorkflowId: input.workflow.id,
1462
- currentWorkflowId: input.workflow.id,
1463
- status: "running",
1464
- health: "healthy",
1465
- startedAt: input.createdAt,
1466
- updatedAt: input.createdAt,
1467
- };
1468
- }
1469
-
1470
- async function readOptionalRunLaunchRequest(runRoot: string) {
1471
- try {
1472
- return await readRunLaunchRequest(runRoot);
1473
- } catch (error) {
1474
- if (isNodeError(error) && error.code === "ENOENT") return undefined;
1475
- throw error;
1476
- }
1477
- }
1478
-
1479
1442
  async function readRunEvents(
1480
1443
  runRoot: string,
1481
1444
  ): Promise<readonly Record<string, unknown>[]> {
@@ -1590,6 +1553,8 @@ function writeJson(value: unknown): void {
1590
1553
  }
1591
1554
 
1592
1555
  function errorCode(error: unknown): string {
1556
+ if (error instanceof NornExecutorStartupError)
1557
+ return "EXECUTOR_STARTUP_FAILED";
1593
1558
  if (error instanceof NornProjectLoadError) return error.code;
1594
1559
  if (error instanceof SyntaxError) return "INVALID_JSON";
1595
1560
  return "NORN_ERROR";
@@ -2,8 +2,8 @@ import type { NornBuildInfo } from "./build-info.ts";
2
2
 
3
3
  export const NORN_GENERATED_BUILD_INFO = {
4
4
  "kind": "npm-registry",
5
- "version": "0.1.0-tip.37310387847.1",
6
- "commit": "420fa7a452c99a457adc3f9da36fc96518ed1e05",
5
+ "version": "0.1.0-tip.43698584363.1",
6
+ "commit": "e1b2d1939aba289ce196184c705548d66ba90149",
7
7
  "packageSpec": "@vimhead.dev/norn-cli@tip",
8
8
  "upgrade": {
9
9
  "supported": false,
@@ -0,0 +1,99 @@
1
+ import { spawn } from "node:child_process";
2
+ import { mkdir, open } from "node:fs/promises";
3
+ import { dirname } from "node:path";
4
+ import { setTimeout as delay } from "node:timers/promises";
5
+ import { isNodeError } from "@vimhead.dev/norn-core/errors";
6
+ import { errorMessage } from "./errors.ts";
7
+ import {
8
+ NornExecutorStartup,
9
+ NornExecutorStartupError,
10
+ } from "./executor-startup.ts";
11
+ import type {
12
+ NornRunLaunchRequest,
13
+ NornRunResumeRequest,
14
+ } from "./launch-request.ts";
15
+
16
+ export type NornExecutorArgv = readonly [executable: string, ...args: string[]];
17
+
18
+ export class NornDetachedExecutor {
19
+ constructor(
20
+ private readonly input: {
21
+ readonly invocation: NornExecutorArgv;
22
+ readonly startupTimeoutMs: number;
23
+ },
24
+ ) {}
25
+
26
+ async start(input: {
27
+ readonly projectRoot: string;
28
+ readonly runRoot: string;
29
+ readonly request: NornRunLaunchRequest | NornRunResumeRequest;
30
+ }): Promise<void> {
31
+ const startup = new NornExecutorStartup(input);
32
+ await mkdir(dirname(startup.diagnosticsPath), { recursive: true });
33
+ const output = await open(startup.diagnosticsPath, "a", 0o600);
34
+ try {
35
+ await startup.begin();
36
+ const child = spawn(
37
+ this.input.invocation[0],
38
+ [...this.input.invocation.slice(1), "execute-run", input.request.id],
39
+ {
40
+ cwd: input.projectRoot,
41
+ detached: true,
42
+ stdio: ["ignore", output.fd, output.fd],
43
+ },
44
+ );
45
+ let exitReason: string | undefined;
46
+ const exited = new Promise<void>((resolveExit) => {
47
+ child.once("error", (error) => {
48
+ exitReason = errorMessage(error);
49
+ resolveExit();
50
+ });
51
+ child.once("exit", (code, signal) => {
52
+ exitReason = `Executor exited before initialization (${signal ? `signal ${signal}` : `code ${code}`})`;
53
+ resolveExit();
54
+ });
55
+ });
56
+ const deadline = Date.now() + this.input.startupTimeoutMs;
57
+ try {
58
+ while (true) {
59
+ const result = await startup.readResult();
60
+ if (result?.status === "ready") return;
61
+ if (exitReason !== undefined)
62
+ throw new Error(
63
+ result?.status === "failed" ? result.error : exitReason,
64
+ );
65
+ if (Date.now() >= deadline)
66
+ throw new Error(
67
+ `Executor did not initialize within ${this.input.startupTimeoutMs}ms`,
68
+ );
69
+ await Promise.race([exited, delay(25)]);
70
+ }
71
+ } catch (error) {
72
+ if (exitReason === undefined && child.pid !== undefined) {
73
+ try {
74
+ if (process.platform === "win32") child.kill("SIGKILL");
75
+ else process.kill(-child.pid, "SIGKILL");
76
+ } catch (killError) {
77
+ if (!isNodeError(killError) || killError.code !== "ESRCH")
78
+ throw killError;
79
+ }
80
+ await exited;
81
+ }
82
+ throw error;
83
+ } finally {
84
+ child.unref();
85
+ }
86
+ } catch (error) {
87
+ const reason = errorMessage(error);
88
+ await startup.fail(reason);
89
+ throw new NornExecutorStartupError({
90
+ runId: input.request.id,
91
+ runRoot: input.runRoot,
92
+ diagnosticsPath: startup.diagnosticsPath,
93
+ reason,
94
+ });
95
+ } finally {
96
+ await output.close();
97
+ }
98
+ }
99
+ }
@@ -11,13 +11,14 @@ import {
11
11
  } from "@vimhead.dev/norn";
12
12
  import { createRunFileCoordinator } from "./file-coordinator.ts";
13
13
  import { randomUUID } from "node:crypto";
14
- import { mkdir } from "node:fs/promises";
14
+ import { mkdir, rm } from "node:fs/promises";
15
15
  import { dirname, join, resolve } from "node:path";
16
16
  import { Value } from "typebox/value";
17
17
  import { NornAgentResponseCollector } from "./agent-response-tool.ts";
18
18
  import { errorMessage, NornRunStoppedError } from "./errors.ts";
19
19
  import {
20
20
  clearRunResumeRequest,
21
+ LAUNCH_REQUEST_FILE_NAME,
21
22
  matchesRunResumeRequest,
22
23
  readOptionalRunResumeRequest,
23
24
  RESUME_START_GRACE_MS,
@@ -52,6 +53,7 @@ export type NornEngineInput = {
52
53
  readonly responseCollector?: NornAgentResponseCollector;
53
54
  readonly gateMode?: "auto" | "pause";
54
55
  readonly config?: Record<string, unknown>;
56
+ readonly onExecutorReady?: () => Promise<void>;
55
57
  };
56
58
 
57
59
  type RunSession = {
@@ -153,6 +155,7 @@ export class NornEngine {
153
155
  const state = await NornRunStateStore.load(stagedRunRoot);
154
156
  await state.prepareForResumeAfterRollback();
155
157
  });
158
+ await rm(join(runRoot, LAUNCH_REQUEST_FILE_NAME), { force: true });
156
159
  if (pendingRequest)
157
160
  await clearRunResumeRequest({
158
161
  runRoot,
@@ -275,6 +278,7 @@ export class NornEngine {
275
278
  ): Promise<NornRunResult> {
276
279
  let currentStep = initialStep;
277
280
  try {
281
+ await this.input.onExecutorReady?.();
278
282
  for (let step = 1; step <= 1_000; step++) {
279
283
  throwIfRunAborted(session.activeRun);
280
284
  if (shouldPauseForGate(currentStep)) {
@@ -0,0 +1,97 @@
1
+ import { createHash } from "node:crypto";
2
+ import { readFile } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { writeJsonAtomically } from "@vimhead.dev/norn-core/atomic-files";
5
+ import { isNodeError } from "@vimhead.dev/norn-core/errors";
6
+ import type {
7
+ NornRunLaunchRequest,
8
+ NornRunResumeRequest,
9
+ } from "./launch-request.ts";
10
+
11
+ export const EXECUTOR_START_TIMEOUT_MS = 60_000;
12
+
13
+ type ExecutorStartupResult =
14
+ | { readonly status: "starting"; readonly at: string }
15
+ | { readonly status: "ready"; readonly at: string }
16
+ | { readonly status: "failed"; readonly at: string; readonly error: string };
17
+
18
+ export class NornExecutorStartup {
19
+ readonly resultPath: string;
20
+ readonly diagnosticsPath: string;
21
+
22
+ constructor(input: {
23
+ readonly runRoot: string;
24
+ readonly request: NornRunLaunchRequest | NornRunResumeRequest;
25
+ }) {
26
+ const request = input.request;
27
+ const identity =
28
+ request.type === "run"
29
+ ? request.id
30
+ : (request.requestId ?? request.createdAt);
31
+ const attempt = createHash("sha256")
32
+ .update(`${request.type}:${identity}`)
33
+ .digest("hex");
34
+ this.resultPath = join(input.runRoot, "executor", `${attempt}.json`);
35
+ this.diagnosticsPath = join(input.runRoot, "executor", `${attempt}.log`);
36
+ }
37
+
38
+ async readResult(): Promise<ExecutorStartupResult | undefined> {
39
+ try {
40
+ const result: ExecutorStartupResult = JSON.parse(
41
+ await readFile(this.resultPath, "utf8"),
42
+ );
43
+ if (
44
+ (result.status !== "starting" &&
45
+ result.status !== "ready" &&
46
+ result.status !== "failed") ||
47
+ typeof result.at !== "string" ||
48
+ Number.isNaN(Date.parse(result.at)) ||
49
+ (result.status === "failed" && typeof result.error !== "string")
50
+ )
51
+ throw new Error(`Invalid executor startup result: ${this.resultPath}`);
52
+ return result;
53
+ } catch (error) {
54
+ if (isNodeError(error) && error.code === "ENOENT") return undefined;
55
+ throw error;
56
+ }
57
+ }
58
+
59
+ async begin(): Promise<void> {
60
+ await writeJsonAtomically(this.resultPath, {
61
+ status: "starting",
62
+ at: new Date().toISOString(),
63
+ });
64
+ }
65
+
66
+ async acknowledge(): Promise<void> {
67
+ const result = await this.readResult();
68
+ if (result?.status === "failed") throw new Error(result.error);
69
+ await writeJsonAtomically(this.resultPath, {
70
+ status: "ready",
71
+ at: new Date().toISOString(),
72
+ });
73
+ }
74
+
75
+ async fail(error: string): Promise<void> {
76
+ await writeJsonAtomically(this.resultPath, {
77
+ status: "failed",
78
+ at: new Date().toISOString(),
79
+ error,
80
+ });
81
+ }
82
+ }
83
+
84
+ export class NornExecutorStartupError extends Error {
85
+ constructor(
86
+ readonly details: {
87
+ readonly runId: string;
88
+ readonly runRoot: string;
89
+ readonly diagnosticsPath: string;
90
+ readonly reason: string;
91
+ },
92
+ ) {
93
+ super(
94
+ `Executor startup failed for run ${details.runId}: ${details.reason}. Diagnostics: ${details.diagnosticsPath}`,
95
+ );
96
+ }
97
+ }
@@ -44,6 +44,17 @@ export async function readRunLaunchRequest(
44
44
  );
45
45
  }
46
46
 
47
+ export async function readOptionalRunLaunchRequest(
48
+ runRoot: string,
49
+ ): Promise<NornRunLaunchRequest | undefined> {
50
+ try {
51
+ return await readRunLaunchRequest(runRoot);
52
+ } catch (error) {
53
+ if (isNodeError(error) && error.code === "ENOENT") return undefined;
54
+ throw error;
55
+ }
56
+ }
57
+
47
58
  export async function writeRunResumeRequest(
48
59
  runRoot: string,
49
60
  request: NornRunResumeRequest,
@@ -9,7 +9,8 @@ import type {
9
9
  NornWorkflowMetrics,
10
10
  } from "@vimhead.dev/norn";
11
11
  import { runCurrentRoot } from "./run-store.ts";
12
- import { RUN_STATE_FILE_NAME } from "./run-state.ts";
12
+ import { getRunInfo, RUN_STATE_FILE_NAME } from "./run-state.ts";
13
+ import { readOptionalRunLaunchRequest } from "./launch-request.ts";
13
14
  import { isNodeError } from "@vimhead.dev/norn-core/errors";
14
15
  import {
15
16
  addAgentUsage,
@@ -60,11 +61,21 @@ type OpenCommandMetrics = {
60
61
 
61
62
  export async function readRunMetrics(runRoot: string): Promise<NornRunMetrics> {
62
63
  const currentRoot = runCurrentRoot(runRoot);
63
- const [state, events] = await Promise.all([
64
- readRunStateSnapshot(currentRoot),
65
- readManifestEvents(join(currentRoot, "manifest.json")),
66
- ]);
67
- return calculateRunMetrics(events, state, new Date());
64
+ try {
65
+ const [state, events] = await Promise.all([
66
+ readRunStateSnapshot(currentRoot),
67
+ readManifestEvents(join(currentRoot, "manifest.json")),
68
+ ]);
69
+ return calculateRunMetrics(events, state, new Date());
70
+ } catch (error) {
71
+ if (
72
+ !isNodeError(error) ||
73
+ error.code !== "ENOENT" ||
74
+ !(await readOptionalRunLaunchRequest(runRoot))
75
+ )
76
+ throw error;
77
+ return calculateRunMetrics([], await getRunInfo(runRoot), new Date());
78
+ }
68
79
  }
69
80
 
70
81
  export function calculateRunMetrics(