@awebai/oats 0.66.0 → 0.68.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 (81) hide show
  1. package/bin/oats.mjs +166 -17
  2. package/docs/capabilities.md +58 -9
  3. package/docs/capability-manifest.schema.json +5 -1
  4. package/docs/design/2026-10-22-module-upgrade.md +192 -0
  5. package/docs/design/README.md +4 -0
  6. package/docs/desktop-cli-api.md +463 -13
  7. package/docs/desktop.md +363 -67
  8. package/docs/first-team.md +5 -3
  9. package/docs/implementation.md +46 -6
  10. package/docs/integrations.md +16 -4
  11. package/docs/knowledge.md +44 -27
  12. package/docs/layers.md +2 -2
  13. package/docs/official-catalog.md +5 -5
  14. package/docs/packages.md +14 -14
  15. package/docs/release-lane.md +16 -0
  16. package/docs/release-notes/v0.67.0.md +366 -0
  17. package/docs/release-notes/v0.67.1.md +64 -0
  18. package/docs/release-notes/v0.68.0.md +504 -0
  19. package/docs/servers.md +8 -2
  20. package/docs/souls-and-instances.md +58 -6
  21. package/docs/tui.md +1033 -237
  22. package/docs/upgrading.md +164 -26
  23. package/docs/workspaces.md +2 -2
  24. package/lib/capability-contract.mjs +8 -7
  25. package/lib/core.mjs +331 -75
  26. package/lib/instance-color.mjs +58 -0
  27. package/lib/instance-events.mjs +1 -1
  28. package/lib/instance-inspect.mjs +107 -23
  29. package/lib/instance-lifecycle.mjs +21 -1
  30. package/lib/instance-naming.mjs +187 -0
  31. package/lib/instance-resolution.mjs +10 -6
  32. package/lib/instance-upgrade.mjs +1445 -0
  33. package/lib/materialize.mjs +287 -89
  34. package/lib/servers.mjs +24 -11
  35. package/lib/soul-composition.mjs +7 -3
  36. package/lib/upgrade-state.mjs +101 -0
  37. package/lib/workspace.mjs +4 -1
  38. package/lib/worktree.mjs +103 -12
  39. package/package-catalog.json +5 -4
  40. package/package.json +1 -1
  41. package/packages/client/cli-adapter.mjs +52 -6
  42. package/packages/client/cli-locator.mjs +2 -2
  43. package/packages/client/composed-gate.mjs +10 -2
  44. package/packages/client/deployment-data.mjs +5 -0
  45. package/packages/client/deployment-identity.mjs +40 -0
  46. package/packages/client/deployment-panel.mjs +9 -3
  47. package/packages/client/inspect-boundary.mjs +11 -7
  48. package/packages/client/inspect-cache.mjs +2 -2
  49. package/packages/client/instance-name.mjs +28 -0
  50. package/packages/client/instance-presentation.mjs +11 -0
  51. package/packages/client/keymap.mjs +133 -28
  52. package/packages/client/keys-file.mjs +126 -0
  53. package/packages/client/own-codes.mjs +4 -2
  54. package/packages/client/panel-views.mjs +78 -12
  55. package/packages/client/spawn-naming.mjs +32 -0
  56. package/packages/client/spawn-preview-cli.mjs +58 -7
  57. package/packages/client/spawn-preview-contract.mjs +59 -0
  58. package/packages/client/spawn-preview-facts.mjs +8 -4
  59. package/packages/client/spawn-preview.mjs +81 -3
  60. package/packages/client/team-members.mjs +4 -1
  61. package/packages/client/workspace-step.mjs +25 -0
  62. package/packages/tui/README.md +7 -7
  63. package/packages/tui/lib/actions.mjs +92 -25
  64. package/packages/tui/lib/client.mjs +9 -4
  65. package/packages/tui/lib/config.mjs +50 -9
  66. package/packages/tui/lib/main.mjs +65 -24
  67. package/packages/tui/lib/model.mjs +292 -75
  68. package/packages/tui/lib/read.mjs +53 -1
  69. package/packages/tui/lib/store.mjs +469 -100
  70. package/packages/tui/lib/term/keys.mjs +22 -6
  71. package/packages/tui/lib/term/kitty.mjs +54 -11
  72. package/packages/tui/lib/term/screen.mjs +15 -6
  73. package/packages/tui/lib/term/through.mjs +66 -28
  74. package/packages/tui/lib/views/frame.mjs +223 -165
  75. package/packages/tui/lib/views/help.mjs +134 -29
  76. package/packages/tui/lib/views/instances.mjs +63 -22
  77. package/packages/tui/lib/views/palette.mjs +14 -4
  78. package/packages/tui/lib/views/souls.mjs +2 -2
  79. package/packages/tui/lib/views/switcher.mjs +6 -1
  80. package/packages/tui/lib/views/workspaces.mjs +55 -0
  81. package/skills/oats-getting-started/SKILL.md +96 -42
package/lib/core.mjs CHANGED
@@ -50,11 +50,13 @@ import { attachSessionTarget, requireDetachKey } from "./session-viewer.mjs";
50
50
  import { createSessionPaneInspector, inspectSessionTarget, inputSessionTarget } from "./session-input.mjs";
51
51
  import { appendEvent, incarnationOf, liveWaiting, recordStartBoundary, retireRefusedReason } from "./instance-events.mjs";
52
52
  import { killGroup } from "./process-group.mjs";
53
+ import { NAMING_CALLS, NAMING_TIMEOUT_MS, suggestInstanceName } from "./instance-naming.mjs";
53
54
  import { interruptExitStatus, isStartToken, originRemoteOf, runWorktreeHooks, selfIdentity, processLiveness, processStartToken, signalGuard, terminateRecordedGroup, treeStillThere, unknownGroupNote, unverifiedGroupWarning, worktreeHooksOf } from "./worktree-hooks.mjs";
54
55
  import { CLAIM_WAIT_MS, acquireClaim, claimUnavailable, claimUnheld, claimWrite, readClaim, releaseClaim, removeGoneClaim, shownHolder, unwritableCode } from "./claim.mjs";
55
56
  import { isInstant as isInstantString, readRetireState } from "./retire-state.mjs";
56
57
  import { captureLoginEnvironment } from "./login-environment.mjs";
57
58
  import { kernelNode } from "./stable-node.mjs";
59
+ import { assertNoPartialUpgrade, packageUpgradeDrift, upgradeCleanupWarnings, upgradeMutexRetry, UPGRADE_RECEIPT_NAME_RE } from "./upgrade-state.mjs";
58
60
 
59
61
  import { oatsError, afterEndedSteps, afterFirstEffect, asKernelError, BEFORE_EFFECT_CODES, checkHolderByHand, errorCause, ifItDoesNotEnd, isAnswerCode, isKernelCode, kernelCode, lifecycleBusy, nothingAfter, reportDefect, OWN_NAME_FAILURES, OWN_START_REMEDY, herdrInstanceBusy, herdrInstanceRemoved, herdrSettingRemoved, HERDR_REMOVED } from "./errors.mjs";
60
62
  import { envRows, recordedTeams, teamsEnv } from "./teams.mjs";
