@awebai/oats 0.43.3 → 0.44.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.
Files changed (32) hide show
  1. package/bin/oats.mjs +98 -27
  2. package/docs/capabilities.md +7 -1
  3. package/docs/configuration.md +65 -0
  4. package/docs/desktop-cli-api.md +149 -4
  5. package/docs/execution-targets.md +75 -0
  6. package/docs/implementation.md +14 -1
  7. package/docs/oats-local.schema.json +19 -1
  8. package/docs/oats-workspace.schema.json +1 -1
  9. package/docs/release-notes/v0.44.0.md +161 -0
  10. package/docs/schedules.md +27 -9
  11. package/docs/souls-and-instances.md +7 -0
  12. package/lib/core.mjs +253 -87
  13. package/lib/instance-events.mjs +1 -1
  14. package/lib/instance-inspect.mjs +39 -6
  15. package/lib/launch-prompt-fixtures/README.md +49 -0
  16. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-05-channel-seeded.txt +35 -0
  17. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-06-first-after-channel.txt +35 -0
  18. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-07-after-channel-200ms.txt +35 -0
  19. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-08-installed-after-channel-200ms.txt +35 -0
  20. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/manifest.json +77 -0
  21. package/lib/launch-prompt-fixtures.mjs +114 -0
  22. package/lib/launch-prompt-policy.mjs +73 -0
  23. package/lib/launch-prompt-transport.mjs +102 -0
  24. package/lib/launch-prompts.mjs +216 -0
  25. package/lib/operator-coverage.mjs +134 -0
  26. package/lib/remote.mjs +15 -9
  27. package/lib/schedule.mjs +57 -10
  28. package/lib/teams-verbs.mjs +3 -3
  29. package/lib/triggers.mjs +2 -2
  30. package/lib/workspace.mjs +20 -2
  31. package/package.json +1 -1
  32. package/skills/oats-getting-started/SKILL.md +15 -0
package/lib/core.mjs CHANGED
@@ -27,6 +27,10 @@
27
27
  * work (worktree|checkout|attached|workspace|directory), harness (pi|claude|codex), model (pi model pattern, optional)
28
28
  * (attached as soul default is for service agents — spawn must supply workDir)
29
29
  */
30
+ import { effectiveLaunchPromptPolicy } from "./launch-prompt-policy.mjs";
31
+ import { createLaunchPromptController } from "./launch-prompts.mjs";
32
+ import { qualifyLaunchPromptFixtures } from "./launch-prompt-fixtures.mjs";
33
+ import { LAUNCH_PANE_FORMAT, launchPaneTarget, launchPromptTransport } from "./launch-prompt-transport.mjs";
30
34
  import { execFileSync, execSync, spawn as spawnProcess, spawnSync } from "node:child_process";
