@awebai/oats 0.69.4 → 0.69.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/oats.mjs +141 -364
- package/docs/configuration.md +12 -0
- package/docs/design/2026-09-26-okf-knowledge-operations.md +2 -0
- package/docs/design/2026-10-29-warm-reader.md +261 -0
- package/docs/design/README.md +4 -0
- package/docs/desktop-cli-api.md +258 -13
- package/docs/execution-targets.md +36 -5
- package/docs/implementation.md +34 -9
- package/docs/integrations.md +2 -2
- package/docs/knowledge.md +18 -8
- package/docs/named-test-runs.md +4 -0
- package/docs/official-catalog.md +5 -5
- package/docs/packages.md +14 -14
- package/docs/release-notes/v0.69.5.md +146 -0
- package/docs/release-notes/v0.69.6.md +165 -0
- package/docs/schedules.md +8 -1
- package/docs/tui.md +23 -5
- package/docs/upgrading.md +20 -5
- package/docs/workspaces.md +2 -2
- package/lib/agents-root.mjs +51 -0
- package/lib/argv.mjs +41 -0
- package/lib/automation-api.mjs +7 -0
- package/lib/automation-scope.mjs +37 -0
- package/lib/automations.mjs +63 -12
- package/lib/captured-context.mjs +12 -0
- package/lib/compile-cache.mjs +36 -0
- package/lib/core.mjs +39 -1348
- package/lib/deployment-path.mjs +127 -0
- package/lib/deployments.mjs +2 -2
- package/lib/drift.mjs +95 -0
- package/lib/hot-reads.mjs +137 -0
- package/lib/install-stamp.mjs +61 -0
- package/lib/instance-address.mjs +21 -0
- package/lib/instance-events.mjs +8 -6
- package/lib/instance-lifecycle.mjs +4 -16
- package/lib/instance-listing.mjs +738 -0
- package/lib/instance-resolution.mjs +5 -166
- package/lib/kernel-features.mjs +10 -0
- package/lib/local-edit.mjs +1 -1
- package/lib/local-inputs.mjs +3 -0
- package/lib/materialize.mjs +2 -87
- package/lib/member-clone.mjs +192 -0
- package/lib/package-catalog.mjs +93 -0
- package/lib/packages.mjs +4 -24
- package/lib/read-call.mjs +143 -0
- package/lib/reader.mjs +203 -0
- package/lib/remote.mjs +47 -6
- package/lib/reserved-launch-env.mjs +20 -0
- package/lib/resolved-deployment.mjs +13 -5
- package/lib/roster-read.mjs +199 -0
- package/lib/schedule.mjs +5 -29
- package/lib/semver.mjs +12 -0
- package/lib/servers.mjs +10 -12
- package/lib/session-end.mjs +3 -2
- package/lib/session-input.mjs +35 -11
- package/lib/session-inspect.mjs +219 -0
- package/lib/soul-listing.mjs +216 -0
- package/lib/status-words.mjs +30 -0
- package/lib/version.mjs +9 -0
- package/lib/workspace-read.mjs +160 -0
- package/lib/write-file-atomic.mjs +28 -0
- package/package-catalog.json +4 -4
- package/package.json +1 -1
- package/packages/client/cli-locator.mjs +1 -0
- package/packages/client/cli-probe-contract.mjs +4 -2
- package/packages/client/deployment-observer.mjs +8 -3
- package/packages/client/deployment-panel.mjs +17 -1
- package/packages/client/deployment-read-cli.mjs +48 -27
- package/packages/client/own-codes.mjs +3 -0
- package/packages/client/warm-reader.mjs +241 -0
- package/packages/tui/lib/client.mjs +2 -1
- package/packages/tui/lib/read.mjs +59 -11
- package/packages/tui/lib/store.mjs +7 -3
- package/skills/oats-getting-started/SKILL.md +3 -3
package/lib/core.mjs
CHANGED
|
@@ -38,22 +38,18 @@ import {
|
|
|
38
38
|
} from "node:fs";
|
|
39
39
|
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
40
40
|
import { homedir } from "node:os";
|
|
41
|
-
import { accessSync, constants as fsConstants
|
|
42
|
-
import { recordLocalInput } from "./local-inputs.mjs";
|
|
43
|
-
import { resolvedDeployment } from "./resolved-deployment.mjs";
|
|
41
|
+
import { accessSync, constants as fsConstants } from "node:fs";
|
|
44
42
|
import { createHash, randomUUID } from "node:crypto";
|
|
45
|
-
import { fileURLToPath } from "node:url";
|
|
46
43
|
import { initializeNativeHistory, prepareNativeStart } from "../packages/record/lib/native-history.mjs";
|
|
47
44
|
import { sameDirectory } from "../packages/record/lib/directory-identity.mjs";
|
|
48
45
|
import { noteRuntimeName } from "./deprecation.mjs";
|
|
49
46
|
import { attachSessionTarget, requireDetachKey } from "./session-viewer.mjs";
|
|
50
|
-
import { AGENT_PANE_OPTION,
|
|
51
|
-
import { appendEvent, incarnationOf,
|
|
47
|
+
import { AGENT_PANE_OPTION, inspectSessionTarget, inputSessionTarget, resolveAgentPane } from "./session-input.mjs";
|
|
48
|
+
import { appendEvent, incarnationOf, recordStartBoundary, retireRefusedReason } from "./instance-events.mjs";
|
|
52
49
|
import { killGroup } from "./process-group.mjs";
|
|
53
50
|
import { NAMING_CALLS, NAMING_TIMEOUT_MS, suggestInstanceName } from "./instance-naming.mjs";
|
|
54
51
|
import { interruptExitStatus, isStartToken, originRemoteOf, runWorktreeHooks, selfIdentity, processLiveness, processStartToken, signalGuard, terminateRecordedGroup, treeStillThere, unknownGroupNote, unverifiedGroupWarning, worktreeHooksOf } from "./worktree-hooks.mjs";
|
|
55
52
|
import { CLAIM_WAIT_MS, acquireClaim, claimUnavailable, claimUnheld, claimWrite, readClaim, releaseClaim, removeGoneClaim, shownHolder, unwritableCode } from "./claim.mjs";
|
|
56
|
-
import { isInstant as isInstantString, readRetireState } from "./retire-state.mjs";
|
|
57
53
|
import { captureLoginEnvironment } from "./login-environment.mjs";
|
|
58
54
|
import { kernelNode } from "./stable-node.mjs";
|
|
59
55
|
import { assertNoPartialUpgrade, packageUpgradeDrift, upgradeCleanupWarnings, upgradeMutexRetry, UPGRADE_RECEIPT_NAME_RE } from "./upgrade-state.mjs";
|
|
@@ -74,7 +70,6 @@ async function plannedSkillsDefault(prepared) { const m = await import("./instan
|
|
|
74
70
|
import { cloneRemoteFor, deploymentLock, resolutionContractWarnings, toCapabilityRows, verifyMemberClone } from "./instance-resolution.mjs";
|
|
75
71
|
import { GIT_FETCH_TIMEOUT_MS, GIT_TIMEOUT_MS, gitEnv } from "./remote.mjs";
|
|
76
72
|
import { loadLocal, loadMachineLaunchConfigs } from "./workspace.mjs";
|
|
77
|
-
import { parseConfigData } from "./config-data.mjs";
|
|
78
73
|
import { renderInstructionText } from "./instruction-composition.mjs";
|
|
79
74
|
import { APPROVED_HOOKS, PORTABLE_ENV_NAME_RE, CORE_LAUNCH_ENV, PROCESS_BOOTSTRAP_ENV, PROCESS_BOOTSTRAP_PREFIXES, manifestContractProblems, disposableHomeRootProblem, disposableHomeRootMatches, contractWarningMessages, locatedContractWarnings } from "./capability-contract.mjs";
|
|
80
75
|
import { validateBindingInterface } from "./provider-binding.mjs";
|
|
@@ -85,7 +80,7 @@ import { validateBindingInterface } from "./provider-binding.mjs";
|
|
|
85
80
|
* and a worktree's untracked and ignored digest, alone and with its bytes from one read (exported so a test holds the one read to the two apart). */
|
|
86
81
|
export { exactTreeDigest, fingerprintTree, generatedWorkDigest, KERNEL_HOME_RECEIPTS, storedTreeDigest, worktreeBytes, worktreeDigests, worktreeGitPaths };
|
|
87
82
|
|
|
88
|
-
import { canonicalJson,
|
|
83
|
+
import { canonicalJson, parseStrictJson } from "./canonical-json.mjs";
|
|
89
84
|
import { readPortableBytes } from "./bounded-read.mjs";
|
|
90
85
|
import { copyTreeSafe, entriesAsBytes, joinBytes, pathBytes, treeDisagreement } from "./tree-copy.mjs";
|
|
91
86
|
import { readAheadConsumed, readingAhead } from "./read-ahead.mjs";
|
|
@@ -94,61 +89,36 @@ import { assertSameWorktreeHead, gitRead, gitRefPresence, gitRepoRead, gitRepoRu
|
|
|
94
89
|
import { systemTool } from "./system-tools.mjs";
|
|
95
90
|
import { SCOPE_ENV_NAMES, agentScope, agentScopeArgv, agentScopeUnit, creatorPlacement, serverScopePlan, serverScopeUnit, serverScopeWarning } from "./tmux-server-scope.mjs";
|
|
96
91
|
import { writeThroughPrivateFile } from "./write-through-private-file.mjs";
|
|
97
|
-
import { readInstanceColor } from "./instance-color.mjs";
|
|
98
92
|
import { readInstanceBackground, writeInstanceBackground } from "./instance-background.mjs";
|
|
99
|
-
import { SAME_WORK_FILE,
|
|
93
|
+
import { SAME_WORK_FILE, writeSameWork } from "./instance-same-work.mjs";
|
|
100
94
|
import { readStartExited, sessionEndOf, START_EXITED_FILE, STOP_RECEIPT_FILE } from "./session-end.mjs";
|
|
101
95
|
import { FRESH_REASON, RESUME_WAITING, SESSION_END } from "./session-resume-contract.mjs";
|
|
102
|
-
import { recordSeen } from "./session-seen.mjs";
|
|
103
96
|
import { START_ENV_FILE, START_ENV_KEY_FILE, START_ENV_TMP, checkStartEnv, fromEnvNames, launchEnvChangedMessage, launchEnvMissingMessage, launchEnvUnverifiedWarning, recordStartEnv } from "./start-env.mjs";
|
|
104
97
|
import { watchResumeConfirmation } from "./launch-prompt-resume.mjs";
|
|
105
98
|
import { lastConversation } from "../packages/record/lib/last-conversation.mjs";
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
99
|
+
import { PKG_ROOT } from "./version.mjs";
|
|
100
|
+
import { canonicalDeploymentPath } from "./deployment-path.mjs";
|
|
101
|
+
import { INSTANCE_NAME_RE, RESERVED, capabilityAgentDirs, enclosingInstanceHome, findInstanceHomes, listAgents, logicalCwd, readSoul, soulOf, stripInternalAnnotations, withConfigFile, yamlKey } from "./soul-listing.mjs";
|
|
102
|
+
import { RETIRE_BASELINE_VERSION, authorityMismatch, findRetirementBaseline, instanceSessionTarget, instancesRetirementRoot, isPlainObject, launchStateAgrees, missingSessionReceipt, readJsonOrUndefined, receiptHomeIdentity, receiptRecordsHome, recordsHerdr, refuseHerdrHome, retirementBaselinePath, runtimeAuthorityOf, tmuxEndpointAgrees } from "./session-inspect.mjs";
|
|
103
|
+
import { CLAIM_VERBS, DEFAULT_TMUX_SESSION, LAUNCH_RECIPE_VERSION, claimAction, defaultTmuxWindows, deferredRetireResultPath, directoryRollbackPath, hostProcesses, isCapturedHome, lookupOnPath, missingSocketUnestablished, namedProcesses, parseLaunchCommand, procReadable, processesWorkingIn, readHomeRecord, readRetirePending, redactLaunchCommand, redactLaunchRecipe, retireClaimPath, retirePendingMarkerPath, retireStateOf, subdirs, tmuxFailure, tmuxOn, tmuxServerAbsence, unreadableRecordSaid, upgradeHomeMeta, upgradeLaunchRecipe } from "./instance-listing.mjs";
|
|
104
|
+
import { LAYERS, PACKAGE_ID_RE } from "./package-catalog.mjs";
|
|
105
|
+
import { RESERVED_LAUNCH_ENV } from "./reserved-launch-env.mjs";
|
|
106
|
+
import { workspaceOf } from "./agents-root.mjs";
|
|
107
|
+
export { RESERVED_LAUNCH_ENV } from "./reserved-launch-env.mjs";
|
|
108
|
+
export { LAYERS, officialCapabilityAliases, officialCatalogFile, officialPackageCatalog, parsePackageCatalog } from "./package-catalog.mjs";
|
|
109
|
+
export { DEFAULT_TMUX_SESSION, IDENTITY_LAUNCH_ENV, LAUNCH_RECIPE_VERSION, deferredRetireResultPath, isCapturedHome, legacyCapturedHomes, legacyLocalAgents, listInstances, parseLaunchCommand, readHomeRecord, recordedKernelBin, redactLaunchCommand, redactLaunchRecipe, retireClaimPath, retirePendingMarkerPath, servedIdentityLine, servedIdentityOf, upgradeHomeMeta, upgradeLaunchRecipe } from "./instance-listing.mjs";
|
|
110
|
+
export { findRetirementBaseline, inspectInstanceSession, retirementBaselinePath } from "./session-inspect.mjs";
|
|
111
|
+
export { RESERVED, assertSafeConfigKey, enclosingInstanceHome, findInstanceHomes, listAgents, logicalCwd, parseYamlFlat, soulHarnessField, stripInternalAnnotations, withConfigFile } from "./soul-listing.mjs";
|
|
112
|
+
export { canonicalAgentsRoot, ensureRoot, findRoot, workspaceOf } from "./agents-root.mjs";
|
|
113
|
+
export { canonicalDeploymentPath } from "./deployment-path.mjs";
|
|
114
|
+
export { OATS_VERSION, PKG_ROOT } from "./version.mjs";
|
|
109
115
|
// Keep the existing public core surface; internal data helpers are not re-exported.
|
|
110
116
|
export { oatsError } from "./errors.mjs";
|
|
111
117
|
export { copyTreeSafe } from "./tree-copy.mjs";
|
|
112
118
|
|
|
113
|
-
export const RESERVED = new Set(["bin"]);
|
|
114
119
|
/** The work modes spawn accepts — also the enum a quarantine cleanup descriptor
|
|
115
120
|
* must satisfy, so the retry cannot skip Git cleanup on an unrecognised value. */
|
|
116
121
|
export const WORK_MODES = ["worktree", "checkout", "attached", "workspace", "directory"];
|
|
117
|
-
/** OATS 0.25 and earlier homed local souls and capability-defined agents at
|
|
118
|
-
* <scope>/local-agents/ (and <root>/local-agents|tmp-agents). The kernel never reads,
|
|
119
|
-
* spawns into or retires from them; it only detects them: `legacyLocalAgents` names
|
|
120
|
-
* what is left there so status/doctor say so. */
|
|
121
|
-
const LEGACY_LOCAL_AGENTS_DIR = "local-agents";
|
|
122
|
-
/** The agent dirs directly under an agents root that hold no soul: capability-defined
|
|
123
|
-
* agents (their soul is read-only in a module; the dir holds only instances/). */
|
|
124
|
-
function capabilityAgentDirs(root) {
|
|
125
|
-
let entries; try { entries = readdirSync(root, { withFileTypes: true }); } catch { return []; }
|
|
126
|
-
return entries.filter((e) => e.isDirectory() && !e.name.startsWith(".") && !RESERVED.has(e.name) && !existsSync(join(root, e.name, "soul", "soul.yaml")))
|
|
127
|
-
.map((e) => ({ name: e.name, dir: join(root, e.name) }));
|
|
128
|
-
}
|
|
129
|
-
/** The names of the non-hidden directories in `d` ([] when it cannot be read). */
|
|
130
|
-
function subdirs(d) {
|
|
131
|
-
try { return readdirSync(d, { withFileTypes: true }).filter((e) => e.isDirectory() && !e.name.startsWith(".")).map((e) => e.name); } catch { return []; }
|
|
132
|
-
}
|
|
133
|
-
/** What OATS 0.25 left under <scope>/local-agents/ (and the nested <root>/local-agents|
|
|
134
|
-
* tmp-agents) for the agents root `root`: one `legacy-local-agents` problem naming the
|
|
135
|
-
* instance homes there, or null. Names only — nothing there is read, spawned into or
|
|
136
|
-
* retired from. */
|
|
137
|
-
export function legacyLocalAgents(root) {
|
|
138
|
-
if (!root) return null;
|
|
139
|
-
const bases = [join(dirname(root), LEGACY_LOCAL_AGENTS_DIR), join(root, LEGACY_LOCAL_AGENTS_DIR), join(root, "tmp-agents")];
|
|
140
|
-
const dirs = [], instances = [];
|
|
141
|
-
for (const base of bases) {
|
|
142
|
-
let st; try { st = lstatSync(base); } catch { continue; }
|
|
143
|
-
if (!st.isDirectory()) continue;
|
|
144
|
-
dirs.push(base);
|
|
145
|
-
for (const agent of subdirs(base)) for (const inst of subdirs(join(base, agent, "instances"))) instances.push(inst);
|
|
146
|
-
}
|
|
147
|
-
if (!dirs.length) return null;
|
|
148
|
-
instances.sort();
|
|
149
|
-
return { code: "legacy-local-agents", dirs, instances,
|
|
150
|
-
message: `${instances.length} instance home${instances.length === 1 ? "" : "s"} under local-agents/ ${instances.length === 1 ? "is" : "are"} from OATS 0.25 and ${instances.length === 1 ? "is" : "are"} not managed by this kernel; retire ${instances.length === 1 ? "it" : "them"} with the 0.25 kernel or delete the directory once ${instances.length === 1 ? "it is" : "they are"} stopped${instances.length ? ` (${instances.join(", ")})` : ""}` };
|
|
151
|
-
}
|
|
152
122
|
/** The instances directories under the agents root `root`: `<root>/<agent>/instances`, one per
|
|
153
123
|
* agent directory, whether or not it exists. */
|
|
154
124
|
export function instancesDirs(root) {
|
|
@@ -175,27 +145,6 @@ export function readableInstanceHomes(root) {
|
|
|
175
145
|
return { code: "home-readable", homes, fix,
|
|
176
146
|
message: `${homes.length} instance home${homes.length === 1 ? " can" : "s can"} be read by other users on this machine (${homes.length === 1 ? "it holds" : "they hold"} identity keys, TASK.md and transcripts); fix: ${fix}` };
|
|
177
147
|
}
|
|
178
|
-
/** The captured homes (the 0.24–0.25 captured/portable path, removed in 0.26) under the
|
|
179
|
-
* agents root `root`: one `legacy-captured-home` problem naming them, or null. They have
|
|
180
|
-
* no 0.26 runtime (start, inspect and in-home commands refuse them); retire still works. */
|
|
181
|
-
export function legacyCapturedHomes(root) {
|
|
182
|
-
if (!root) return null;
|
|
183
|
-
const homes = [];
|
|
184
|
-
for (const agent of subdirs(root)) for (const inst of subdirs(join(root, agent, "instances"))) {
|
|
185
|
-
const home = join(root, agent, "instances", inst);
|
|
186
|
-
let meta; try { meta = JSON.parse(readFileSync(join(home, "instance.json"), "utf8")); } catch { continue; }
|
|
187
|
-
if (isCapturedHome(meta)) homes.push({ instance: inst, home });
|
|
188
|
-
}
|
|
189
|
-
if (!homes.length) return null;
|
|
190
|
-
homes.sort((a, b) => a.instance.localeCompare(b.instance));
|
|
191
|
-
const one = homes.length === 1;
|
|
192
|
-
return { code: "legacy-captured-home", instances: homes.map((h) => h.instance), homes: homes.map((h) => h.home),
|
|
193
|
-
message: `${homes.length} captured home${one ? "" : "s"} (0.24–0.25; the captured/portable path was removed in 0.26) ${one ? "has" : "have"} no 0.26 runtime: start, inspect and in-home commands refuse ${one ? "it" : "them"}; retire ${one ? "it" : "them"} (\`oats retire\` still works) and re-spawn from the deployment (${homes.map((h) => h.instance).join(", ")})` };
|
|
194
|
-
}
|
|
195
|
-
// The tmux session a new tmux instance opens its window in, when oats-local.yaml session.tmuxSession
|
|
196
|
-
// names none (0.31). PI_AGENTS_TMUX_SESSION is the pre-0.31 variable, still honoured. The Desktop keeps
|
|
197
|
-
// the same default in packages/client/tmux-status.mjs (it does not import lib/): change both.
|
|
198
|
-
export const DEFAULT_TMUX_SESSION = process.env.OATS_TMUX_SESSION || process.env.PI_AGENTS_TMUX_SESSION || "oats-agents";
|
|
199
148
|
/**
|
|
200
149
|
* The tmux session a NEW tmux launch opens its window in (0.31): the caller's, else the deployment's
|
|
201
150
|
* oats-local.yaml `session.tmuxSession`, else OATS_TMUX_SESSION, else PI_AGENTS_TMUX_SESSION, else
|
|
@@ -208,9 +157,6 @@ export function sessionDefaults(dir, { tmuxSession } = {}, env = process.env) {
|
|
|
208
157
|
const declared = local?.local?.session ?? {};
|
|
209
158
|
return { tmuxSession: tmuxSession || declared.tmuxSession || env.OATS_TMUX_SESSION || env.PI_AGENTS_TMUX_SESSION || "oats-agents" };
|
|
210
159
|
}
|
|
211
|
-
/** Package root (this file lives in <pkg>/lib/). */
|
|
212
|
-
export const PKG_ROOT = join(dirname(fileURLToPath(import.meta.url)), "..");
|
|
213
|
-
export const OATS_VERSION = JSON.parse(readFileSync(join(PKG_ROOT, "package.json"), "utf8")).version;
|
|
214
160
|
/** Skills shipped with the kernel. Only oats-getting-started is ambient; spawn composes selected skills locally. */
|
|
215
161
|
export const PACKAGED_SKILLS_DIR = join(PKG_ROOT, "skills");
|
|
216
162
|
|
|
@@ -265,54 +211,7 @@ function which(bin) {
|
|
|
265
211
|
return whichMemo.get(key);
|
|
266
212
|
}
|
|
267
213
|
|
|
268
|
-
// ---------- yaml-ish ----------
|
|
269
|
-
/** `__proto__` is never data in a plain-object mapping: assigning it REWRITES
|
|
270
|
-
* the parsed object's prototype, so the entry vanishes from `Object.keys` —
|
|
271
|
-
* past every key validator — while still answering property reads (a document
|
|
272
|
-
* could smuggle an unvalidated `name:` or `capabilities:` that way). No OATS
|
|
273
|
-
* document has a use for the key, so the readers refuse it rather than parse
|
|
274
|
-
* it: fail closed, never silently drop.
|
|
275
|
-
*
|
|
276
|
-
* THE single refusal, shared by the readers and by every WRITER that assigns an
|
|
277
|
-
* operator-supplied key into a config map — a write path that let the inherited
|
|
278
|
-
* setter swallow the entry and then reported success would be the same defect
|
|
279
|
-
* with a friendlier face. The readers parse strings and cannot name the
|
|
280
|
-
* document, so `where` is filled in by whoever holds the file
|
|
281
|
-
* (`withConfigFile`); the raw message therefore says "mapping key", not
|
|
282
|
-
* "oats-config key" — soul.yaml and skill frontmatter go through here too. */
|
|
283
|
-
export function assertSafeConfigKey(key, where) {
|
|
284
|
-
if (key === "__proto__") {
|
|
285
|
-
throw oatsError("unsafe-config-key", `unsupported mapping key "__proto__"${where ? ` in ${where}` : ""} — "__proto__" cannot be a mapping key in an OATS document (it rewrites the parsed object's prototype instead of becoming data)`, where ? [{ file: where }] : undefined);
|
|
286
|
-
}
|
|
287
|
-
return key;
|
|
288
|
-
}
|
|
289
|
-
/** Run a reader that may raise the typed key refusal and re-raise it naming the
|
|
290
|
-
* FILE. Every caller with a path in hand wraps its read — the readers parse
|
|
291
|
-
* strings and cannot name a document — so the CLI boundary can print one line
|
|
292
|
-
* the operator can act on.
|
|
293
|
-
*
|
|
294
|
-
* The insertion uses a REPLACER FUNCTION, never a replacement string: `$&`,
|
|
295
|
-
* `$'`, `` $` `` and `$1` are substitution syntax in `String.replace`, so a
|
|
296
|
-
* config path containing one of them (`/tmp/$&/oats-config.yaml` — legal on every
|
|
297
|
-
* POSIX filesystem) was expanded against the match and the reported filename
|
|
298
|
-
* came out corrupted. A function receives the path as data. */
|
|
299
|
-
export function withConfigFile(file, read) {
|
|
300
|
-
try { return read(); }
|
|
301
|
-
catch (e) {
|
|
302
|
-
if (e?.code !== "unsafe-config-key" || e.provenance) throw e;
|
|
303
|
-
throw oatsError(e.code, e.message.replace(" — ", () => ` in ${file} — `), [{ file }]);
|
|
304
|
-
}
|
|
305
|
-
}
|
|
306
214
|
|
|
307
|
-
const yamlKey = (key) => assertSafeConfigKey(key);
|
|
308
|
-
export function parseYamlFlat(text) {
|
|
309
|
-
const o = {};
|
|
310
|
-
for (const line of text.split("\n")) {
|
|
311
|
-
const m = line.match(/^([A-Za-z_][A-Za-z0-9_-]*):\s*(.*?)\s*(#.*)?$/);
|
|
312
|
-
if (m) o[yamlKey(m[1])] = m[2].replace(/^["']|["']$/g, "");
|
|
313
|
-
}
|
|
314
|
-
return o;
|
|
315
|
-
}
|
|
316
215
|
/** Small dependency-free YAML subset used by oats-config.yaml.
|
|
317
216
|
* Supports nested maps, namespaced/quoted keys, booleans, numbers, and inline arrays/maps. */
|
|
318
217
|
function yamlScalar(raw) {
|
|
@@ -433,167 +332,6 @@ export function parseYamlNested(text) {
|
|
|
433
332
|
return root;
|
|
434
333
|
}
|
|
435
334
|
|
|
436
|
-
// ---------- root discovery ----------
|
|
437
|
-
/** Closest agents/ walking up from `cwd`. A deployment whose agents/ was never
|
|
438
|
-
* created has no root here; ensureRoot names the remedy. */
|
|
439
|
-
export function findRoot(cwd = process.cwd()) {
|
|
440
|
-
if (process.env.PI_AGENTS_ROOT) return resolve(process.env.PI_AGENTS_ROOT);
|
|
441
|
-
let d = resolve(cwd);
|
|
442
|
-
while (true) {
|
|
443
|
-
if (basename(d) === "agents" && lstatSync(d).isDirectory()) return d;
|
|
444
|
-
const candidate = join(d, "agents");
|
|
445
|
-
if (existsSync(candidate) && lstatSync(candidate).isDirectory()) return candidate;
|
|
446
|
-
const parent = dirname(d);
|
|
447
|
-
if (parent === d) return undefined;
|
|
448
|
-
d = parent;
|
|
449
|
-
}
|
|
450
|
-
}
|
|
451
|
-
/** Is there a Git marker (`.git` dir or worktree pointer file) at or above `dir`?
|
|
452
|
-
* Filesystem-only: it answers "does Git own this location" even when the git
|
|
453
|
-
* binary is missing, refuses the repo (dubious ownership), or cannot read its
|
|
454
|
-
* metadata — cases where a probe failure must NOT be read as "not a repo". */
|
|
455
|
-
function hasGitMarker(dir) {
|
|
456
|
-
let d = resolve(dir);
|
|
457
|
-
while (true) {
|
|
458
|
-
if (existsSync(join(d, ".git"))) return true;
|
|
459
|
-
const parent = dirname(d);
|
|
460
|
-
if (parent === d) return false;
|
|
461
|
-
d = parent;
|
|
462
|
-
}
|
|
463
|
-
}
|
|
464
|
-
|
|
465
|
-
/** Canonicalize any deployment path that determines where an instance HOME is
|
|
466
|
-
* created — the agents root, and the agent directory derived from it.
|
|
467
|
-
*
|
|
468
|
-
* findRoot() walks up from the INVOCATION directory, so the path can sit inside
|
|
469
|
-
* a LINKED git worktree: a human running `oats spawn` from a worktree, or (far
|
|
470
|
-
* more common) an agent that ran `cd ./work` first. Instance homes must live in
|
|
471
|
-
* the soul-owning repo's PRIMARY checkout — `agents/*/instances/` is gitignored,
|
|
472
|
-
* so a home created in a linked worktree is invisible in status, and it dies
|
|
473
|
-
* with the tree that hosted it.
|
|
474
|
-
*
|
|
475
|
-
* Canonical identity comes from Git, never from a branch name: the FIRST record
|
|
476
|
-
* of `git worktree list --porcelain` is the main worktree. Probes are argv-based
|
|
477
|
-
* (paths may contain shell metacharacters) and read-only.
|
|
478
|
-
*
|
|
479
|
-
* Returns the path unchanged only when Git does not own the location, when it is
|
|
480
|
-
* already in the main worktree, or when it lies outside the work tree it was
|
|
481
|
-
* discovered from. Throws E_NO_CANONICAL_ROOT whenever Git DOES own the location
|
|
482
|
-
* but the primary checkout cannot be established — including a failed probe,
|
|
483
|
-
* which must never pass as "not a repo" (reviewer-2366d09): guessing recreates
|
|
484
|
-
* the very misplacement this exists to prevent.
|
|
485
|
-
*
|
|
486
|
-
* `self`: the path is a deployment directory, owned by the repository it sits
|
|
487
|
-
* in, that repository's root included (this computer's deployments list,
|
|
488
|
-
* lib/deployments.mjs). The probe starts at the directory itself rather than
|
|
489
|
-
* its parent, and the root of a linked worktree maps to the primary checkout's
|
|
490
|
-
* root. Without it (the agents roots), a path that is a work tree's root is left
|
|
491
|
-
* where it is.
|
|
492
|
-
*/
|
|
493
|
-
export function canonicalDeploymentPath(p, { self = false } = {}) {
|
|
494
|
-
if (!p) return p;
|
|
495
|
-
const abs = resolve(p);
|
|
496
|
-
const probe = (argv) => {
|
|
497
|
-
try { return { ok: true, out: execFileSync(argv[0], argv.slice(1), { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }) }; }
|
|
498
|
-
catch (e) { return { ok: false, err: String(e.stderr || e.message || "").trim() }; }
|
|
499
|
-
};
|
|
500
|
-
// The scope that owns the path. The directory itself may not exist yet
|
|
501
|
-
// (local-only scopes, an agent dir created on first use), so probe from the
|
|
502
|
-
// nearest existing ancestor.
|
|
503
|
-
let scope = self ? abs : dirname(abs);
|
|
504
|
-
while (!existsSync(scope) && dirname(scope) !== scope) scope = dirname(scope);
|
|
505
|
-
const top = probe(["git", "-C", scope, "rev-parse", "--show-toplevel"]);
|
|
506
|
-
if (!top.ok) {
|
|
507
|
-
// A failed probe is NOT evidence of a non-Git scope. Only the absence of any
|
|
508
|
-
// Git marker is — otherwise an unavailable/erroring git would silently let a
|
|
509
|
-
// linked worktree through, which is exactly the fail-open this prevents.
|
|
510
|
-
if (hasGitMarker(scope)) {
|
|
511
|
-
throw oatsError("E_NO_CANONICAL_ROOT", `${abs} is inside a Git-owned location whose repository could not be read (${top.err || "git rev-parse failed"}) — instance homes must live in the soul-owning repo's primary checkout, and OATS cannot confirm this is it; fix the Git error or pass --dir <primary checkout>`);
|
|
512
|
-
}
|
|
513
|
-
return abs; // genuinely not a Git work tree
|
|
514
|
-
}
|
|
515
|
-
const toplevel = top.out.trim();
|
|
516
|
-
if (!toplevel) return abs;
|
|
517
|
-
// Git reports CANONICAL paths, so every comparison and every relative()
|
|
518
|
-
// below must be realpath-based: on macOS a temp/agents root reached through
|
|
519
|
-
// /var while Git reports /private/var would otherwise look "outside" the
|
|
520
|
-
// work tree and silently skip canonicalization. So would a root given in
|
|
521
|
-
// another letter case on a case-insensitive filesystem: Git's paths are in
|
|
522
|
-
// their on-disk spelling, and so are both sides here. The agents dir itself
|
|
523
|
-
// may not exist yet (local-only scopes), so resolve the nearest existing
|
|
524
|
-
// ancestor and re-append the remainder.
|
|
525
|
-
const realOf = canonicalHomePath;
|
|
526
|
-
const same = (a, b) => realOf(a) === realOf(b);
|
|
527
|
-
// Linked or main? `--git-dir` equals `--git-common-dir` in the MAIN worktree
|
|
528
|
-
// and points at <common>/worktrees/<name> in a linked one. This settles it
|
|
529
|
-
// without `git worktree list`, so the overwhelmingly common main-checkout
|
|
530
|
-
// path costs one probe and — crucially — cannot be failed by a hiccup in a
|
|
531
|
-
// command it does not need (a forced `worktree list` failure used to reject
|
|
532
|
-
// an ordinary main-checkout spawn).
|
|
533
|
-
const dirs = probe(["git", "-C", scope, "rev-parse", "--path-format=absolute", "--git-dir", "--git-common-dir"]);
|
|
534
|
-
const [gitDir, commonDir] = dirs.ok
|
|
535
|
-
? dirs.out.trim().split("\n").map((l) => l.trim())
|
|
536
|
-
// Pre-2.31 git has no --path-format: fall back to plain output, whose paths
|
|
537
|
-
// may be relative to the scope.
|
|
538
|
-
: (() => {
|
|
539
|
-
const plain = probe(["git", "-C", scope, "rev-parse", "--git-dir", "--git-common-dir"]);
|
|
540
|
-
if (!plain.ok) return [];
|
|
541
|
-
return plain.out.trim().split("\n").map((l) => resolve(scope, l.trim()));
|
|
542
|
-
})();
|
|
543
|
-
if (!gitDir || !commonDir) {
|
|
544
|
-
throw oatsError("E_NO_CANONICAL_ROOT", `${abs} is inside the Git work tree ${toplevel}, but OATS could not tell a linked worktree from the primary checkout (${dirs.err || "git rev-parse --git-dir/--git-common-dir failed"}) — instance homes must live in the soul-owning repo's primary checkout; fix the Git error or pass --dir <primary checkout>`);
|
|
545
|
-
}
|
|
546
|
-
// Main checkout: the common case, and the one that must stay free — returned
|
|
547
|
-
// untouched, in the caller's own path form.
|
|
548
|
-
if (same(gitDir, commonDir)) return abs;
|
|
549
|
-
// Linked worktree from here on — the primary checkout is REQUIRED, not optional.
|
|
550
|
-
const list = probe(["git", "-C", scope, "worktree", "list", "--porcelain", "-z"]);
|
|
551
|
-
const mainWorktree = list.ok
|
|
552
|
-
? (list.out.split("\0").find((f) => f.startsWith("worktree ")) || "").slice("worktree ".length)
|
|
553
|
-
: undefined;
|
|
554
|
-
if (!list.ok) throw oatsError("E_NO_CANONICAL_ROOT", `${abs} is inside the linked Git worktree ${toplevel}, and the primary checkout could not be determined (${list.err || "git worktree list failed"}) — instance homes must live in the soul-owning repo's primary checkout; re-run from it or pass --dir <primary checkout>`);
|
|
555
|
-
if (!mainWorktree) throw oatsError("E_NO_CANONICAL_ROOT", `${abs} is inside the linked Git worktree ${toplevel}, but \`git worktree list\` reported no main worktree — instance homes must live in the soul-owning repo's primary checkout; re-run from it or pass --dir <primary checkout>`);
|
|
556
|
-
if (!existsSync(mainWorktree)) throw oatsError("E_NO_CANONICAL_ROOT", `${abs} is inside the linked Git worktree ${toplevel}, whose primary checkout ${mainWorktree} does not exist — instance homes must live in the soul-owning repo's primary checkout; restore it or pass --dir <primary checkout>`);
|
|
557
|
-
// Map the root's position within the linked tree onto the primary checkout.
|
|
558
|
-
// A root OUTSIDE the work tree (sibling agents/ beside the repo) is not a
|
|
559
|
-
// worktree artifact and is left exactly where it is.
|
|
560
|
-
const rel = relative(realOf(toplevel), realOf(abs));
|
|
561
|
-
if ((rel === "" && !self) || rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel)) return abs;
|
|
562
|
-
const canonical = join(realOf(mainWorktree), rel);
|
|
563
|
-
const back = relative(realOf(mainWorktree), canonical);
|
|
564
|
-
if (back === ".." || back.startsWith(`..${sep}`) || isAbsolute(back)) {
|
|
565
|
-
throw oatsError("E_NO_CANONICAL_ROOT", `canonical root for ${abs} would escape the primary checkout ${mainWorktree}`);
|
|
566
|
-
}
|
|
567
|
-
return canonical;
|
|
568
|
-
}
|
|
569
|
-
/** The canonical deployment root — where instance homes belong. */
|
|
570
|
-
export function canonicalAgentsRoot(root) { return canonicalDeploymentPath(root); }
|
|
571
|
-
export function ensureRoot(cwd) {
|
|
572
|
-
const root = findRoot(cwd);
|
|
573
|
-
if (!root) {
|
|
574
|
-
const from = resolve(cwd ?? process.cwd());
|
|
575
|
-
// Workspace model: an oats-local.yaml above `from` IS a deployment whose instance
|
|
576
|
-
// root (<deployment>/agents/) was never created — name that remedy, not a v1 verb.
|
|
577
|
-
let localDeployment = null;
|
|
578
|
-
for (let d = from; ; d = dirname(d)) { if (existsSync(join(d, "oats-local.yaml"))) { localDeployment = d; break; } if (dirname(d) === d) break; }
|
|
579
|
-
if (localDeployment) {
|
|
580
|
-
throw oatsError("E_NO_DEPLOYMENT",
|
|
581
|
-
`no instance root walking up from ${from}: ${join(localDeployment, "oats-local.yaml")} names this deployment but ${join(localDeployment, "agents")} does not exist — mkdir ${join(localDeployment, "agents")} (or run \`oats sync --dir ${localDeployment}\`, which creates it)`,
|
|
582
|
-
{ from, looked: ["agents/"], deployment: localDeployment, local: join(localDeployment, "oats-local.yaml"), remedy: `mkdir ${join(localDeployment, "agents")} (or run oats sync)` });
|
|
583
|
-
}
|
|
584
|
-
throw oatsError("E_NO_DEPLOYMENT",
|
|
585
|
-
`no deployment found walking up from ${from}: no agents/ directory — run from the deployment (where oats-local.yaml lives; \`oats onboard\` creates one), or set PI_AGENTS_ROOT`,
|
|
586
|
-
{ from, looked: ["agents/"] });
|
|
587
|
-
}
|
|
588
|
-
// Deployment root ≠ invocation CWD: homes always land in the primary checkout.
|
|
589
|
-
const canonical = canonicalAgentsRoot(root);
|
|
590
|
-
resolvedDeployment(dirname(canonical), { canonical: true });
|
|
591
|
-
return canonical;
|
|
592
|
-
}
|
|
593
|
-
export function workspaceOf(root) { return dirname(root); }
|
|
594
|
-
|
|
595
|
-
// ---------- capability slots ----------
|
|
596
|
-
export const LAYERS = ["knowledge", "messaging", "tasks"];
|
|
597
335
|
|
|
598
336
|
|
|
599
337
|
// ---------- launch configurations ----------
|
|
@@ -610,21 +348,6 @@ export const LAUNCH_CONFIG_KEYS = new Set(["harness", "runtime", "executable", "
|
|
|
610
348
|
export const launchConfigHarness = (entry) => (Object.hasOwn(entry, "harness") ? entry.harness : entry.runtime);
|
|
611
349
|
const LAUNCH_CONFIG_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
|
|
612
350
|
const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
613
|
-
/** Environment the kernel sets for every launch (identity, home, roots) and
|
|
614
|
-
* its reference aliases: a configuration may not name them. */
|
|
615
|
-
export const RESERVED_LAUNCH_ENV = new Set(["OATS_INSTANCE", "OATS_INSTANCE_HOME", "OATS_HOME", "OATS_AGENT", "OATS_SOUL", "OATS_SOUL_ID", "OATS_ROOT", "OATS_CONTEXT", "OATS_WORKSPACE", "OATS_EVENT", "OATS_SETTINGS", "OATS_SETTINGS_ORIGINS", "OATS_CLI_BIN", "OATS_NODE_BIN", "PI_AGENT_INSTANCE", "PI_AGENT_HOME", "PI_AGENTS_ROOT",
|
|
616
|
-
// The test seam that replaces the login shell (lib/login-environment.mjs): never a launch's to set.
|
|
617
|
-
"OATS_TEST_LOGIN_SHELL",
|
|
618
|
-
// The test seams of #796, the same: a worktree hook's fixed timeout, the fetch timeout of
|
|
619
|
-
// `oats worktree add` (lib/worktree-hooks.mjs, lib/worktree.mjs), and the `ps` path of a
|
|
620
|
-
// process's start time on a host with procfs, and the `ps` it runs (lib/worktree-hooks.mjs processStart).
|
|
621
|
-
"OATS_TEST_WORKTREE_HOOK_TIMEOUT_MS", "OATS_TEST_WORKTREE_FETCH_TIMEOUT_MS", "OATS_TEST_PROCESS_START_PS",
|
|
622
|
-
// The test seams of #915 and #1559: the cgroup the kernel judges itself in, whether the host was
|
|
623
|
-
// booted with systemd, and the directories its systemd-run comes from (lib/tmux-server-scope.mjs,
|
|
624
|
-
// lib/system-tools.mjs).
|
|
625
|
-
"OATS_TEST_CGROUP", "OATS_TEST_SYSTEMD_BOOTED", "OATS_TEST_SYSTEM_TOOL_DIRS",
|
|
626
|
-
// The test seam of #1421 §3: the naming call's time limit (lib/instance-naming.mjs NAMING_TIMEOUT_MS).
|
|
627
|
-
"OATS_TEST_NAMING_TIMEOUT_MS"]);
|
|
628
351
|
export const LAUNCH_REF_PREFIX = "OATS_LAUNCH_REF_";
|
|
629
352
|
const reservedLaunchEnv = (n) => RESERVED_LAUNCH_ENV.has(n) || n.startsWith(LAUNCH_REF_PREFIX);
|
|
630
353
|
export function validateLaunchConfig(name, entry, where) {
|
|
@@ -849,40 +572,6 @@ function validateCapabilityManifest(m, mf) {
|
|
|
849
572
|
return id;
|
|
850
573
|
}
|
|
851
574
|
|
|
852
|
-
/** The `_`-prefixed namespace on a parsed document belongs to the KERNEL: `_dir`,
|
|
853
|
-
* `_origin`, `_package`, `_capabilityLock`, `_soulDir` … are the
|
|
854
|
-
* kernel's own statements ABOUT an artifact — where it was found, which lock row
|
|
855
|
-
* governs it, whether it is trusted. They are internal annotations, so they must
|
|
856
|
-
* be unforgeable: an artifact that can write them into its own on-disk document
|
|
857
|
-
* asserts its own provenance. That was reachable — a capability whose `oats.json`
|
|
858
|
-
* declared `"_capabilityLock": {...}` spread straight through `{ ...m }` and
|
|
859
|
-
* silenced doctor's "in installed/ but has no lock entry" warning for an
|
|
860
|
-
* artifact nothing locks.
|
|
861
|
-
*
|
|
862
|
-
* So every parsed document that later RECEIVES annotations is stripped first.
|
|
863
|
-
* Stripping (rather than refusing) keeps the reader tolerant of documents that
|
|
864
|
-
* merely carry an unknown underscore key, while making the namespace
|
|
865
|
-
* unreachable from disk.
|
|
866
|
-
*
|
|
867
|
-
* `__proto__` starts with `_`, so a JSON document's own `__proto__` key is
|
|
868
|
-
* dropped here too rather than re-assigned through the inherited setter. */
|
|
869
|
-
/** A flat soul.yaml names its harness `harness:` (0.27.0) or, as released
|
|
870
|
-
* souls and capability-defined agents do (oats.aweb 1.13.1), `runtime:` —
|
|
871
|
-
* set both, read either until no released package writes `runtime`. Both,
|
|
872
|
-
* disagreeing, is refused. Returns the soul with `harness` only. */
|
|
873
|
-
export function soulHarnessField(soul, file) {
|
|
874
|
-
if (!soul || !Object.hasOwn(soul, "runtime")) return soul;
|
|
875
|
-
const { runtime, ...rest } = soul;
|
|
876
|
-
if (Object.hasOwn(soul, "harness") && soul.harness !== runtime) {
|
|
877
|
-
throw oatsError("E_BAD_MANIFEST", `${file} declares harness: ${soul.harness} and runtime: ${runtime}; \`runtime\` is the pre-0.27 name of \`harness\` — keep one`, { file, harness: soul.harness, runtime });
|
|
878
|
-
}
|
|
879
|
-
return { ...rest, harness: Object.hasOwn(soul, "harness") ? soul.harness : runtime };
|
|
880
|
-
}
|
|
881
|
-
export function stripInternalAnnotations(parsed) {
|
|
882
|
-
const out = {};
|
|
883
|
-
for (const key of Object.keys(parsed)) if (!key.startsWith("_")) out[key] = parsed[key];
|
|
884
|
-
return out;
|
|
885
|
-
}
|
|
886
575
|
|
|
887
576
|
function loadManifestAt(idir, origin, { strict = false } = {}) {
|
|
888
577
|
const mf = join(idir, "oats.json");
|
|
@@ -1048,82 +737,6 @@ export const DEFAULT_PACKAGE_PATH = "oats-package";
|
|
|
1048
737
|
|
|
1049
738
|
|
|
1050
739
|
|
|
1051
|
-
/** Official package catalog: identity + discovery ONLY — resolving through it
|
|
1052
|
-
* never advances a lock and never grants executable trust (contract §1).
|
|
1053
|
-
* Workstream 3 seeds the kernel-bundled catalog; OATS_PACKAGE_CATALOG points
|
|
1054
|
-
* tests/deployments at an alternate catalog JSON ({ packages: { <id>: { url, ref? } } }). */
|
|
1055
|
-
export function officialPackageCatalog() {
|
|
1056
|
-
return readCatalogFile().packages;
|
|
1057
|
-
}
|
|
1058
|
-
/** Parse the catalog file once: { packages: { <id>: { url, ref?, path? } },
|
|
1059
|
-
* capabilities?: { <legacy capability id>: <package id> } }. Both maps are
|
|
1060
|
-
* returned with a null prototype so inherited Object.prototype names can never
|
|
1061
|
-
* impersonate a catalog entry. */
|
|
1062
|
-
function readCatalogFile() {
|
|
1063
|
-
const file = officialCatalogFile();
|
|
1064
|
-
const empty = { packages: Object.create(null), capabilities: Object.create(null), file };
|
|
1065
|
-
// An OATS_PACKAGE_CATALOG override is local configuration (observation.localRevision); the bundled
|
|
1066
|
-
// catalog belongs to the kernel install.
|
|
1067
|
-
const override = !!process.env.OATS_PACKAGE_CATALOG;
|
|
1068
|
-
if (!existsSync(file)) { if (override) recordLocalInput(file, null); return empty; }
|
|
1069
|
-
const text = readFileSync(file, "utf8");
|
|
1070
|
-
if (override) recordLocalInput(file, text);
|
|
1071
|
-
return parsePackageCatalog(text, file);
|
|
1072
|
-
}
|
|
1073
|
-
/** A package catalog's text, parsed and checked as the kernel reads it (named `file` in errors):
|
|
1074
|
-
* { packages, capabilities, file }, both maps null-prototype; invalid-source when it is broken. */
|
|
1075
|
-
export function parsePackageCatalog(text, file) {
|
|
1076
|
-
let doc;
|
|
1077
|
-
try { doc = JSON.parse(text); }
|
|
1078
|
-
catch (e) {
|
|
1079
|
-
// JSON.parse does not say where; the kernel's strict reader (same grammar) locates the error.
|
|
1080
|
-
let line;
|
|
1081
|
-
try { parseStrictJson(text, { maxBytes: 64 * 1024 * 1024 }); } catch (s) { if (Number.isInteger(s.provenance?.offset)) line = lineAt(text, s.provenance.offset); }
|
|
1082
|
-
throw oatsError("invalid-source", `broken package catalog ${file}${line ? ` (line ${line})` : ""}: ${e.message}`);
|
|
1083
|
-
}
|
|
1084
|
-
if (!doc || typeof doc !== "object" || Array.isArray(doc)) throw oatsError("invalid-source", `broken package catalog ${file}: root must be a JSON object`);
|
|
1085
|
-
const out = { packages: Object.create(null), capabilities: Object.create(null), file };
|
|
1086
|
-
const packages = doc.packages;
|
|
1087
|
-
if (packages !== undefined) {
|
|
1088
|
-
if (packages === null || typeof packages !== "object" || Array.isArray(packages)) throw oatsError("invalid-source", `broken package catalog ${file}: "packages" must be an object map`);
|
|
1089
|
-
for (const [id, entry] of Object.entries(packages)) out.packages[id] = entry;
|
|
1090
|
-
}
|
|
1091
|
-
// Capability aliases (0.19.1 migration contract): legacy capability id →
|
|
1092
|
-
// official package id. Identity mappings (package id == capability id) need
|
|
1093
|
-
// no entry; an alias exists for capabilities a package exports under another
|
|
1094
|
-
// package identity (oats.developer is exported by package oats.engineering).
|
|
1095
|
-
//
|
|
1096
|
-
// The object form may also carry "capability": the id the package exports
|
|
1097
|
-
// TODAY in place of the legacy id (a RENAMING alias, the oas.* → oats.*
|
|
1098
|
-
// migration contract). A plain alias promises the package exports the legacy
|
|
1099
|
-
// id itself; a renaming alias promises it exports the successor instead.
|
|
1100
|
-
const aliases = doc.capabilities;
|
|
1101
|
-
if (aliases !== undefined) {
|
|
1102
|
-
if (aliases === null || typeof aliases !== "object" || Array.isArray(aliases)) throw oatsError("invalid-source", `broken package catalog ${file}: "capabilities" must be a map of capability id → package id`);
|
|
1103
|
-
for (const [capId, target] of Object.entries(aliases)) {
|
|
1104
|
-
const obj = typeof target === "string" ? { package: target } : (target && typeof target === "object" && !Array.isArray(target) ? target : undefined);
|
|
1105
|
-
const pkgId = obj?.package;
|
|
1106
|
-
if (typeof pkgId !== "string" || !PACKAGE_ID_RE.test(pkgId)) throw oatsError("invalid-source", `broken package catalog ${file}: capability alias "${capId}" must name a package id (string, or { "package": "<id>" })`);
|
|
1107
|
-
if (!PACKAGE_ID_RE.test(capId)) throw oatsError("invalid-source", `broken package catalog ${file}: capability alias key "${capId}" is not a valid capability id`);
|
|
1108
|
-
const renamed = obj.capability;
|
|
1109
|
-
if (renamed !== undefined && (typeof renamed !== "string" || !PACKAGE_ID_RE.test(renamed))) throw oatsError("invalid-source", `broken package catalog ${file}: capability alias "${capId}" has an invalid "capability" rename target`);
|
|
1110
|
-
out.capabilities[capId] = renamed && renamed !== capId ? { package: pkgId, capability: renamed } : pkgId;
|
|
1111
|
-
}
|
|
1112
|
-
}
|
|
1113
|
-
return out;
|
|
1114
|
-
}
|
|
1115
|
-
|
|
1116
|
-
/** The catalog's legacy-capability → official-package aliases (null-prototype). */
|
|
1117
|
-
export function officialCapabilityAliases() {
|
|
1118
|
-
return readCatalogFile().capabilities;
|
|
1119
|
-
}
|
|
1120
|
-
/** The effective official catalog file: `OATS_PACKAGE_CATALOG`, else the bundled one. */
|
|
1121
|
-
export function officialCatalogFile() {
|
|
1122
|
-
return process.env.OATS_PACKAGE_CATALOG || join(PKG_ROOT, "package-catalog.json");
|
|
1123
|
-
}
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
740
|
|
|
1128
741
|
|
|
1129
742
|
|
|
@@ -1891,33 +1504,6 @@ export function runLifecycleHooks(event, { home, instance, agentName, soulDir, s
|
|
|
1891
1504
|
|
|
1892
1505
|
|
|
1893
1506
|
|
|
1894
|
-
// ---------- agents ----------
|
|
1895
|
-
function soulOf(agentDir) { return join(agentDir, "soul"); }
|
|
1896
|
-
function readSoul(agentDir, soulDir = soulOf(agentDir)) {
|
|
1897
|
-
const p = join(soulDir, "soul.yaml");
|
|
1898
|
-
if (!existsSync(p)) return undefined;
|
|
1899
|
-
// Stripped before annotation: `_soulDir` is consumed as "the read-only soul
|
|
1900
|
-
// inside a package" (spawn, roster) and `_dir` as the agent home, so a
|
|
1901
|
-
// soul.yaml that could declare either would be describing itself to the
|
|
1902
|
-
// kernel. See stripInternalAnnotations.
|
|
1903
|
-
const text = readFileSync(p, "utf8");
|
|
1904
|
-
const flat = withConfigFile(p, () => parseYamlFlat(text));
|
|
1905
|
-
// A workspace-model soul.yaml (schemaVersion 2) nests maps (capabilities,
|
|
1906
|
-
// knowledge …): the flat reader would turn them into "" and the version into a
|
|
1907
|
-
// string. It is read with the real parser; a classic soul keeps the flat reader.
|
|
1908
|
-
let parsed = flat;
|
|
1909
|
-
if (flat.schemaVersion === "2") {
|
|
1910
|
-
try { const v = parseConfigData(text, { format: "yaml" }).value; if (v && typeof v === "object" && !Array.isArray(v)) parsed = v; }
|
|
1911
|
-
catch { /* unreadable as YAML: the flat view is what the classic readers saw */ }
|
|
1912
|
-
}
|
|
1913
|
-
const soul = soulHarnessField(stripInternalAnnotations(parsed), p);
|
|
1914
|
-
soul._dir = agentDir;
|
|
1915
|
-
// A package soul homes at <package>--<soul> (lib/workspace.mjs packageSoulAgentName): that
|
|
1916
|
-
// directory, not the soul.yaml name, is its agent name, so its instances never share a
|
|
1917
|
-
// member soul's name or roster row.
|
|
1918
|
-
soul.name = basename(agentDir).includes("--") ? basename(agentDir) : (soul.name || basename(agentDir));
|
|
1919
|
-
return soul;
|
|
1920
|
-
}
|
|
1921
1507
|
export function findAgent(root, name) {
|
|
1922
1508
|
return readSoul(join(root, name));
|
|
1923
1509
|
}
|
|
@@ -1929,19 +1515,6 @@ export function findAgentAt(root, name, soulDir) {
|
|
|
1929
1515
|
return agent;
|
|
1930
1516
|
}
|
|
1931
1517
|
|
|
1932
|
-
export function listAgents(root) {
|
|
1933
|
-
const agents = [];
|
|
1934
|
-
const scan = (base, kind) => {
|
|
1935
|
-
if (!existsSync(base)) return;
|
|
1936
|
-
for (const e of readdirSync(base, { withFileTypes: true })) {
|
|
1937
|
-
if (!e.isDirectory() || (kind === "persistent" && RESERVED.has(e.name))) continue;
|
|
1938
|
-
const soul = readSoul(join(base, e.name));
|
|
1939
|
-
if (soul) { soul.kind = soul.kind || kind; agents.push(soul); }
|
|
1940
|
-
}
|
|
1941
|
-
};
|
|
1942
|
-
scan(root, "persistent");
|
|
1943
|
-
return agents;
|
|
1944
|
-
}
|
|
1945
1518
|
|
|
1946
1519
|
export function defaultRepo(cwd = process.cwd()) {
|
|
1947
1520
|
return shTry(`git -C ${shq(resolve(cwd))} rev-parse --show-toplevel`);
|
|
@@ -2153,20 +1726,6 @@ export function explicitInstanceName(name) {
|
|
|
2153
1726
|
/** The window names of `session` on the user's DEFAULT tmux server: only for a home that records no
|
|
2154
1727
|
* socket (listInstances). OATS creates nothing there: new sessions live on the OATS server below. */
|
|
2155
1728
|
export function tmuxWindows(session = DEFAULT_TMUX_SESSION) { return defaultTmuxWindows(session).windows; }
|
|
2156
|
-
/** tmuxWindows' read, keeping a missing socket file apart (#624): `{ windows }`, with `missingSocket`
|
|
2157
|
-
* (tmux's words) when the default server's socket file is missing. Any other failure reads as no
|
|
2158
|
-
* session. `has-session` first, as ever: it is the read-only probe a caller may expect for a home
|
|
2159
|
-
* that records no socket, and it words a missing socket file as list-windows does. */
|
|
2160
|
-
function defaultTmuxWindows(session) {
|
|
2161
|
-
const run = (args) => execFileSync("tmux", args, { encoding: "utf8", timeout: 10000, maxBuffer: 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] });
|
|
2162
|
-
try {
|
|
2163
|
-
run(["has-session", "-t", session]);
|
|
2164
|
-
return { windows: run(["list-windows", "-t", session, "-F", "#{window_name}"]).split("\n").filter(Boolean) };
|
|
2165
|
-
} catch (e) {
|
|
2166
|
-
// Either read: the socket file can go between the two.
|
|
2167
|
-
return tmuxServerAbsence(e) === "missing-socket" ? { windows: [], missingSocket: tmuxFailure(e, "tmux failed") } : { windows: [] };
|
|
2168
|
-
}
|
|
2169
|
-
}
|
|
2170
1729
|
|
|
2171
1730
|
// ---------- the OATS tmux server ----------
|
|
2172
1731
|
/** The tmux server OATS creates its sessions on, selected by name (`tmux -L oats`): one per host user,
|
|
@@ -2187,7 +1746,6 @@ const OATS_WINDOW_COLOURS = [["window-style", "default"], ["window-active-style"
|
|
|
2187
1746
|
function tmuxOatsServer(args, io, options = {}) {
|
|
2188
1747
|
return (io?.exec || execFileSync)("tmux", ["-u", "-L", OATS_TMUX_SERVER, ...args], { encoding: "utf8", timeout: 10000, maxBuffer: 1024 * 1024, stdio: ["ignore", "pipe", "pipe"], ...options });
|
|
2189
1748
|
}
|
|
2190
|
-
const tmuxFailure = (e, fallback) => String(e?.stderr ?? e?.message ?? "").trim() || fallback;
|
|
2191
1749
|
/** A failed call in one line: the first line of its stderr, else how it ended. */
|
|
2192
1750
|
const failureLine = (e) => String(e?.stderr ?? "").trim().split("\n")[0] || (Number.isInteger(e?.status) ? `exit ${e.status}` : e?.signal ? `signal ${e.signal}` : String(e?.message || "failed"));
|
|
2193
1751
|
/** A failed call that ran to its own exit: it has a status, no signal ended it, and Node reports no
|
|
@@ -2347,16 +1905,6 @@ function creatorTmux(session) {
|
|
|
2347
1905
|
if (found) return found;
|
|
2348
1906
|
throw refuse("no tmux was found on this process's PATH");
|
|
2349
1907
|
}
|
|
2350
|
-
/** `name` as an exec looks it up on `path`: the first entry, in order, that holds a regular
|
|
2351
|
-
* executable file of that name, as an absolute path; null when none does. A relative entry, and
|
|
2352
|
-
* an empty one (an empty PATH is one empty entry), are `cwd`. Nothing is run. */
|
|
2353
|
-
function lookupOnPath(name, path, cwd = process.cwd()) {
|
|
2354
|
-
for (const dir of path.split(":")) {
|
|
2355
|
-
const candidate = resolve(cwd, dir || ".", name);
|
|
2356
|
-
try { accessSync(candidate, fsConstants.X_OK); if (statSync(candidate).isFile()) return candidate; } catch { /* not here */ }
|
|
2357
|
-
}
|
|
2358
|
-
return null;
|
|
2359
|
-
}
|
|
2360
1908
|
/**
|
|
2361
1909
|
* The environment a `new-session` on the OATS server runs with: the only tmux call that can start
|
|
2362
1910
|
* a server, so every one of them gets this, whether or not a server was seen a moment earlier. A
|
|
@@ -3026,68 +2574,6 @@ function verifyHarnessPackages(harness, resolved, contextDir, { bin, env } = {})
|
|
|
3026
2574
|
return found.filter((x) => (seen.has(x.identity) ? false : seen.add(x.identity))).sort((a, b) => a.identity.localeCompare(b.identity));
|
|
3027
2575
|
}
|
|
3028
2576
|
|
|
3029
|
-
// ---------- launch recipes ----------
|
|
3030
|
-
// What a harness start is made of, recorded in instance.json (`launch`) so a
|
|
3031
|
-
// later start or restart can re-render it, select another configuration, or
|
|
3032
|
-
// switch harness without guessing from the command string. The rendered
|
|
3033
|
-
// command (`command`) stays beside it, byte-identical to what spawn rendered
|
|
3034
|
-
// before recipes existed when no configuration is selected. Version 2 (0.27.0)
|
|
3035
|
-
// names the harness `harness`; version 1 (0.26.0 homes) said `runtime` and is
|
|
3036
|
-
// read as version 2 (upgradeLaunchRecipe); the next start or restart rewrites it.
|
|
3037
|
-
export const LAUNCH_RECIPE_VERSION = 2;
|
|
3038
|
-
/** A recorded recipe as this kernel reads it: version 1 `{runtime}` (0.26.0) is
|
|
3039
|
-
* version 2 `{harness}` (lead call 6: read either, write new). Anything else is
|
|
3040
|
-
* returned as it is, for assertLaunchRecipe to judge. */
|
|
3041
|
-
export function upgradeLaunchRecipe(recipe) {
|
|
3042
|
-
if (!isPlainObject(recipe) || recipe.version !== 1 || Object.hasOwn(recipe, "harness")) return recipe;
|
|
3043
|
-
const { runtime, ...rest } = recipe;
|
|
3044
|
-
return { ...rest, version: LAUNCH_RECIPE_VERSION, harness: runtime };
|
|
3045
|
-
}
|
|
3046
|
-
/** A home's instance.json as this kernel reads it: 0.26.0 recorded `runtime` and a
|
|
3047
|
-
* version-1 recipe; both read as `harness` (lead call 6). Every reader of a home's
|
|
3048
|
-
* harness goes through here; the next start or restart writes the new names. */
|
|
3049
|
-
export function upgradeHomeMeta(meta, home) {
|
|
3050
|
-
if (!isPlainObject(meta)) return meta;
|
|
3051
|
-
const old = Object.hasOwn(meta, "runtime") || (isPlainObject(meta.launch) && meta.launch.version === 1 && !Object.hasOwn(meta.launch, "harness"));
|
|
3052
|
-
if (!old) return meta;
|
|
3053
|
-
noteRuntimeName(`instance.json of ${home || meta.home || meta.instance} (a 0.26.0 home: its next start or restart records harness)`);
|
|
3054
|
-
const { runtime, ...rest } = meta;
|
|
3055
|
-
return { ...rest, ...(runtime !== undefined || meta.harness !== undefined ? { harness: meta.harness ?? runtime } : {}), ...(meta.launch !== undefined ? { launch: upgradeLaunchRecipe(meta.launch) } : {}) };
|
|
3056
|
-
}
|
|
3057
|
-
/** A home's record (`<home>/instance.json`) as it is on disk. Total: it never throws, so that one
|
|
3058
|
-
* home's record decides only for that home (awebai/oats#896). One of:
|
|
3059
|
-
* - `{ state: "record", path, meta }`: the JSON object the file holds, as written (a reader of
|
|
3060
|
-
* the home's harness passes it through upgradeHomeMeta);
|
|
3061
|
-
* - `{ state: "absent", path }`: no entry of that name, or a home this process cannot look into,
|
|
3062
|
-
* where whether there is one cannot be told (answered as a home without a record, as before);
|
|
3063
|
-
* - `{ state: "unreadable", path, reason }`: an entry is there and gives no JSON object: cut off,
|
|
3064
|
-
* empty, kept from this user, a directory, a link to nothing, or JSON that is not an object.
|
|
3065
|
-
* `reason` is the system's or the parser's, in words, without the path.
|
|
3066
|
-
* An unreadable record is never an absent one: the home may be a whole instance with work, and
|
|
3067
|
-
* "cannot read" is not "is not there". */
|
|
3068
|
-
export function readHomeRecord(home) {
|
|
3069
|
-
const path = join(home, "instance.json");
|
|
3070
|
-
const unreadable = (reason) => ({ state: "unreadable", path, reason });
|
|
3071
|
-
let text;
|
|
3072
|
-
try {
|
|
3073
|
-
// Only a regular file is read: a read of a directory fails, and one of a pipe would not return.
|
|
3074
|
-
const entry = statSync(path);
|
|
3075
|
-
if (!entry.isFile()) return unreadable(entry.isDirectory() ? "it is a directory" : "it is not a regular file");
|
|
3076
|
-
text = readFileSync(path, "utf8");
|
|
3077
|
-
} catch (e) {
|
|
3078
|
-
let entry;
|
|
3079
|
-
try { entry = lstatSync(path); } catch { return { state: "absent", path }; }
|
|
3080
|
-
if (entry.isSymbolicLink() && e?.code === "ENOENT") return unreadable("it is a symbolic link to nothing");
|
|
3081
|
-
// The system's words without the path, which the answer already names: `EACCES: permission denied`.
|
|
3082
|
-
return unreadable(String(e?.message ?? e).replace(/, [a-z]+ '.*'$/s, ""));
|
|
3083
|
-
}
|
|
3084
|
-
let value;
|
|
3085
|
-
try { value = JSON.parse(text); } catch (e) { return unreadable(String(e?.message ?? e)); }
|
|
3086
|
-
if (!isPlainObject(value)) return unreadable(`it holds ${value === null ? "null" : Array.isArray(value) ? "an array" : `a ${typeof value}`}, not a JSON object`);
|
|
3087
|
-
return { state: "record", path, meta: value };
|
|
3088
|
-
}
|
|
3089
|
-
/** What an answer says of a record that cannot be read (readHomeRecord): the file and the reason. */
|
|
3090
|
-
const unreadableRecordSaid = (record) => `${record.path} cannot be read (${record.reason})`;
|
|
3091
2577
|
/** The refusal of a lifecycle verb (retire, stop, session start) for a home whose record is there
|
|
3092
2578
|
* and cannot be read: E_UNIDENTIFIED_INSTANCE_HOME, with the file, the reason, `nothing` (what the
|
|
3093
2579
|
* verb had done by then: nothing; a spawn that names the home says "nothing was spawned") and the
|
|
@@ -3800,28 +3286,6 @@ export function describeLaunchCommand(command) {
|
|
|
3800
3286
|
const argv = tokens.slice(binary + 1).map((t) => t.kind === "sep" ? "--" : t.kind === "prompt" ? t.text : t.value);
|
|
3801
3287
|
return { executable: tokens[binary].value, argv, environment };
|
|
3802
3288
|
}
|
|
3803
|
-
/** A persisted command with every environment value withheld (references
|
|
3804
|
-
* stay references); a command the parser refuses is withheld whole. */
|
|
3805
|
-
/** The identity environment every launch carries: public facts (instance
|
|
3806
|
-
* name, home path), shown in public renderings; everything else is withheld. */
|
|
3807
|
-
export const IDENTITY_LAUNCH_ENV = new Set(["OATS_INSTANCE", "OATS_INSTANCE_HOME"]);
|
|
3808
|
-
export function redactLaunchCommand(command) {
|
|
3809
|
-
try { return parseLaunchCommand(command).tokens.map((t) => t.kind === "env" && !IDENTITY_LAUNCH_ENV.has(t.name) ? `${t.name}='<redacted>'` : t.text).join(" "); }
|
|
3810
|
-
catch { return "<unparseable launch command withheld>"; }
|
|
3811
|
-
}
|
|
3812
|
-
/** The recipe as answers carry it: every environment value withheld, and without `kernelBin`
|
|
3813
|
-
* (the home's record keeps it; human `oats status` reads it from there). */
|
|
3814
|
-
export function redactLaunchRecipe(recipe) {
|
|
3815
|
-
const env = Object.fromEntries(Object.keys(recipe.env || {}).sort().map((n) => [n, typeof recipe.env[n] === "string" ? { redacted: true } : { fromEnv: recipe.env[n].fromEnv }]));
|
|
3816
|
-
const hooks = recipe.hooks ? { ...recipe.hooks, env: Object.fromEntries(Object.keys(recipe.hooks.env || {}).sort().map((n) => [n, { redacted: true }])) } : undefined;
|
|
3817
|
-
const { kernelBin: _recorded, ...answered } = recipe;
|
|
3818
|
-
return { ...answered, env, ...(hooks ? { hooks } : {}) };
|
|
3819
|
-
}
|
|
3820
|
-
/** The kernel a home's last launch pointed its `oats` at (instance.json launch.kernelBin), or null. */
|
|
3821
|
-
export function recordedKernelBin(home) {
|
|
3822
|
-
try { const bin = JSON.parse(readFileSync(join(home, "instance.json"), "utf8"))?.launch?.kernelBin; return typeof bin === "string" ? bin : null; }
|
|
3823
|
-
catch { return null; }
|
|
3824
|
-
}
|
|
3825
3289
|
/** Spawn. With `o.prepared` (workspace model: a resolution prepared by
|
|
3826
3290
|
* instance-resolution.mjs) this is ASYNC — capabilities are fetched and copied
|
|
3827
3291
|
* into the home. Without it (classic soul-directory spawn: schedules, tests,
|
|
@@ -5485,295 +4949,11 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
|
|
|
5485
4949
|
}
|
|
5486
4950
|
}
|
|
5487
4951
|
|
|
5488
|
-
/** Decision 27 (K2): the principal an instance ACTS AS, as its messaging-layer provider reported
|
|
5489
|
-
* it — a documented layer contract `{ mode: "local"|"global", alias, team, address|null, resident|null,
|
|
5490
|
-
* grant?: { id, expiresAt, scopes } }` under `identity` in the provider's hook meta. The kernel copies it
|
|
5491
|
-
* through and never interprets `grant`. Preference: the capability whose captured layer is "messaging";
|
|
5492
|
-
* else any capability that emitted an `identity` object. Null when none did. */
|
|
5493
|
-
export function servedIdentityOf(meta) {
|
|
5494
|
-
const cm = meta?.capabilityMeta;
|
|
5495
|
-
if (!cm || typeof cm !== "object") return null;
|
|
5496
|
-
const harness = Array.isArray(meta.capabilityRuntime) ? meta.capabilityRuntime : [];
|
|
5497
|
-
const messaging = harness.filter((c) => c && c.layer === "messaging").map((c) => c.id);
|
|
5498
|
-
const pick = (ids) => { for (const id of ids) { const v = cm[id]?.identity; if (v && typeof v === "object" && !Array.isArray(v)) return { ...v, provider: id }; } return null; };
|
|
5499
|
-
return pick(messaging) ?? pick(Object.keys(cm));
|
|
5500
|
-
}
|
|
5501
|
-
/** One line for a roster/inspect: `acts as <address> via grant, expires <t>` or `alias <alias> on <team>`. */
|
|
5502
|
-
export function servedIdentityLine(identity) {
|
|
5503
|
-
if (!identity) return null;
|
|
5504
|
-
if (identity.mode === "global" && identity.grant) return `acts as ${identity.address || identity.alias || identity.resident || "?"} via grant${identity.grant.expiresAt ? `, expires ${identity.grant.expiresAt}` : ""}`;
|
|
5505
|
-
return `alias ${identity.alias || "?"} on ${identity.team || "?"}`;
|
|
5506
|
-
}
|
|
5507
|
-
/** The window names of `session` on the tmux server at `socket`: `{ windows }`, empty when the server
|
|
5508
|
-
* or the session is gone, with `missingSocket` (tmux's words) when the socket file is missing, which
|
|
5509
|
-
* alone does not say the server is gone (#624); `{ error }` when the server could not be read. */
|
|
5510
|
-
function recordedTmuxWindows(socket, session, io) {
|
|
5511
|
-
try { return { windows: tmuxOn(socket, ["list-windows", "-t", `=${session}`, "-F", "#{window_name}"], io).split("\n").filter(Boolean) }; }
|
|
5512
|
-
catch (e) {
|
|
5513
|
-
const absence = tmuxServerAbsence(e);
|
|
5514
|
-
if (absence === "missing-socket") return { windows: [], missingSocket: tmuxFailure(e, "tmux list-windows failed") };
|
|
5515
|
-
if (absence || /can't find session/i.test(String(e.stderr ?? ""))) return { windows: [] };
|
|
5516
|
-
return { error: String(e.stderr ?? e.message ?? "").trim() || "tmux list-windows failed" };
|
|
5517
|
-
}
|
|
5518
|
-
}
|
|
5519
|
-
/** A status row's harness liveness from its session's panes: unknown (not false) when the server could not
|
|
5520
|
-
* be read, and, for a row whose server holds its endpoint (`endpoint`), when its socket file is
|
|
5521
|
-
* missing while a process works in the home or the scan (`scanHome()`, processesInHome's answer for
|
|
5522
|
-
* it) cannot tell (#624). */
|
|
5523
|
-
function tmuxLiveness({ windows, error, missingSocket, panes, windowIds }, window, scanHome, endpoint, inspectPanes) {
|
|
5524
|
-
if (error) return { running: null, runtimeState: "unreachable", runtimeError: error };
|
|
5525
|
-
const running = windows.includes(window);
|
|
5526
|
-
const why = !running && missingSocket && endpoint ? missingSocketUnestablished(missingSocket, scanHome()) : null;
|
|
5527
|
-
if (why) return { running: null, runtimeState: "unreachable", runtimeError: why };
|
|
5528
|
-
if (!running) return { running: false };
|
|
5529
|
-
try {
|
|
5530
|
-
// Two windows of one name: tmux finds neither by name, so no session command reaches this one.
|
|
5531
|
-
if (windowIds?.get(window)?.size > 1) throw new Error(`the session has ${windowIds.get(window).size} windows named ${window}`);
|
|
5532
|
-
const observed = inspectPanes(panes.get(window) ?? [], { name: window });
|
|
5533
|
-
return { running: harnessRunning(observed), ...(observed.state === "shell" ? { runtimeState: "shell" } : {}) };
|
|
5534
|
-
} catch (e) { return { running: null, runtimeState: "unreachable", runtimeError: tmuxFailure(e, "tmux pane inspection failed") }; }
|
|
5535
|
-
}
|
|
5536
|
-
/** One extra read per socket/session, never per row. Keep window discovery's missing-socket
|
|
5537
|
-
* handling; a failed pane read after successful discovery is unknown, not proof of a stop. */
|
|
5538
|
-
function statusTmuxPanes(snapshot, socket, session, io) {
|
|
5539
|
-
if (!snapshot.windows?.length) return snapshot;
|
|
5540
|
-
try {
|
|
5541
|
-
const args = ["list-panes", "-s", "-t", `=${session}`, "-F", `#{window_name}\t#{window_id}\t#{pane_id}\t#{pane_dead}\t#{pane_current_command}\t#{pane_pid}\t#{${AGENT_PANE_OPTION}}`];
|
|
5542
|
-
const output = socket ? tmuxOn(socket, args, io) : (io?.exec || execFileSync)("tmux", ["-u", ...args], {
|
|
5543
|
-
encoding: "utf8", timeout: 10000, maxBuffer: 1024 * 1024, stdio: ["ignore", "pipe", "pipe"],
|
|
5544
|
-
});
|
|
5545
|
-
const panes = new Map(), windowIds = new Map();
|
|
5546
|
-
for (const line of output.split("\n").filter(Boolean)) {
|
|
5547
|
-
const [window, windowId, ...pane] = line.split("\t");
|
|
5548
|
-
if (!pane.length) throw new Error("invalid tmux pane response");
|
|
5549
|
-
if (!panes.has(window)) { panes.set(window, []); windowIds.set(window, new Set()); }
|
|
5550
|
-
panes.get(window).push(pane.join("\t"));
|
|
5551
|
-
windowIds.get(window).add(windowId);
|
|
5552
|
-
}
|
|
5553
|
-
return { ...snapshot, panes, windowIds };
|
|
5554
|
-
} catch (e) { return { error: tmuxFailure(e, "tmux list-panes failed") }; }
|
|
5555
|
-
}
|
|
5556
|
-
export function listInstances(root, tmuxSession = DEFAULT_TMUX_SESSION, io) {
|
|
5557
|
-
// Liveness reads each home's RECORDED endpoint (a pre-0.31 home records pi-agents): the recorded
|
|
5558
|
-
// socket, never the ambient $TMUX server: one window read and one pane read per socket/session,
|
|
5559
|
-
// plus one lazy process scan for shell descendants, independent of the number of homes.
|
|
5560
|
-
// A home without a recorded socket reads the default server.
|
|
5561
|
-
// A row whose socket file is missing is checked against one process scan of the host, made the
|
|
5562
|
-
// first time a row needs it and shared by every row (`io` reaches it: processesInHome).
|
|
5563
|
-
let hostScan;
|
|
5564
|
-
const scanOf = (home) => () => {
|
|
5565
|
-
hostScan ??= hostProcesses(io);
|
|
5566
|
-
return hostScan.ok ? { ok: true, processes: processesWorkingIn(hostScan.processes, home) } : hostScan;
|
|
5567
|
-
};
|
|
5568
|
-
const inspectPanes = createSessionPaneInspector(io);
|
|
5569
|
-
const tmuxByEndpoint = new Map();
|
|
5570
|
-
const windowsOf = (session, socket) => {
|
|
5571
|
-
const key = JSON.stringify([socket ?? null, session]);
|
|
5572
|
-
if (!tmuxByEndpoint.has(key)) tmuxByEndpoint.set(key, statusTmuxPanes(
|
|
5573
|
-
socket ? recordedTmuxWindows(socket, session, io) : defaultTmuxWindows(session), socket, session, io));
|
|
5574
|
-
return tmuxByEndpoint.get(key);
|
|
5575
|
-
};
|
|
5576
|
-
const readInstancesOf = (agentDir) => {
|
|
5577
|
-
const instancesDir = join(agentDir, "instances");
|
|
5578
|
-
// An instance name starts with a letter or digit (INSTANCE_NAME_RE); a
|
|
5579
|
-
// dot-directory under instances/ is kernel bookkeeping (.oats-retirement
|
|
5580
|
-
// holds baselines and recoveries), never a home (oats-5xl).
|
|
5581
|
-
return (existsSync(instancesDir) ? readdirSync(instancesDir, { withFileTypes: true }) : [])
|
|
5582
|
-
.filter((e) => e.isDirectory() && !e.name.startsWith("."))
|
|
5583
|
-
.map((e) => {
|
|
5584
|
-
const home = join(instancesDir, e.name);
|
|
5585
|
-
// The record decides for this home only: one that is there and cannot be read gives the
|
|
5586
|
-
// row of a home without a record, whose liveness says why (below), never a failed listing.
|
|
5587
|
-
const record = readHomeRecord(home);
|
|
5588
|
-
const meta = record.state === "record" ? upgradeHomeMeta(record.meta, home) : { instance: e.name, home };
|
|
5589
|
-
// A home retained by an incomplete rollback is NOT a live instance: it
|
|
5590
|
-
// is preserved state awaiting cleanup, and must read that way.
|
|
5591
|
-
const fallback = directoryRollbackPath(home);
|
|
5592
|
-
const quarantine = existsSync(fallback) ? fallback : join(home, ".oats-rollback-incomplete.json");
|
|
5593
|
-
let rollbackIncomplete, spawnInProgress;
|
|
5594
|
-
if (existsSync(quarantine)) {
|
|
5595
|
-
try { rollbackIncomplete = JSON.parse(readFileSync(quarantine, "utf8")); }
|
|
5596
|
-
catch { rollbackIncomplete = { reason: "rollback incomplete" }; }
|
|
5597
|
-
// #796: a spawn still running its worktree hooks keeps a marker that names it
|
|
5598
|
-
// (`inProgress`). While that process is verifiably alive the home is a spawn in
|
|
5599
|
-
// progress, not a failed one; otherwise the marker reads as the quarantine. A process whose
|
|
5600
|
-
// start cannot be read is not shown in progress either: on a host that never reads it, the
|
|
5601
|
-
// row would say "setting up" forever. It reads as the quarantine (its `inProgress` names
|
|
5602
|
-
// the pid), and retire, which never takes it for gone, refuses it with the way out.
|
|
5603
|
-
if (rollbackIncomplete?.inProgress && processLiveness(rollbackIncomplete.inProgress).state === "alive") { rollbackIncomplete = undefined; spawnInProgress = true; }
|
|
5604
|
-
}
|
|
5605
|
-
// A self-retire that has been requested but not completed: the home is
|
|
5606
|
-
// owed a retirement, not live work. Read-only here — completion is the
|
|
5607
|
-
// detached child's or an operator's `oats retire`, never status.
|
|
5608
|
-
const { retirePending, marker } = readRetirePending(home);
|
|
5609
|
-
const retire = retireStateOf(home, marker);
|
|
5610
|
-
// A home opened in Herdr (removed in 0.31.0) is listed, never observed: its row says so.
|
|
5611
|
-
// A home whose record cannot be read is listed, never observed: where its session is, is in the record.
|
|
5612
|
-
const liveness = record.state === "unreadable" ? { running: null, runtimeState: "unreachable", runtimeError: `E_UNIDENTIFIED_INSTANCE_HOME: ${unreadableRecordSaid(record)}` }
|
|
5613
|
-
: recordsHerdr(meta, readJsonOrUndefined(findRetirementBaseline(home)))
|
|
5614
|
-
? { running: null, runtimeState: "unsupported", runtimeError: `E_HERDR_REMOVED: ${herdrInstanceRemoved(e.name).message}` }
|
|
5615
|
-
: tmuxLiveness(windowsOf(meta.tmux?.session || tmuxSession, meta.tmux?.socket), meta.tmux?.window || meta.instance || e.name, scanOf(home),
|
|
5616
|
-
// A home that records no socket and no launch (--no-launch) reads the default server only
|
|
5617
|
-
// by default: that server's missing socket says nothing about it, and stays "not running".
|
|
5618
|
-
!!meta.tmux?.socket || meta.launched === true, inspectPanes);
|
|
5619
|
-
const identity = servedIdentityOf(meta);
|
|
5620
|
-
// Feature desktop-facts: `startedAt` — the last session start or restart (the receipt's restarts[]),
|
|
5621
|
-
// else the spawn's own launch (createdAt), else null (never launched); `identityAddress` — the
|
|
5622
|
-
// messaging identity's address (or alias) its capability recorded, null otherwise; `modelFrom` — null
|
|
5623
|
-
// for a home spawned before it was recorded.
|
|
5624
|
-
const lastStart = Array.isArray(meta.restarts) && meta.restarts.length ? meta.restarts[meta.restarts.length - 1]?.startedAt ?? null : null;
|
|
5625
|
-
const facts = { startedAt: lastStart ?? (meta.launched ? meta.createdAt ?? null : null), identityAddress: identity ? identity.address ?? identity.alias ?? null : null, modelFrom: meta.modelFrom ?? null };
|
|
5626
|
-
// The home IS the directory enumerated here, and the instance its name:
|
|
5627
|
-
// a file inside it cannot relocate or rename itself in the roster (every
|
|
5628
|
-
// consumer acting on `home` — retire, inspect --home, the Desktop's file
|
|
5629
|
-
// roots — would inherit the claim). A disagreeing claim survives only as
|
|
5630
|
-
// a diagnostic.
|
|
5631
|
-
const claims = {
|
|
5632
|
-
...(meta.home !== undefined && meta.home !== home ? { recordedHome: meta.home } : {}),
|
|
5633
|
-
...(meta.instance !== undefined && meta.instance !== e.name ? { recordedInstance: meta.instance } : {}),
|
|
5634
|
-
};
|
|
5635
|
-
// Feature waiting-on-you: a producer's live claim that the instance is
|
|
5636
|
-
// blocked on a human, read only for a running row (one bounded read of
|
|
5637
|
-
// its home log); null otherwise, and null means unknown. Pane liveness is
|
|
5638
|
-
// already observed in the batch; still require the independent receipt
|
|
5639
|
-
// to agree before showing a claim, just as session inspect does.
|
|
5640
|
-
let waitingOnYou = liveness.running === true ? liveWaiting(home) : null;
|
|
5641
|
-
if (waitingOnYou) {
|
|
5642
|
-
try { const s = instanceSessionTarget(home); if (!s.target) waitingOnYou = null; }
|
|
5643
|
-
catch { waitingOnYou = null; }
|
|
5644
|
-
}
|
|
5645
|
-
// `retire` is only ever the value read above, and `background` and `sameWork` the home's own records
|
|
5646
|
-
// (below): a record that carries any of them (hand-edited, or copied from a row) never stands in for it.
|
|
5647
|
-
const { retire: _recordedRetire, background: _recordedBackground, sameWork: _recordedSameWork, ...recorded } = meta;
|
|
5648
|
-
// Feature session-resume: how the last session of a launched home that does not run ended
|
|
5649
|
-
// (lib/session-end.mjs): lost, stopped or exited. Absent while it runs or reads unknown, for a
|
|
5650
|
-
// home never launched, and for one being set up, retired or quarantined.
|
|
5651
|
-
const sessionEnd = record.state === "record" && liveness.running === false && meta.launched === true && !rollbackIncomplete && !spawnInProgress && !retirePending ? sessionEndOf(home, meta) : null;
|
|
5652
|
-
// Feature instance-color: the home's own colour record (lib/instance-color.mjs), a palette name or
|
|
5653
|
-
// null, after the record so that nothing in instance.json stands in for it.
|
|
5654
|
-
// Feature instance-same-work: `sameWork: true` only while the home's flag is bound to the parent
|
|
5655
|
-
// its readable record names (lib/instance-same-work.mjs sameWorkOf); absent otherwise, never false.
|
|
5656
|
-
const sameWork = record.state === "record" && sameWorkOf(home, meta.parentInstance);
|
|
5657
|
-
return { ...recorded, ...claims, home, instance: e.name, ...facts, color: readInstanceColor(home), ...(readInstanceBackground(home) ? { background: true } : {}), ...(sameWork ? { sameWork: true } : {}), ...(identity ? { identity } : {}), ...(meta.launch && typeof meta.launch === "object" ? { launch: redactLaunchRecipe(meta.launch) } : {}), ...(typeof meta.command === "string" ? { command: redactLaunchCommand(meta.command) } : {}), ...liveness, ...(sessionEnd ? { sessionEnd } : {}), waitingOnYou, ...(rollbackIncomplete ? { rollbackIncomplete } : {}), ...(spawnInProgress ? { spawnInProgress } : {}), ...(retirePending ? { retirePending } : {}), ...(retire ? { retire } : {}) };
|
|
5658
|
-
|
|
5659
|
-
});
|
|
5660
|
-
};
|
|
5661
|
-
// Failed deferred self-retirements leave their outcome beside the home; a
|
|
5662
|
-
// successful one is evidence only and is not a problem to surface.
|
|
5663
|
-
const readRetireFailuresOf = (agentDir) => {
|
|
5664
|
-
const instancesDir = join(agentDir, "instances");
|
|
5665
|
-
if (!existsSync(instancesDir)) return [];
|
|
5666
|
-
const out = [];
|
|
5667
|
-
for (const e of readdirSync(instancesDir, { withFileTypes: true })) {
|
|
5668
|
-
const m = e.isFile() && /^\.oats-retired-(.+)\.json$/.exec(e.name);
|
|
5669
|
-
if (!m) continue;
|
|
5670
|
-
try {
|
|
5671
|
-
const r = JSON.parse(readFileSync(join(instancesDir, e.name), "utf8"));
|
|
5672
|
-
if (r.ok === false) out.push({ instance: m[1], completedAt: r.completedAt, error: r.error?.message, incomplete: r.result?.rollbackIncomplete, retry: r.retry, resultPath: join(instancesDir, e.name) });
|
|
5673
|
-
} catch { out.push({ instance: m[1], error: "unreadable result file", resultPath: join(instancesDir, e.name) }); }
|
|
5674
|
-
}
|
|
5675
|
-
return out;
|
|
5676
|
-
};
|
|
5677
|
-
const withFailures = (entry, agentDir) => {
|
|
5678
|
-
const retireFailures = readRetireFailuresOf(agentDir);
|
|
5679
|
-
return retireFailures.length ? { ...entry, retireFailures } : entry;
|
|
5680
|
-
};
|
|
5681
|
-
const out = listAgents(root).map((a) => {
|
|
5682
|
-
const { _dir, ...soul } = a;
|
|
5683
|
-
return withFailures({ ...soul, dir: _dir, instances: readInstancesOf(a._dir) }, a._dir);
|
|
5684
|
-
});
|
|
5685
|
-
// Capability-defined agents home under <root>/<name>/ WITHOUT a soul there (it
|
|
5686
|
-
// lives read-only in the module) — surface their instances too. A soul-less dir
|
|
5687
|
-
// none of whose homes is a capability agent's is not one.
|
|
5688
|
-
const seen = new Set(out.map((a) => a.name));
|
|
5689
|
-
for (const { name, dir } of capabilityAgentDirs(root)) {
|
|
5690
|
-
if (seen.has(name)) continue;
|
|
5691
|
-
const instances = readInstancesOf(dir);
|
|
5692
|
-
const retireFailures = readRetireFailuresOf(dir);
|
|
5693
|
-
if (!instances.some((i) => i.kind === "capability") && !retireFailures.length) continue;
|
|
5694
|
-
const cap = instances.find((i) => i.capability)?.capability;
|
|
5695
|
-
out.push({ name, kind: "capability", capability: cap, description: cap ? `capability agent (${cap})` : "capability agent", dir, instances, ...(retireFailures.length ? { retireFailures } : {}) });
|
|
5696
|
-
seen.add(name);
|
|
5697
|
-
}
|
|
5698
|
-
// Feature session-resume: what this local listing saw of each home's session, for the sweep
|
|
5699
|
-
// (lib/session-seen.mjs). It never changes the listing, and never throws or prints.
|
|
5700
|
-
recordSeen(root, out.flatMap((a) => a.instances || []));
|
|
5701
|
-
return out;
|
|
5702
|
-
}
|
|
5703
|
-
|
|
5704
|
-
/** The working directory as the shell names it: $PWD when it is the process's own directory, else
|
|
5705
|
-
* the physical cwd. A path through a symlink (an attached instance's work/, which links into its
|
|
5706
|
-
* owner's tree) then still belongs to the instance it was entered from. */
|
|
5707
|
-
export function logicalCwd() {
|
|
5708
|
-
const cwd = process.cwd(), pwd = process.env.PWD;
|
|
5709
|
-
try { if (pwd && isAbsolute(pwd) && realpathSync(pwd) === realpathSync(cwd)) return pwd; } catch { /* a stale PWD */ }
|
|
5710
|
-
return cwd;
|
|
5711
|
-
}
|
|
5712
|
-
/** The instance home enclosing `dir` (itself or its nearest such ancestor): a directory laid out
|
|
5713
|
-
* as <agents-root>/<agent>/instances/<name> whose instance.json records `instance: <name>`.
|
|
5714
|
-
* For a process whose harness strips the session env (Codex's shared app-server daemon runs
|
|
5715
|
-
* tool commands outside the session); the caller validates the home as it does one named by
|
|
5716
|
-
* OATS_INSTANCE_HOME. undefined when no such directory encloses `dir`. */
|
|
5717
|
-
export function enclosingInstanceHome(dir) {
|
|
5718
|
-
for (let d = resolve(dir); ; d = dirname(d)) {
|
|
5719
|
-
if (basename(dirname(d)) === "instances" && INSTANCE_NAME_RE.test(basename(d))) {
|
|
5720
|
-
try { if (JSON.parse(readFileSync(join(d, "instance.json"), "utf8"))?.instance === basename(d)) return d; }
|
|
5721
|
-
catch { /* no readable instance.json: not a home */ }
|
|
5722
|
-
}
|
|
5723
|
-
if (dirname(d) === d) return undefined;
|
|
5724
|
-
}
|
|
5725
|
-
}
|
|
5726
|
-
|
|
5727
|
-
// Locate an instance home under an agents root, including capability-defined
|
|
5728
|
-
// agents homing under <root>/<name>/ WITHOUT a soul there (listAgents cannot
|
|
5729
|
-
// see those). Shared by retireInstance and `oats spawn --parent`.
|
|
5730
|
-
// SECURITY: `name` is caller-controlled (CLI args, API bodies). It must be a
|
|
5731
|
-
// plain instance name — reject path separators/dots up front, and verify the
|
|
5732
|
-
// hit resolves to an IMMEDIATE child of an instances/ dir (realpath
|
|
5733
|
-
// containment), or `oats retire ../../dev/soul` would existence-match and
|
|
5734
|
-
// recursively delete a canonical soul.
|
|
5735
|
-
const INSTANCE_NAME_RE = /^[a-z0-9][a-z0-9-]*$/;
|
|
5736
4952
|
export function findInstanceHome(root, name) {
|
|
5737
4953
|
const all = findInstanceHomes(root, name);
|
|
5738
4954
|
return all.length ? all[0] : undefined;
|
|
5739
4955
|
}
|
|
5740
4956
|
|
|
5741
|
-
/** ALL homes matching an instance name under one agents root. Spawn keeps names
|
|
5742
|
-
* unique across the deployment since 0.26.0, but homes from earlier kernels (a
|
|
5743
|
-
* generated-name collision like `dev --purpose foo-1` vs agent `dev-foo`) and
|
|
5744
|
-
* direct kernel callers passing `instance` can still share one.
|
|
5745
|
-
* Ambiguity-sensitive callers must use this, not first-match. Same
|
|
5746
|
-
* containment/charset guarantees as findInstanceHome. */
|
|
5747
|
-
export function findInstanceHomes(root, name) {
|
|
5748
|
-
if (typeof name !== "string" || !INSTANCE_NAME_RE.test(name)) return [];
|
|
5749
|
-
const contained = (agentDir) => {
|
|
5750
|
-
const home = join(agentDir, "instances", name);
|
|
5751
|
-
if (!existsSync(home)) return undefined;
|
|
5752
|
-
try {
|
|
5753
|
-
const real = realpathSync(home);
|
|
5754
|
-
if (dirname(real) !== realpathSync(join(agentDir, "instances")) || basename(real) !== name) return undefined;
|
|
5755
|
-
} catch { return undefined; }
|
|
5756
|
-
return home;
|
|
5757
|
-
};
|
|
5758
|
-
const out = [];
|
|
5759
|
-
const seen = new Set();
|
|
5760
|
-
const push = (agent, home) => {
|
|
5761
|
-
// Dedupe by canonical home so all-matches callers never see double hits.
|
|
5762
|
-
let key; try { key = realpathSync(home); } catch { key = resolve(home); }
|
|
5763
|
-
if (seen.has(key)) return;
|
|
5764
|
-
seen.add(key);
|
|
5765
|
-
out.push({ agent, home });
|
|
5766
|
-
};
|
|
5767
|
-
for (const a of listAgents(root)) {
|
|
5768
|
-
const home = contained(a._dir);
|
|
5769
|
-
if (home) push(a, home);
|
|
5770
|
-
}
|
|
5771
|
-
for (const { name: agentName, dir } of capabilityAgentDirs(root)) {
|
|
5772
|
-
const home = contained(dir);
|
|
5773
|
-
if (home) push({ name: agentName, kind: "capability", _dir: dir }, home);
|
|
5774
|
-
}
|
|
5775
|
-
return out;
|
|
5776
|
-
}
|
|
5777
4957
|
|
|
5778
4958
|
/** The quarantine cleanup-descriptor contract version. Bump when the shape the
|
|
5779
4959
|
* retry consumes changes, so an older/newer marker fails closed instead of
|
|
@@ -5788,11 +4968,6 @@ export const QUARANTINE_CLEANUP_VERSION = 1;
|
|
|
5788
4968
|
/** The rollback-owned Git steps a quarantine can still owe. */
|
|
5789
4969
|
export const QUARANTINE_GIT_DEBT = ["worktree", "branch"];
|
|
5790
4970
|
|
|
5791
|
-
// A substituted/missing home cannot hold its own receipt. This sibling fallback
|
|
5792
|
-
// is independent of both home bytes and the recovery storage that may have failed.
|
|
5793
|
-
function directoryRollbackPath(home) {
|
|
5794
|
-
return join(dirname(home), `.oats-directory-rollback-${basename(home)}.json`);
|
|
5795
|
-
}
|
|
5796
4971
|
|
|
5797
4972
|
function assertDirectoryHome(home, canonicalHome = realPathOrNearest(home)) {
|
|
5798
4973
|
let st;
|
|
@@ -6002,24 +5177,6 @@ function quarantineInstanceHome({ home, instance, agent, soulDir, soulId, incomp
|
|
|
6002
5177
|
return ` — rollback INCOMPLETE. The instance home is RETAINED at ${home} because it holds the state needed to finish cleanup; it is not a live instance. Retry with \`oats retire ${instance}\`, then remove it once cleanup succeeds. Outstanding: ${incomplete.join("; ")}`;
|
|
6003
5178
|
}
|
|
6004
5179
|
|
|
6005
|
-
/** A cleanup descriptor is usable only if it can DRIVE the retry, so it is checked
|
|
6006
|
-
* as the strict contract its one producer writes — the rollback above — and to the
|
|
6007
|
-
* depth the retry CONSUMES it. Three rounds of review landed on this: validating
|
|
6008
|
-
* the outer shape only moved the failure from "unparseable" to "parseable and
|
|
6009
|
-
* useless", and every tolerance ("field optional", "array is enough") turned into
|
|
6010
|
-
* a retry that resolved nothing, reported no failures, and CLEARED the quarantine
|
|
6011
|
-
* — deleting the credential while the external state it was holding survived.
|
|
6012
|
-
*
|
|
6013
|
-
* Required, because the producer always writes them and the retry needs each one:
|
|
6014
|
-
* `version` (the contract), `repo` (resolves capabilities and reruns hooks),
|
|
6015
|
-
* `work` + `branch`-when-worktree (the rollback-owned Git steps; an unrecognised
|
|
6016
|
-
* mode silently skips them), `capabilityRuntime` (handed to runLifecycleHooks AS
|
|
6017
|
-
* the capability set, so it must BE one and must contain every outstanding hook),
|
|
6018
|
-
* and `outstanding.hooks` (what the retry has to prove it reran).
|
|
6019
|
-
*
|
|
6020
|
-
* Anything else reads as ABSENT — no more retryable than a missing marker — so the
|
|
6021
|
-
* home fails closed by default and `--force` can clear it. */
|
|
6022
|
-
function isPlainObject(v) { return !!v && typeof v === "object" && !Array.isArray(v); }
|
|
6023
5180
|
function nonEmptyString(v) { return typeof v === "string" && !!v.trim(); }
|
|
6024
5181
|
function usableCleanupDescriptor(marker) {
|
|
6025
5182
|
const c = marker?.cleanup;
|
|
@@ -6057,9 +5214,6 @@ function usableCleanupDescriptor(marker) {
|
|
|
6057
5214
|
return true;
|
|
6058
5215
|
}
|
|
6059
5216
|
|
|
6060
|
-
// The stored digests are versioned apart (`digestVersion`, BASELINE_DIGEST_VERSION): this version
|
|
6061
|
-
// also gates runtime, directory-home and provider-exclusion authority, so a bump would refuse them all.
|
|
6062
|
-
const RETIRE_BASELINE_VERSION = 2;
|
|
6063
5217
|
/** The version of the stored digests a spawn baseline is written with (fingerprintTrees,
|
|
6064
5218
|
* generatedWorkDigest); a baseline without `digestVersion` holds the legacy ones, 1. */
|
|
6065
5219
|
const BASELINE_DIGEST_VERSION = 2;
|
|
@@ -6071,74 +5225,16 @@ function baselineDigestVersion(baseline) {
|
|
|
6071
5225
|
return baseline.digestVersion === BASELINE_DIGEST_VERSION ? BASELINE_DIGEST_VERSION : undefined;
|
|
6072
5226
|
}
|
|
6073
5227
|
|
|
6074
|
-
function retirementStateRoot(home) {
|
|
6075
|
-
// Independent of the bytes it authenticates, but colocated with the agent's
|
|
6076
|
-
// already instance-owned storage rather than the source repository or user
|
|
6077
|
-
// config home. Retiring <instances>/<name> never removes this sibling.
|
|
6078
|
-
return instancesRetirementRoot(dirname(home));
|
|
6079
|
-
}
|
|
6080
|
-
/** The retirement state of the homes in the instances directory `instances`. */
|
|
6081
|
-
function instancesRetirementRoot(instances) {
|
|
6082
|
-
return join(instances, ".oats-retirement");
|
|
6083
|
-
}
|
|
6084
5228
|
/** Where retire writes the recovery copies of the homes in the instances directory `instances`. */
|
|
6085
5229
|
export function retirementRecoveryRoot(instances) {
|
|
6086
5230
|
return join(instancesRetirementRoot(instances), "recovery");
|
|
6087
5231
|
}
|
|
6088
5232
|
|
|
6089
|
-
/** A home's identity as a receipt records it: its on-disk spelling, own name included. A home that
|
|
6090
|
-
* is a symlink is not followed: its parent's on-disk spelling and its name as given (a home
|
|
6091
|
-
* exchanged for a symlink is not the home it points at). */
|
|
6092
|
-
function receiptHomeIdentity(home) {
|
|
6093
|
-
let st;
|
|
6094
|
-
try { st = lstatSync(home); } catch { /* not there: spelled as the nearest existing ancestor */ }
|
|
6095
|
-
return st && !st.isSymbolicLink() ? canonicalHomePath(home) : join(canonicalHomePath(dirname(home)), basename(home));
|
|
6096
|
-
}
|
|
6097
5233
|
|
|
6098
|
-
/** Whether a receipt's recorded home is this home, whatever spelling either was written in.
|
|
6099
|
-
* `current` is the home as the caller resolves it for the comparison. */
|
|
6100
|
-
function receiptRecordsHome(baseline, current) {
|
|
6101
|
-
return typeof baseline?.home === "string" && receiptHomeIdentity(baseline.home) === current;
|
|
6102
|
-
}
|
|
6103
5234
|
|
|
6104
|
-
function retirementBaselineFile(identity) {
|
|
6105
|
-
return join(retirementStateRoot(identity), "baselines", `${createHash("sha256").update(identity).digest("hex")}.json`);
|
|
6106
|
-
}
|
|
6107
5235
|
|
|
6108
|
-
/** Where a spawn writes a home's receipt: keyed by its canonical identity. */
|
|
6109
|
-
export function retirementBaselinePath(home) {
|
|
6110
|
-
return retirementBaselineFile(receiptHomeIdentity(home));
|
|
6111
|
-
}
|
|
6112
5236
|
|
|
6113
|
-
/** Where a kernel before 0.49.0 wrote it: keyed by the parent's realpath in the spawn's own
|
|
6114
|
-
* spelling, which on a case-insensitive filesystem need not be the on-disk one. */
|
|
6115
|
-
function legacyRetirementBaselinePath(home) {
|
|
6116
|
-
return retirementBaselineFile(join(realPathOrNearest(dirname(home)), basename(home)));
|
|
6117
|
-
}
|
|
6118
5237
|
|
|
6119
|
-
/** The receipt every reader uses: the canonical one if it exists, else one an earlier kernel left
|
|
6120
|
-
* under this caller's spelling, else the canonical path (absent). Read-only: a receipt found at the
|
|
6121
|
-
* legacy key is used where it is, never moved, copied or rewritten elsewhere.
|
|
6122
|
-
*
|
|
6123
|
-
* Limits. A legacy receipt written under spelling S is found only from S, or from the canonical
|
|
6124
|
-
* spelling when that is S: a third spelling of such a home misses it (address the home as
|
|
6125
|
-
* `oats status` prints it, the spawn's spelling). Receipts outlive retire, so a reused name can
|
|
6126
|
-
* leave an earlier incarnation's receipt behind; the canonical one wins, which is right for every
|
|
6127
|
-
* home spawned from 0.49.0 on. It is wrong in one case: two incarnations of the same name, both
|
|
6128
|
-
* spawned by a kernel before 0.49.0 under different spellings, the earlier one under the canonical
|
|
6129
|
-
* spelling. The later home then reads the earlier one's receipt. Its stale endpoint disagrees with
|
|
6130
|
-
* instance.json (E_RUNTIME_AUTHORITY_MISMATCH) unless the later incarnation sits at the same
|
|
6131
|
-
* endpoint, where session control already targets the right session. Retire finds the home
|
|
6132
|
-
* fingerprint changed and preserves the home, less the stale receipt's disposable roots; a
|
|
6133
|
-
* directory-work disagreement is E_WORK_INSPECTION_FAILED; and a start's record rewrites the stale
|
|
6134
|
-
* file, as a kernel before 0.49.0 already does when a caller's spelling matches an earlier
|
|
6135
|
-
* incarnation's. */
|
|
6136
|
-
export function findRetirementBaseline(home) {
|
|
6137
|
-
const canonical = retirementBaselinePath(home);
|
|
6138
|
-
if (existsSync(canonical)) return canonical;
|
|
6139
|
-
const legacy = legacyRetirementBaselinePath(home);
|
|
6140
|
-
return legacy !== canonical && existsSync(legacy) ? legacy : canonical;
|
|
6141
|
-
}
|
|
6142
5238
|
|
|
6143
5239
|
/** git's output for a large tree (status with untracked and ignored files,
|
|
6144
5240
|
* the index listing, a large blob) easily exceeds Node's 1 MiB default child
|
|
@@ -7060,136 +6156,15 @@ function recordedBranchExists(repo, branch) {
|
|
|
7060
6156
|
return !r.error && r.status === 0;
|
|
7061
6157
|
}
|
|
7062
6158
|
|
|
7063
|
-
|
|
7064
|
-
|
|
7065
|
-
|
|
7066
|
-
|
|
7067
|
-
|
|
7068
|
-
|
|
7069
|
-
|
|
7070
|
-
|
|
7071
|
-
|
|
7072
|
-
* missing or unreadable): before any receipt validation, so the refusal is never an endpoint error. */
|
|
7073
|
-
function refuseHerdrHome(home) {
|
|
7074
|
-
if (recordsHerdr(readJsonOrUndefined(join(home, "instance.json")), readJsonOrUndefined(findRetirementBaseline(home)))) throw herdrInstanceRemoved(basename(home));
|
|
7075
|
-
}
|
|
7076
|
-
|
|
7077
|
-
function runtimeAuthorityOf(baseline) {
|
|
7078
|
-
const runtime = baseline?.runtime;
|
|
7079
|
-
if (!isPlainObject(runtime) || typeof runtime.launched !== "boolean") return undefined;
|
|
7080
|
-
if (!runtime.launched) return { launched: false };
|
|
7081
|
-
if (runtime.sessionTarget !== undefined) return undefined;
|
|
7082
|
-
const tmux = runtime.tmux;
|
|
7083
|
-
if (!isPlainObject(tmux) || ![tmux.session, tmux.window, tmux.socket].every((v) => typeof v === "string" && v.length > 0)) return undefined;
|
|
7084
|
-
return { launched: true, tmux: { session: tmux.session, window: tmux.window, socket: resolve(tmux.socket) } };
|
|
7085
|
-
}
|
|
7086
|
-
|
|
7087
|
-
/** The fields of instance.json's tmux endpoint that differ from the one the independent receipt
|
|
7088
|
-
* authorises, as fixed labels in a fixed order: `tmux.session`, `tmux.window`, `tmux.socket`. */
|
|
7089
|
-
function tmuxEndpointDifferences(meta, authority) {
|
|
7090
|
-
return [
|
|
7091
|
-
...(meta.tmux?.session === authority.tmux?.session ? [] : ["tmux.session"]),
|
|
7092
|
-
...(meta.tmux?.window === authority.tmux?.window ? [] : ["tmux.window"]),
|
|
7093
|
-
...(resolve(meta.tmux?.socket || ".") === authority.tmux?.socket ? [] : ["tmux.socket"]),
|
|
7094
|
-
];
|
|
7095
|
-
}
|
|
7096
|
-
/** instance.json's tmux endpoint is the one the independent receipt authorises. */
|
|
7097
|
-
function tmuxEndpointAgrees(meta, authority) { return tmuxEndpointDifferences(meta, authority).length === 0; }
|
|
7098
|
-
|
|
7099
|
-
/** Whether a blocked or incomplete launch prompt explains metadata's `launched: false` beside a
|
|
7100
|
-
* launched receipt. */
|
|
7101
|
-
function promptRetained(meta, authority) {
|
|
7102
|
-
return authority.launched === true && meta.launched === false && ["blocked", "incomplete"].includes(meta.launchPrompts?.status);
|
|
7103
|
-
}
|
|
7104
|
-
/** A blocked prompt is a retained runtime, not evidence that no process exists.
|
|
7105
|
-
* The independent launched receipt and exact endpoint agreement remain mandatory. */
|
|
7106
|
-
function launchStateAgrees(meta, authority) {
|
|
7107
|
-
return meta.launched === authority.launched || (promptRetained(meta, authority) && tmuxEndpointAgrees(meta, authority));
|
|
7108
|
-
}
|
|
7109
|
-
|
|
7110
|
-
/** The refusal for instance.json that disagrees with the independent receipt. `details.fields` names
|
|
7111
|
-
* what differs, from a fixed vocabulary in a fixed order: `launched` (unless a blocked or incomplete
|
|
7112
|
-
* launch prompt explains metadata's `launched: false`), then, for a launched receipt, each differing
|
|
7113
|
-
* tmux endpoint field. Labels only: never a path, a value or the receipt. Callers throw it only once
|
|
7114
|
-
* their own comparison has refused, so these labels diagnose a refusal and never decide one. */
|
|
7115
|
-
function authorityMismatch(message, meta, authority) {
|
|
7116
|
-
const fields = [
|
|
7117
|
-
...(meta.launched === authority.launched || promptRetained(meta, authority) ? [] : ["launched"]),
|
|
7118
|
-
...(authority.launched ? tmuxEndpointDifferences(meta, authority) : []),
|
|
7119
|
-
];
|
|
7120
|
-
return Object.assign(oatsError("E_RUNTIME_AUTHORITY_MISMATCH", message), { details: { fields } });
|
|
7121
|
-
}
|
|
7122
|
-
|
|
7123
|
-
/** The refusal for a home whose session receipt is at neither key its path gives (findRetirementBaseline):
|
|
7124
|
-
* the canonical one, and the one an earlier kernel used for this spelling when that differs. The
|
|
7125
|
-
* receipt is keyed by the home's path, so a moved deployment looks elsewhere. */
|
|
7126
|
-
function missingSessionReceipt(home) {
|
|
7127
|
-
const canonical = retirementBaselinePath(home), legacy = legacyRetirementBaselinePath(home);
|
|
7128
|
-
const where = legacy === canonical ? canonical : `${canonical} (nor at ${legacy}, where a kernel before 0.49.0 kept it for this spelling)`;
|
|
7129
|
-
return oatsError("E_RUNTIME_ENDPOINT_UNKNOWN", `no session receipt for ${home} at ${where}. First address the home exactly as \`oats status\` prints it (a deployment directory moved since spawn looks for the receipt elsewhere, and so does a letter-case spelling other than the spawn's, for a home spawned before 0.49.0). Otherwise the home was copied, the .oats-retirement beside it was removed, or its creation did not finish: stop its session yourself if one runs, then \`oats retire ${basename(home)} --plan\` and \`oats retire ${basename(home)}\` (work is preserved), and respawn.`);
|
|
7130
|
-
}
|
|
7131
|
-
|
|
7132
|
-
/** Why a file could not be read or parsed, in the system's or the parser's words, without the path
|
|
7133
|
-
* the sentence already names: `EACCES: permission denied`; a missing file is "it is missing". */
|
|
7134
|
-
const unreadableBecause = (e) => e?.code === "ENOENT" ? "it is missing" : String(e?.message ?? e).replace(/, [a-z]+ '.*'$/s, "");
|
|
7135
|
-
|
|
7136
|
-
/** Session control uses the independent endpoint receipt. The receipt and the record are read
|
|
7137
|
-
* apart, so that a failure names the file that failed (#1092): one `catch` over both cannot know. */
|
|
7138
|
-
function instanceSessionTarget(home, { absentMeta } = {}) {
|
|
7139
|
-
if (typeof home !== "string" || !isAbsolute(home)) throw oatsError("E_BAD_ARGS", "session needs an absolute instance home");
|
|
7140
|
-
home = realPathOrNearest(home);
|
|
7141
|
-
refuseHerdrHome(home);
|
|
7142
|
-
const receiptPath = findRetirementBaseline(home), recordPath = join(home, "instance.json");
|
|
7143
|
-
let baseline, meta;
|
|
7144
|
-
try { baseline = JSON.parse(readFileSync(receiptPath, "utf8")); } catch (e) {
|
|
7145
|
-
if (e.code === "ENOENT" && e.path === receiptPath) throw missingSessionReceipt(home);
|
|
7146
|
-
throw oatsError("E_RUNTIME_ENDPOINT_UNKNOWN", `cannot read session receipt for ${home} at ${receiptPath}: ${unreadableBecause(e)}`);
|
|
7147
|
-
}
|
|
7148
|
-
try { meta = JSON.parse(readFileSync(recordPath, "utf8")); }
|
|
7149
|
-
catch (e) {
|
|
7150
|
-
// Upgrade may be between the two metadata renames. Its durable journal
|
|
7151
|
-
// supplies only the missing record; the independent endpoint still decides.
|
|
7152
|
-
if (e.code === "ENOENT" && isPlainObject(absentMeta)) meta = absentMeta;
|
|
7153
|
-
else throw oatsError("E_RUNTIME_ENDPOINT_UNKNOWN", `cannot read ${recordPath}: ${unreadableBecause(e)}`);
|
|
7154
|
-
}
|
|
7155
|
-
// A record that is JSON and no object gives no endpoint to compare the receipt with.
|
|
7156
|
-
if (!isPlainObject(meta)) throw oatsError("E_RUNTIME_ENDPOINT_UNKNOWN", `cannot read ${recordPath}: it holds no JSON object`);
|
|
7157
|
-
const authority = baseline.version === RETIRE_BASELINE_VERSION && receiptRecordsHome(baseline, canonicalHomePath(home)) && runtimeAuthorityOf(baseline);
|
|
7158
|
-
if (!authority) throw oatsError("E_RUNTIME_ENDPOINT_UNKNOWN", `independent session receipt is missing or invalid for ${home}`);
|
|
7159
|
-
if (!launchStateAgrees(meta, authority) || (authority.launched && !tmuxEndpointAgrees(meta, authority))) throw authorityMismatch("instance metadata disagrees with independent session receipt", meta, authority);
|
|
7160
|
-
return { home, target: authority.launched ? { backend: "tmux", ...authority.tmux } : undefined };
|
|
7161
|
-
}
|
|
7162
|
-
|
|
7163
|
-
/** `io` (`{ exec }`) is the tmux and process-table seam inspectSessionTarget takes. */
|
|
7164
|
-
export function inspectInstanceSession(home, { io, absentMeta } = {}) {
|
|
7165
|
-
if (typeof home === "string" && isAbsolute(home) && !existsSync(home)) return { home: realPathOrNearest(home), backend: null, present: false, state: "stopped", running: false, waitingOnYou: null };
|
|
7166
|
-
const s = instanceSessionTarget(home, { absentMeta });
|
|
7167
|
-
if (!s.target) return { home: s.home, backend: null, present: false, state: "not-launched", running: false, waitingOnYou: null };
|
|
7168
|
-
let observed;
|
|
7169
|
-
try { observed = inspectSessionTarget(s.target, io, { includeSize: true }); }
|
|
7170
|
-
// The tmux failure stays the cause: sessionServerGone judges it.
|
|
7171
|
-
catch (e) { throw Object.assign(oatsError("E_SESSION_UNAVAILABLE", `cannot inspect session: ${e.message}`), { cause: e }); }
|
|
7172
|
-
// Features session-inspect-running and waiting-on-you: beside `state`, whose enum is unchanged.
|
|
7173
|
-
// `running` is status's own liveness predicate over this observation, never a second reading.
|
|
7174
|
-
const running = harnessRunning(observed);
|
|
7175
|
-
return { home: s.home, ...observed, running, waitingOnYou: running ? liveWaiting(s.home) : null };
|
|
7176
|
-
}
|
|
7177
|
-
/** Whether an observed session runs a harness: present, and neither a
|
|
7178
|
-
* fallback shell nor a dead pane. Only such a session can be waiting on a human. */
|
|
7179
|
-
function harnessRunning(observed) { return observed?.present === true && observed.state !== "shell" && observed.state !== "stopped"; }
|
|
7180
|
-
|
|
7181
|
-
/** How a failed tmux call reads the server it addressed (#624). "gone": no server listens on the
|
|
7182
|
-
* socket (`no server running on`, or a refused connection), which is definitive. "missing-socket":
|
|
7183
|
-
* the socket file is not there (`No such file or directory`). After a reboot the server is gone,
|
|
7184
|
-
* but a tmux server outlives its removed socket file, so that alone establishes nothing: a caller
|
|
7185
|
-
* concludes stopped from it only when no process works in the home (missingSocketUnestablished).
|
|
7186
|
-
* null: anything else. */
|
|
7187
|
-
function tmuxServerAbsence(e) {
|
|
7188
|
-
const text = String(e?.stderr ?? e?.message ?? "");
|
|
7189
|
-
if (/no server running on |(?:error connecting to|failed to connect to) .*Connection refused/i.test(text)) return "gone";
|
|
7190
|
-
if (/(?:error connecting to|failed to connect to) .*No such file or directory/i.test(text)) return "missing-socket";
|
|
7191
|
-
return null;
|
|
7192
|
-
}
|
|
6159
|
+
|
|
6160
|
+
|
|
6161
|
+
|
|
6162
|
+
|
|
6163
|
+
|
|
6164
|
+
|
|
6165
|
+
|
|
6166
|
+
|
|
6167
|
+
|
|
7193
6168
|
function tmuxServerLost(e) { return tmuxServerAbsence(e) !== null; }
|
|
7194
6169
|
/** Whether the tmux server of `home`'s recorded session is gone, judged from `error`, a failed tmux
|
|
7195
6170
|
* call on its socket (#921). No server on the socket is gone. A missing socket file is gone only when
|
|
@@ -7200,27 +6175,6 @@ export function sessionServerGone(home, error, io) {
|
|
|
7200
6175
|
const why = absence === "missing-socket" ? missingSocketUnestablished(tmuxFailure(error, error.message), processesInHome(home, io)) : null;
|
|
7201
6176
|
return { gone: absence !== null && !why, why };
|
|
7202
6177
|
}
|
|
7203
|
-
/** tmux's own way back for a server that lost its socket file (tmux(1), `-S`). Named, never performed. */
|
|
7204
|
-
const TMUX_SOCKET_REMEDY = "tmux recreates a removed socket file when its server process receives SIGUSR1";
|
|
7205
|
-
/** Processes as a refusal names them: pid and program, at most five, then how many more. */
|
|
7206
|
-
function namedProcesses(processes) {
|
|
7207
|
-
return `${processes.slice(0, 5).map((p) => `pid ${p.pid} ${p.command}`).join(", ")}${processes.length > 5 ? `, and ${processes.length - 5} more` : ""}`;
|
|
7208
|
-
}
|
|
7209
|
-
/** A missing socket file (`detail`, tmux's words) checked against `scan`, processesInHome's answer
|
|
7210
|
-
* for the home (#624): null when it ran and found no process there, so the server is taken as gone,
|
|
7211
|
-
* as after a reboot; otherwise why the state is not established. Any process working in the home
|
|
7212
|
-
* counts, a person's shell included: the words name it, so the person can act on it. */
|
|
7213
|
-
function missingSocketUnestablished(detail, scan) {
|
|
7214
|
-
if (!scan.ok) return `${detail}; whether a process still works in this home could not be established (${scan.error})`;
|
|
7215
|
-
if (scan.processes.length) return `${detail}; a process still works in this home (${namedProcesses(scan.processes)}), so its tmux server may still be running without its socket file: ${TMUX_SOCKET_REMEDY}`;
|
|
7216
|
-
return null;
|
|
7217
|
-
}
|
|
7218
|
-
/** Whether this host's /proc can be read: Linux, and this process's own `cwd` link resolves. */
|
|
7219
|
-
function procReadable() {
|
|
7220
|
-
if (process.platform !== "linux") return { ok: false, error: "this host has no /proc to read (it is not Linux)" };
|
|
7221
|
-
try { readlinkSync("/proc/self/cwd"); return { ok: true }; }
|
|
7222
|
-
catch (e) { return { ok: false, error: `/proc/self/cwd cannot be read (${e.code || e.message})` }; }
|
|
7223
|
-
}
|
|
7224
6178
|
/** Which process scan this host offers, checked cheaply and without scanning (doctor reports it):
|
|
7225
6179
|
* /proc on Linux, else lsof when it is on PATH. → { mechanism: "proc" | "lsof" } | { mechanism: null, error } */
|
|
7226
6180
|
export function processScanAvailability() {
|
|
@@ -7235,85 +6189,6 @@ export function processScanInformation(availability = processScanAvailability())
|
|
|
7235
6189
|
if (availability.mechanism) return [];
|
|
7236
6190
|
return [`process-scan-unavailable: ${availability.error}; retire refuses where it must rule out a live process in an instance home (a home without its session receipt, a missing recorded tmux socket, a Herdr home), and session start/stop refuse when a recorded tmux socket is missing; install lsof`];
|
|
7237
6191
|
}
|
|
7238
|
-
/**
|
|
7239
|
-
* Every live process on the host (other than this one and its direct children) with its working
|
|
7240
|
-
* directory, from one scan: /proc on Linux (`io.procRoot` names another root), else one `lsof -a -d
|
|
7241
|
-
* cwd` listing; an injected `io.exec` stands in for the host's commands, so it is lsof's. Each cwd
|
|
7242
|
-
* is kept in its on-disk spelling (canonicalHomePath); one the kernel reports deleted (`<path>
|
|
7243
|
-
* (deleted)`) is kept as both spellings. A process this user may not inspect (another user's, or a
|
|
7244
|
-
* non-dumpable one) is not seen by either mechanism.
|
|
7245
|
-
* → { ok: true, processes: [{pid, command, cwds}] } | { ok: false, error }
|
|
7246
|
-
*/
|
|
7247
|
-
function hostProcesses(io) {
|
|
7248
|
-
const rows = typeof io?.procRoot === "string" ? procRows(io.procRoot)
|
|
7249
|
-
: !io?.exec && procReadable().ok ? procRows("/proc")
|
|
7250
|
-
: lsofRows(io);
|
|
7251
|
-
if (!rows.ok) return rows;
|
|
7252
|
-
const processes = [];
|
|
7253
|
-
for (const { pid, ppid, command, cwd } of rows.rows) {
|
|
7254
|
-
if (!pid || pid === process.pid || ppid === process.pid || typeof cwd !== "string") continue;
|
|
7255
|
-
const spellings = cwd.endsWith(" (deleted)") ? [cwd, cwd.slice(0, -" (deleted)".length)] : [cwd];
|
|
7256
|
-
processes.push({ pid, command: command ?? "?", cwds: spellings.map((p) => canonicalHomePath(p)) });
|
|
7257
|
-
}
|
|
7258
|
-
return { ok: true, processes };
|
|
7259
|
-
}
|
|
7260
|
-
/** The processes of a hostProcesses listing that work in `home`, compared in its on-disk spelling. */
|
|
7261
|
-
function processesWorkingIn(processes, home) {
|
|
7262
|
-
const realHome = canonicalHomePath(home);
|
|
7263
|
-
return processes.filter((p) => p.cwds.some((cwd) => cwd === realHome || cwd.startsWith(`${realHome}/`))).map(({ pid, command }) => ({ pid, command }));
|
|
7264
|
-
}
|
|
7265
|
-
/** /proc read as a scan: each numeric entry's `cwd` link, `comm` and `stat` (its ppid is the second
|
|
7266
|
-
* field after the last `)`, which ends the command). A pid that cannot be read (it ended meanwhile,
|
|
7267
|
-
* this user may not inspect it, or any other failure on that one pid) is not seen. A root that
|
|
7268
|
-
* cannot be listed, or one that lists no readable process, is a failed scan, never an empty one. */
|
|
7269
|
-
function procRows(root) {
|
|
7270
|
-
let names;
|
|
7271
|
-
try { names = readdirSync(root); }
|
|
7272
|
-
catch (e) { return { ok: false, error: `${root} cannot be read (${e.code || e.message})` }; }
|
|
7273
|
-
const rows = [];
|
|
7274
|
-
for (const name of names) {
|
|
7275
|
-
if (!/^\d+$/.test(name)) continue;
|
|
7276
|
-
try {
|
|
7277
|
-
const cwd = readlinkSync(join(root, name, "cwd"));
|
|
7278
|
-
const command = readFileSync(join(root, name, "comm"), "utf8").replace(/\n$/, "");
|
|
7279
|
-
const stat = readFileSync(join(root, name, "stat"), "utf8");
|
|
7280
|
-
rows.push({ pid: Number(name), ppid: Number(stat.slice(stat.lastIndexOf(")") + 1).trim().split(/\s+/)[1]), command, cwd });
|
|
7281
|
-
} catch { /* not seen */ }
|
|
7282
|
-
}
|
|
7283
|
-
// A real /proc always lists at least this process.
|
|
7284
|
-
if (!rows.length) return { ok: false, error: `${root} listed no process` };
|
|
7285
|
-
return { ok: true, rows };
|
|
7286
|
-
}
|
|
7287
|
-
function lsofRows(io) {
|
|
7288
|
-
let out;
|
|
7289
|
-
try { out = (io?.exec || execFileSync)("lsof", ["-a", "-d", "cwd", "-F", "pRcn", "-w"], { encoding: "utf8", timeout: 20000, maxBuffer: 16 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] }); }
|
|
7290
|
-
catch (e) {
|
|
7291
|
-
// lsof exits 1 with a full listing when some process could not be read. That is the one failure
|
|
7292
|
-
// whose output is a scan: lsof ended by itself with status 1 (no signal, and no error code, which
|
|
7293
|
-
// Node sets when the capture itself failed: a timeout, too much output). A scan that was cut off
|
|
7294
|
-
// is a failed scan whatever it printed first. The error says what happened, never a line of the
|
|
7295
|
-
// listing.
|
|
7296
|
-
const completed = e?.status === 1 && e.signal == null && e.code === undefined;
|
|
7297
|
-
if (completed && typeof e.stdout === "string") out = e.stdout;
|
|
7298
|
-
else return { ok: false, error: e?.code === "ENOENT" ? "lsof is not on PATH; install lsof"
|
|
7299
|
-
: e?.code === "ETIMEDOUT" ? "lsof timed out"
|
|
7300
|
-
: e?.code === "ENOBUFS" ? "lsof printed more output than the scan reads"
|
|
7301
|
-
: e?.signal ? `lsof was ended by ${e.signal}`
|
|
7302
|
-
: String(e?.stderr || e?.message || "lsof failed").trim().split("\n")[0] };
|
|
7303
|
-
}
|
|
7304
|
-
// A listing holds at least one process (lsof and its caller are always in it), whichever exit it came with.
|
|
7305
|
-
if (!/^p\d+$/m.test(String(out))) return { ok: false, error: "lsof listed no process" };
|
|
7306
|
-
const rows = [];
|
|
7307
|
-
let cur = {};
|
|
7308
|
-
for (const line of String(out).split("\n")) {
|
|
7309
|
-
const tag = line[0], value = line.slice(1);
|
|
7310
|
-
if (tag === "p") { cur = { pid: Number(value) }; rows.push(cur); }
|
|
7311
|
-
else if (tag === "R") cur.ppid = Number(value);
|
|
7312
|
-
else if (tag === "c") cur.command = value;
|
|
7313
|
-
else if (tag === "n") cur.cwd = value;
|
|
7314
|
-
}
|
|
7315
|
-
return { ok: true, rows };
|
|
7316
|
-
}
|
|
7317
6192
|
/**
|
|
7318
6193
|
* The live processes (other than this one and its direct children) whose working directory is
|
|
7319
6194
|
* inside `home`, from one scan of the host (hostProcesses: /proc on Linux, else lsof). A pid and a
|
|
@@ -7403,7 +6278,7 @@ function stopStartId(home) {
|
|
|
7403
6278
|
* receipt `.oats-stop.json`, `stop` being what was done to the harness (stopHarness's receipt, or
|
|
7404
6279
|
* null when nothing was signalled). Its `startId` names the start, so the home reads `stopped`
|
|
7405
6280
|
* and no resume brings that start back. The one writer of the receipt: a stop, an idle stop, and
|
|
7406
|
-
* a retire before
|
|
6281
|
+
* a retire and a restart before they end the session. Throws what the write throws. */
|
|
7407
6282
|
function recordStop(home, stop) {
|
|
7408
6283
|
writeJsonAtomic(join(home, STOP_RECEIPT_FILE), { instance: basename(home), at: new Date().toISOString(), stop, retained: ["home", "work", "transcript", "launch"], startId: stopStartId(home) });
|
|
7409
6284
|
}
|
|
@@ -7522,10 +6397,6 @@ export function inputInstanceSession(home, text) {
|
|
|
7522
6397
|
|
|
7523
6398
|
// ---------------------------------------------------------------- session start
|
|
7524
6399
|
|
|
7525
|
-
/** The prompt token of a recorded claude or codex command that hands the harness the task's own
|
|
7526
|
-
* text in argv, where any local user can read it: `"$(cat TASK.md)"`. It is parsed, and replaced
|
|
7527
|
-
* when the home starts (withSafeTaskPrompt). */
|
|
7528
|
-
const LAUNCH_PROMPT_TOKEN = '"$(cat TASK.md)"';
|
|
7529
6400
|
/** A recorded command with its harness's safe task prompt: a `"$(cat TASK.md)"` token becomes
|
|
7530
6401
|
* TASK_PROMPT[harness]. Applied when a home starts from its recorded command, which is saved so. */
|
|
7531
6402
|
export function withSafeTaskPrompt(command, harness) {
|
|
@@ -7535,79 +6406,6 @@ export function withSafeTaskPrompt(command, harness) {
|
|
|
7535
6406
|
return renderLaunchCommand(tokens.map((t) => t.kind === "prompt" ? { kind: "word", value: TASK_PROMPT[harness], quoted: true, text: shq(TASK_PROMPT[harness]) } : t));
|
|
7536
6407
|
}
|
|
7537
6408
|
|
|
7538
|
-
/** Tokenize a persisted OATS launch command. The grammar is exactly what
|
|
7539
|
-
* spawn renders: space-separated tokens that are env assignments NAME='v',
|
|
7540
|
-
* single-quoted words ('...' with '\'' escapes, i.e. shq output), bare words
|
|
7541
|
-
* with no shell metacharacters (flags and capability launch args), the bare
|
|
7542
|
-
* `--` separator, or the exact prompt token "$(cat TASK.md)". Anything else
|
|
7543
|
-
* is refused with its position: the command was not one OATS
|
|
7544
|
-
* generated, and rewriting it would be guessing. Re-rendering joins the
|
|
7545
|
-
* tokens' original text, so untouched tokens are byte-identical. */
|
|
7546
|
-
export function parseLaunchCommand(command) {
|
|
7547
|
-
if (typeof command !== "string" || !command.trim() || command.includes("\0")) throw oatsError("E_LAUNCH_COMMAND_UNSUPPORTED", "instance has no valid persisted launch command to start from");
|
|
7548
|
-
const bad = (at, why) => { throw oatsError("E_LAUNCH_COMMAND_UNSUPPORTED", `persisted launch command is not a shape this kernel re-renders (${why} at offset ${at}); inspect the saved command in instance.json before starting this home manually`); };
|
|
7549
|
-
const tokens = [];
|
|
7550
|
-
const n = command.length;
|
|
7551
|
-
let i = 0;
|
|
7552
|
-
while (i < n) {
|
|
7553
|
-
if (command[i] === " ") { i++; continue; }
|
|
7554
|
-
const start = i;
|
|
7555
|
-
if (command.startsWith(LAUNCH_PROMPT_TOKEN, i)) {
|
|
7556
|
-
i += LAUNCH_PROMPT_TOKEN.length;
|
|
7557
|
-
if (i < n && command[i] !== " ") bad(start, "text glued to the prompt token");
|
|
7558
|
-
tokens.push({ kind: "prompt", text: LAUNCH_PROMPT_TOKEN });
|
|
7559
|
-
continue;
|
|
7560
|
-
}
|
|
7561
|
-
// NAME="$SOURCE": an environment reference, resolved on the execution
|
|
7562
|
-
// host when the command runs; the persisted command carries no value.
|
|
7563
|
-
const ref = /^([A-Za-z_][A-Za-z0-9_]*)="\$([A-Za-z_][A-Za-z0-9_]*)"(?= |$)/.exec(command.slice(i));
|
|
7564
|
-
if (ref) { tokens.push({ kind: "envref", name: ref[1], source: ref[2], text: ref[0] }); i += ref[0].length; continue; }
|
|
7565
|
-
let envName;
|
|
7566
|
-
const m = /^([A-Za-z_][A-Za-z0-9_]*)='/.exec(command.slice(i));
|
|
7567
|
-
if (m) { envName = m[1]; i += envName.length + 1; }
|
|
7568
|
-
if (command[i] === "'") {
|
|
7569
|
-
i++;
|
|
7570
|
-
let value = "";
|
|
7571
|
-
for (;;) {
|
|
7572
|
-
if (i >= n) bad(start, "unterminated single quote");
|
|
7573
|
-
if (command[i] === "'") {
|
|
7574
|
-
if (command.startsWith("'\\''", i)) { value += "'"; i += 4; continue; }
|
|
7575
|
-
i++; break;
|
|
7576
|
-
}
|
|
7577
|
-
value += command[i++];
|
|
7578
|
-
}
|
|
7579
|
-
if (i < n && command[i] !== " ") bad(start, "text glued to a quoted token");
|
|
7580
|
-
const text = command.slice(start, i);
|
|
7581
|
-
tokens.push(envName ? { kind: "env", name: envName, value, text } : { kind: "word", value, quoted: true, text });
|
|
7582
|
-
continue;
|
|
7583
|
-
}
|
|
7584
|
-
if (envName) bad(start, "unquoted env value");
|
|
7585
|
-
while (i < n && command[i] !== " ") {
|
|
7586
|
-
if (/[\s'"$`\\;|&<>(){}*?~#]/.test(command[i])) bad(start, "shell metacharacter outside quotes");
|
|
7587
|
-
i++;
|
|
7588
|
-
}
|
|
7589
|
-
const word = command.slice(start, i);
|
|
7590
|
-
tokens.push(word === "--" ? { kind: "sep", text: word } : { kind: "word", value: word, quoted: false, text: word });
|
|
7591
|
-
}
|
|
7592
|
-
let binary = -1;
|
|
7593
|
-
for (let k = 0; k < tokens.length; k++) {
|
|
7594
|
-
if (tokens[k].kind === "env" || tokens[k].kind === "envref") { if (binary >= 0) bad(0, "env assignment after the binary"); continue; }
|
|
7595
|
-
if (binary < 0) { if (tokens[k].kind !== "word" || !tokens[k].quoted) bad(0, "no quoted binary after the env prefix"); binary = k; }
|
|
7596
|
-
}
|
|
7597
|
-
if (binary < 0) bad(0, "no binary");
|
|
7598
|
-
let modelIndex = -1;
|
|
7599
|
-
for (let k = binary + 1; k < tokens.length; k++) {
|
|
7600
|
-
if (tokens[k].kind === "sep") break;
|
|
7601
|
-
if (tokens[k].kind === "word" && !tokens[k].quoted && tokens[k].value === "--model") {
|
|
7602
|
-
const v = tokens[k + 1];
|
|
7603
|
-
if (!v || v.kind !== "word" || v.value.startsWith("-")) bad(0, "--model without a value");
|
|
7604
|
-
if (modelIndex >= 0) bad(0, "duplicate --model options");
|
|
7605
|
-
modelIndex = k + 1;
|
|
7606
|
-
k++;
|
|
7607
|
-
}
|
|
7608
|
-
}
|
|
7609
|
-
return { tokens, binary, modelIndex };
|
|
7610
|
-
}
|
|
7611
6409
|
|
|
7612
6410
|
export function renderLaunchCommand(tokens) { return tokens.map((t) => t.text).join(" "); }
|
|
7613
6411
|
|
|
@@ -7623,17 +6421,6 @@ export function withLaunchModel(command, model) {
|
|
|
7623
6421
|
return renderLaunchCommand(tokens);
|
|
7624
6422
|
}
|
|
7625
6423
|
|
|
7626
|
-
/** One tmux command on `socket`. With `env` (a window client: oatsWindowEnvironment, which has no
|
|
7627
|
-
* PATH) the tmux is the absolute one this process's own PATH finds, so its lookup never depends on
|
|
7628
|
-
* the environment it is passed; none found is reported as tmux being unavailable (ENOENT). */
|
|
7629
|
-
function tmuxOn(socket, args, io, env) {
|
|
7630
|
-
let tmux = "tmux";
|
|
7631
|
-
if (env) {
|
|
7632
|
-
tmux = process.env.PATH === undefined ? null : lookupOnPath("tmux", process.env.PATH);
|
|
7633
|
-
if (!tmux) throw Object.assign(new Error("no tmux was found on this process's PATH"), { code: "ENOENT" });
|
|
7634
|
-
}
|
|
7635
|
-
return (io?.exec || execFileSync)(tmux, ["-u", "-S", socket, ...args], { encoding: "utf8", timeout: 10000, maxBuffer: 1024 * 1024, stdio: ["ignore", "pipe", "pipe"], ...(env ? { env } : {}) });
|
|
7636
|
-
}
|
|
7637
6424
|
|
|
7638
6425
|
/** Write `value` as JSON at `path` through a private file beside it (`<path>.tmp-<pid>`), renamed
|
|
7639
6426
|
* over it, by the kernel's one such writer (lib/write-through-private-file.mjs): when the write or
|
|
@@ -7854,11 +6641,6 @@ export function restartInstanceSession(home, o = {}) { return startInstanceSessi
|
|
|
7854
6641
|
export function isWorkspaceHome(meta) {
|
|
7855
6642
|
return !!meta && typeof meta.modules === "object" && meta.modules !== null && !Array.isArray(meta.modules);
|
|
7856
6643
|
}
|
|
7857
|
-
/** Does this instance.json describe a captured home (the 0.24–0.25 captured/portable path,
|
|
7858
|
-
* removed in 0.26)? It records its incarnation instead of modules. */
|
|
7859
|
-
export function isCapturedHome(meta) {
|
|
7860
|
-
return !!meta && typeof meta === "object" && ["executionBinding", "incarnationId", "captured"].some((key) => Object.hasOwn(meta, key));
|
|
7861
|
-
}
|
|
7862
6644
|
/** The refusal for a captured home: E_UNSUPPORTED_MODE (lead decisions on (e), D1). */
|
|
7863
6645
|
export function capturedHomeRefusal(home, what) {
|
|
7864
6646
|
return Object.assign(oatsError("E_UNSUPPORTED_MODE", `${home} is a captured home (0.24–0.25; the captured/portable path was removed in 0.26): it has no 0.26 runtime — retire it (\`oats retire\` still works on it) and re-spawn from the deployment; ${what}`), { details: { home, captured: true } });
|
|
@@ -8320,6 +7102,13 @@ function startSession(home, o) {
|
|
|
8320
7102
|
// Restart: every preflight above passed, so ask the running harness to
|
|
8321
7103
|
// end and wait, bounded. A harness still there afterwards is reported
|
|
8322
7104
|
// as running; nothing is escalated and nothing is launched.
|
|
7105
|
+
// The stop is recorded first, for the start instance.json still names (recordStop, as a
|
|
7106
|
+
// retire does), so a relaunch that fails, or a process that dies before it, leaves a home
|
|
7107
|
+
// that reads `stopped`, never `lost`: no resume brings back what was being restarted. The
|
|
7108
|
+
// relaunch records a new start, which the record does not name. A stop refused here leaves
|
|
7109
|
+
// the record with the harness running: should that harness die later, the home reads
|
|
7110
|
+
// `stopped`. A record that cannot be written (a full disk) does not block the restart.
|
|
7111
|
+
try { recordStop(realHome, null); } catch { /* see above */ }
|
|
8323
7112
|
stopReceipt = stopHarness(target, { graceMs: o.stopGraceMs ?? 20000, io: o.io, kill: o.io?.kill, sleep: o.io?.sleep });
|
|
8324
7113
|
writeJsonAtomic(join(realHome, ".oats-restart.json"), { instance: meta.instance, at: new Date().toISOString(), stop: stopReceipt, next: { harness: launchPlan?.harness || harness, launchConfig: launchPlan?.recipe.launchConfig ?? null, model: model ?? null } }, 0o600);
|
|
8325
7114
|
appendEvent(realHome, { kind: stopReceipt.exited ? "restarted" : "stop-refused", data: { phase: "restart-stop", signal: stopReceipt.signal, waitedMs: stopReceipt.waitedMs, stillRunning: stopReceipt.stillRunning ?? [] } });
|
|
@@ -10033,23 +8822,7 @@ function relinkAttachedWork(kidHome, to) {
|
|
|
10033
8822
|
catch (e) { try { rmSync(tmp, { force: true }); } catch { /* the first error is the one reported */ } throw e; }
|
|
10034
8823
|
}
|
|
10035
8824
|
|
|
10036
|
-
/** Marker a self-retiring instance leaves BESIDE its home: the retirement is
|
|
10037
|
-
* requested and owed, and a detached completion is on its way. It is not
|
|
10038
|
-
* written into the home, so the caller changes no instance bytes and the
|
|
10039
|
-
* completion's work inspection sees exactly what the instance left. */
|
|
10040
|
-
export function retirePendingMarkerPath(home) {
|
|
10041
|
-
return join(dirname(home), `.oats-retire-pending-${basename(home)}.json`);
|
|
10042
|
-
}
|
|
10043
8825
|
|
|
10044
|
-
/** The retire-pending marker of `home` as a status row reads it → `{ retirePending, marker }`: both
|
|
10045
|
-
* undefined when there is none; `retirePending` what it parsed as (a placeholder when it did not
|
|
10046
|
-
* parse), `marker` what retireStateOf takes. */
|
|
10047
|
-
function readRetirePending(home) {
|
|
10048
|
-
const pending = retirePendingMarkerPath(home);
|
|
10049
|
-
if (!existsSync(pending)) return {};
|
|
10050
|
-
try { const read = JSON.parse(readFileSync(pending, "utf8")); return { retirePending: read, marker: { read } }; }
|
|
10051
|
-
catch { return { retirePending: { reason: "retire pending" }, marker: { read: undefined } }; }
|
|
10052
|
-
}
|
|
10053
8826
|
/** The retire `home` owes, as a status row's `retire` reads it (retireStateOf), or undefined. */
|
|
10054
8827
|
function owedRetire(home) {
|
|
10055
8828
|
return retireStateOf(home, readRetirePending(home).marker);
|
|
@@ -10060,68 +8833,7 @@ export function owedRetireSaid(instance, state) {
|
|
|
10060
8833
|
return `${instance} is owed a retire (its retire ${said}); a home OATS is retiring is never resumed`;
|
|
10061
8834
|
}
|
|
10062
8835
|
|
|
10063
|
-
/** A status row's `retire` (feature status-retire-state, lib/retire-state.mjs): whether a retire of
|
|
10064
|
-
* `home` runs, could not be told, failed or was interrupted, read from what is beside the home
|
|
10065
|
-
* (`marker`: `{ read }` when its retire marker is there, `read` what its file parsed as, undefined
|
|
10066
|
-
* when it did not parse; the row's own read, so `retirePending` and this agree). Only read: no
|
|
10067
|
-
* claim is taken, no file removed, no process signalled. → the value, or undefined when no retire
|
|
10068
|
-
* runs, is scheduled or is owed.
|
|
10069
|
-
* - The marker of a self-retire comes first, whatever the claim says (its completion holds the
|
|
10070
|
-
* claim for its own retire), and gives `self: true`. A completion's result that says `ok:
|
|
10071
|
-
* false` is `failed`, with its time, code and message. Otherwise, a result that says anything
|
|
10072
|
-
* else included, the marker's completion decides: `running` while it lives (pid and recorded
|
|
10073
|
-
* start), `interrupted` once it is gone, and `unknown` when that cannot be read or the marker
|
|
10074
|
-
* names no completion. A marker that does not parse is `unknown`.
|
|
10075
|
-
* - Without a marker, the home's claim held for a retire is `running` while its holder lives and
|
|
10076
|
-
* `unknown` when that cannot be read, with `self: false`. A holder that is gone, a stop's claim
|
|
10077
|
-
* or no claim gives no value.
|
|
10078
|
-
* `since` is required (a reader drops a value without one): the recorded time when it is an
|
|
10079
|
-
* instant as `toISOString()` gives it (the result's `completedAt`, then the marker's
|
|
10080
|
-
* `requestedAt`; the claim's `at`), else the marker's or the claim file's mtime. When none can be
|
|
10081
|
-
* read there is no value at all. */
|
|
10082
|
-
function retireStateOf(home, marker) {
|
|
10083
|
-
const mtimeOf = (path) => { try { return statSync(path).mtime.toISOString(); } catch { return undefined; } };
|
|
10084
|
-
// A file beside the home as JSON, only when it is a regular file: opened without blocking and
|
|
10085
|
-
// checked on the open descriptor, so a pipe (whose open or read would not return) or a device put
|
|
10086
|
-
// there is no value, never a status that hangs. Anything that does not read is undefined.
|
|
10087
|
-
const regularJson = (path) => {
|
|
10088
|
-
let fd;
|
|
10089
|
-
try {
|
|
10090
|
-
fd = openSync(path, fsConstants.O_RDONLY | (fsConstants.O_NONBLOCK ?? 0));
|
|
10091
|
-
return fstatSync(fd).isFile() ? JSON.parse(readFileSync(fd, "utf8")) : undefined;
|
|
10092
|
-
} catch { return undefined; } finally { if (fd !== undefined) closeSync(fd); }
|
|
10093
|
-
};
|
|
10094
|
-
const instantOr = (...times) => times.find((t) => isInstantString(t));
|
|
10095
|
-
if (marker) {
|
|
10096
|
-
const pending = marker.read, markerTime = () => mtimeOf(retirePendingMarkerPath(home));
|
|
10097
|
-
if (!isPlainObject(pending)) return readRetireState({ state: "unknown", self: true, since: markerTime() });
|
|
10098
|
-
const result = regularJson(deferredRetireResultPath(home));
|
|
10099
|
-
if (isPlainObject(result) && result.ok === false) {
|
|
10100
|
-
return readRetireState({ state: "failed", self: true, since: instantOr(result.completedAt, pending.requestedAt) ?? markerTime(), code: result.error?.code, message: result.error?.message });
|
|
10101
|
-
}
|
|
10102
|
-
const pid = pending.completionPid;
|
|
10103
|
-
const state = !Number.isSafeInteger(pid) || pid <= 0 ? "unknown"
|
|
10104
|
-
: { alive: "running", gone: "interrupted" }[processLiveness({ pid, processStart: pending.completionStart }).state] ?? "unknown";
|
|
10105
|
-
return readRetireState({ state, self: true, since: instantOr(pending.requestedAt) ?? markerTime() });
|
|
10106
|
-
}
|
|
10107
|
-
// Most rows have no claim: asked without the throw of a read that finds none, which is most of
|
|
10108
|
-
// what reading it costs. A path that is not there (a dangling link too) reads as no claim either way.
|
|
10109
|
-
// The claim is read as homeClaimHolder reads it (claimAction, processLiveness), through regularJson.
|
|
10110
|
-
const lock = retireClaimPath(home);
|
|
10111
|
-
if (!existsSync(lock)) return undefined;
|
|
10112
|
-
const holder = regularJson(lock);
|
|
10113
|
-
if (!isPlainObject(holder) || claimAction(holder) !== "retire") return undefined;
|
|
10114
|
-
const { state } = processLiveness(holder);
|
|
10115
|
-
if (state !== "alive" && state !== "unknown") return undefined;
|
|
10116
|
-
return readRetireState({ state: state === "alive" ? "running" : "unknown", self: false, since: shownHolder(holder).since ?? mtimeOf(lock) });
|
|
10117
|
-
}
|
|
10118
8836
|
|
|
10119
|
-
/** Where a deferred self-retirement writes its explicit outcome: a FILE beside
|
|
10120
|
-
* the (former) home, so it survives the home's removal and never reads as an
|
|
10121
|
-
* instance directory. */
|
|
10122
|
-
export function deferredRetireResultPath(home) {
|
|
10123
|
-
return join(dirname(home), `.oats-retired-${basename(home)}.json`);
|
|
10124
|
-
}
|
|
10125
8837
|
|
|
10126
8838
|
/** What the detached completion of a self-retire runs. Its intent is its own input: it takes the
|
|
10127
8839
|
* variable out of its environment once it has read it, before the retire runs anything, so that
|
|
@@ -10426,28 +9138,7 @@ export const RETIRE_UNDER_CLAIM = Symbol("oats.retireUnderClaim");
|
|
|
10426
9138
|
* claim of the first (that one removed, a same-named home of another agent made, in between). */
|
|
10427
9139
|
const RETIRE_CLAIM_RESTARTS = 2;
|
|
10428
9140
|
|
|
10429
|
-
|
|
10430
|
-
* the homes, never inside one: a home's bytes are what its retire observes, copies and removes.
|
|
10431
|
-
* One file for every verb that holds a home (a retire, a stop, an upgrade, a resume): its record
|
|
10432
|
-
* names the holder's verb (`action`) from the instant it exists (lib/claim.mjs `facts`). One file
|
|
10433
|
-
* for every spelling of the home: `<instances>` is the instances directory's own spelling on disk
|
|
10434
|
-
* (canonicalHomePath), and `<name>` the home's name once `.` and `..` are resolved, so that
|
|
10435
|
-
* `H/.`, or `H` through a link to its deployment, names H's claim. */
|
|
10436
|
-
export function retireClaimPath(home) {
|
|
10437
|
-
const at = resolve(home);
|
|
10438
|
-
return join(instancesRetirementRoot(canonicalHomePath(dirname(at))), "claims", `${basename(at)}.lock`);
|
|
10439
|
-
}
|
|
10440
|
-
|
|
10441
|
-
/** The verbs that take a home's lifecycle claim: what claimHomeFor accepts, and so every `action`
|
|
10442
|
-
* a claim of the kernel's names. `resume` is a `session start --resume`. */
|
|
10443
|
-
const CLAIM_VERBS = Object.freeze(["retire", "stop", "upgrade", "resume"]);
|
|
10444
|
-
/** The verb the holder of a home's claim recorded (`action`): one of CLAIM_VERBS, never the
|
|
10445
|
-
* record's text. A claim is read back as whatever is in its file, which other instances of the
|
|
10446
|
-
* deployment can write, and this goes into messages, remedies and `details` (lib/claim.mjs
|
|
10447
|
-
* shownHolder, the same rule for the holder's own fields). Anything else is a retire's, as a
|
|
10448
|
-
* record without one is: a kernel before feature `lifecycle-claim-stop` wrote none, and only its
|
|
10449
|
-
* retire took the claim. */
|
|
10450
|
-
const claimAction = (holder) => CLAIM_VERBS.includes(holder?.action) ? holder.action : "retire";
|
|
9141
|
+
|
|
10451
9142
|
/** The command that takes a home's claim for `action`, as a person types it. */
|
|
10452
9143
|
const claimCommand = (action) => action === "resume" ? "oats session start --resume" : ["stop", "upgrade"].includes(action) ? `oats instance ${action}` : `oats ${action}`;
|
|
10453
9144
|
/** What each verb that meets a held claim says it did not do: the words its refusals end with,
|