omp-superagent 0.1.17 → 0.1.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/DESIGN.md +15 -12
  2. package/config.example.json +4 -1
  3. package/docs/OPERATIONS.en.md +205 -59
  4. package/docs/OPERATIONS.md +173 -47
  5. package/docs/design/execution.md +119 -37
  6. package/docs/design/messaging.md +160 -45
  7. package/docs/releases/0.1.18.md +10 -0
  8. package/docs/releases/0.1.19.md +10 -0
  9. package/gateway/bin/omp-gateway-darwin-arm64 +0 -0
  10. package/gateway/bin/omp-gateway-darwin-x64 +0 -0
  11. package/gateway/bin/omp-gateway-linux-arm64 +0 -0
  12. package/gateway/bin/omp-gateway-linux-x64 +0 -0
  13. package/host-owner/bin/omp-host-owner-darwin-arm64 +0 -0
  14. package/host-owner/bin/omp-host-owner-darwin-x64 +0 -0
  15. package/host-owner/bin/omp-host-owner-linux-arm64 +0 -0
  16. package/host-owner/bin/omp-host-owner-linux-x64 +0 -0
  17. package/package.json +1 -1
  18. package/skills/head/SKILL.md +6 -5
  19. package/skills/head/references/model-selection.md +8 -22
  20. package/skills/head/references/routing.md +36 -17
  21. package/skills/lane/SKILL.md +24 -76
  22. package/skills/lane/references/workflow.md +7 -94
  23. package/src/cli.ts +36 -16
  24. package/src/config/config.ts +21 -2
  25. package/src/contracts.ts +66 -7
  26. package/src/cron/cron-jobs.ts +135 -92
  27. package/src/cron/cron-pr-intake.ts +18 -11
  28. package/src/extension.ts +25 -10
  29. package/src/gateway/gateway-client.ts +3 -1
  30. package/src/host-extension.ts +76 -8
  31. package/src/lane/lane-report.ts +1 -1
  32. package/src/lane/lane-rows.ts +2 -1
  33. package/src/lane/workflow.ts +12 -6
  34. package/src/lane-extension.ts +4 -21
  35. package/src/managed-super-probe.ts +21 -15
  36. package/src/messaging/messenger-command-catalog.json +1 -1
  37. package/src/messaging/messenger-commands.ts +8 -3
  38. package/src/messaging/result-attachment.ts +77 -19
  39. package/src/messaging/slack-context.ts +50 -0
  40. package/src/messaging/written-directives.ts +56 -0
  41. package/src/omp/exit-record.ts +27 -0
  42. package/src/omp/host-protocol.ts +20 -0
  43. package/src/omp/host.ts +73 -20
  44. package/src/omp/installed-omp.ts +15 -12
  45. package/src/omp/managed-super.ts +135 -65
  46. package/src/omp/superkit-skills.ts +15 -2
  47. package/src/pr/pr-intake-order.ts +62 -0
  48. package/src/pr/pr-intake-review.ts +49 -31
  49. package/src/pr/pr-intake-work.ts +3 -2
  50. package/src/routing/message-order.ts +22 -1
  51. package/src/routing/topic-request.ts +48 -4
  52. package/src/runtime/controller.ts +968 -338
  53. package/src/runtime/deferred-routing.ts +12 -4
  54. package/src/runtime/dm-timeline.ts +3 -3
  55. package/src/runtime/inbound-attachments.ts +70 -0
  56. package/src/runtime/local-host-fence.ts +85 -0
  57. package/src/runtime/model-journal.ts +14 -9
  58. package/src/runtime/native-frames.ts +5 -1
  59. package/src/runtime/result-attachments.ts +151 -24
  60. package/src/runtime/worker-result-download.ts +36 -0
  61. package/src/storage/deferred-routing.ts +25 -4
  62. package/src/storage/store.ts +445 -75
  63. package/src/worker/worker-checkout.ts +89 -9
  64. package/src/worker/worker-destination.ts +8 -7
  65. package/src/worker/worker-doctor.ts +29 -9
  66. package/src/worker/worker-enrollment.ts +44 -12
  67. package/src/worker/worker-git-startup.ts +157 -0
  68. package/src/worker/worker-host.ts +16 -26
  69. package/src/worker/worker-ledger.ts +42 -18
  70. package/src/worker/worker-placement-intent.ts +13 -0
  71. package/src/worker/worker-placement.ts +204 -28
  72. package/src/worker/worker-profile.ts +18 -65
  73. package/src/worker/worker-project-startup.ts +106 -0
  74. package/src/worker/worker-registration.ts +85 -30
  75. package/src/worker/worker-repository.ts +55 -6
  76. package/src/worker/worker-request.ts +13 -6
  77. package/src/worker/worker-result-attachments.ts +185 -0
  78. package/src/worker/worker-result-wire.ts +12 -0
  79. package/src/worker/worker-service.ts +51 -23
  80. package/src/worker/worker-trust.ts +19 -4
  81. package/src/worker/worker-wire.ts +47 -14
  82. package/upstream/super.json +2 -3
package/src/omp/host.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { spawn, type ChildProcess } from "node:child_process";
2
+ import { once } from "node:events";
2
3
  import { constants, type Stats } from "node:fs";
3
4
  import * as fs from "node:fs/promises";
4
5
  import * as net from "node:net";
@@ -14,8 +15,9 @@ import { RPC_GOAL_CONTINUATION_MODE } from "@oh-my-pi/pi-coding-agent/modes/rpc/
14
15
  import { HostChannel, PR_REVIEW_GITHUB_ENV, PR_REVIEW_SYSTEM_PROMPT, type HostResponse, type HostState } from "./host-protocol";
15
16
  import { requireHostOwner } from "./host-owner-path";
16
17
  import { inspectInstalledOmp, resolveOmpCommand } from "./installed-omp";
17
- import type { DialogResponse, LanePresetSnapshot } from "../contracts";
18
+ import type { DialogResponse, LanePresetSnapshot, LocalHostIdentity } from "../contracts";
18
19
  import type { WorkerHostProfile } from "../worker/worker-profile";
20
+ import { matchesWorkerCheckoutDirectory, type WorkerCheckoutPin } from "../worker/worker-checkout";
19
21
  import { WORKER_MEMORY_PROFILE_ENV, type WorkerMemoryBinding } from "../worker/worker-memory-storage";