31
35
  import {
32
36
  chmodSync, closeSync, copyFileSync, existsSync, lstatSync, mkdirSync, mkdtempSync, openSync, readFileSync, readdirSync, readlinkSync, realpathSync, renameSync, rmSync, rmdirSync, statSync, symlinkSync, writeFileSync,
@@ -626,6 +630,49 @@ function validateLaunchConfigs(map, file) {
626
630
  for (const [name, entry] of Object.entries(map)) validateLaunchConfig(name, entry, file);
627
631
  validateLaunchConfigDefaults(map, file);
628
632
  }
633
+ export function launchPromptPolicyAt(deployment, home) {
634
+ let found;
635
+ try { found = loadLocal(deployment); }
636
+ catch (e) { if (e.code !== "E_LOCAL_MISSING") throw e; }
637
+ return effectiveLaunchPromptPolicy(found?.local ?? {}, realPathOrNearest(home), found?.path ?? null);
638
+ }
639
+ const promptOptedIn = policy => policy.awebDevelopmentChannel === true;
640
+ function assertLaunchHome(home, expected) {
641
+ const actual = directoryIdentity(home);
642
+ if (!expected || actual.dev !== expected.dev || actual.ino !== expected.ino) throw oatsError("E_RUNTIME_AUTHORITY_MISMATCH", "launch home identity changed");
643
+ }
644
+ function promptController(home, startId, harness, policy, command, io, expectedHomeIdentity) {
645
+ assertLaunchHome(home, expectedHomeIdentity);
646
+ const described = describeLaunchCommand(command);
647
+ const qualification = qualifyLaunchPromptFixtures({ home: realPathOrNearest(home), harness, executablePath: described.executable, argv: described.argv });
648
+ return createLaunchPromptController({ home: realPathOrNearest(home), startId, ...qualification, policy, expectedHomeIdentity,
649
+ transport: launchPromptTransport(io), audit: data => appendEvent(home, { kind: "launch-prompt", data }),
650
+ ...(io?.now ? { now: io.now } : {}), ...(io?.sleep ? { sleep: io.sleep } : {}) });
651
+ }
652
+ function retainedPromptError(home, instance, target, parentLineageCommitted, launchPrompts) {
653
+ return Object.assign(oatsError("E_SPAWN_INCOMPLETE", `${launchPrompts.reason}; home and pane retained: inspect ${home}, then use oats session start --home ${shellWord(home)}. If the harness changed, refresh its qualified prompt fixtures; never broaden the matcher.`), {
654
+ instance, home, launched: "unknown",
655
+ details: { retained: true, unconfirmed: true, instance, home, launched: "unknown", target, parentLineageCommitted, launchPrompts },
656
+ });
657
+ }
658
+ function incompleteLaunchPrompt(home, startId, target, reason, previous, expectedHomeIdentity) {
659
+ try { assertLaunchHome(home, expectedHomeIdentity); }
660
+ catch {
661
+ // A replaced/unverifiable home is the explicit audit exception: appendEvent
662
+ // resolves its address from current home metadata, even with workspaceOnly.
663
+ // Neither log is a pinned original-incarnation destination here. Do not read
664
+ // replacement authority or write a row there; zero destinations were tried.
665
+ return { status: "incomplete", answers: previous?.answers ?? [],
666
+ reason: "launch home identity changed; metadata retained at original home",
667
+ receipt: [...(previous?.receipt ?? []), { ok: false, results: [] }] };
668
+ }
669
+ const audit = appendEvent(home, { kind: "launch-prompt", data: { startId, ...target, status: "incomplete", reason } });
670
+ return { status: "incomplete", answers: previous?.answers ?? [], reason: audit.ok === true ? reason : "launch prompt audit failed",
671
+ receipt: [...(previous?.receipt ?? []), { ok: audit.ok === true, ...(audit.row ? { row: audit.row } : {}), results: audit.results ?? [] }] };
672
+ }
673
+ export const LAUNCH_PROMPT_UPDATE_WARNING = "Launch prompt answers are opted in for this home. A harness update can block launch again (blocked: unexpected prompt); refresh qualified fixtures. No fallback key is sent.";
674
+
675
+
629
676
  /** The launch configurations effective at `dir`: the `launch-configs:` of the
630
677
  * oats-local.yaml found walking up from it (the deployment), validated. None
631
678
  * when no deployment is in reach. `source` is the deployment directory (a
@@ -3059,7 +3106,8 @@ export function planLaunch({ home, instance, meta, contextDir, agentLike, select
3059
3106
  const { trustHome } = launchFolderTrust({ harness, home, meta, yolo: recipe.yolo, env });
3060
3107
  const command = renderLaunchRecipe(recipe, { home, instance: inst, trustHome });
3061
3108
  const selectionSource = frozen ? (config?.frozen || (!config && !selection.launchConfig && !selection.harness) ? "frozen" : "config") : "config";
3062
- return { recipe, command, trustHome, harness, model: model || undefined, modelSource, yolo, config, executable, preflight: problems, ok: problems.every((c) => c.ok), selectionSource, frozen, launchChoice, warnings: hooks.warnings || [], previewedHooks: hooks.previewed || [], volatileEnv: hooks.volatileEnv || [], ...(hooks.meta ? { hookMeta: hooks.meta } : {}) };
3109
+ const launchPromptAnswers = preview ? launchPromptPolicyAt(dirname(dirname(dirname(dirname(home)))), home) : null;
3110
+ return { ...(preview ? { launchPromptAnswers } : {}), recipe, command, trustHome, harness, model: model || undefined, modelSource, yolo, config, executable, preflight: problems, ok: problems.every((c) => c.ok), selectionSource, frozen, launchChoice, warnings: [...(hooks.warnings || []), ...(launchPromptAnswers && promptOptedIn(launchPromptAnswers) ? [LAUNCH_PROMPT_UPDATE_WARNING] : [])], previewedHooks: hooks.previewed || [], volatileEnv: hooks.volatileEnv || [], ...(hooks.meta ? { hookMeta: hooks.meta } : {}) };
3063
3111
  }
3064
3112
  /** The environment a planned launch runs under: the host's base, the
3065
3113
  * capabilities' validated env, the configuration's literals and its
@@ -3224,6 +3272,7 @@ function* spawnBody(root, agent, o = {}) {
3224
3272
  // Completion custody: the home exists from the first metadata write, but
3225
3273
  // the launch/lineage/events that make it a finished spawn may not have
3226
3274
  // happened (crash in the interval). Say which, never replay a half-spawn.
3275
+ if (["blocked", "incomplete"].includes(prior.launchPrompts?.status)) throw retainedPromptError(prior.home, prior.instance, prior.launchPromptTarget ?? prior.tmux, prior.parentLineageCommitted === true, prior.launchPrompts);
3227
3276
  if (prior.spawnCompleted !== true) throw unconfirmedSpawn(Object.assign(oatsError("E_SPAWN_INCOMPLETE", `${prior.instance} was created for this key but its spawn did not complete (launch or lineage unfinished); inspect it with oats session inspect --home ${prior.home} — do not spawn again`), { instance: prior.instance, home: prior.home, launched: prior.launched === true ? "unknown" : false }));
3228
3277
  return { ...prior, replayed: true, launch: undefined, command: undefined, wake: prior.wake ?? { requested: null, saved: null, error: null } };
3229
3278
  }
@@ -3401,7 +3450,8 @@ function* spawnBody(root, agent, o = {}) {
3401
3450
  }
3402
3451
  }
3403
3452
  const anchorMetaPath = anchorHome ? join(anchorHome, "instance.json") : undefined;
3404
- const anchorMeta = anchorMetaPath && existsSync(anchorMetaPath) ? JSON.parse(readFileSync(anchorMetaPath, "utf8")) : undefined;
3453
+ const anchorOriginal = anchorMetaPath && existsSync(anchorMetaPath) ? readFileSync(anchorMetaPath, "utf8") : null;
3454
+ const anchorMeta = anchorOriginal === null ? undefined : JSON.parse(anchorOriginal);
3405
3455
  if ((relation === "sibling" || relation === "parent") && !anchorMeta) {
3406
3456
  throw new Error(`relation "${relation}" needs the anchor's recorded lineage, but instance "${relativeTo}" has no instance.json`);
3407
3457
  }
@@ -3600,6 +3650,7 @@ function* spawnBody(root, agent, o = {}) {
3600
3650
  d.revision = createHash("sha256").update(canonicalJson(d)).digest("hex").slice(0, 24);
3601
3651
  return d;
3602
3652
  };
3653
+ const launchPromptAnswers = launchPromptPolicyAt(o.prepared.deployment || workspaceOf(root), home);
3603
3654
  if (o.preview === true) {
3604
3655
  const decision = buildDecision();
3605
3656
  // Workspace model (M3): the preview reports what APPLY will produce — every
@@ -3622,7 +3673,7 @@ function* spawnBody(root, agent, o = {}) {
3622
3673
  // Team model v2: the soul's teams here (unmapped rows included) and its default — the choice a
3623
3674
  // Desktop offers before anything is minted; joining any but the default is the provider's explicit act.
3624
3675
  ...{ modules: o.prepared.preview ?? null, teams: structuredClone(o.prepared.resolution.teams ?? []), defaultTeam: structuredClone(o.prepared.resolution.defaultTeam ?? null), resolution: o.prepared.resolution.revision, declRevision: o.prepared.resolution.declRevision ?? null, payloadRevision: o.prepared.resolution.payloadRevision ?? null, workspace: o.prepared.discovery?.key ?? null, standalone: o.prepared.discovery?.standalone === true, providers: preparedProviders, settings: preparedSettings, settingsOrigins: preparedSettingsOrigins },
3625
- spawnPreviewApi: 2, preview: true, agent: agent.name, kind: agent.kind || "persistent", instance, home, repo: repoAbs, work,
3676
+ spawnPreviewApi: 2, preview: true, launchPromptAnswers, ...(promptOptedIn(launchPromptAnswers) ? { warnings: [LAUNCH_PROMPT_UPDATE_WARNING] } : {}), agent: agent.name, kind: agent.kind || "persistent", instance, home, repo: repoAbs, work,
3626
3677
  subject: o.subject ?? { soul: agent.name, agentsRoot: root, context: null },
3627
3678
  decision, preflight,
3628
3679
  backendStatus: launch ? { name: backend, installed: !!which(backend), started: false } : null,
@@ -3660,6 +3711,7 @@ function* spawnBody(root, agent, o = {}) {
3660
3711
  if (e?.code === "EEXIST") throw Object.assign(oatsError("E_PLACEMENT_TAKEN", `${instance} already exists at ${home} (a concurrent spawn won the placement); nothing was created by this call`), { instance, home });
3661
3712
  throw e;
3662
3713
  }
3714
+ const createdHomeIdentity = directoryIdentity(home);
3663
3715
  // Names are deployment-wide, but the reservation above is per soul: a concurrent
3664
3716
  // spawn of ANOTHER soul under the same name reserves its own directory. Re-check
3665
3717
  // now that ours exists — two holders means neither may keep it (at most one
@@ -3941,7 +3993,7 @@ function* spawnBody(root, agent, o = {}) {
3941
3993
  branch = shTry(`git -C ${shq(repoAbs)} rev-parse --abbrev-ref HEAD`);
3942
3994
  }
3943
3995
 
3944
- const warnings = [];
3996
+ const warnings = promptOptedIn(launchPromptAnswers) ? [LAUNCH_PROMPT_UPDATE_WARNING] : [];
3945
3997
 
3946
3998
  // Establish directory ownership while these are still the kernel's own roots.
3947
3999
  // A hook may replace either path; it must never mint authority for that target.
@@ -3976,6 +4028,27 @@ function* spawnBody(root, agent, o = {}) {
3976
4028
  // a capability configured itself, independent of whatever the hook printed.
3977
4029
  const hookReceipt = (res) => { const failedBy = new Map((res.failures || []).map((f) => [f.capability, f])); return (res.order || []).map((id) => ({ capability: id, ok: !failedBy.has(id), ...(failedBy.has(id) ? { required: failedBy.get(id).required === true, contract: failedBy.get(id).contract ?? null } : {}), meta: Object.hasOwn(res.meta || {}, id) })); };
3978
4030
  const requiredFailures = (hookRes.failures || []).filter((f) => f.required);
4031
+ let parentLineageCommitted = false, anchorWritten;
4032
+ const commitParentLineage = () => {
4033
+ if (relation !== "parent" || !anchorMeta || !anchorMetaPath || parentLineageCommitted) return;
4034
+ const next = { ...anchorMeta, parentInstance: instance };
4035
+ delete next.siblingInstance;
4036
+ anchorWritten = JSON.stringify(next, null, 2) + "\n";
4037
+ // Preserve the established atomic parent-write contract, including the
4038
+ // instance-scoped temp path, error context and unconfirmed temp cleanup.
4039
+ const tmpPath = `${anchorMetaPath}.tmp-${instance}`;
4040
+ try {
4041
+ if (readFileSync(anchorMetaPath, "utf8") !== anchorOriginal) throw new Error("parent anchor changed during spawn preparation");
4042
+ writeFileSync(tmpPath, anchorWritten);
4043
+ renameSync(tmpPath, anchorMetaPath);
4044
+ parentLineageCommitted = true;
4045
+ } catch (e) {
4046
+ try { rmSync(tmpPath, { force: true }); }
4047
+ catch (cleanupError) { ancillaryCleanup.push(`temp file ${tmpPath}: ${cleanupError.message}`); }
4048
+ throw new Error(`relation "parent": failed to re-point anchor "${relativeTo}" (${e.message})`);
4049
+ }
4050
+ };
4051
+ let promptDispatched = false, promptTarget, promptResult, promptStartId;
3979
4052
  let windowMayExist = false;
3980
4053
  let spawnTmux;
3981
4054
  const ancillaryCleanup = [];
@@ -4311,46 +4384,41 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
4311
4384
  const windowCmd = paneCommand(executionCommand);
4312
4385
  const paneEnvFlags = launchEnvRefs(recipe, process.env).flatMap((r) => ["-e", `${r.name}=${r.value}`]);
4313
4386
  const launchFailed = (step, refused, e) => oatsError("E_SPAWN_LAUNCH_FAILED", `tmux ${step} failed for ${instance} (${e.code === "ENOENT" ? "tmux unavailable" : refused}); the command line and tmux's output are withheld from this message because they can carry reference values; run tmux -S ${shellWord(socket)} list-windows -t ${shellWord(session)} to inspect`);
4387
+ const policy = launchPromptPolicyAt(o.prepared.deployment || workspaceOf(root), home);
4388
+ // Only a consented prompt launch needs lineage committed before dispatch:
4389
+ // its uncertain input outcome retains the new process and parent link.
4390
+ // Ordinary launches keep their established post-launch commit/rollback.
4391
+ if (promptOptedIn(policy)) commitParentLineage();
4392
+ promptStartId = randomUUID();
4393
+ const controller = promptOptedIn(policy) ? promptController(home, promptStartId, harness, policy, cmdline, undefined, createdHomeIdentity) : null;
4314
4394
  windowMayExist = true;
4395
+ promptDispatched = !!controller;
4315
4396
  let windowId;
4316
- try { windowId = tmuxOn(socket, ["new-window", "-P", "-F", "#{window_id}", "-t", `=${session}:`, "-n", instance, "-c", home, ...paneEnvFlags, windowCmd], undefined, oatsWindowEnvironment()).trim(); }
4397
+
4398
+ try { windowId = tmuxOn(socket, ["new-window", "-P", "-F", controller ? LAUNCH_PANE_FORMAT : "#{window_id}", "-t", `=${session}:`, "-n", instance, "-c", home, ...paneEnvFlags, windowCmd], undefined, oatsWindowEnvironment()).trim(); }
4317
4399
  catch (e) { throw launchFailed("new-window", "the window command was refused", e); }
4400
+ if (controller) { promptTarget = { ...meta.tmux, ...launchPaneTarget(socket, windowId) }; windowId = promptTarget.windowId; }
4318
4401
  try { prepareAgentWindow(socket, windowId); }
4319
4402
  catch (e) { throw launchFailed("set-option", "the new window's options were refused", e); }
4403
+ if (controller) {
4404
+ promptResult = controller.observeNew(promptTarget);
4405
+ meta.launchPrompts = promptResult;
4406
+ meta.launchPromptTarget = promptTarget;
4407
+ meta.parentLineageCommitted = parentLineageCommitted;
4408
+ meta.launched = promptResult.status === "completed";
4409
+ assertLaunchHome(home, createdHomeIdentity);
4410
+ writeJsonAtomic(join(home, "instance.json"), meta);
4411
+ if (!meta.launched) throw retainedPromptError(home, instance, promptTarget, parentLineageCommitted, promptResult);
4412
+ }
4320
4413
  } else {
4321
4414
  meta.launched = false;
4322
4415
  writeFileSync(join(home, "instance.json"), JSON.stringify(meta, null, 2) + "\n");
4323
4416
  writeRetirementBaseline(home, join(home, "work"), work, resolvedCfg.capabilities, { launched: false, tmux: meta.tmux });
4324
4417
  }
4325
4418
 
4326
- // parent relation: re-point the ANCHOR's recorded lineage so its parent is
4327
- // the new instance (e.g. a maintainer reviewing the spawner sits above it).
4328
- // Committed LAST — after every other fallible step incl. launch — so a
4329
- // failed spawn (missing tmux, window collision, new-window error) never
4330
- // leaves the anchor's graph pointing at a zombie. --no-launch reaches here
4331
- // too: the scaffold itself succeeded, which is that path's definition of
4332
- // success. The write ITSELF is fallible (anchor retired concurrently,
4333
- // unwritable file): on failure the spawn is COMPENSATED — kill the launched
4334
- // window and remove the scaffold — so the operation stays all-or-nothing:
4335
- // either agent live + lineage recorded, or neither.
4336
- if (relation === "parent" && anchorMeta && anchorMetaPath) {
4337
- // Atomic anchor update: writeFileSync truncates-then-writes, so a mid-write
4338
- // failure (ENOSPC, I/O) could leave the anchor's instance.json empty.
4339
- // Write a same-directory temp file and rename it over the anchor — rename
4340
- // is atomic on POSIX, so the anchor is always either old or new, never
4341
- // truncated.
4342
- const tmpPath = `${anchorMetaPath}.tmp-${instance}`;
4343
- try {
4344
- anchorMeta.parentInstance = instance;
4345
- delete anchorMeta.siblingInstance; // the new parent carries the old sibling link
4346
- writeFileSync(tmpPath, JSON.stringify(anchorMeta, null, 2) + "\n");
4347
- renameSync(tmpPath, anchorMetaPath);
4348
- } catch (e) {
4349
- try { rmSync(tmpPath, { force: true }); }
4350
- catch (cleanupError) { ancillaryCleanup.push(`temp file ${tmpPath}: ${cleanupError.message}`); }
4351
- throw new Error(`relation "parent": failed to re-point anchor "${relativeTo}" (${e.message})`);
4352
- }
4353
- }
4419
+ // Ordinary launches and scaffolds commit here; opted-in launches already
4420
+ // committed before dispatch so retained prompt failures keep their lineage.
4421
+ commitParentLineage();
4354
4422
 
4355
4423
  appendEvent(home, { kind: "spawned", data: { agent: agent.name, work, branch: branch ?? null, harness, model: model || null, parentInstance: meta.parentInstance ?? null, relation: relation ?? null, launched: launch, hooks: hookReceipt(hookRes) } });
4356
4424
  if (launch) appendEvent(home, { kind: "launched", data: { harness, backend, launchConfig: launchConfig?.name ?? null } });
@@ -4361,6 +4429,33 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
4361
4429
  }
4362
4430
  return deliver({ ...meta, ...(o.expectDecision !== undefined ? { replayed: false } : {}), launch: redactLaunchRecipe(recipe), command: redactLaunchCommand(cmdline), attach: launch ? `tmux -S ${shellWord(meta.tmux.socket)} attach -t ${shellWord(session)}` : `oats session attach --home ${shellWord(home)}`, warnings: spawnWarnings.length ? spawnWarnings : undefined });
4363
4431
  } catch (error) {
4432
+ if (promptDispatched) {
4433
+ // Once opted-in launch dispatch occurred, uncertainty retains all effects.
4434
+ // The independent baseline remains launched:true: metadata is not proof of quiescence.
4435
+ let result = promptResult?.status === "blocked" || promptResult?.status === "incomplete" ? promptResult : incompleteLaunchPrompt(home, promptStartId, promptTarget ?? spawnTmux, "launch prompt dispatch or recording incomplete", promptResult, createdHomeIdentity);
4436
+ try {
4437
+ assertLaunchHome(home, createdHomeIdentity);
4438
+ const retained = JSON.parse(readFileSync(join(home, "instance.json"), "utf8"));
4439
+ retained.launched = false; retained.launchPrompts = result;
4440
+ retained.launchPromptTarget = promptTarget ?? spawnTmux;
4441
+ retained.parentLineageCommitted = parentLineageCommitted;
4442
+ retained.spawnCompleted = false;
4443
+ writeJsonAtomic(join(home, "instance.json"), retained);
4444
+ } catch { result = incompleteLaunchPrompt(home, promptStartId, promptTarget ?? spawnTmux, "launch prompt metadata recording incomplete", result, createdHomeIdentity); }
4445
+ throw retainedPromptError(home, instance, promptTarget ?? spawnTmux, parentLineageCommitted, result);
4446
+ }
4447
+ if (parentLineageCommitted) {
4448
+ try {
4449
+ if (readFileSync(anchorMetaPath, "utf8") !== anchorWritten) throw new Error("parent anchor changed; cannot restore lineage safely");
4450
+ writeJsonAtomic(anchorMetaPath, JSON.parse(anchorOriginal));
4451
+ parentLineageCommitted = false;
4452
+ } catch (anchorError) {
4453
+ // A concurrent anchor edit must survive, but cannot prevent cleanup of
4454
+ // this spawn's independent window, hooks and scaffold.
4455
+ error.message += ` — rollback INCOMPLETE: parent lineage could not be restored: ${anchorError.message}`;
4456
+ unconfirmedSpawn(error);
4457
+ }
4458
+ }
4364
4459
  try {
4365
4460
  const compensation = compensateSpawn();
4366
4461
  error.message += compensation.note;
@@ -5095,7 +5190,7 @@ function retirementDisposableRoots(work, capabilities) {
5095
5190
  * home is ever re-blessed: an agent's STATE.md written seconds after launch
5096
5191
  * is still recovered at retire. (Replaces a whole-home re-stamp that could
5097
5192
  * bless authored bytes written in the launch→completion interval.) */
5098
- const KERNEL_POST_SPAWN_FIELDS = ["spawnCompleted", "wake"];
5193
+ const KERNEL_POST_SPAWN_FIELDS = ["spawnCompleted", "wake", "launchPrompts", "launchPromptTarget", "parentLineageCommitted"];
5099
5194
  function kernelNeutralInstanceJson(bytes) {
5100
5195
  try {
5101
5196
  // Bytes that are not UTF-8 would each read as the replacement character,
@@ -5353,6 +5448,13 @@ function tmuxEndpointAgrees(meta, authority) {
5353
5448
  return meta.tmux?.session === authority.tmux?.session && meta.tmux?.window === authority.tmux?.window && resolve(meta.tmux?.socket || ".") === authority.tmux?.socket;
5354
5449
  }
5355
5450
 
5451
+ /** A blocked prompt is a retained runtime, not evidence that no process exists.
5452
+ * The independent launched receipt and exact endpoint agreement remain mandatory. */
5453
+ function launchStateAgrees(meta, authority) {
5454
+ return meta.launched === authority.launched || (authority.launched === true && meta.launched === false &&
5455
+ ["blocked", "incomplete"].includes(meta.launchPrompts?.status) && tmuxEndpointAgrees(meta, authority));
5456
+ }
5457
+
5356
5458
  /** Session control uses the independent endpoint receipt. */
5357
5459
  function instanceSessionTarget(home) {
5358
5460
  if (typeof home !== "string" || !isAbsolute(home)) throw oatsError("E_BAD_ARGS", "session needs an absolute instance home");
@@ -5365,7 +5467,7 @@ function instanceSessionTarget(home) {
5365
5467
  } catch (e) { throw oatsError("E_RUNTIME_ENDPOINT_UNKNOWN", `cannot read session receipt for ${home}: ${e.message}`); }
5366
5468
  const authority = baseline.version === RETIRE_BASELINE_VERSION && baseline.home === home && runtimeAuthorityOf(baseline);
5367
5469
  if (!authority) throw oatsError("E_RUNTIME_ENDPOINT_UNKNOWN", `independent session receipt is missing or invalid for ${home}`);
5368
- if (meta.launched !== authority.launched || (authority.launched && !tmuxEndpointAgrees(meta, authority))) throw oatsError("E_RUNTIME_AUTHORITY_MISMATCH", "instance metadata disagrees with independent session receipt");
5470
+ if (!launchStateAgrees(meta, authority) || (authority.launched && !tmuxEndpointAgrees(meta, authority))) throw oatsError("E_RUNTIME_AUTHORITY_MISMATCH", "instance metadata disagrees with independent session receipt");
5369
5471
  return { home, target: authority.launched ? { backend: "tmux", ...authority.tmux } : undefined };
5370
5472
  }
5371
5473
 
@@ -5888,7 +5990,7 @@ export function startInstanceSession(home, o = {}) {
5888
5990
  // The independent receipt first (retire and session consult it), then the
5889
5991
  // mutable metadata; both tmp+rename. A failure between them is what the
5890
5992
  // pending receipt exists for.
5891
- const record = (meta, { id, target, model, command, startedAt, reused, launch, harness: newHarness, yolo: newYolo, stop, nativeRecordId, hookMeta, modelFrom, launchFrom, launchAt, launchDeclared }, clearPending = true) => {
5993
+ const record = (meta, { id, target, model, command, startedAt, reused, launch, harness: newHarness, yolo: newYolo, stop, nativeRecordId, hookMeta, modelFrom, launchFrom, launchAt, launchDeclared, launchPrompts, launchPromptTarget }, clearPending = true) => {
5892
5994
  checkRoots();
5893
5995
  const baselinePath = retirementBaselinePath(realHome);
5894
5996
  let baseline;
@@ -5906,10 +6008,14 @@ export function startInstanceSession(home, o = {}) {
5906
6008
  // Launch-hook meta lands per capability over the spawn's record; a hook
5907
6009
  // that answered without meta keeps its previous entry (retire reads it).
5908
6010
  ...(hookMeta ? { capabilityMeta: { ...(meta.capabilityMeta || {}), ...hookMeta } } : {}) };
6011
+ if (launchPrompts) {
6012
+ next.launchPrompts = launchPrompts; next.launchPromptTarget = launchPromptTarget ?? target;
6013
+ next.launched = launchPrompts.status === "completed";
6014
+ } else { delete next.launchPrompts; delete next.launchPromptTarget; }
5909
6015
  next.tmux = { session: target.session, window: target.window, socket: resolve(target.socket) };
5910
6016
  writeJsonAtomic(metaPath, next);
5911
6017
  if (clearPending) { checkRoots(); rmSync(pendingPath, { force: true }); }
5912
- return { instance: meta.instance, agent: meta.agent, home: realHome, harness: next.harness, backend: "tmux", model: model ?? null, launchConfig: next.launch?.launchConfig ?? null, yolo: next.yolo ?? null, target, startedAt, restartCount: next.restartCount, reused, warnings: [], ...(nativeRecordId ? { nativeRecordId } : {}), ...(stop ? { stop } : {}) };
6018
+ return { instance: meta.instance, agent: meta.agent, home: realHome, harness: next.harness, backend: "tmux", model: model ?? null, launchConfig: next.launch?.launchConfig ?? null, yolo: next.yolo ?? null, target, startedAt, restartCount: next.restartCount, reused, warnings: [], ...(launchPrompts ? { launchPrompts } : {}), ...(nativeRecordId ? { nativeRecordId } : {}), ...(stop ? { stop } : {}) };
5913
6019
  };
5914
6020
  try { mkdirSync(lock); }
5915
6021
  catch (e) {
@@ -5956,30 +6062,51 @@ export function startInstanceSession(home, o = {}) {
5956
6062
  const exited = existsSync(exitedPath) && readFileSync(exitedPath, "utf8").trim() === pending.id;
5957
6063
  if (!exited) throw oatsError("E_SESSION_START_BUSY", `${basename(realHome)} is still starting; refresh its status before retrying`);
5958
6064
  }
5959
- // Reconcile even an exited target: the independent baseline may
5960
- // already name it while metadata still names the old allocation.
5961
6065
  const meta = readMeta();
5962
- // The adopted start's session boundary, at its launch time, completed
5963
- // in whichever log the interrupted start did not record it.
5964
- recordStartBoundary(realHome, { startId: pending.id, startedAt: pending.startedAt, harness: pending.harness ?? meta.harness ?? null, backend: "tmux", launchConfig: pending.launch?.launchConfig ?? meta.launch?.launchConfig ?? null, phase: "recovered" });
5965
- const done = record(meta, { ...pending, model: pending.model ?? undefined, reused: "adopted" }, !st.present || st.state === "shell");
5966
- // The adopted target is on another server than the home recorded (the start that allocated it
5967
- // could not record it): this adoption records it, and says so once, here.
5968
- const recordedSocket = typeof meta.tmux?.socket === "string" && meta.tmux.socket ? resolve(meta.tmux.socket) : null;
5969
- if (recordedSocket && recordedSocket !== resolve(pending.target.socket)) {
5970
- const message = sessionMovedWarning(meta.instance, recordedSocket, resolve(pending.target.socket));
5971
- appendEvent(realHome, { kind: "launch-warning", data: { message } });
5972
- movedWarnings.push(message);
6066
+ // A completed start (#691): its receipt names the start instance.json already records, on the
6067
+ // target it records. The receipt is history then, never authority: nothing of it is recorded
6068
+ // again, so a newer launch recipe or provider metadata stays as it is.
6069
+ const rt = meta.tmux;
6070
+ const sameTarget = rt && rt.session === pt.session && rt.window === pt.window && typeof rt.socket === "string" && !!rt.socket && resolve(rt.socket) === resolve(pt.socket);
6071
+ const running = st.present && st.state !== "shell";
6072
+ // The same start on another target is ambiguous while that other target runs; a restart once it
6073
+ // no longer runs is the way out (the recorded target is instance.json's, the ordinary path's).
6074
+ if (meta.startId === pending.id && !sameTarget && (!o.restart || running)) {
6075
+ throw oatsError("E_SESSION_UNKNOWN", `the start ${pending.id} of ${meta.instance} is recorded on tmux ${rt?.session ?? "?"}:${rt?.window ?? "?"} on ${rt?.socket ?? "?"} (\`oats session inspect --home ${realHome}\` shows it), but its receipt ${pendingPath} names tmux ${pt.session}:${pt.window} on ${pt.socket}; the receipt is kept and nothing was started. If that other target is not this instance's session, stop it (\`tmux -S ${shq(pt.socket)} kill-window -t ${shq(`=${pt.session}:=${pt.window}`)}\`), then run \`oats session restart --home ${realHome}\``);
5973
6076
  }
5974
- if (st.present && st.state !== "shell") {
5975
- if (o.restart) { rmSync(pendingPath, { force: true }); }
5976
- else {
5977
- // The recovered target runs what the receipt says; a choice made
5978
- // now (model, configuration, harness, yolo) was not applied to it.
5979
- if (o.model != null && String(o.model).trim() && resolveModelPreference(String(o.model), done.harness || meta.harness) !== done.model) throw oatsError("E_SESSION_RUNNING", `${meta.instance} is already running with its previously requested model; its target was recovered, but the new model was not applied`);
5980
- if (o.launchConfig !== undefined || o.harness !== undefined || o.yolo !== undefined) throw oatsError("E_SESSION_RUNNING", `${meta.instance} is already running (its pending start was recovered); the requested launch configuration, harness or yolo was not applied; stop it, or use session restart`);
5981
- if (meta.startId === pending.id) throw oatsError("E_SESSION_RUNNING", `${meta.instance} is already running; nothing was started`);
5982
- return { ...done, warnings: [...done.warnings, ...movedWarnings] };
6077
+ if (meta.startId === pending.id) {
6078
+ if (running && !o.restart) {
6079
+ const asked = (o.model != null && String(o.model).trim() && resolveModelPreference(String(o.model), meta.harness) !== meta.model) || o.launchConfig !== undefined || o.harness !== undefined || o.yolo !== undefined || o.reselectLaunch === true;
6080
+ throw oatsError("E_SESSION_RUNNING", `${meta.instance} is already running; nothing was started${asked ? "; the requested model, launch configuration, harness or yolo was not applied: use session restart" : ""}`);
6081
+ }
6082
+ // A restart, or a target that is gone or a harness that exited: the ordinary start below
6083
+ // reads instance.json as it is, and its own receipt replaces this one when it launches. A
6084
+ // start refused before that leaves this receipt as it was. The completed start recorded its
6085
+ // own session boundary; it is not recorded again.
6086
+ } else {
6087
+ // Reconcile even an exited target: the independent baseline may
6088
+ // already name it while metadata still names the old allocation.
6089
+ // The adopted start's session boundary, at its launch time, completed
6090
+ // in whichever log the interrupted start did not record it.
6091
+ recordStartBoundary(realHome, { startId: pending.id, startedAt: pending.startedAt, harness: pending.harness ?? meta.harness ?? null, backend: "tmux", launchConfig: pending.launch?.launchConfig ?? meta.launch?.launchConfig ?? null, phase: "recovered" });
6092
+ const done = record(meta, { ...pending, model: pending.model ?? undefined, reused: "adopted" }, !st.present || st.state === "shell");
6093
+ // The adopted target is on another server than the home recorded (the start that allocated it
6094
+ // could not record it): this adoption records it, and says so once, here.
6095
+ const recordedSocket = typeof meta.tmux?.socket === "string" && meta.tmux.socket ? resolve(meta.tmux.socket) : null;
6096
+ if (recordedSocket && recordedSocket !== resolve(pending.target.socket)) {
6097
+ const message = sessionMovedWarning(meta.instance, recordedSocket, resolve(pending.target.socket));
6098
+ appendEvent(realHome, { kind: "launch-warning", data: { message } });
6099
+ movedWarnings.push(message);
6100
+ }
6101
+ if (st.present && st.state !== "shell") {
6102
+ if (o.restart) { rmSync(pendingPath, { force: true }); }
6103
+ else {
6104
+ // The recovered target runs what the receipt says; a choice made
6105
+ // now (model, configuration, harness, yolo) was not applied to it.
6106
+ if (o.model != null && String(o.model).trim() && resolveModelPreference(String(o.model), done.harness || meta.harness) !== done.model) throw oatsError("E_SESSION_RUNNING", `${meta.instance} is already running with its previously requested model; its target was recovered, but the new model was not applied`);
6107
+ if (o.launchConfig !== undefined || o.harness !== undefined || o.yolo !== undefined) throw oatsError("E_SESSION_RUNNING", `${meta.instance} is already running (its pending start was recovered); the requested launch configuration, harness or yolo was not applied; stop it, or use session restart`);
6108
+ return { ...done, warnings: [...done.warnings, ...movedWarnings] };
6109
+ }
5983
6110
  }
5984
6111
  }
5985
6112
  }
@@ -6141,6 +6268,8 @@ export function startInstanceSession(home, o = {}) {
6141
6268
  const planExtra = launchPlan ? { launch: launchPlan.recipe, harness: launchPlan.harness, yolo: launchPlan.yolo, ...(launchPlan.modelFrom ? { modelFrom: launchPlan.modelFrom } : {}),
6142
6269
  ...(launchPlan.launchFrom ? { launchFrom: launchPlan.launchFrom, launchAt: launchPlan.launchAt, launchDeclared: launchPlan.launchDeclared } : {}),
6143
6270
  ...(hookMeta ? { hookMeta } : {}) } : (explicitModelFrom ? { modelFrom: explicitModelFrom } : {});
6271
+ const launchPromptAnswers = launchPromptPolicyAt(dirname(dirname(dirname(dirname(home)))), realHome);
6272
+ if (promptOptedIn(launchPromptAnswers)) warnings.push(LAUNCH_PROMPT_UPDATE_WARNING);
6144
6273
  let stopReceipt = null;
6145
6274
  if (state.present && state.state !== "shell") {
6146
6275
  // Restart: every preflight above passed, so ask the running harness to
@@ -6158,6 +6287,9 @@ export function startInstanceSession(home, o = {}) {
6158
6287
  writeKernelShim(realHome);
6159
6288
  const startedAt = new Date().toISOString();
6160
6289
  const id = randomUUID();
6290
+ const makeLaunchController = () => promptOptedIn(launchPromptAnswers) ? promptController(realHome, id, launchPlan?.harness || harness, launchPromptAnswers, command, o.io, originalHomeIdentity) : null;
6291
+ let launchController;
6292
+ let launchPromptTarget, launchPrompts, beforeRespawn, promptDispatched = false;
6161
6293
  checkRoots();
6162
6294
  const windowCommand = () => paneCommand(`${nativeRecordCommand(command, realHome, launchPlan?.harness || harness)}; oats_start_status=$?; printf '%s\\n' ${shq(id)} > ${shq(exitedPath)}`);
6163
6295
  let reused = "new";
@@ -6170,36 +6302,68 @@ export function startInstanceSession(home, o = {}) {
6170
6302
  // the agent's own pane: the command runs there, on the server the home
6171
6303
  // recorded, no other window touched and no option set.
6172
6304
  const inPlace = state.paneId && (state.present || state.state === "stopped");
6173
- if (inPlace) {
6174
- checkRoots();
6175
- writeJsonAtomic(pendingPath, { id, target, command, model: model ?? null, startedAt, ...planExtra }, 0o600);
6176
- try { tmuxOn(socket, ["respawn-pane", "-k", "-t", state.paneId, "-c", realHome, ...paneEnvFlags, windowCmd], o.io, oatsWindowEnvironment()); }
6177
- catch (e) { throw launchFailure(e); }
6178
- reused = "pane";
6179
- } else {
6180
- const instancesRoot = dirname(realHome);
6181
- const hq = existsSync(dirname(dirname(instancesRoot))) ? dirname(dirname(instancesRoot)) : realHome;
6182
- checkRoots();
6183
- // A replacement window (never launched, recorded window gone, recorded server gone) is created
6184
- // on the OATS server, wherever the home was recorded: one socket from here to the record.
6185
- const recordedSocket = socket ? resolve(socket) : null;
6186
- socket = ensureOatsTmuxSession(session, hq, o.io, tmuxSessionPlan);
6187
- if (lookAgain(() => panePath(socket, session, o.io, realHome))) { planExtra.launch = launchPlan.recipe; windowCmd = windowCommand(); }
6188
- let names;
6189
- try { names = tmuxOn(socket, ["list-windows", "-t", `=${session}`, "-F", "#{window_name}"], o.io).split("\n").filter(Boolean); }
6190
- catch (e) {
6191
- if (oatsCoded(e)) throw e;
6192
- throw oatsError("E_SESSION_UNKNOWN", `cannot list tmux windows on ${socket}: ${tmuxFailure(e, "tmux list-windows failed")}`);
6305
+ try {
6306
+ if (inPlace) {
6307
+ launchController = makeLaunchController();
6308
+ if (launchController) {
6309
+ try {
6310
+ const oldTarget = launchPromptTransport(o.io).identity(socket, state.paneId);
6311
+ beforeRespawn = launchController.captureBeforeRespawn(oldTarget);
6312
+ } catch { /* a missing prior capture can never authorize input */ }
6313
+ }
6314
+ checkRoots();
6315
+ writeJsonAtomic(pendingPath, { id, target, command, model: model ?? null, startedAt, ...planExtra }, 0o600);
6316
+ promptDispatched = !!launchController;
6317
+ try {
6318
+ const output = tmuxOn(socket, ["respawn-pane", "-k", "-t", state.paneId, "-c", realHome, ...paneEnvFlags, windowCmd, ...(launchController ? [";", "display-message", "-p", "-t", state.paneId, LAUNCH_PANE_FORMAT] : [])], o.io, oatsWindowEnvironment());
6319
+ if (launchController) launchPromptTarget = { ...target, ...launchPaneTarget(socket, output) };
6320
+ }
6321
+ catch (e) { throw launchFailure(e); }
6322
+ reused = "pane";
6323
+ } else {
6324
+ const instancesRoot = dirname(realHome);
6325
+ const hq = existsSync(dirname(dirname(instancesRoot))) ? dirname(dirname(instancesRoot)) : realHome;
6326
+ checkRoots();
6327
+ // A replacement window (never launched, recorded window gone, recorded server gone) is created
6328
+ // on the OATS server, wherever the home was recorded: one socket from here to the record.
6329
+ const recordedSocket = socket ? resolve(socket) : null;
6330
+ socket = ensureOatsTmuxSession(session, hq, o.io, tmuxSessionPlan);
6331
+ if (lookAgain(() => panePath(socket, session, o.io, realHome))) { planExtra.launch = launchPlan.recipe; windowCmd = windowCommand(); }
6332
+ let names;
6333
+ try { names = tmuxOn(socket, ["list-windows", "-t", `=${session}`, "-F", "#{window_name}"], o.io).split("\n").filter(Boolean); }
6334
+ catch (e) {
6335
+ if (oatsCoded(e)) throw e;
6336
+ throw oatsError("E_SESSION_UNKNOWN", `cannot list tmux windows on ${socket}: ${tmuxFailure(e, "tmux list-windows failed")}`);
6337
+ }
6338
+ if (names.includes(window)) throw oatsError("E_SESSION_RUNNING", `tmux window ${session}:${window} appeared on ${socket} during the start; nothing was started`);
6339
+ target = { backend: "tmux", session, window, socket };
6340
+ launchController = makeLaunchController();
6341
+ checkRoots();
6342
+ writeJsonAtomic(pendingPath, { id, target, command, model: model ?? null, startedAt, ...planExtra }, 0o600);
6343
+ promptDispatched = !!launchController;
6344
+ try {
6345
+ const output = tmuxOn(socket, ["new-window", "-P", "-F", launchController ? LAUNCH_PANE_FORMAT : "#{window_id}", "-t", `=${session}:`, "-n", window, "-c", realHome, ...paneEnvFlags, windowCmd], o.io, oatsWindowEnvironment()).trim();
6346
+ if (launchController) launchPromptTarget = { ...target, ...launchPaneTarget(socket, output) };
6347
+ prepareAgentWindow(socket, launchController ? launchPromptTarget.windowId : output, o.io);
6348
+ }
6349
+ catch (e) { throw launchFailure(e); }
6350
+ if (recordedSocket && recordedSocket !== socket) moved = sessionMovedWarning(meta.instance, recordedSocket, socket);
6193
6351
  }
6194
- if (names.includes(window)) throw oatsError("E_SESSION_RUNNING", `tmux window ${session}:${window} appeared on ${socket} during the start; nothing was started`);
6195
- target = { backend: "tmux", session, window, socket };
6196
- checkRoots();
6197
- writeJsonAtomic(pendingPath, { id, target, command, model: model ?? null, startedAt, ...planExtra }, 0o600);
6198
- try { prepareAgentWindow(socket, tmuxOn(socket, ["new-window", "-P", "-F", "#{window_id}", "-t", `=${session}:`, "-n", window, "-c", realHome, ...paneEnvFlags, windowCmd], o.io, oatsWindowEnvironment()).trim(), o.io); }
6199
- catch (e) { throw launchFailure(e); }
6200
- if (recordedSocket && recordedSocket !== socket) moved = sessionMovedWarning(meta.instance, recordedSocket, socket);
6352
+ if (launchController) launchPrompts = inPlace ? launchController.observeRespawn(launchPromptTarget, beforeRespawn) : launchController.observeNew(launchPromptTarget);
6353
+ } catch (error) {
6354
+ if (!promptDispatched) throw error;
6355
+ launchPrompts = incompleteLaunchPrompt(realHome, id, launchPromptTarget ?? target, "launch prompt dispatch or recording incomplete", launchPrompts, originalHomeIdentity);
6201
6356
  }
6202
6357
  target = { backend: "tmux", session, window, socket: resolve(socket) };
6358
+ if (launchPrompts) {
6359
+ try { assertLaunchHome(realHome, originalHomeIdentity); }
6360
+ catch { throw retainedPromptError(realHome, meta.instance, launchPromptTarget ?? target, false, incompleteLaunchPrompt(realHome, id, launchPromptTarget ?? target, "launch home identity changed; metadata retained at original home", launchPrompts, originalHomeIdentity)); }
6361
+ planExtra.launchPrompts = launchPrompts;
6362
+ planExtra.launchPromptTarget = launchPromptTarget ?? target;
6363
+ // Recovery retains evidence but never reconstructs this invocation's answer authority.
6364
+ try { writeJsonAtomic(pendingPath, { id, target, command, model: model ?? null, startedAt, ...planExtra }, 0o600); }
6365
+ catch { throw retainedPromptError(realHome, meta.instance, launchPromptTarget ?? target, false, incompleteLaunchPrompt(realHome, id, launchPromptTarget ?? target, "launch prompt pending receipt incomplete", launchPrompts, originalHomeIdentity)); }
6366
+ }
6203
6367
  // The session exists: its boundary (lib/instance-events.mjs) is recorded
6204
6368
  // now, before the metadata, so a start whose metadata write fails still
6205
6369
  // voids the claims of the session it replaced; its adoption only completes a log it missed.
@@ -6210,9 +6374,11 @@ export function startInstanceSession(home, o = {}) {
6210
6374
  let done;
6211
6375
  try { done = record(meta, { id, target, model, command, startedAt, reused, ...planExtra, ...(stopReceipt ? { stop: stopReceipt } : {}) }, false); }
6212
6376
  catch (e) {
6377
+ if (launchPrompts) throw retainedPromptError(realHome, meta.instance, launchPromptTarget ?? target, false, incompleteLaunchPrompt(realHome, id, launchPromptTarget ?? target, "launch prompt metadata recording incomplete", launchPrompts, originalHomeIdentity));
6213
6378
  if (e.code && String(e.code).startsWith("E_")) throw e;
6214
6379
  throw oatsError("E_SESSION_START_INCOMPLETE", `${meta.instance} was started (tmux ${target.session}:${target.window} on ${target.socket}) but its metadata could not be recorded: ${e.message}; the actual target is kept in ${pendingPath} and the next start adopts it instead of allocating another`);
6215
6380
  }
6381
+ if (launchPrompts && launchPrompts.status !== "completed") throw retainedPromptError(realHome, meta.instance, launchPromptTarget ?? target, false, launchPrompts);
6216
6382
  // Said once the new socket is recorded: a start that could not record leaves it to the adoption.
6217
6383
  if (moved) { appendEvent(realHome, { kind: "launch-warning", data: { message: moved } }); movedWarnings.push(moved); }
6218
6384
  return { ...done, warnings: [...warnings, ...movedWarnings] };
@@ -7383,7 +7549,7 @@ export function retireInstance(root, name, o = {}) {
7383
7549
  }
7384
7550
  }
7385
7551
  if (runtimeAuthority) {
7386
- const metaAgrees = meta.launched === runtimeAuthority.launched && (!runtimeAuthority.launched || tmuxEndpointAgrees(meta, runtimeAuthority));
7552
+ const metaAgrees = launchStateAgrees(meta, runtimeAuthority) && (!runtimeAuthority.launched || tmuxEndpointAgrees(meta, runtimeAuthority));
7387
7553
  if (!metaAgrees) {
7388
7554
  throw oatsError("E_RUNTIME_AUTHORITY_MISMATCH", `cannot quiesce ${name}: mutable instance metadata disagrees with independent runtime endpoint authority`);
7389
7555
  }
@@ -45,7 +45,7 @@ export const EVENTS_API = 2;
45
45
  const HOME_LOG = ".oats-events.jsonl";
46
46
  const MAX_BYTES = 4 * 1024 * 1024;
47
47
 
48
- export const EVENT_KINDS = ["spawned", "launched", "restarted", "stopped", "stop-refused", "retire-planned", "retired", "worktree-retained", "worktree-removed", "branch-deleted", "child-spawn-refused", "launch-warning", "recomposed", "waiting"];
48
+ export const EVENT_KINDS = ["spawned", "launched", "restarted", "stopped", "stop-refused", "retire-planned", "retired", "worktree-retained", "worktree-removed", "branch-deleted", "child-spawn-refused", "launch-warning", "launch-prompt", "recomposed", "waiting"];
49
49
 
50
50
  /** Kernel rows that end or begin a session: a waiting claim older than the
51
51
  * incarnation's latest one is not live. */