@@ -62,13 +64,14 @@ import { PANE_PATH_FIX, harnessNotOnPanePath, harnessUnavailable, launchConfigAm
62
64
  import { shq, shellWord } from "./shell-word.mjs";
63
65
  import { CONFIG_DIR_VAR, HARNESS_FOLDER_VAR, claudeTrusts, codexTrustsRoot, harnessConfigFile, harnessTrustWarning, launchConfigFolder } from "./harness-trust.mjs";
64
66
  async function materializePreparedDefault(prepared, home) { const m = await import("./instance-resolution.mjs"); return m.materializePrepared(prepared, home); }
67
+ async function plannedSkillsDefault(prepared) { const m = await import("./instance-resolution.mjs"); return m.plannedPreparedSkills(prepared); }
65
68
  // Capability rows for a PREPARED spawn (workspace model): the one function that
66
69
  // turns a Resolution's modules into the row shape hooks/environment/requirements/
67
70
  // retirement consume. Called twice per spawn — PLANNED before the home exists
68
71
  // (manifest, settings, origin, trust; no skills/inject since the copies are not
69
72
  // there yet) and REBUILT after materialize against what actually landed. Static
70
73
  // import: instance-resolution.mjs does not depend on core.mjs (no cycle).
71
- import { cloneRemoteFor, resolutionContractWarnings, toCapabilityRows, verifyMemberClone } from "./instance-resolution.mjs";
74
+ import { cloneRemoteFor, deploymentLock, resolutionContractWarnings, toCapabilityRows, verifyMemberClone } from "./instance-resolution.mjs";
72
75
  import { GIT_FETCH_TIMEOUT_MS, GIT_TIMEOUT_MS, gitEnv } from "./remote.mjs";
73
76
  import { loadLocal } from "./workspace.mjs";
74
77
  import { parseConfigData } from "./config-data.mjs";
@@ -90,6 +93,7 @@ import { assertSameWorktreeHead, gitRead, gitRefPresence, gitRepoRead, gitRepoRu
90
93
  import { systemTool } from "./system-tools.mjs";
91
94
  import { creatorPlacement, serverScopePlan, serverScopeUnit, serverScopeWarning } from "./tmux-server-scope.mjs";
92
95
  import { writeThroughPrivateFile } from "./write-through-private-file.mjs";
96
+ import { readInstanceColor } from "./instance-color.mjs";
93
97
  /** The package and capability id grammar (namespaced, lowercase): an id names a
94
98
  * directory (a home's module copy), so no path spelling fits it. */
95
99
  const PACKAGE_ID_RE = /^[a-z0-9][a-z0-9._-]*$/;
@@ -608,7 +612,9 @@ export const RESERVED_LAUNCH_ENV = new Set(["OATS_INSTANCE", "OATS_INSTANCE_HOME
608
612
  "OATS_TEST_WORKTREE_HOOK_TIMEOUT_MS", "OATS_TEST_WORKTREE_FETCH_TIMEOUT_MS", "OATS_TEST_PROCESS_START_PS",
609
613
  // The test seams of #915: the cgroup the kernel judges itself in, and the directories its systemd-run
610
614
  // comes from (lib/tmux-server-scope.mjs, lib/system-tools.mjs).
611
- "OATS_TEST_CGROUP", "OATS_TEST_SYSTEM_TOOL_DIRS"]);
615
+ "OATS_TEST_CGROUP", "OATS_TEST_SYSTEM_TOOL_DIRS",
616
+ // The test seam of #1421 §3: the naming call's time limit (lib/instance-naming.mjs NAMING_TIMEOUT_MS).
617
+ "OATS_TEST_NAMING_TIMEOUT_MS"]);
612
618
  export const LAUNCH_REF_PREFIX = "OATS_LAUNCH_REF_";
613
619
  const reservedLaunchEnv = (n) => RESERVED_LAUNCH_ENV.has(n) || n.startsWith(LAUNCH_REF_PREFIX);