20
22
  import { activeManagedUlw, managedUlwLaunch, MANAGED_ULW_ENV, MANAGED_ULW_FIXTURE_ENV, MANAGED_ULW_FIXTURE_ROOT_ENV, validateManagedUlwPackage } from "./managed-super";
21
23
 
@@ -53,6 +55,10 @@ export interface HostOptions {
53
55
  readonly prReviewOnly?: true;
54
56
  /** Target-owned launch policy, never decoded from an SSH request. */
55
57
  readonly worker?: WorkerHostProfile;
58
+ /** Exact target checkout admitted for worker-current placement. */
59
+ readonly workerCheckoutPin?: WorkerCheckoutPin;
60
+ /** Admitted cwd inode for result copy on non-current worker lanes. */
61
+ readonly workerResultWorkspace?: string;
56
62
  socketPath: string;
57
63
  sessionFile: string;
58
64
  cwd: string;
@@ -74,6 +80,8 @@ export interface HostOptions {
74
80
 
75
81
  export type HostFrame = Record<string, unknown>;
76
82
 
83
+ const unspawnedWorkerAttempts = new WeakMap<HostStartError, string>();
84
+
77
85
  export class HostStartError extends Error {
78
86
  constructor(message: string, options?: ErrorOptions) {
79
87
  super(message, options);
@@ -81,6 +89,10 @@ export class HostStartError extends Error {
81
89
  }
82
90
  }
83
91
 
92
+ export function workerOwnerWasNotSpawned(error: unknown, attempt: string): boolean {
93
+ return error instanceof HostStartError && unspawnedWorkerAttempts.get(error) === attempt;
94
+ }
95
+
84
96
  function assertSocketPath(socketPath: string): void {
85
97
  // Match the core host's portable limit, including macOS sockaddr_un.
86
98
  if (!path.isAbsolute(socketPath) || Buffer.byteLength(socketPath) > 100) {
@@ -173,6 +185,8 @@ export class HostConnection {
173
185
  readonly exited: Promise<void>;
174
186
  readonly #listeners = new Set<(frame: HostFrame) => void>();
175
187
  readonly #channel: HostChannel;
188
+ #localIdentity?: LocalHostIdentity;
189
+ get localIdentity() { return this.#localIdentity; }
176
190
  #close: Promise<void> | undefined;
177
191
 
178
192
  private constructor(transport: SocketProcess) {
@@ -242,12 +256,14 @@ export class HostConnection {
242
256
  try {
243
257
  const state = await connection.#handshake();
244
258
  const after = await socketIdentity(socketPath);
245
- if (before.dev !== after.dev || before.ino !== after.ino) {
259
+ if (before.dev !== after.dev || before.ino !== after.ino || before.ctimeMs !== after.ctimeMs) {
246
260
  throw new Error("RPC socket identity changed while connecting");
247
261
  }
248
262
  if (messageUpdates === "activity-v1") await connection.#enableActivityUpdates(state);
249
- return { connection, state, identity: { pid: state.hostPid, ownerPid: state.adapterOwnerPid,
250
- sessionId: state.sessionId, sessionFile: state.sessionFile, dev: after.dev, ino: after.ino } };
263
+ const identity = { pid: state.hostPid, ownerPid: state.adapterOwnerPid,
264
+ sessionId: state.sessionId, sessionFile: state.sessionFile, dev: after.dev, ino: after.ino };
265
+ connection.#localIdentity = { ...identity, ctimeMs: after.ctimeMs };
266
+ return { connection, state, identity };
251
267
  } catch (error) {
252
268
  await connection.close();
253
269
  throw error;
@@ -328,7 +344,8 @@ async function assertPrReviewState(state: HostState, cwd: string): Promise<void>
328
344
  }
329
345
 
330
346
  async function assertPrReviewLaunch(options: HostOptions): Promise<void> {
331
- if (options.worker || options.modelPreset || options.modelSettings || options.env.OMP_SUPERAGENT_WORKER_ATTEMPT)
347
+ if (options.worker || options.workerCheckoutPin || options.workerResultWorkspace || options.modelPreset ||
348
+ options.modelSettings || options.env.OMP_SUPERAGENT_WORKER_ATTEMPT)
332
349
  throw new Error("Static PR review requires an exact-model local Host, without worker or preset policy");
333
350
  const { extractProfileFlags } = await import("@oh-my-pi/pi-coding-agent/cli/profile-bootstrap");
334
351
  const bootstrap = extractProfileFlags(options.command.slice(1));
@@ -391,15 +408,28 @@ function selectManagedUlw(options: HostOptions): string {
391
408
  }
392
409
 
393
410
  /** Launch only a new host. Existing endpoints require the caller's explicit adoption decision. */
394
- export async function startHost(options: HostOptions, beforeSessionPrepare?: (memory?: WorkerMemoryBinding) => void): Promise<{ pid: number }> {
395
- try { return await launchHost(options, beforeSessionPrepare); }
411
+ export async function startHost(options: HostOptions, beforeSessionPrepare?: (memory?: WorkerMemoryBinding) => void) {
412
+ const lifecycle = { ownerMayExist: false };
413
+ const workerAttempt = options.worker && options.env.OMP_SUPERAGENT_WORKER_ATTEMPT;
414
+ try { return await launchHost(options, lifecycle, beforeSessionPrepare); }
396
415
  catch (cause) {
397
416
  // Never read child output into errors: logs can contain credentials or prompt content.
398
- throw new HostStartError(cause instanceof Error ? cause.message : "OMP host startup failed", { cause });
417
+ const error = new HostStartError(cause instanceof Error ? cause.message : "OMP host startup failed", { cause });
418
+ // In-process proof from this invocation only: neither a prepared journal,
419
+ // a missing socket nor a dead launcher can attest that spawn never happened.
420
+ if (workerAttempt && !lifecycle.ownerMayExist) unspawnedWorkerAttempts.set(error, workerAttempt);
421
+ throw error;
399
422
  }
400
423
  }
401
424
 
402
- async function launchHost(options: HostOptions, beforeSessionPrepare?: (memory?: WorkerMemoryBinding) => void): Promise<{ pid: number }> {
425
+ async function launchHost(options: HostOptions, lifecycle: { ownerMayExist: boolean },
426
+ beforeSessionPrepare?: (memory?: WorkerMemoryBinding) => void) {
427
+ const checkoutPin = options.workerCheckoutPin;
428
+ const requirePinnedDirectory = () => {
429
+ if (checkoutPin && !matchesWorkerCheckoutDirectory(options.cwd, checkoutPin))
430
+ throw new Error("Worker-current checkout directories changed during Host preparation");
431
+ };
432
+ requirePinnedDirectory();
403
433
  // Snapshot once before any awaits; an updater may activate a newer revision
404
434
  // during startup, but this Host must load one exact immutable package.
405
435
  if (options.prReviewOnly) {
@@ -416,7 +446,7 @@ async function launchHost(options: HostOptions, beforeSessionPrepare?: (memory?:
416
446
  })) throw new Error("Static PR review workspace must be outside a Git checkout");
417
447
  if (path.dirname(dir) === dir) break;
418
448
  }
419
- const { assertWorkerWorkspaceStartup } = await import("../worker/worker-profile");
449
+ const { assertWorkerWorkspaceStartup } = await import("../worker/worker-project-startup");
420
450
  assertWorkerWorkspaceStartup(cwd, options.env.HOME ?? "");
421
451
  const env = { ...options.env };
422
452
  for (const name of [...PR_REVIEW_GITHUB_ENV,
@@ -450,9 +480,6 @@ async function launchHost(options: HostOptions, beforeSessionPrepare?: (memory?:
450
480
  throw new Error(`RPC socket already hosts session ${state.sessionId} at ${state.sessionFile}; explicit adoption required`);
451
481
  } finally { await connection.close(); }
452
482
  }
453
- const { executable, processBackend } = await inspectInstalledOmp(options.command, [], options.env);
454
- options = { ...options, command: [executable, ...options.command.slice(1)] };
455
-
456
483
  const launchDirectory = await fs.mkdtemp(path.join(path.dirname(options.socketPath), ".launch-"));
457
484
  const configPath = path.join(launchDirectory, "config.json");
458
485
  let child: ChildProcess | undefined;
@@ -461,6 +488,9 @@ async function launchHost(options: HostOptions, beforeSessionPrepare?: (memory?:
461
488
  let cleanup: Promise<void> | undefined;
462
489
  const cleanLaunch = () => cleanup ??= fs.rm(launchDirectory, { recursive: true });
463
490
  try {
491
+ const { executable, processBackend } = await inspectInstalledOmp(options.command, [], options.env,
492
+ options.worker ? launchDirectory : undefined);
493
+ options = { ...options, command: [executable, ...options.command.slice(1)] };
464
494
  const initialSettings = options.modelPreset?.preset ?? options.modelSettings;
465
495
  const hostSettings = {
466
496
  ...options.worker?.config,
@@ -475,7 +505,7 @@ async function launchHost(options: HostOptions, beforeSessionPrepare?: (memory?:
475
505
  },
476
506
  ...(initialSettings.defaultThinkingLevel !== undefined
477
507
  ? { defaultThinkingLevel: initialSettings.defaultThinkingLevel } : {}),
478
- } : options.model ? { modelRoles: { default: options.model } } : {}),
508
+ } : options.model ? { modelRoles: { ...options.worker?.config.modelRoles, default: options.model } } : {}),
479
509
  };
480
510
  await fs.writeFile(configPath, JSON.stringify(hostSettings), { flag: "wx", mode: 0o600 });
481
511
  log = await fs.open(options.logPath, constants.O_WRONLY | constants.O_APPEND | constants.O_CREAT | constants.O_NOFOLLOW, 0o600);
@@ -496,10 +526,14 @@ async function launchHost(options: HostOptions, beforeSessionPrepare?: (memory?:
496
526
  // is sent. Preparation and owner startup share the same deadline.
497
527
  const { composition, prepared, deadline } = await managedUlwLaunch({ cwd: options.cwd, managedUlwPath,
498
528
  extensionPaths, configPath, parentConfigPath: process.env.OMP_SUPERAGENT_HOST_CONFIG, commandArgs: options.command.slice(1),
499
- ...(options.worker ? { worker: { extensionPaths: options.worker.extensionPaths, memory: options.worker.memory } } : {}),
529
+ ...(options.worker ? { worker: { extensionPaths: options.worker.extensionPaths, memory: options.worker.memory,
530
+ trustedWorkspaceRoot: options.worker.trustedWorkspaceRoot } } : {}),
500
531
  launchArgs: managedUlwPath === undefined ? [] : [...options.command.slice(1), ...await buildHostArgs(options, configPath)],
501
532
  env: options.env, bunCommand: [bun, "--no-env-file"] }, {
502
- stderr: log.fd, timeoutMs: START_TIMEOUT_MS, beforeManifest: () => beforeSessionPrepare?.(workerMemory?.binding),
533
+ stderr: log.fd, timeoutMs: START_TIMEOUT_MS, beforeManifest: () => {
534
+ requirePinnedDirectory();
535
+ beforeSessionPrepare?.(workerMemory?.binding);
536
+ },
503
537
  manifest: async composition => {
504
538
  if (options.worker?.memory?.previous && !composition.workerMemory && !composition.workerMemoryDormant)
505
539
  throw new Error("Worker memory cannot resume without its verified private bank");
@@ -520,6 +554,7 @@ async function launchHost(options: HostOptions, beforeSessionPrepare?: (memory?:
520
554
  return manifest;
521
555
  },
522
556
  });
557
+ requirePinnedDirectory();
523
558
  if (deadline === undefined || prepared === undefined) throw new Error("Native session preparation did not confirm tool selection");
524
559
  if (performance.now() >= deadline) throw new Error("Native session preparation timed out");
525
560
  const flags = JSON.parse(prepared);
@@ -534,17 +569,30 @@ async function launchHost(options: HostOptions, beforeSessionPrepare?: (memory?:
534
569
  noTools: flags.noTools, ...(options.prReviewOnly ? { emptyToolSelection: true } : {}),
535
570
  inventory: flags.inventory, nativeProfileBinding: flags.nativeProfileBinding, replayableArgvHash: flags.replayableArgvHash }), { flag: "wx", mode: 0o600 });
536
571
  if (performance.now() >= deadline) throw new Error("Native Host startup timed out before launch");
572
+ const env = workerMemory ? { ...options.env, ...workerMemory.env,
573
+ [WORKER_MEMORY_PROFILE_ENV]: JSON.stringify(flags.workerMemoryProfileBinding ?? null) } : options.env;
574
+ // From the moment spawn is invoked a crash or an unknown failure must be
575
+ // treated as potentially owning a process, even before a socket exists.
576
+ lifecycle.ownerMayExist = true;
537
577
  child = spawn(hostOwnerExecutable, [manifestPath], {
538
- cwd: options.cwd, env: workerMemory ? { ...options.env, ...workerMemory.env,
539
- [WORKER_MEMORY_PROFILE_ENV]: JSON.stringify(flags.workerMemoryProfileBinding ?? null) } : options.env,
578
+ cwd: options.worker ? launchDirectory : options.cwd, env,
540
579
  detached: true, stdio: ["ignore", log.fd, log.fd], shell: false,
541
580
  });
542
- child.once("error", error => { failure = error; });
581
+ const owner = child;
582
+ owner.once("error", error => {
583
+ // child_process reports a failed OS spawn without assigning a child PID.
584
+ if (owner.pid === undefined && "syscall" in error && error.syscall === `spawn ${hostOwnerExecutable}`)
585
+ lifecycle.ownerMayExist = false;
586
+ failure = error;
587
+ });
543
588
  child.once("exit", (code, signal) => {
544
589
  failure = new Error(`OMP host exited during startup (${signal ?? code}); see ${options.logPath}`);
545
590
  void cleanLaunch().catch(() => {});
546
591
  });
547
592
  child.unref();
593
+ // With no PID yet, obtain the spawn/error notification before the
594
+ // next readiness deadline check can obscure a definitive spawn failure.
595
+ if (owner.pid === undefined) await once(owner, "spawn");
548
596
  await log.close();
549
597
  log = undefined;
550
598
  let startingSocket: Stats | undefined;
@@ -583,8 +631,13 @@ async function launchHost(options: HostOptions, beforeSessionPrepare?: (memory?:
583
631
  throw new Error("Launched RPC host identified a different session file");
584
632
  }
585
633
  if (options.prReviewOnly) await assertPrReviewState(state, options.cwd);
634
+ if (checkoutPin && (state.workerCheckoutProof?.checkoutIdentity !== checkoutPin.checkoutIdentity ||
635
+ state.workerCheckoutProof.revision !== checkoutPin.revision ||
636
+ !matchesWorkerCheckoutDirectory(options.cwd, checkoutPin))) {
637
+ throw new Error("Native Host did not confirm the admitted worker-current checkout");
638
+ }
586
639
  if (failure) throw failure;
587
- return { pid: identity.pid };
640
+ return { pid: identity.pid, localIdentity: connection.localIdentity };
588
641
  } finally { await connection.close(); }
589
642
  }
590
643
  throw new Error(`OMP host startup timed out; see ${options.logPath}`);
@@ -116,27 +116,30 @@ function executionIdentity(
116
116
  * repeated Host starts do not respawn the probes.
117
117
  */
118
118
  export async function inspectInstalledOmp(
119
- command: string[], credentials: string[] = [], environment: NodeJS.ProcessEnv = process.env,
119
+ command: string[], credentials: string[] = [], environment: NodeJS.ProcessEnv = process.env, cwd = process.cwd(),
120
120
  ): Promise<InstalledOmp> {
121
121
  const path = environment.PATH ?? "";
122
- const [entry] = resolveOmpCommand(command, path);
122
+ const [entry] = resolveOmpCommand(command, path, cwd);
123
123
  const executable = entry && (isAbsolute(entry) ? entry : Bun.which(entry, { PATH: path }));
124
124
  if (!executable) throw new Error(`Cannot find the configured OMP executable ${entry ?? ""} on PATH`);
125
- let identity: string | null;
126
- try { identity = executionIdentity(executable, path, credentials, environment); }
127
- catch { return probeInstalledOmp(executable, credentials, environment); }
128
- if (identity === null) return probeInstalledOmp(executable, credentials, environment);
125
+ const inspect = () => probeInstalledOmp(executable, credentials, environment, cwd);
126
+ const identify = () => {
127
+ try {
128
+ const identity = executionIdentity(executable, path, credentials, environment);
129
+ return identity === null ? null : JSON.stringify([cwd, identity]);
130
+ } catch { return null; } // An unidentifiable executable must be probed without caching.
131
+ };
132
+ const identity = identify();
133
+ if (identity === null) return inspect();
129
134
  const cached = inspected.get(executable);
130
135
  if (cached?.identity === identity) return cached.result;
131
- const result = probeInstalledOmp(executable, credentials, environment);
136
+ const result = inspect();
132
137
  inspected.set(executable, { identity, result });
133
138
  const forget = () => { if (inspected.get(executable)?.result === result) inspected.delete(executable); };
134
139
  try {
135
140
  const value = await result;
136
141
  // A file replaced while it was probed may not be the one that answered.
137
- let unchanged = false;
138
- try { unchanged = executionIdentity(executable, path, credentials, environment) === identity; } catch {}
139
- if (!unchanged) forget();
142
+ if (identify() !== identity) forget();
140
143
  return value;
141
144
  } catch (error) {
142
145
  forget();
@@ -145,7 +148,7 @@ export async function inspectInstalledOmp(
145
148
  }
146
149
 
147
150
  async function probeInstalledOmp(
148
- executable: string, credentials: string[], environment: NodeJS.ProcessEnv,
151
+ executable: string, credentials: string[], environment: NodeJS.ProcessEnv, cwd: string,
149
152
  ) {
150
153
  const env = { ...environment };
151
154
  for (const name of credentials) delete env[name];
@@ -155,7 +158,7 @@ async function probeInstalledOmp(
155
158
  const child = Bun.spawn([executable, ...args], {
156
159
  // Unlike --version, root help loads the CLI's bundled native addon.
157
160
  // Its first extraction and load on macOS can take more than ten seconds.
158
- env, stdin: "ignore", stdout: "pipe", stderr: "ignore", timeout: args[0] === "--version" ? 10_000 : 30_000,
161
+ cwd, env, stdin: "ignore", stdout: "pipe", stderr: "ignore", timeout: args[0] === "--version" ? 10_000 : 30_000,
159
162
  });
160
163
  const [stdout, code] = await Promise.all([new Response(child.stdout).text(), child.exited]);
161
164
  if (code !== 0) throw new Error(`OMP executable ${executable}: ${args.join(" ")} failed (${code}); diagnostic output suppressed to protect credentials`);
@@ -1,4 +1,5 @@
1
1
  import { Database } from "bun:sqlite";
2
+ import { createHash } from "node:crypto";
2
3
  import { lstatSync, readFileSync, realpathSync } from "node:fs";
3
4
  import { chmod, link, lstat, mkdir, mkdtemp, readFile, readdir, realpath, rename, rm, writeFile } from "node:fs/promises";
4
5
  import { dirname, isAbsolute, join, resolve, sep } from "node:path";
@@ -10,6 +11,10 @@ import type { NativeProfile, NativeProfileBinding, NativeProfilePaths } from "./
10
11
  const projectRoot = fileURLToPath(new URL("../../", import.meta.url));
11
12
  const ownership = "omp-superagent-managed-ulw-v1";
12
13
  const hash = /^[0-9a-f]{40,64}$/;
14
+ const sha256 = /^[0-9a-f]{64}$/;
15
+ const releaseVersion = /^v(\d+\.\d+\.\d+)$/;
16
+ const officialReleaseApi = "https://api.github.com/repos/dbc-hbin/omp-superkit/releases/latest";
17
+ const releaseTokenEnv = "OMP_SUPERAGENT_SUPERKIT_GITHUB_TOKEN";
13
18
  export const MANAGED_ULW_ENV = "OMP_SUPERAGENT_MANAGED_ULW_PATH";
14
19
  // Only explicitly injected fixtures propagate. The per-Host revision marker above
15
20
  // is informational: a new lane must resolve the current active revision afresh.
@@ -18,23 +23,25 @@ export const MANAGED_ULW_FIXTURE_ROOT_ENV = "OMP_SUPERAGENT_TEST_MANAGED_ULW_ROO
18
23
 
19
24
  export interface UlwManifest {
20
25
  repository: string;
21
- ref: "HEAD";
26
+ releaseApi: string;
22
27
  directory: string;
23
28
  checkIntervalMs: number;
24
29
  commandTimeoutMs: number;
25
30
  probeTimeoutMs: number;
26
- materialize: string | null;
27
31
  }
28
32
  export interface ManagedUlwStatus {
29
33
  revision: string | null;
34
+ releaseTag: string | null;
30
35
  packagePath: string | null;
31
36
  upstreamRevision: string | null;
37
+ upstreamReleaseTag: string | null;
32
38
  checkedAt: string | null;
33
39
  error: string | null;
34
40
  updating: boolean;
35
41
  injected?: boolean;
36
42
  }
37
- interface ActiveRevision { revision: string; repository: string; branch: string; preparedAt: string }
43
+ type ReleaseIdentity = { readonly tag: string; readonly sha256: string };
44
+ interface ActiveRevision { revision: string; repository: string; branch?: string; release?: ReleaseIdentity; preparedAt: string }
38
45
  interface PackageManifest {
39
46
  name?: string;
40
47
  omp?: { extensions?: string[]; skills?: string[]; [key: string]: unknown };
@@ -57,11 +64,10 @@ function matchesUlwRepository(previous: string, current: string): boolean {
57
64
 
58
65
  export function readUlwManifest(manifestPath = join(projectRoot, "upstream/super.json")): UlwManifest {
59
66
  const value = JSON.parse(readFileSync(manifestPath, "utf8")) as UlwManifest;
60
- if (!value.repository || value.ref !== "HEAD" || !value.directory ||
67
+ if (!value.repository || typeof value.releaseApi !== "string" || !/^https?:\/\//.test(value.releaseApi) || !value.directory ||
61
68
  !Number.isSafeInteger(value.checkIntervalMs) || value.checkIntervalMs < 60_000 ||
62
69
  !Number.isSafeInteger(value.commandTimeoutMs) || value.commandTimeoutMs < 1_000 ||
63
- !Number.isSafeInteger(value.probeTimeoutMs) || value.probeTimeoutMs < 1_000 ||
64
- !(value.materialize === null || typeof value.materialize === "string"))
70
+ !Number.isSafeInteger(value.probeTimeoutMs) || value.probeTimeoutMs < 1_000)
65
71
  throw new Error("Invalid managed ULW manifest");
66
72
  return value;
67
73
  }
@@ -78,10 +84,20 @@ function assertOwned(root: string): void {
78
84
  function readActive(root: string): ActiveRevision | null {
79
85
  try {
80
86
  const value = JSON.parse(readFileSync(join(root, "active.json"), "utf8")) as ActiveRevision;
81
- if (!hash.test(value.revision) || !value.repository || !value.branch) throw new Error("Invalid managed ULW active pointer");
87
+ if (!hash.test(value.revision) || !value.repository ||
88
+ (value.release === undefined ? !value.branch
89
+ : !value.release || typeof value.release.tag !== "string" || !releaseVersion.test(value.release.tag) ||
90
+ typeof value.release.sha256 !== "string" || !sha256.test(value.release.sha256)))
91
+ throw new Error("Invalid managed ULW active pointer");
82
92
  return value;
83
93
  } catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return null; throw error; }
84
94
  }
95
+ function installationDirectory(root: string, active: ActiveRevision): string {
96
+ return active.release ? join(root, "releases", active.release.sha256) : join(root, "revisions", active.revision);
97
+ }
98
+ function sameRelease(a?: ReleaseIdentity, b?: ReleaseIdentity): boolean {
99
+ return a?.tag === b?.tag && a?.sha256 === b?.sha256;
100
+ }
85
101
  export function readManagedUlwPackage(packagePath: string) {
86
102
  if (!isAbsolute(packagePath)) throw new Error("Managed ULW package must have an absolute path");
87
103
  const canonical = realpathSync(packagePath);
@@ -109,9 +125,10 @@ export function activeManagedUlw(options: ManagedUlwOptions = {}): string {
109
125
  }
110
126
  const active = readActive(root);
111
127
  if (!active) throw new Error("Mandatory managed ULW is not installed; run bun run prepare:ulw");
112
- const revisionRoot = join(root, "revisions", active.revision);
128
+ const revisionRoot = installationDirectory(root, active);
113
129
  const provenance = JSON.parse(readFileSync(join(revisionRoot, "provenance.json"), "utf8")) as ActiveRevision;
114
- if (provenance.revision !== active.revision || provenance.repository !== active.repository)
130
+ if (provenance.revision !== active.revision || provenance.repository !== active.repository ||
131
+ !sameRelease(provenance.release, active.release))
115
132
  throw new Error("Managed ULW provenance does not match its active pointer");
116
133
  return validateManagedUlwPackage(join(revisionRoot, "package"));
117
134
  }
@@ -121,8 +138,9 @@ export function managedUlwStatus(options: ManagedUlwOptions = {}): ManagedUlwSta
121
138
  try { saved = JSON.parse(readFileSync(join(root, "status.json"), "utf8")); }
122
139
  catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
123
140
  const active = readActive(root);
124
- return { revision: active?.revision ?? null, packagePath: active ? join(root, "revisions", active.revision, "package") : null,
125
- upstreamRevision: saved.upstreamRevision ?? null, checkedAt: saved.checkedAt ?? null,
141
+ return { revision: active?.revision ?? null, releaseTag: active?.release?.tag ?? null,
142
+ packagePath: active ? join(installationDirectory(root, active), "package") : null,
143
+ upstreamRevision: saved.upstreamRevision ?? null, upstreamReleaseTag: saved.upstreamReleaseTag ?? null, checkedAt: saved.checkedAt ?? null,
126
144
  error: saved.error ?? null, updating: saved.updating ?? false };
127
145
  }
128
146
  async function atomicJson(path: string, value: unknown): Promise<void> {
@@ -156,12 +174,70 @@ async function initialize(root: string): Promise<void> {
156
174
  }
157
175
  assertOwned(root);
158
176
  }
159
- async function run(args: string[], cwd: string, timeout: number, env?: Record<string, string>): Promise<string> {
160
- const child = Bun.spawn(args, { cwd, env, stdin: "ignore", stdout: "pipe", stderr: "pipe", timeout, killSignal: "SIGKILL" });
177
+ async function run(args: string[], cwd: string, timeout: number, options: {
178
+ readonly env?: Record<string, string>;
179
+ readonly input?: Blob;
180
+ } = {}): Promise<string> {
181
+ const { [releaseTokenEnv]: _token, ...publicEnv } = process.env;
182
+ const child = Bun.spawn(args, { cwd, env: options.env ?? publicEnv, stdin: options.input ?? "ignore",
183
+ stdout: "pipe", stderr: "pipe", timeout, killSignal: "SIGKILL" });
161
184
  const [stdout, stderr, exit] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]);
162
185
  if (exit !== 0) throw new Error(`${args[0]} ${args[1] ?? ""} failed (${exit}): ${stderr.slice(-2000)}`);
163
186
  return stdout.trim();
164
187
  }
188
+ function download(url: string, options: {
189
+ readonly cwd: string;
190
+ readonly timeout: number;
191
+ readonly args: readonly string[];
192
+ readonly authorization?: Blob;
193
+ }): Promise<string> {
194
+ // Send authenticated metadata requests directly: never forward the header on
195
+ // redirects or expose it in curl's arguments or environment.
196
+ const route = options.authorization ? ["--header", "@-"]
197
+ : ["--location", "--max-redirs", "5", "--proto-redir", "=https"];
198
+ return run(["curl", "--disable", "--fail", "--silent", "--show-error", "--proto", "=http,https",
199
+ ...route, ...options.args, "--", url], options.cwd, options.timeout, { input: options.authorization });
200
+ }
201
+ function record(value: unknown): value is Record<string, unknown> {
202
+ return typeof value === "object" && value !== null;
203
+ }
204
+ async function latestRelease(manifest: UlwManifest, root: string): Promise<ReleaseIdentity & { readonly url: string }> {
205
+ const token = manifest.releaseApi === officialReleaseApi ? process.env[releaseTokenEnv] : undefined;
206
+ // Keep GitHub's access token opaque; only reject characters unsafe in an HTTP header.
207
+ if (token && /[\p{Cc}\s]/u.test(token)) throw new Error(`Invalid ${releaseTokenEnv}`);
208
+ const data: unknown = JSON.parse(await download(manifest.releaseApi, {
209
+ cwd: root, timeout: manifest.commandTimeoutMs,
210
+ args: ["--header", "Accept: application/vnd.github+json", "--max-filesize", "2097152"],
211
+ authorization: token ? new Blob([`Authorization: Bearer ${token}\n`]) : undefined,
212
+ }));
213
+ const tag = record(data) ? data.tag_name : undefined;
214
+ const version = typeof tag === "string" ? releaseVersion.exec(tag)?.[1] : undefined;
215
+ if (!record(data) || typeof tag !== "string" || !version || data.draft !== false || data.prerelease !== false ||
216
+ !Array.isArray(data.assets)) throw new Error("ULW upstream did not advertise a stable GitHub release");
217
+ const assets: unknown[] = data.assets;
218
+ const matches = assets.filter(asset => record(asset) && asset.name === `omp-superkit-${version}.zip`);
219
+ const [asset] = matches;
220
+ const digest = record(asset) && typeof asset.digest === "string" ? /^sha256:([0-9a-f]{64})$/.exec(asset.digest)?.[1] : undefined;
221
+ if (matches.length !== 1 || !digest || !record(asset) || typeof asset.browser_download_url !== "string" ||
222
+ !/^https?:\/\//.test(asset.browser_download_url))
223
+ throw new Error(`Superkit release ${tag} does not have a unique packaged ZIP with a SHA-256 digest`);
224
+ return { tag, sha256: digest, url: asset.browser_download_url };
225
+ }
226
+
227
+ async function unpackRelease(release: ReleaseIdentity & { readonly url: string }, stage: string, timeout: number): Promise<string> {
228
+ const zip = join(stage, "release.zip");
229
+ await download(release.url, { cwd: stage, timeout, args: ["--max-filesize", "67108864", "--output", zip] });
230
+ const checksum = createHash("sha256");
231
+ for await (const chunk of Bun.file(zip).stream()) checksum.update(chunk);
232
+ if (checksum.digest("hex") !== release.sha256) throw new Error(`Superkit release ${release.tag} ZIP failed SHA-256 verification`);
233
+ const unpacked = join(stage, "unpacked");
234
+ await mkdir(unpacked, { mode: 0o700 });
235
+ await run(["unzip", "-q", zip, "-d", unpacked], stage, timeout);
236
+ const packagePath = join(unpacked, "omp-superkit");
237
+ if (!(await lstat(packagePath)).isDirectory()) throw new Error("Superkit ZIP does not contain an omp-superkit package directory");
238
+ await checkLinks(packagePath);
239
+ return packagePath;
240
+ }
165
241
  async function immutableTree(directory: string): Promise<void> {
166
242
  for (const entry of await readdir(directory, { withFileTypes: true })) {
167
243
  const path = join(directory, entry.name);
@@ -188,7 +264,7 @@ async function probe(packagePath: string, stage: string, manifest: UlwManifest):
188
264
  XDG_DATA_HOME: join(home, "data"), XDG_CACHE_HOME: join(home, "cache"), CI: "true", NO_COLOR: "1" };
189
265
  if (process.env.PI_NATIVES_DIR) env.PI_NATIVES_DIR = process.env.PI_NATIVES_DIR;
190
266
  await run([process.execPath, fileURLToPath(new URL("../managed-super-probe.ts", import.meta.url)), packagePath],
191
- home, manifest.probeTimeoutMs, env);
267
+ home, manifest.probeTimeoutMs, { env });
192
268
  }
193
269
 
194
270
  export type ManagedUlwLaunchInput = {
@@ -201,7 +277,7 @@ export type ManagedUlwLaunchInput = {
201
277
  commandArgs: string[];
202
278
  /** Exact native OMP argv, including the original command's flags and generated Host args; no executable prefix. */
203
279
  launchArgs: string[];
204
- worker?: Pick<WorkerHostProfile, "extensionPaths" | "memory">;
280
+ worker?: Pick<WorkerHostProfile, "extensionPaths" | "memory" | "trustedWorkspaceRoot">;
205
281
  expectedNativeProfile?: NativeProfile;
206
282
  };
207
283
  type ManagedUlwLaunchOptions = Omit<ManagedUlwLaunchInput, "managedUlwPath"> & {
@@ -349,11 +425,11 @@ export async function managedUlwLaunchComposition(input: ManagedUlwLaunchInput):
349
425
  }
350
426
 
351
427
  async function workerLaunchComposition(input: ManagedUlwLaunchInput & {
352
- worker: Pick<WorkerHostProfile, "extensionPaths" | "memory">;
428
+ worker: NonNullable<ManagedUlwLaunchInput["worker"]>;
353
429
  }): Promise<ManagedUlwLaunchComposition> {
354
- const { assertWorkerWorkspaceStartup } = await import("../worker/worker-profile");
430
+ const { assertWorkerWorkspaceStartup } = await import("../worker/worker-project-startup");
355
431
  const { homedir } = await import("node:os");
356
- assertWorkerWorkspaceStartup(input.cwd, homedir());
432
+ assertWorkerWorkspaceStartup(input.cwd, homedir(), input.worker.trustedWorkspaceRoot);
357
433
  const { parseNativeLaunch } = await import("./native-launch-profile");
358
434
  const parsed = await parseNativeLaunch(input.launchArgs);
359
435
  if (!parsed.noExtensions || !parsed.noLsp)
@@ -581,65 +657,60 @@ export async function updateManagedUlw(options: ManagedUlwOptions = {}): Promise
581
657
  }
582
658
  let stage: string | undefined;
583
659
  let upstreamRevision: string | null = null;
660
+ let upstreamReleaseTag: string | null = null;
584
661
  const checkedAt = new Date().toISOString();
585
662
  try {
586
663
  await atomicJson(join(root, "status.json"), { ...managedUlwStatus(options), checkedAt, updating: true, error: null });
587
664
  const git = (args: string[], cwd = root) => run(["git", "-c", "core.hooksPath=/dev/null", ...args], cwd, manifest.commandTimeoutMs,
588
- { PATH: process.env.PATH ?? "/usr/bin:/bin", HOME: root, USERPROFILE: root,
589
- GIT_TERMINAL_PROMPT: "0", GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: "/dev/null" });
590
- const remote = await git(["ls-remote", "--symref", manifest.repository, "HEAD"]);
591
- const branch = /^ref: (refs\/heads\/[^\s]+)\s+HEAD$/m.exec(remote)?.[1];
592
- upstreamRevision = /^([0-9a-f]{40,64})\s+HEAD$/m.exec(remote)?.[1] ?? null;
593
- if (!branch || !upstreamRevision) throw new Error("ULW upstream did not advertise an unambiguous default branch and HEAD commit");
665
+ { env: { PATH: process.env.PATH ?? "/usr/bin:/bin", HOME: root, USERPROFILE: root,
666
+ GIT_TERMINAL_PROMPT: "0", GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: "/dev/null" } });
594
667
  const active = readActive(root);
595
- let nextActive: ActiveRevision | undefined;
596
668
  if (active && !matchesUlwRepository(active.repository, manifest.repository))
597
669
  throw new Error("Managed ULW source repository changed; explicit operator reconciliation required");
598
- if (active?.revision === upstreamRevision) {
670
+ const latest = await latestRelease(manifest, root);
671
+ const release = { tag: latest.tag, sha256: latest.sha256 };
672
+ upstreamReleaseTag = release.tag;
673
+ const ref = `refs/tags/${release.tag}`;
674
+ const remote = await git(["ls-remote", "--exit-code", "--", manifest.repository, ref, `${ref}^{}`]);
675
+ const refs = new Map(remote.split("\n").map(line => {
676
+ const [revision, name] = line.split("\t");
677
+ return [name, revision];
678
+ }));
679
+ const revision = refs.get(`${ref}^{}`) ?? refs.get(ref);
680
+ if (!revision || !hash.test(revision)) throw new Error(`ULW upstream did not advertise Git tag ${release.tag}`);
681
+ upstreamRevision = revision;
682
+ let selected: ActiveRevision;
683
+ if (active?.revision === upstreamRevision && sameRelease(active.release, release)) {
599
684
  activeManagedUlw(options);
685
+ selected = active;
600
686
  } else {
601
- const revisionRoot = join(root, "revisions", upstreamRevision);
687
+ const provenance: ActiveRevision = { revision: upstreamRevision, repository: manifest.repository, release, preparedAt: new Date().toISOString() };
688
+ const revisionRoot = installationDirectory(root, provenance);
602
689
  let preparedRepository: string | undefined;
603
690
  try {
604
- const provenance = JSON.parse(await readFile(join(revisionRoot, "provenance.json"), "utf8")) as ActiveRevision;
605
- if (provenance.revision !== upstreamRevision || !matchesUlwRepository(provenance.repository, manifest.repository))
691
+ const prepared = JSON.parse(await readFile(join(revisionRoot, "provenance.json"), "utf8")) as ActiveRevision;
692
+ if (prepared.revision !== upstreamRevision || !matchesUlwRepository(prepared.repository, manifest.repository) ||
693
+ !sameRelease(prepared.release, release))
606
694
  throw new Error("Existing immutable ULW revision has different provenance");
607
695
  validateManagedUlwPackage(join(revisionRoot, "package"));
608
- preparedRepository = provenance.repository;
696
+ preparedRepository = prepared.repository;
609
697
  } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
610
- const provenance: ActiveRevision = { revision: upstreamRevision, repository: manifest.repository, branch, preparedAt: new Date().toISOString() };
611
698
  stage = await mkdtemp(join(root, ".stage-"));
612
- const source = join(stage, preparedRepository ? "ancestry" : "source");
613
699
  const distribution = join(stage, "distribution");
614
700
  const packagePath = join(preparedRepository ? revisionRoot : distribution, "package");
615
- if (!preparedRepository) await mkdir(packagePath, { recursive: true, mode: 0o700 });
616
- // A previously prepared revision may have been active before a remote
617
- // rewind. Do not bypass ancestry merely because its files already exist.
618
- if (!preparedRepository || active) {
619
- await git(["clone", "--no-checkout", "--no-local", manifest.repository, source]);
620
- await git(["fetch", "origin", upstreamRevision], source);
621
- }
622
- if (!preparedRepository) {
623
- await git(["checkout", "--detach", upstreamRevision], source);
624
- if (await git(["rev-parse", "HEAD"], source) !== upstreamRevision) throw new Error("ULW checkout revision changed while staging");
625
- }
626
- if (active) {
627
- try { await git(["merge-base", "--is-ancestor", active.revision, upstreamRevision], source); }
701
+ // Use Git only to verify ancestry, never to supply the installed files.
702
+ if (active && active.revision !== upstreamRevision) {
703
+ const ancestry = join(stage, "ancestry");
704
+ await git(["init", "--bare", ancestry]);
705
+ await git(["fetch", "--no-tags", "--", manifest.repository, ref], ancestry);
706
+ if (await git(["rev-parse", "FETCH_HEAD^{commit}"], ancestry) !== upstreamRevision)
707
+ throw new Error("ULW release tag changed during ancestry verification");
708
+ try { await git(["merge-base", "--is-ancestor", active.revision, upstreamRevision], ancestry); }
628
709
  catch { throw new Error("ULW upstream update is not a provable fast-forward; explicit operator reconciliation required"); }
629
710
  }
630
711
  if (!preparedRepository) {
631
- await git(["submodule", "update", "--init", "--recursive", "--depth=1"], source);
632
- await checkLinks(source);
633
- // Export tracked runtime/resources, not .git, dev node_modules, or the
634
- // user's checkout. Gitlinks are only build inputs for materialization.
635
- const archive = join(stage, "source.tar");
636
- await git(["archive", "--format=tar", `--output=${archive}`, "HEAD"], source);
637
- await run(["tar", "-xf", archive, "-C", packagePath], stage, manifest.commandTimeoutMs);
638
- if (manifest.materialize) {
639
- const materialize = resolve(source, manifest.materialize);
640
- if (!materialize.startsWith(source + sep)) throw new Error("ULW materializer leaves source checkout");
641
- await run([process.execPath, materialize, "--target-root", join(packagePath, "skills/frontend")], source, manifest.commandTimeoutMs);
642
- }
712
+ await mkdir(distribution, { mode: 0o700 });
713
+ await rename(await unpackRelease(latest, stage, manifest.commandTimeoutMs), packagePath);
643
714
  const pkgPath = join(packagePath, "package.json");
644
715
  const pkg = JSON.parse(await readFile(pkgPath, "utf8")) as PackageManifest;
645
716
  pkg.omp = { ...pkg.omp, skills: pkg.omp?.skills ?? ["./skills"] };
@@ -654,26 +725,25 @@ export async function updateManagedUlw(options: ManagedUlwOptions = {}): Promise
654
725
  if (!preparedRepository) {
655
726
  await writeFile(join(distribution, "provenance.json"), JSON.stringify(provenance, null, 2) + "\n", { mode: 0o444 });
656
727
  await immutableTree(packagePath);
657
- await mkdir(join(root, "revisions"), { recursive: true, mode: 0o700 });
728
+ await mkdir(dirname(revisionRoot), { recursive: true, mode: 0o700 });
658
729
  await rename(distribution, revisionRoot);
659
730
  }
660
- nextActive = { ...provenance, repository: preparedRepository ?? provenance.repository };
731
+ selected = { ...provenance, repository: preparedRepository ?? provenance.repository };
661
732
  }
662
733
  // Finish fallible staging cleanup/status publication before committing the
663
734
  // active pointer, so a failed preparation never reports a rollback after
664
735
  // it has already activated a new revision.
665
736
  if (stage) { await rm(stage, { recursive: true, force: true }); stage = undefined; }
666
- await atomicJson(join(root, "status.json"), { upstreamRevision, checkedAt, updating: false, error: null });
667
- const selected = nextActive ?? active!;
668
- const result: ManagedUlwStatus = { revision: selected.revision,
669
- packagePath: join(root, "revisions", selected.revision, "package"), upstreamRevision, checkedAt, updating: false, error: null };
737
+ await atomicJson(join(root, "status.json"), { upstreamRevision, upstreamReleaseTag, checkedAt, updating: false, error: null });
738
+ const result: ManagedUlwStatus = { revision: selected.revision, releaseTag: selected.release?.tag ?? null,
739
+ packagePath: join(installationDirectory(root, selected), "package"), upstreamRevision, upstreamReleaseTag, checkedAt, updating: false, error: null };
670
740
  // The only activation write. Old immutable directories are never pruned:
671
741
  // running Hosts and their native children may still import from them.
672
- if (nextActive) await atomicJson(join(root, "active.json"), nextActive);
742
+ if (selected !== active) await atomicJson(join(root, "active.json"), selected);
673
743
  return result;
674
744
  } catch (error) {
675
745
  const message = error instanceof Error ? error.message : "Managed ULW update failed";
676
- await atomicJson(join(root, "status.json"), { upstreamRevision, checkedAt, updating: false, error: message });
746
+ await atomicJson(join(root, "status.json"), { upstreamRevision, upstreamReleaseTag, checkedAt, updating: false, error: message });
677
747
  throw new Error(`Managed ULW update failed; previous active revision retained: ${message}`, { cause: error });
678
748
  } finally {
679
749
  // Never delete an immutable revision or any path outside this invocation's