614
620
  export function validateLaunchConfig(name, entry, where) {
@@ -1141,8 +1147,8 @@ function plannedCapabilityRows(resolution) {
1141
1147
  * `node <abs script> <args>`, exactly as `manifestHookCommands` renders a classic
1142
1148
  * capability. The script must exist inside the module's copy under
1143
1149
  * <home>/.oats/modules/<cap>/ — a path escaping it is a manifest defect. Only
1144
- * the events the kernel approves (soul-scaffold, spawn, retire, launch, worktree) are kept. */
1145
- function materializedHookCommands(row, home) {
1150
+ * the events the kernel approves (soul-scaffold, spawn, retire, launch, worktree, upgrade) are kept. */
1151
+ export function materializedHookCommands(row, home) {
1146
1152
  const out = {};
1147
1153
  const moduleDir = row.dir || join(home, ".oats", "modules", row.id);
1148
1154
  for (const [event, spec] of Object.entries(row.hooks || {})) {
@@ -3244,6 +3250,16 @@ export function kernelBin() { return realpathSync(join(PKG_ROOT, "bin", "oats.mj
3244
3250
  /** Where a home's `oats` lives: first on its harness's PATH, so plain `oats` inside an instance is
3245
3251
  * the kernel that launched it, whatever other `oats` the host's PATH finds first. */
3246
3252
  export const kernelShimDir = (home) => join(home, ".oats", "bin");
3253
+ /** Inspect existing shim parents without following them or creating anything.
3254
+ * Receipt fences must preserve this refusal for an unsafe module root. */
3255
+ function assertKernelShimParents(home) {
3256
+ for (const path of [join(home, ".oats"), kernelShimDir(home)]) {
3257
+ let stat;
3258
+ try { stat = lstatSync(path); }
3259
+ catch (error) { if (error.code === "ENOENT") return; throw error; }
3260
+ if (!stat.isDirectory()) throw oatsError("E_LAUNCH_SHIM", `cannot write the kernel shim ${join(kernelShimDir(home), "oats")}: ${path} is ${stat.isSymbolicLink() ? "a symbolic link" : "not a directory"}; nothing was started`);
3261
+ }
3262
+ }
3247
3263
  /** Write <home>/.oats/bin/oats, a symlink to this kernel's CLI, replacing any shim a previous
3248
3264
  * launch (perhaps by another kernel) left: built aside, then renamed over. `.oats` and `.oats/bin`
3249
3265
  * must be directories of the home itself: a link there would carry the write outside the home.
@@ -3254,6 +3270,7 @@ export function writeKernelShim(home) {
3254
3270
  let target, aside;
3255
3271
  try {
3256
3272
  target = kernelBin();
3273
+ assertKernelShimParents(home);
3257
3274
  for (const d of [join(home, ".oats"), dir]) {
3258
3275
  let st;
3259
3276
  try { st = lstatSync(d); }
@@ -3730,6 +3747,72 @@ function callerSpawnOrigin(root) {
3730
3747
  return matches.some((m) => realpathSync(m.home) === canonical) ? "instance" : "operator";
3731
3748
  } catch { return "operator"; }
3732
3749
  }
3750
+ /** A soul name as a spawn names it, by shape only: a slug, after an optional `<package or member>/`
3751
+ * and an optional `<package>--` (lib/instance-naming.mjs soulRole reads its role from the same). */
3752
+ const SOUL_NAME_SHAPE = /^(?:[A-Za-z0-9][A-Za-z0-9._-]*(?:\/[A-Za-z0-9][A-Za-z0-9._-]*)*\/)?(?:[a-z0-9]+(?:-[a-z0-9]+)*--)?[a-z0-9]+(?:-[a-z0-9]+)*$/;
3753
+ /** `oats instance suggest-name` (feature instance-suggest-name, awebai/oats#1490 §2): the name a spawn
3754
+ * of `soul` would get by `--suggest-name`, chosen on THIS machine for a spawn that may land on another.
3755
+ * `soul` is only a name (it gives the role) and needn't exist here: nothing resolves it. It resolves no
3756
+ * souls, members, lock or remote: it reads only this machine's launch configurations (the
3757
+ * oats-local.yaml in reach of `dir`) and the OATS tmux server's environment, writes nothing and
3758
+ * reserves no name. The name is not made unique: the host the spawn lands on owns uniqueness
3759
+ * (E_INSTANCE_NAME_TAKEN at its apply). The harness: `harness`, else the configuration's, else claude;
3760
+ * its executable and environment are what a spawn here would launch it with (`launchConfig`, else this
3761
+ * machine's default configuration for the harness), and the call is the preview's (lib/instance-
3762
+ * naming.mjs: its argv, isolation and bounds), the only process it starts. The model: `model`, else the
3763
+ * configuration's (`@native-default` for none; a list's first entry, with no catalogue probe). → Promise
3764
+ * of `{ name?, naming }`, `name` only when `naming.source` is "suggested". A naming failure is never an
3765
+ * error (an executable that is not there is `harness-failed`); bad arguments are. */
3766
+ export async function suggestSpawnName({ dir = process.cwd(), soul, task, harness: asked, model: askedModel, launchConfig: named } = {}) {
3767
+ if (typeof soul !== "string" || soul.length > 256 || !SOUL_NAME_SHAPE.test(soul)) throw oatsError("E_BAD_ARGS", `--soul ${JSON.stringify(soul)} is not a soul name (a slug, optionally qualified as <package>/<soul>)`);
3768
+ if (typeof task !== "string") throw oatsError("E_BAD_ARGS", "the task must be text");
3769
+ if (asked !== undefined && !LAUNCH_HARNESSES.includes(asked)) throw oatsError("E_BAD_ARGS", `--harness must be one of ${LAUNCH_HARNESSES.join("|")}`);
3770
+ if (askedModel !== undefined && (typeof askedModel !== "string" || !askedModel)) throw oatsError("E_BAD_ARGS", "--model needs a model id");
3771
+ let deployment = null;
3772
+ try { deployment = dirname(loadLocal(dir).path); } catch (e) { if (e?.code !== "E_LOCAL_MISSING") throw e; }
3773
+ const configs = deployment ? launchConfigsAt(deployment) : Object.create(null);
3774
+ let config = null;
3775
+ if (named !== undefined && named !== "none") {
3776
+ if (typeof named !== "string" || !Object.hasOwn(configs, named)) throw launchConfigUnknown({ name: named, from: "flag", at: "--launch-config" });
3777
+ config = configs[named];
3778
+ if (asked !== undefined && asked !== config.harness) throw oatsError("E_BAD_ARGS", `launch configuration ${named} runs ${config.harness}, not ${asked}: a named configuration is a unit; drop --harness or name another configuration`);
3779
+ }
3780
+ const harness = asked ?? config?.harness ?? "claude";
3781
+ if (named === undefined) config = harnessDefaultConfig(configs, harness);
3782
+ // Where a spawn here would look: the configuration's env, else the OATS tmux server's when one runs
3783
+ // (never started for this), else this process's; relative PATH entries from this process's directory.
3784
+ const launchEnv = launchEnvironment({ configEnv: config?.env, configName: config?.name, env: process.env, pane: () => previewPaneEnvironment({ deployment: deployment ?? dir }), cwd: process.cwd() });
3785
+ let bin = null, problem = null;
3786
+ const missing = missingLaunchEnvRefs(config?.env || {}, process.env);
3787
+ if (missing.length) problem = `launch configuration ${config.name} references ${missing.join(", ")}, not set in this environment`;
3788
+ else {
3789
+ try {
3790
+ const executable = resolveLaunchExecutable({ harness, declared: config?.executable, declaringDir: config?.source, contextDir: deployment ?? undefined, lookup: config?.executable?.includes("/") ? undefined : launchLookup(launchEnv) });
3791
+ if (!executable.path) problem = config?.executable ? `launch configuration ${config.name}: ${executable.missing}` : `${harness} is not installed on this machine (${executable.missing})`;
3792
+ else {
3793
+ const bad = checkLaunchExecutable(executable.path);
3794
+ if (bad) problem = config ? `launch configuration ${config.name}: ${bad}` : bad; else bin = executable.path;
3795
+ }
3796
+ } catch (e) { if (!isKernelCode(e?.code)) throw e; problem = e.message; }
3797
+ }
3798
+ // The model, read as a spawn reads it (resolveLaunchSelection) but with no catalogue probe: the naming
3799
+ // call is the only process this command starts. `@native-default` is none; a pi preference list names
3800
+ // its first entry (pi answers one it cannot use as harness-failed); another harness's list is
3801
+ // resolveModelPreference's, which starts nothing for it.
3802
+ const preference = askedModel ?? (typeof config?.model === "string" && config.model ? config.model : undefined);
3803
+ const firstEntry = (list) => list.split(",").map((m) => m.trim()).find(Boolean) ?? "";
3804
+ const namingModel = preference === undefined || preference === NATIVE_DEFAULT_MODEL ? null : (harness === "pi" ? firstEntry(preference) : resolveModelPreference(preference, harness)) || null;
3805
+ const seam = Number(process.env.OATS_TEST_NAMING_TIMEOUT_MS);
3806
+ const call = {
3807
+ soulName: soul, harness, bin, task, timeoutMs: seam > 0 ? seam : NAMING_TIMEOUT_MS,
3808
+ instanceModel: namingModel,
3809
+ env: () => launchEffectiveEnv({ base: process.env, configEnv: config?.env || {}, launch: launchEnv, harness }),
3810
+ taken: () => false,
3811
+ };
3812
+ // The call's own answers come first (no task, a harness with no naming call); then no executable.
3813
+ if (problem && task.trim() && Object.hasOwn(NAMING_CALLS, harness)) return { naming: { source: "numbered", reason: "harness-failed", message: `${harness} could not be run: ${problem}`, ms: 0 } };
3814
+ return suggestInstanceName(call);
3815
+ }
3733
3816
  export async function spawnInstanceAsync(root, agent, o = {}) {
3734
3817
  const it = spawnBody(root, agent, o);
3735
3818
  let step = it.next();
@@ -3822,6 +3905,20 @@ function* spawnBody(root, agent, o = {}) {
3822
3905
  }
3823
3906
  }
3824
3907
 
3908
+ // --suggest-name (features spawn-suggest-name, spawn-apply-suggest-name: awebai/oats#1421 §3,
3909
+ // #1490 §3): a spawn that also chooses the name, by a naming call through this launch's harness and
3910
+ // executable, under its environment, after the preflight's probes (below, where the executable is
3911
+ // known): a preview's within its one budget, an apply's within NAMING_TIMEOUT_MS. Until then the
3912
+ // spawn proceeds with the numbered name, holding any refusal that is that name's own
3913
+ // (`provisional`); a suggested name is then placed exactly as `--name <suggested>` is, so a
3914
+ // preview's instance, home, branch and decision are that preview's, and an apply with `--name
3915
+ // <instance> --expect-decision <revision>` matches it. Otherwise the numbered name stands, its held
3916
+ // refusal with it. `naming` says which, and why; a failed call is never an error.
3917
+ let naming, provisional;
3918
+ const suggesting = o.suggestName === true;
3919
+ if (suggesting && (o.name !== undefined || o.purpose !== undefined || o.instance !== undefined || o.expectDecision !== undefined)) {
3920
+ throw oatsError("E_BAD_ARGS", o.expectDecision !== undefined ? "--suggest-name chooses the name, and --expect-decision's decision already binds one: apply the previewed name with --name <instance> --expect-decision <revision>" : "--suggest-name chooses the name: it takes no --name or --purpose");
3921
+ }
3825
3922
  if (o.name !== undefined && (o.purpose !== undefined || o.instance !== undefined)) throw oatsError("E_BAD_ARGS", "name and purpose are mutually exclusive: --name is the exact instance name, --purpose derives <soul>-<purpose>");
3826
3923
  let instance;
3827
3924
  if (o.name !== undefined) instance = explicitInstanceName(o.name);
@@ -3951,6 +4048,7 @@ function* spawnBody(root, agent, o = {}) {
3951
4048
  // too, since the anchor's instance.json is re-pointed.
3952
4049
  let anchorHome;
3953
4050
  let anchorRoot;
4051
+ let reverseShadow = () => null;
3954
4052
  if (relativeTo) {
3955
4053
  const hits = [];
3956
4054
  for (const h of findInstanceHomes(root, relativeTo)) hits.push({ root, home: h.home });
@@ -3985,11 +4083,16 @@ function* spawnBody(root, agent, o = {}) {
3985
4083
  // relation=parent re-points the ANCHOR at the NEW instance by bare name:
3986
4084
  // that reverse edge must round-trip from the ANCHOR's root as well.
3987
4085
  if (relation === "parent") {
3988
- const rev = findInstanceHome(chosen.root, instance);
3989
4086
  // The new instance does not exist yet — a hit here IS a shadow.
3990
- if (rev) throw Object.assign(
3991
- new Error(`relation "parent": an existing instance named "${instance}" (${rev.home}) would shadow the new instance from the anchor's root — the re-pointed edge would resolve to the wrong instance; pick a different --purpose or --name`),
3992
- { code: "E_RELATIVE_AMBIGUOUS" });
4087
+ reverseShadow = (name) => {
4088
+ const rev = findInstanceHome(chosen.root, name);
4089
+ return rev ? Object.assign(
4090
+ new Error(`relation "parent": an existing instance named "${name}" (${rev.home}) would shadow the new instance from the anchor's root — the re-pointed edge would resolve to the wrong instance; pick a different --purpose or --name`),
4091
+ { code: "E_RELATIVE_AMBIGUOUS" }) : null;
4092
+ };
4093
+ const shadow = reverseShadow(instance);
4094
+ if (shadow && !suggesting) throw shadow;
4095
+ provisional ??= shadow ?? undefined;
3993
4096
  }
3994
4097
  }
3995
4098
  }
@@ -4070,47 +4173,54 @@ function* spawnBody(root, agent, o = {}) {
4070
4173
  }
4071
4174
  }
4072
4175
 
4073
- const home = join(agent._dir, "instances", instance);
4074
- // A home that exists already is the same refusal as losing the exclusive mkdir below (a
4075
- // concurrent apply that got there first, or anything else): E_PLACEMENT_TAKEN, nothing created.
4076
- if (existsSync(home)) throw Object.assign(oatsError("E_PLACEMENT_TAKEN", `${instance} already exists at ${home}; nothing was created by this call`), { instance, home });
4077
- // AUTHORITATIVE placement check, on the DESTINATION rather than on lexical
4078
- // paths, immediately before the first side effect. The earlier root/agent-dir
4079
- // checks are lexical and can be walked around by a symlink anywhere along the
4080
- // way — `agents/alias -> <linked-worktree>/agents/dev`, or a pre-existing
4081
- // `agent._dir/instances` symlink — which classifies as the primary checkout
4082
- // while the home is really created in the worktree (reviewer-249aa7b).
4083
- // Resolving through the nearest existing ancestor is what closes that.
4084
- const homeReal = realPathOrNearest(home);
4085
- const homeCanonical = canonicalDeploymentPath(homeReal);
4086
- if (resolve(homeCanonical) !== resolve(homeReal)) {
4087
- throw oatsError("E_NO_CANONICAL_ROOT", `instance home ${home} resolves to ${homeReal}, inside a linked Git worktree — homes must be created in the primary checkout (${homeCanonical}); a symlink on the path to the agent directory or its instances/ dir does not change where the home really lands`);
4088
- }
4089
- // CONTAINMENT, which the check above does not give. canonicalDeploymentPath
4090
- // only redirects paths inside a LINKED WORKTREE; an escape to a directory Git
4091
- // does not own at all comes back unchanged and passed (reviewer-aggregate2 —
4092
- // reproduced: a pre-existing `instances/` symlink to a sibling temp dir spawned
4093
- // successfully, reporting a home under the deployment while the real one, with
4094
- // the capability credentials a hook writes into it, was created outside).
4095
- // The home must BE the immediate `instances/` child of the resolved agent
4096
- // directory, and that directory must live in this deployment.
4097
- const withinDir = (child, parent) => {
4098
- const rel = relative(parent, child);
4099
- return rel === "" || (!!rel && !rel.startsWith("..") && !isAbsolute(rel));
4176
+ // The home and its placement checks, for a name: the numbered one here, a suggested one again below.
4177
+ const place = (name) => {
4178
+ const home = join(agent._dir, "instances", name);
4179
+ // A home that exists already is the same refusal as losing the exclusive mkdir below (a
4180
+ // concurrent apply that got there first, or anything else): E_PLACEMENT_TAKEN, nothing created.
4181
+ if (existsSync(home)) throw Object.assign(oatsError("E_PLACEMENT_TAKEN", `${name} already exists at ${home}; nothing was created by this call`), { instance: name, home });
4182
+ // AUTHORITATIVE placement check, on the DESTINATION rather than on lexical
4183
+ // paths, immediately before the first side effect. The earlier root/agent-dir
4184
+ // checks are lexical and can be walked around by a symlink anywhere along the
4185
+ // way — `agents/alias -> <linked-worktree>/agents/dev`, or a pre-existing
4186
+ // `agent._dir/instances` symlink — which classifies as the primary checkout
4187
+ // while the home is really created in the worktree (reviewer-249aa7b).
4188
+ // Resolving through the nearest existing ancestor is what closes that.
4189
+ const homeReal = realPathOrNearest(home);
4190
+ const homeCanonical = canonicalDeploymentPath(homeReal);
4191
+ if (resolve(homeCanonical) !== resolve(homeReal)) {
4192
+ throw oatsError("E_NO_CANONICAL_ROOT", `instance home ${home} resolves to ${homeReal}, inside a linked Git worktree — homes must be created in the primary checkout (${homeCanonical}); a symlink on the path to the agent directory or its instances/ dir does not change where the home really lands`);
4193
+ }
4194
+ // CONTAINMENT, which the check above does not give. canonicalDeploymentPath
4195
+ // only redirects paths inside a LINKED WORKTREE; an escape to a directory Git
4196
+ // does not own at all comes back unchanged and passed (reviewer-aggregate2 —
4197
+ // reproduced: a pre-existing `instances/` symlink to a sibling temp dir spawned
4198
+ // successfully, reporting a home under the deployment while the real one, with
4199
+ // the capability credentials a hook writes into it, was created outside).
4200
+ // The home must BE the immediate `instances/` child of the resolved agent
4201
+ // directory, and that directory must live in this deployment.
4202
+ const withinDir = (child, parent) => {
4203
+ const rel = relative(parent, child);
4204
+ return rel === "" || (!!rel && !rel.startsWith("..") && !isAbsolute(rel));
4205
+ };
4206
+ const agentDirReal = realPathOrNearest(agent._dir);
4207
+ // The only base is the agents root: souls and capability-defined agents alike
4208
+ // live directly under it (the 0.25 local-agents/ bases are gone). The root itself
4209
+ // may legitimately be a symlink (it is the deployment anchor, and OATS is pointed
4210
+ // AT it); the agent dirs OATS derives from it may not lead somewhere else.
4211
+ const allowedBases = [realPathOrNearest(root)];
4212
+ if (!allowedBases.some((b) => withinDir(agentDirReal, b))) {
4213
+ throw oatsError("E_NO_CANONICAL_ROOT", `agent directory for "${agent.name}" resolves to ${agentDirReal}, which is outside this deployment (${allowedBases.join(", ")}) — a symlinked agent directory would place the home, and any capability credentials written into it, outside the deployment entirely`);
4214
+ }
4215
+ const expectedHome = join(agentDirReal, "instances", name);
4216
+ if (resolve(homeReal) !== resolve(expectedHome)) {
4217
+ throw oatsError("E_NO_CANONICAL_ROOT", `instance home ${home} resolves to ${homeReal}, not to ${expectedHome} — a symlinked instances/ directory does not change where the home really lands, and OATS will not create an instance (or the capability credentials that go in it) outside the agent's own directory`);
4218
+ }
4219
+ return { home, homeReal, expectedHome };
4100
4220
  };
4101
- const agentDirReal = realPathOrNearest(agent._dir);
4102
- // The only base is the agents root: souls and capability-defined agents alike
4103
- // live directly under it (the 0.25 local-agents/ bases are gone). The root itself
4104
- // may legitimately be a symlink (it is the deployment anchor, and OATS is pointed
4105
- // AT it); the agent dirs OATS derives from it may not lead somewhere else.
4106
- const allowedBases = [realPathOrNearest(root)];
4107
- if (!allowedBases.some((b) => withinDir(agentDirReal, b))) {
4108
- throw oatsError("E_NO_CANONICAL_ROOT", `agent directory for "${agent.name}" resolves to ${agentDirReal}, which is outside this deployment (${allowedBases.join(", ")}) — a symlinked agent directory would place the home, and any capability credentials written into it, outside the deployment entirely`);
4109
- }
4110
- const expectedHome = join(agentDirReal, "instances", instance);
4111
- if (resolve(homeReal) !== resolve(expectedHome)) {
4112
- throw oatsError("E_NO_CANONICAL_ROOT", `instance home ${home} resolves to ${homeReal}, not to ${expectedHome} — a symlinked instances/ directory does not change where the home really lands, and OATS will not create an instance (or the capability credentials that go in it) outside the agent's own directory`);
4113
- }
4221
+ let home, homeReal, expectedHome;
4222
+ try { ({ home, homeReal, expectedHome } = place(instance)); }
4223
+ catch (e) { if (!suggesting) throw e; provisional ??= e; home = join(agent._dir, "instances", instance); }
4114
4224
  // Compose and PREFLIGHT before the home exists. Composition is pure (it only
4115
4225
  // reads the soul, config chain and capability content), so resolving it here
4116
4226
  // lets every "declared but missing" failure happen with zero side effects to
@@ -4132,8 +4242,14 @@ function* spawnBody(root, agent, o = {}) {
4132
4242
  // Where this launch will run (launchEnvironment): what its configuration sets, else its pane's.
4133
4243
  // `expectedEnv` is the preflight's answer, over the pane this plan expects; the launch reads the
4134
4244
  // session it actually gets (below). A spawn that launches nothing has no pane to read.
4135
- const launchEnvOn = (pane, removed = []) => launchEnvironment({ configEnv: launchConfig?.env, configName: launchConfig?.name, removed, env: process.env, pane, cwd: home });
4136
- const expectedEnv = launchEnvOn(launch ? () => expectedPaneEnvironment(tmuxSessionPlan, session, undefined, home) : NO_LAUNCH);
4245
+ // The pane's working directory only resolves the relative entries of its PATH and its harness
4246
+ // configuration folders. While the name is open (a suggesting preview), a sibling of the homes that
4247
+ // no instance can be named stands in for the home: its `..` entries resolve as the home's do, and
4248
+ // nothing is inside either, so the executable and the probes are the ones the final home would get,
4249
+ // and the naming call runs that same executable.
4250
+ let paneCwd = suggesting ? join(agent._dir, "instances", ".oats-suggest-name") : home;
4251
+ const launchEnvOn = (pane, removed = []) => launchEnvironment({ configEnv: launchConfig?.env, configName: launchConfig?.name, removed, env: process.env, pane, cwd: paneCwd });
4252
+ const expectedEnv = launchEnvOn(launch ? () => expectedPaneEnvironment(tmuxSessionPlan, session, undefined, paneCwd) : NO_LAUNCH);
4137
4253
  // A launched harness is looked up where its pane will look it up (launchLookup): this is the
4138
4254
  // preflight against the expected PATH; the launch looks again on the session it gets. Without a
4139
4255
  // launch (or a known destination) the lookup is this process's PATH, as before.
@@ -4174,8 +4290,35 @@ function* spawnBody(root, agent, o = {}) {
4174
4290
  const note = unestablishedNote(expectedEnv, [...new Set(checks.flatMap(([, names]) => names))]);
4175
4291
  return note ? `${checks.map(([what]) => what).join(", ")}: ${note}` : null;
4176
4292
  };
4177
- if (o.preview === true) { preflight = { status: previewPreflightBudget?.exhausted ? "timeout" : "complete", budgetMs: preflightBudgetMs, elapsedMs: Date.now() - preflightStarted }; previewPreflightBudget = null; }
4178
4293
  const task = o.task ?? (o.taskFile ? readFileSync(o.taskFile, "utf8") : "");
4294
+ // The naming call (#1421 §3): a preview's probes have run, so it takes what is left of their budget
4295
+ // (at most its own 20 s). Its time counts in the preflight's elapsedMs, but the preflight's status
4296
+ // stays its checks': a call the budget ends is `naming.reason` "timeout", and the numbered preview it
4297
+ // leaves is as confirmable as a plain one. An apply has no such budget: the call takes its own 20 s,
4298
+ // before anything is placed, and every later bound of the apply (hooks, the launch) starts after it.
4299
+ let suggested;
4300
+ if (suggesting) {
4301
+ const seam = Number(process.env.OATS_TEST_NAMING_TIMEOUT_MS), own = seam > 0 ? seam : NAMING_TIMEOUT_MS;
4302
+ const left = o.preview === true ? preflightStarted + preflightBudgetMs - Date.now() : own, souls = deploymentSoulNames(root, o.prepared), homes = deploymentInstanceHomes(root);
4303
+ let windows;
4304
+ const suggestion = yield () => suggestInstanceName({
4305
+ soulName: agent.name, harness, bin, instanceModel: model || null, task, timeoutMs: Math.min(own, left),
4306
+ env: () => launchEffectiveEnv({ base: process.env, configEnv: launchConfig?.env || {}, launch: expectedEnv, harness }),
4307
+ taken: (n) => homes.has(n) || souls.has(n) || (windows ??= oatsTmuxWindows(session)).includes(n),
4308
+ });
4309
+ naming = suggestion.naming;
4310
+ suggested = suggestion.name;
4311
+ }
4312
+ if (o.preview === true) { preflight = { status: previewPreflightBudget?.exhausted ? "timeout" : "complete", budgetMs: preflightBudgetMs, elapsedMs: Date.now() - preflightStarted }; previewPreflightBudget = null; }
4313
+ // A suggested name is placed as `--name` places it (its shadow, its home); otherwise the numbered name
4314
+ // keeps its own refusal. From here the home is known: an apply's launch reads its pane from there.
4315
+ if (suggested) {
4316
+ instance = suggested;
4317
+ const shadow = reverseShadow(instance);
4318
+ if (shadow) throw shadow;
4319
+ ({ home, homeReal, expectedHome } = place(instance));
4320
+ } else if (provisional) throw provisional;
4321
+ if (suggesting) paneCwd = home;
4179
4322
 
4180
4323
  if (existsSync(directoryRollbackPath(homeReal))) throw oatsError("E_WORK_INSPECTION_FAILED", `directory cleanup is still owed for ${home}; restore and retire the retained home before reusing its name`);
4181
4324
  // K6: everything a spawn decides is decided by here — and nothing has been
@@ -4226,10 +4369,15 @@ function* spawnBody(root, agent, o = {}) {
4226
4369
  if (o.preview === true) {
4227
4370
  const decision = buildDecision();
4228
4371
  // Workspace model (M3): the preview reports what APPLY will produce — every
4229
- // module as a capability (name + origin) and every module skill by its
4230
- // directory basename with a `module:<cap>` source — not the classic chain's view.
4372
+ // module as a capability (name + origin) and every module skill with a
4373
+ // `module:<cap>` source — not the classic chain's view. The skill names are the
4374
+ // ones materialize copies, by its own precedence (lib/materialize.mjs
4375
+ // plannedModuleSkills: the resolution's rows, else the manifest's, else skills/*
4376
+ // read over the remote), so a root of skills (`skills: ["skills"]`) lists each skill
4377
+ // under it and a manifest with no `skills` its skills/ children, as
4378
+ // `inspect --soul --composed-skills` does.
4231
4379
  const preparedCapabilities = o.prepared.resolution.modules.map((m) => ({ name: m.name, origin: m.from.kind === "package" ? `package:${m.from.package}@${m.from.version}` : `member:${m.from.repoKey}@${m.from.commit}` }));
4232
- const preparedSkills = o.prepared.resolution.modules.flatMap((m) => (m.manifest?.skills || []).filter((s) => typeof s === "string" && s).map((s) => ({ name: basename(s.replace(/\/+$/, "")), source: `module:${m.name}` })));
4380
+ const preparedSkills = (yield () => (o.plannedSkills ?? plannedSkillsDefault)(o.prepared)).map((s) => ({ name: s.name, source: `module:${s.module}` }));
4233
4381
  // R5 (0.25.2, decision 14): the preview shows the provider payloads the apply
4234
4382
  // will record — `providers` is the --provider map exactly as parsed (what the
4235
4383
  // operator typed; prepareInstance keeps it on prepared.spawn.providers) and
@@ -4260,6 +4408,7 @@ function* spawnBody(root, agent, o = {}) {
4260
4408
  relation: relation || null, parentInstance: parentInstance && parentInstance !== instance ? parentInstance : null,
4261
4409
  policy: { childSpawns: ownChildPolicy }, executable: bin, capabilities: preparedCapabilities,
4262
4410
  skills: [...expectedResources.filter((r) => r.type === "skill-tree" && !r.deferred).flatMap((r) => r.entries || []), ...preparedSkills], task: task || null,
4411
+ ...(naming ? { naming } : {}),
4263
4412
  });
4264
4413
  }
4265
4414
  if (o.expectDecision !== undefined) {
@@ -4298,7 +4447,8 @@ function* spawnBody(root, agent, o = {}) {
4298
4447
  if (holders.length > 1) {
4299
4448
  try { rmdirSync(home); } catch { /* empty by construction; leave it rather than recurse */ }
4300
4449
  const other = holders.find((h) => resolve(h) !== resolve(home)) ?? null;
4301
- if (o.name !== undefined) throw Object.assign(oatsError("E_INSTANCE_NAME_TAKEN", `instance name "${instance}" was taken by a concurrent spawn in this deployment (${other}); nothing was created by this call — pick another --name`), { instance, home: other });
4450
+ // A suggested name is refused as the same name given with --name would be.
4451
+ if (o.name !== undefined || suggested) throw Object.assign(oatsError("E_INSTANCE_NAME_TAKEN", `instance name "${instance}" was taken by a concurrent spawn in this deployment (${other}); nothing was created by this call — ${suggested ? "spawn again to have another name suggested" : "pick another --name"}`), { instance, home: other });
4302
4452
  throw Object.assign(oatsError("E_PLACEMENT_TAKEN", `${instance} was taken by a concurrent spawn of another soul (${other}); nothing was created by this call — preview again`), { instance, home: other });
4303
4453
  }
4304
4454
  }
@@ -5124,7 +5274,7 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
5124
5274
  meta.spawnCompleted = true;
5125
5275
  writeFileSync(join(home, "instance.json"), JSON.stringify(meta, null, 2) + "\n"); // a kernel-owned field: the baseline fingerprint ignores it
5126
5276
  }
5127
- return deliver({ ...meta, ...(o.expectDecision !== undefined ? { replayed: false } : {}), ...(worktreeRun ? { worktreeHooks: worktreeRun.receipt } : {}), 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 });
5277
+ return deliver({ ...meta, ...(o.expectDecision !== undefined ? { replayed: false } : {}), ...(worktreeRun ? { worktreeHooks: worktreeRun.receipt } : {}), 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, ...(naming ? { naming } : {}) });
5128
5278
  } catch (error) {
5129
5279
  if (promptDispatched) {
5130
5280
  // Once a launch that engages the confirmation was dispatched, uncertainty retains all effects.
@@ -5343,7 +5493,9 @@ export function listInstances(root, tmuxSession = DEFAULT_TMUX_SESSION, io) {
5343
5493
  // `retire` is only ever the value read above: a record that carries one (hand-edited, or
5344
5494
  // copied from a row) never stands in for it.
5345
5495
  const { retire: _recordedRetire, ...recorded } = meta;
5346
- return { ...recorded, ...claims, home, instance: e.name, ...facts, ...(identity ? { identity } : {}), ...(meta.launch && typeof meta.launch === "object" ? { launch: redactLaunchRecipe(meta.launch) } : {}), ...(typeof meta.command === "string" ? { command: redactLaunchCommand(meta.command) } : {}), ...liveness, waitingOnYou, ...(rollbackIncomplete ? { rollbackIncomplete } : {}), ...(spawnInProgress ? { spawnInProgress } : {}), ...(retirePending ? { retirePending } : {}), ...(retire ? { retire } : {}) };
5496
+ // Feature instance-color: the home's own colour record (lib/instance-color.mjs), a palette name or
5497
+ // null, after the record so that nothing in instance.json stands in for it.
5498
+ return { ...recorded, ...claims, home, instance: e.name, ...facts, color: readInstanceColor(home), ...(identity ? { identity } : {}), ...(meta.launch && typeof meta.launch === "object" ? { launch: redactLaunchRecipe(meta.launch) } : {}), ...(typeof meta.command === "string" ? { command: redactLaunchCommand(meta.command) } : {}), ...liveness, waitingOnYou, ...(rollbackIncomplete ? { rollbackIncomplete } : {}), ...(spawnInProgress ? { spawnInProgress } : {}), ...(retirePending ? { retirePending } : {}), ...(retire ? { retire } : {}) };
5347
5499
 
5348
5500
  });
5349
5501
  };
@@ -5792,7 +5944,7 @@ function retirementBaselineFile(identity) {
5792
5944
  }
5793
5945
 
5794
5946
  /** Where a spawn writes a home's receipt: keyed by its canonical identity. */
5795
- function retirementBaselinePath(home) {
5947
+ export function retirementBaselinePath(home) {
5796
5948
  return retirementBaselineFile(receiptHomeIdentity(home));
5797
5949
  }
5798
5950
 
@@ -5819,7 +5971,7 @@ function legacyRetirementBaselinePath(home) {
5819
5971
  * directory-work disagreement is E_WORK_INSPECTION_FAILED; and a start's record rewrites the stale
5820
5972
  * file, as a kernel before 0.49.0 already does when a caller's spelling matches an earlier
5821
5973
  * incarnation's. */
5822
- function findRetirementBaseline(home) {
5974
+ export function findRetirementBaseline(home) {
5823
5975
  const canonical = retirementBaselinePath(home);
5824
5976
  if (existsSync(canonical)) return canonical;
5825
5977
  const legacy = legacyRetirementBaselinePath(home);
@@ -5892,7 +6044,8 @@ function retireGitProbe(repo, args, { encoding } = {}) {
5892
6044
  * MUST be added in the same change to the names a capability may not declare
5893
6045
  * as its own (`retirement.disposable.home`: KERNEL_HOME_NAMES and
5894
6046
  * KERNEL_HOME_NAME_PREFIXES in lib/capability-contract.mjs, and the schema). */
5895
- const KERNEL_HOME_RECEIPTS = new Set([".oats-events.jsonl", ".oats-stop.json", ".oats-stop-receipt.json", ".oats-restart.json"]);
6047
+ // `.oats-color.json` (feature instance-color) is presentation anyone may change at any time: never work.
6048
+ const KERNEL_HOME_RECEIPTS = new Set([".oats-events.jsonl", ".oats-stop.json", ".oats-stop-receipt.json", ".oats-restart.json", ".oats-color.json"]);
5896
6049
  const KERNEL_HOME_RECEIPT_PATTERNS = [/^\.oats-stop-receipt\..+\.json$/, /^\.oats-agents-md\..+\.previous$/];
5897
6050
  /** Harness project settings in the home are configuration, not work: the
5898
6051
  * home's `.claude/` is harness layout the kernel already shapes (the skills
@@ -6041,7 +6194,7 @@ function treeDigests(root, { excludeRoot = new Set(), excludePaths = [], instanc
6041
6194
  const childRel = rel.length ? Buffer.concat([rel, PATH_SEPARATOR_BYTES, nameBytes]) : nameBytes;
6042
6195
  if ((!relText && excludeRoot.has(name)) || (excluded.size && excluded.has(childRel.toString("hex")))) continue;
6043
6196
  const childRelText = relText ? join(relText, name) : name;
6044
- const storedPassesOver = instanceHome && ((!relText && (KERNEL_HOME_RECEIPTS.has(name) || KERNEL_HOME_RECEIPT_PATTERNS.some((p) => p.test(name)))) || HARNESS_HOME_SETTINGS.has(childRelText) || KERNEL_HOME_STATE_DIRS.has(childRelText));
6197
+ const storedPassesOver = instanceHome && ((!relText && (KERNEL_HOME_RECEIPTS.has(name) || KERNEL_HOME_RECEIPT_PATTERNS.some((p) => p.test(name)))) || HARNESS_HOME_SETTINGS.has(childRelText) || KERNEL_HOME_STATE_DIRS.has(childRelText) || (relText === ".oats" && (UPGRADE_RECEIPT_NAME_RE.test(name) || /^\.staging-upgrade-[a-f0-9]+$/.test(name))));
6045
6198
  if (storedPassesOver && !x) continue;
6046
6199
  const on = storedOn && !storedPassesOver;
6047
6200
  const s = on ? outerS : null, v = on ? outerV : null;
@@ -6584,7 +6737,79 @@ export function retirementRecoveryFacts(home) {
6584
6737
  const baseline = readJsonOrUndefined(findRetirementBaseline(home));
6585
6738
  return { recoveryRoot: retirementRecoveryRoot(dirname(home)), disposableHome: retirementBaselineValid(baseline, home) ? baselineDisposableHome(baseline) : [] };
6586
6739
  }
6587
- function writeRetirementBaseline(home, work, mode, capabilities, runtime, { exclusive = false, incarnationId, executionBinding } = {}) {
6740
+ /** A projection is local to one fingerprint, never a persistent exclusion. */
6741
+ function retirementTransientFiles(home, transientHomePaths) {
6742
+ if (!Array.isArray(transientHomePaths) || transientHomePaths.some(path => typeof path !== "string" || !path || isAbsolute(path) || /[\x00*?\[\]{}]/.test(path) || path.split(/[\/\\]/).some(part => !part || part === "." || part === ".."))) throw oatsError("E_BAD_ARGS", "retirement baseline transientHomePaths must be exact relative paths without globs");
6743
+ return transientHomePaths.map(path => {
6744
+ let at = home;
6745
+ const parts = path.split(/[\/\\]/);
6746
+ try {
6747
+ for (const component of parts.slice(0, -1)) {
6748
+ at = join(at, component);
6749
+ if (!lstatSync(at).isDirectory()) throw new Error("not a real parent directory");
6750
+ }
6751
+ at = join(at, parts.at(-1));
6752
+ const stat = lstatSync(at);
6753
+ if (!stat.isFile()) throw new Error("not a regular file");
6754
+ return { relative: pathBytes(join(...parts)), path: at, stat };
6755
+ } catch { throw oatsError("E_WORK_INSPECTION_FAILED", `retirement baseline transient path ${path} must exist as a regular file inside ${home}`); }
6756
+ });
6757
+ }
6758
+
6759
+ function assertRetirementTransientsUnchanged(transientFiles) {
6760
+ for (const file of transientFiles) {
6761
+ let now;
6762
+ try { now = lstatSync(file.path); } catch { /* refused below */ }
6763
+ if (!now?.isFile() || now.dev !== file.stat.dev || now.ino !== file.stat.ino) throw oatsError("E_WORK_INSPECTION_FAILED", `retirement baseline transient file changed while projecting ${file.path}`);
6764
+ }
6765
+ }
6766
+
6767
+ /** Upgrade may adjust the fingerprint only while preserving a valid independent
6768
+ * baseline. Missing authority is never reconstructed from mutable home metadata. */
6769
+ function upgradeRetirementBaseline(home) {
6770
+ const path = findRetirementBaseline(home);
6771
+ const baseline = readJsonOrUndefined(path);
6772
+ const digestVersion = baselineDigestVersion(baseline);
6773
+ if (!retirementBaselineValid(baseline, home) || digestVersion === undefined || typeof baseline.homeFingerprint !== "string" || !/^sha256:[a-f0-9]{64}$/.test(baseline.homeFingerprint)) {
6774
+ throw oatsError("E_UPGRADE_INTEGRITY", `the independent retirement baseline at ${path} is missing or invalid; restore the original baseline or respawn the instance before upgrading; no retirement authority was replaced`);
6775
+ }
6776
+ return { path, baseline, digestVersion };
6777
+ }
6778
+
6779
+ function upgradeHomeFingerprint(home, baseline, digestVersion, transientHomePaths) {
6780
+ const transientFiles = retirementTransientFiles(home, transientHomePaths);
6781
+ // Retire resolves exclusions from the independent spawn record and verified
6782
+ // extra trees, never from the newly installed capability manifests.
6783
+ const extraTrees = extraWorktreesOf(home);
6784
+ const homeExclusions = resolveHomeExclusions(home, baselineDisposableHome(baseline), extraTrees);
6785
+ const digest = storedTreeDigest(home, digestVersion, { excludeRoot: homeExclusions.excludeRoot, excludePaths: transientFiles.map(file => file.relative), instanceHome: true });
6786
+ assertRetirementTransientsUnchanged(transientFiles);
6787
+ return digest;
6788
+ }
6789
+
6790
+ /** Read before upgrade creates previous copies or staging: the same stored
6791
+ * digest and exclusions retire compares with the original spawn baseline. */
6792
+ export function retirementHomeChanged(home, { transientHomePaths = [] } = {}) {
6793
+ const { baseline, digestVersion } = upgradeRetirementBaseline(home);
6794
+ return baseline.homeFingerprint !== upgradeHomeFingerprint(home, baseline, digestVersion, transientHomePaths);
6795
+ }
6796
+
6797
+ /** A dirty home retains its original baseline byte for byte, so old kernels
6798
+ * also preserve its pre-upgrade edits. A clean home's authorized module move
6799
+ * changes only homeFingerprint; work, exclusion and runtime authority stay as
6800
+ * recorded, including a legacy digest version or its absence. */
6801
+ export function rebaseUpgradeRetirementBaseline(home, { homeChangedSinceSpawn } = {}) {
6802
+ if (typeof homeChangedSinceSpawn !== "boolean") throw oatsError("E_BAD_ARGS", "upgrade baseline rebase needs the pre-upgrade homeChangedSinceSpawn boolean");
6803
+ const { path, baseline, digestVersion } = upgradeRetirementBaseline(home);
6804
+ if (homeChangedSinceSpawn) return;
6805
+ const homeFingerprint = upgradeHomeFingerprint(home, baseline, digestVersion, [".oats-start.lock"]);
6806
+ writeJsonAtomic(path, { ...baseline, homeFingerprint }, 0o600);
6807
+ }
6808
+
6809
+ /** Project transaction-owned temporary files out of this baseline only. Later
6810
+ * fingerprints still hold them: a stale mutex is work to preserve, not invisible state. */
6811
+ export function writeRetirementBaseline(home, work, mode, capabilities, runtime, { exclusive = false, incarnationId, executionBinding, transientHomePaths = [] } = {}) {
6812
+ const transientFiles = retirementTransientFiles(home, transientHomePaths);
6588
6813
  if (mode === "directory") assertDirectoryRoots(home);
6589
6814
  const isWorktree = mode === "worktree";
6590
6815
  const statusBytes = isWorktree && existsSync(work) ? worktreeStatusBytes(work) : Buffer.alloc(0);
@@ -6596,7 +6821,7 @@ function writeRetirementBaseline(home, work, mode, capabilities, runtime, { excl
6596
6821
  ...(incarnationId ? { incarnationId, executionBinding } : {}),
6597
6822
  ...(mode === "directory" ? { directoryWork: true, directoryRoots: { home: directoryRootIdentity(home), work: directoryRootIdentity(work) } } : {}),
6598
6823
  home: canonicalHomePath(home),
6599
- homeFingerprint: storedTreeDigest(home, BASELINE_DIGEST_VERSION, { excludeRoot: resolveHomeExclusions(home, disposableHome).excludeRoot, instanceHome: true }),
6824
+ homeFingerprint: storedTreeDigest(home, BASELINE_DIGEST_VERSION, { excludeRoot: resolveHomeExclusions(home, disposableHome).excludeRoot, excludePaths: transientFiles.map(file => file.relative), instanceHome: true }),
6600
6825
  disposableReceipts,
6601
6826
  disposableHome,
6602
6827
  generatedWorkFingerprint: isWorktree ? generatedWorkDigest(work, statusBytes, disposableReceipts.map((r) => r.root)) : undefined,
@@ -6605,9 +6830,14 @@ function writeRetirementBaseline(home, work, mode, capabilities, runtime, { excl
6605
6830
  ...(runtime?.tmux ? { tmux: { session: runtime.tmux.session, window: runtime.tmux.window, ...(runtime.tmux.socket ? { socket: resolve(runtime.tmux.socket) } : {}) } } : {}),
6606
6831
  },
6607
6832
  };
6833
+ assertRetirementTransientsUnchanged(transientFiles);
6608
6834
  const path = retirementBaselinePath(home);
6609
6835
  mkdirSync(dirname(path), { recursive: true });
6610
- writeFileSync(path, JSON.stringify(baseline, null, 2) + "\n", { mode: 0o600, ...(exclusive ? { flag: "wx" } : {}) });
6836
+ // Replacements must leave readable independent session authority even if a
6837
+ // short write or SIGKILL interrupts publication. Spawn's exclusive option
6838
+ // still creates directly with wx and never replaces an existing receipt.
6839
+ if (exclusive) writeFileSync(path, JSON.stringify(baseline, null, 2) + "\n", { mode: 0o600, flag: "wx" });
6840
+ else writeJsonAtomic(path, baseline, 0o600);
6611
6841
  }
6612
6842
 
6613
6843
  /** The repositories a recovery rebuilds from a clone, under a worktree at
@@ -6718,7 +6948,7 @@ const unreadableBecause = (e) => e?.code === "ENOENT" ? "it is missing" : String
6718
6948
 
6719
6949
  /** Session control uses the independent endpoint receipt. The receipt and the record are read
6720
6950
  * apart, so that a failure names the file that failed (#1092): one `catch` over both cannot know. */
6721
- function instanceSessionTarget(home) {
6951
+ function instanceSessionTarget(home, { absentMeta } = {}) {
6722
6952
  if (typeof home !== "string" || !isAbsolute(home)) throw oatsError("E_BAD_ARGS", "session needs an absolute instance home");
6723
6953
  home = realPathOrNearest(home);
6724
6954
  refuseHerdrHome(home);
@@ -6729,7 +6959,12 @@ function instanceSessionTarget(home) {
6729
6959
  throw oatsError("E_RUNTIME_ENDPOINT_UNKNOWN", `cannot read session receipt for ${home} at ${receiptPath}: ${unreadableBecause(e)}`);
6730
6960
  }
6731
6961
  try { meta = JSON.parse(readFileSync(recordPath, "utf8")); }
6732
- catch (e) { throw oatsError("E_RUNTIME_ENDPOINT_UNKNOWN", `cannot read ${recordPath}: ${unreadableBecause(e)}`); }
6962
+ catch (e) {
6963
+ // Upgrade may be between the two metadata renames. Its durable journal
6964
+ // supplies only the missing record; the independent endpoint still decides.
6965
+ if (e.code === "ENOENT" && isPlainObject(absentMeta)) meta = absentMeta;
6966
+ else throw oatsError("E_RUNTIME_ENDPOINT_UNKNOWN", `cannot read ${recordPath}: ${unreadableBecause(e)}`);
6967
+ }
6733
6968
  // A record that is JSON and no object gives no endpoint to compare the receipt with.
6734
6969
  if (!isPlainObject(meta)) throw oatsError("E_RUNTIME_ENDPOINT_UNKNOWN", `cannot read ${recordPath}: it holds no JSON object`);
6735
6970
  const authority = baseline.version === RETIRE_BASELINE_VERSION && receiptRecordsHome(baseline, canonicalHomePath(home)) && runtimeAuthorityOf(baseline);
@@ -6739,9 +6974,9 @@ function instanceSessionTarget(home) {
6739
6974
  }
6740
6975
 
6741
6976
  /** `io` (`{ exec }`) is the tmux and process-table seam inspectSessionTarget takes. */
6742
- export function inspectInstanceSession(home, { io } = {}) {
6977
+ export function inspectInstanceSession(home, { io, absentMeta } = {}) {
6743
6978
  if (typeof home === "string" && isAbsolute(home) && !existsSync(home)) return { home: realPathOrNearest(home), backend: null, present: false, state: "stopped", running: false, waitingOnYou: null };
6744
- const s = instanceSessionTarget(home);
6979
+ const s = instanceSessionTarget(home, { absentMeta });
6745
6980
  if (!s.target) return { home: s.home, backend: null, present: false, state: "not-launched", running: false, waitingOnYou: null };
6746
6981
  let observed;
6747
6982
  try { observed = inspectSessionTarget(s.target, io, { includeSize: true }); }
@@ -7317,6 +7552,7 @@ export function prepareLaunchHooks({ frozen, harness, resolvedCfg, home, meta, c
7317
7552
  if (!trust.trusted) throw oatsError("E_LAUNCH_PREPARATION", `${p.id} was part of this home's launch at spawn but is no longer trusted in the scope (${trust.reason || "not trusted"}); respawn the instance; nothing was stopped`);
7318
7553
  const hooks = manifestHookCommands(manifest);
7319
7554
  if (hooks.launch) withLaunchHook.push({ id: p.id, capability: p.id, manifest, layer: p.contribution?.layer ?? p.binding?.layer ?? manifest.layer ?? null, level: p.contribution?.level ?? p.binding?.level ?? null, settings: p.settings, settingsOrigins: p.settingsOrigins, hooks, trust, environment: [...(manifest.environment || [])], environmentNamespaces: [...(manifest.environmentNamespaces || [])], missingRequires: [] });
7555
+
7320
7556
  }
7321
7557
  const aware = withLaunchHook.filter((c) => c.manifest.launchPreview === true);
7322
7558
  const unaware = withLaunchHook.filter((c) => c.manifest.launchPreview !== true);
@@ -7427,6 +7663,8 @@ export function startInstanceSession(home, o = {}) {
7427
7663
  refuseHerdrHome(realPathOrNearest(home));
7428
7664
  if (readJsonOrUndefined(join(realPathOrNearest(home), ".oats-start-pending.json"))?.target?.backend === "herdr") throw herdrInstanceRemoved(basename(realPathOrNearest(home)));
7429
7665
  if (existsSync(directoryRollbackPath(home))) throw oatsError("E_INSTANCE_RETIRING", `${home} has retained directory cleanup; restore and retire it before starting anything there`);
7666
+ assertKernelShimParents(home);
7667
+ assertNoPartialUpgrade(realPathOrNearest(home));
7430
7668
  const directoryGuard = sessionDirectoryGuard(home);
7431
7669
  {
7432
7670
  let metadata; try { metadata = parseStrictJson(readPortableBytes(join(home, "instance.json"))); } catch { /* the receipt checks below report unreadable metadata */ }
@@ -7454,6 +7692,8 @@ export function startInstanceSession(home, o = {}) {
7454
7692
  // spawned records no modules, and there is no scope configuration left to
7455
7693
  // re-resolve it against. Retire still works on it.
7456
7694
  if (!isWorkspaceHome(readMeta())) throw preWorkspaceHome(realHome, "nothing was started");
7695
+ let drift; // Read under the start lock, so an upgrade cannot swap modules between reads.
7696
+ let cleanupWarnings = [];
7457
7697
  // A missing socket file is a stopped server only when no process works in this home (#624): its
7458
7698
  // check, for a recorded session and for the OATS server lookup. A failed read of a recorded session
7459
7699
  // is `{ stopped: true }` when its server is gone (or its socket file is missing and that check
@@ -7503,14 +7743,30 @@ export function startInstanceSession(home, o = {}) {
7503
7743
  next.tmux = { session: target.session, window: target.window, socket: resolve(target.socket) };
7504
7744
  writeJsonAtomic(metaPath, next);
7505
7745
  if (clearPending) { checkRoots(); rmSync(pendingPath, { force: true }); }
7506
- 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 } : {}) };
7746
+ return { ...(drift.length ? { drift } : {}), 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: cleanupWarnings, ...(launchPrompts ? { launchPrompts } : {}), ...(nativeRecordId ? { nativeRecordId } : {}), ...(stop ? { stop } : {}) };
7507
7747
  };
7508
7748
  try { mkdirSync(lock); }
7509
7749
  catch (e) {
7510
- if (e.code === "EEXIST") throw oatsError("E_SESSION_START_BUSY", `another start of ${basename(realHome)} is in progress (${lock}); if no start is running, remove that directory and retry`);
7750
+ if (e.code === "EEXIST") {
7751
+ const retry = upgradeMutexRetry(realHome);
7752
+ if (retry) throw oatsError("E_SESSION_START_BUSY", `a package upgrade of ${basename(realHome)} holds the start mutex (${lock}); nothing was stopped or started. Retry ${retry} to finish the upgrade before starting`);
7753
+ throw oatsError("E_SESSION_START_BUSY", `another start of ${basename(realHome)} is in progress (${lock}); if no start is running, remove that directory and retry`);
7754
+ }
7511
7755
  throw e;
7512
7756
  }
7513
7757
  try {
7758
+ // Upgrade holds this same start lock while applying; re-read after taking it.
7759
+ assertNoPartialUpgrade(realHome);
7760
+ cleanupWarnings = upgradeCleanupWarnings(realHome);
7761
+ // Compare the frozen package copies with the local deployment lock; starting never moves them.
7762
+ const driftDeployment = dirname(dirname(dirname(dirname(realHome))));
7763
+ let driftLock;
7764
+ try { driftLock = deploymentLock(driftDeployment); }
7765
+ catch (error) {
7766
+ // Drift is advisory; an unreadable deployment lock cannot invalidate a frozen home's launch.
7767
+ cleanupWarnings.push(`package module drift could not be read from ${join(driftDeployment, "oats-lock.json")}: ${error.message}`);
7768
+ }
7769
+ drift = driftLock === undefined ? [] : packageUpgradeDrift(readMeta(), { lock: driftLock });
7514
7770
  if (existsSync(join(realHome, ".oats-rollback-incomplete.json"))) throw oatsError("E_INSTANCE_RETIRING", `${realHome} is a quarantined home whose cleanup is incomplete; finish its retirement (oats retire) before starting anything there`);
7515
7771
  // A self-retirement leaves this marker while its detached teardown runs:
7516
7772
  // the home is about to disappear, so nothing is relaunched into it.
@@ -7890,7 +8146,7 @@ export function startInstanceSession(home, o = {}) {
7890
8146
  if (launchPrompts && !promptLaunched(launchPrompts.status)) throw retainedPromptError(realHome, meta.instance, launchPromptTarget ?? target, false, launchPrompts);
7891
8147
  // Said once the new socket is recorded: a start that could not record leaves it to the adoption.
7892
8148
  if (moved) { appendEvent(realHome, { kind: "launch-warning", data: { message: moved } }); movedWarnings.push(moved); }
7893
- return { ...done, warnings: [...warnings, ...movedWarnings] };
8149
+ return { ...done, warnings: [...done.warnings, ...warnings, ...movedWarnings] };
7894
8150
  } finally {
7895
8151
  // A hook may have replaced the home itself. Never follow that replacement
7896
8152
  // to remove a target's lock; keep the original retry state with its home.
@@ -9825,7 +10081,7 @@ export function retireClaimPath(home) {
9825
10081
 
9826
10082
  /** The verbs that take a home's lifecycle claim: what claimHomeFor accepts, and so every `action`
9827
10083
  * a claim of the kernel's names. */
9828
- const CLAIM_VERBS = Object.freeze(["retire", "stop"]);
10084
+ const CLAIM_VERBS = Object.freeze(["retire", "stop", "upgrade"]);
9829
10085
  /** The verb the holder of a home's claim recorded (`action`): one of CLAIM_VERBS, never the
9830
10086
  * record's text. A claim is read back as whatever is in its file, which other instances of the
9831
10087
  * deployment can write, and this goes into messages, remedies and `details` (lib/claim.mjs
@@ -9834,11 +10090,11 @@ const CLAIM_VERBS = Object.freeze(["retire", "stop"]);
9834
10090
  * retire took the claim. */
9835
10091
  const claimAction = (holder) => CLAIM_VERBS.includes(holder?.action) ? holder.action : "retire";
9836
10092
  /** The command that takes a home's claim for `action`, as a person types it. */
9837
- const claimCommand = (action) => action === "stop" ? "oats instance stop" : `oats ${action}`;
10093
+ const claimCommand = (action) => ["stop", "upgrade"].includes(action) ? `oats instance ${action}` : `oats ${action}`;
9838
10094
  /** What each verb that meets a held claim says it did not do: the words its refusals end with,
9839
10095
  * before any effect. After a takeover ended a dead holder's step, every verb says the same
9840
10096
  * (lib/errors.mjs nothingAfter). */
9841
- const CLAIM_NOTHING = { retire: "nothing was done", stop: "nothing was stopped", "worktree add": "no tree was made" };
10097
+ const CLAIM_NOTHING = { upgrade: "no modules were upgraded", retire: "nothing was done", stop: "nothing was stopped", "worktree add": "no tree was made", "instance color": "the colour was not changed" };
9842
10098
 
9843
10099
  /** The refusals of `arriving` ("retire", "stop", or "worktree add", which reads the claim and does
9844
10100
  * not take it) of `name` (home `home`) that meets the lifecycle claim `lock`, as lib/claim.mjs asks
@@ -9861,7 +10117,7 @@ const CLAIM_NOTHING = { retire: "nothing was done", stop: "nothing was stopped",
9861
10117
  export function lifecycleClaimRefusals(arriving, name, home, lock) {
9862
10118
  const nothing = (ended) => nothingAfter(ended, CLAIM_NOTHING[arriving]);
9863
10119
  const own = { instance: name, home };
9864
- const holders = "oats retire or oats instance stop";
10120
+ const holders = "oats retire, oats instance stop or oats instance upgrade";
9865
10121
  // The holder of `at`, as an answer names it: `shown` for the message, `details` beside it.
9866
10122
  const held = (holder, at) => {
9867
10123
  const shown = shownHolder(holder), action = claimAction(holder);