@awebai/oats 0.66.0 → 0.68.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/oats.mjs +166 -17
- package/docs/capabilities.md +58 -9
- package/docs/capability-manifest.schema.json +5 -1
- package/docs/design/2026-10-22-module-upgrade.md +192 -0
- package/docs/design/README.md +4 -0
- package/docs/desktop-cli-api.md +463 -13
- package/docs/desktop.md +363 -67
- package/docs/first-team.md +5 -3
- package/docs/implementation.md +46 -6
- package/docs/integrations.md +16 -4
- package/docs/knowledge.md +44 -27
- package/docs/layers.md +2 -2
- package/docs/official-catalog.md +5 -5
- package/docs/packages.md +14 -14
- package/docs/release-lane.md +16 -0
- package/docs/release-notes/v0.67.0.md +366 -0
- package/docs/release-notes/v0.67.1.md +64 -0
- package/docs/release-notes/v0.68.0.md +504 -0
- package/docs/servers.md +8 -2
- package/docs/souls-and-instances.md +58 -6
- package/docs/tui.md +1033 -237
- package/docs/upgrading.md +164 -26
- package/docs/workspaces.md +2 -2
- package/lib/capability-contract.mjs +8 -7
- package/lib/core.mjs +331 -75
- package/lib/instance-color.mjs +58 -0
- package/lib/instance-events.mjs +1 -1
- package/lib/instance-inspect.mjs +107 -23
- package/lib/instance-lifecycle.mjs +21 -1
- package/lib/instance-naming.mjs +187 -0
- package/lib/instance-resolution.mjs +10 -6
- package/lib/instance-upgrade.mjs +1445 -0
- package/lib/materialize.mjs +287 -89
- package/lib/servers.mjs +24 -11
- package/lib/soul-composition.mjs +7 -3
- package/lib/upgrade-state.mjs +101 -0
- package/lib/workspace.mjs +4 -1
- package/lib/worktree.mjs +103 -12
- package/package-catalog.json +5 -4
- package/package.json +1 -1
- package/packages/client/cli-adapter.mjs +52 -6
- package/packages/client/cli-locator.mjs +2 -2
- package/packages/client/composed-gate.mjs +10 -2
- package/packages/client/deployment-data.mjs +5 -0
- package/packages/client/deployment-identity.mjs +40 -0
- package/packages/client/deployment-panel.mjs +9 -3
- package/packages/client/inspect-boundary.mjs +11 -7
- package/packages/client/inspect-cache.mjs +2 -2
- package/packages/client/instance-name.mjs +28 -0
- package/packages/client/instance-presentation.mjs +11 -0
- package/packages/client/keymap.mjs +133 -28
- package/packages/client/keys-file.mjs +126 -0
- package/packages/client/own-codes.mjs +4 -2
- package/packages/client/panel-views.mjs +78 -12
- package/packages/client/spawn-naming.mjs +32 -0
- package/packages/client/spawn-preview-cli.mjs +58 -7
- package/packages/client/spawn-preview-contract.mjs +59 -0
- package/packages/client/spawn-preview-facts.mjs +8 -4
- package/packages/client/spawn-preview.mjs +81 -3
- package/packages/client/team-members.mjs +4 -1
- package/packages/client/workspace-step.mjs +25 -0
- package/packages/tui/README.md +7 -7
- package/packages/tui/lib/actions.mjs +92 -25
- package/packages/tui/lib/client.mjs +9 -4
- package/packages/tui/lib/config.mjs +50 -9
- package/packages/tui/lib/main.mjs +65 -24
- package/packages/tui/lib/model.mjs +292 -75
- package/packages/tui/lib/read.mjs +53 -1
- package/packages/tui/lib/store.mjs +469 -100
- package/packages/tui/lib/term/keys.mjs +22 -6
- package/packages/tui/lib/term/kitty.mjs +54 -11
- package/packages/tui/lib/term/screen.mjs +15 -6
- package/packages/tui/lib/term/through.mjs +66 -28
- package/packages/tui/lib/views/frame.mjs +223 -165
- package/packages/tui/lib/views/help.mjs +134 -29
- package/packages/tui/lib/views/instances.mjs +63 -22
- package/packages/tui/lib/views/palette.mjs +14 -4
- package/packages/tui/lib/views/souls.mjs +2 -2
- package/packages/tui/lib/views/switcher.mjs +6 -1
- package/packages/tui/lib/views/workspaces.mjs +55 -0
- package/skills/oats-getting-started/SKILL.md +96 -42
|
@@ -0,0 +1,1445 @@
|
|
|
1
|
+
/** Package module upgrades are explicit stopped-home acts. Composition is materialize's
|
|
2
|
+
* transaction; this module owns adoption, durable forward recovery and the plan fence.
|
|
3
|
+
* A successful provider hook is the irreversible boundary: old modules must never be
|
|
4
|
+
* restored under host state adopted by a new provider. */
|
|
5
|
+
import { createHash } from "node:crypto";
|
|
6
|
+
import { execSync } from "node:child_process";
|
|
7
|
+
import {
|
|
8
|
+
existsSync,
|
|
9
|
+
openSync,
|
|
10
|
+
closeSync,
|
|
11
|
+
fstatSync,
|
|
12
|
+
writeFileSync,
|
|
13
|
+
lstatSync,
|
|
14
|
+
mkdirSync,
|
|
15
|
+
mkdtempSync,
|
|
16
|
+
readFileSync,
|
|
17
|
+
readdirSync,
|
|
18
|
+
renameSync,
|
|
19
|
+
rmSync,
|
|
20
|
+
} from "node:fs";
|
|
21
|
+
import { tmpdir } from "node:os";
|
|
22
|
+
import { dirname, join, relative, resolve, sep } from "node:path";
|
|
23
|
+
import { oatsError } from "./errors.mjs";
|
|
24
|
+
import { resolveInstance } from "./instance-lifecycle.mjs";
|
|
25
|
+
import {
|
|
26
|
+
claimHomeFor,
|
|
27
|
+
releaseHomeClaim,
|
|
28
|
+
homeClaimHolder,
|
|
29
|
+
lifecycleClaimRefusals,
|
|
30
|
+
retirePendingMarkerPath,
|
|
31
|
+
identifiedHomeRecord,
|
|
32
|
+
inspectInstanceSession,
|
|
33
|
+
lifecycleHookEnv,
|
|
34
|
+
resolvedFromHome,
|
|
35
|
+
materializedHookCommands,
|
|
36
|
+
shq,
|
|
37
|
+
composeInstanceAgentsMd,
|
|
38
|
+
retirementHomeChanged,
|
|
39
|
+
rebaseUpgradeRetirementBaseline,
|
|
40
|
+
planInstanceResources,
|
|
41
|
+
findRetirementBaseline,
|
|
42
|
+
officialPackageCatalog,
|
|
43
|
+
} from "./core.mjs";
|
|
44
|
+
import {
|
|
45
|
+
stageMaterialize,
|
|
46
|
+
driftOf,
|
|
47
|
+
moduleSkills,
|
|
48
|
+
refForKey,
|
|
49
|
+
} from "./materialize.mjs";
|
|
50
|
+
import {
|
|
51
|
+
toCapabilityRows,
|
|
52
|
+
discoverOrStandalone,
|
|
53
|
+
} from "./instance-resolution.mjs";
|
|
54
|
+
import {
|
|
55
|
+
lockedPackageCapabilities,
|
|
56
|
+
lockedCapability,
|
|
57
|
+
revisionOf,
|
|
58
|
+
kernelCompatibility,
|
|
59
|
+
} from "./resolve.mjs";
|
|
60
|
+
import { readLock, writeFileAtomic } from "./packages.mjs";
|
|
61
|
+
import { loadLocal, memberSoulPath } from "./workspace.mjs";
|
|
62
|
+
import { copyTreeSafe, treeDisagreement } from "./tree-copy.mjs";
|
|
63
|
+
import { appendEvent, readEvents } from "./instance-events.mjs";
|
|
64
|
+
import {
|
|
65
|
+
assertNoPartialUpgrade,
|
|
66
|
+
readUpgradeReceipts,
|
|
67
|
+
} from "./upgrade-state.mjs";
|
|
68
|
+
import * as remote from "./remote.mjs";
|
|
69
|
+
|
|
70
|
+
const KEY = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
|
|
71
|
+
const CAP = /^[a-z0-9][a-z0-9._-]*$/;
|
|
72
|
+
const object = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
|
|
73
|
+
const readJson = (path) => {
|
|
74
|
+
try {
|
|
75
|
+
const value = JSON.parse(readFileSync(path, "utf8"));
|
|
76
|
+
if (object(value)) return value;
|
|
77
|
+
} catch {
|
|
78
|
+
/* invalid or unavailable state is an input refusal */
|
|
79
|
+
}
|
|
80
|
+
throw fail(
|
|
81
|
+
"E_UPGRADE_INTEGRITY",
|
|
82
|
+
`${path} cannot be read as a JSON object; restore the recorded bytes or respawn the instance`,
|
|
83
|
+
);
|
|
84
|
+
};
|
|
85
|
+
const clone = (v) => JSON.parse(JSON.stringify(v));
|
|
86
|
+
const fileDigest = (path) =>
|
|
87
|
+
createHash("sha256").update(readFileSync(path)).digest("hex");
|
|
88
|
+
const hash = (v) =>
|
|
89
|
+
createHash("sha256").update(JSON.stringify(v)).digest("hex").slice(0, 24);
|
|
90
|
+
const receiptPath = (home, key) =>
|
|
91
|
+
join(home, ".oats", `upgrade-receipt.${key}.json`);
|
|
92
|
+
const writeJson = (p, v) =>
|
|
93
|
+
writeFileAtomic(p, JSON.stringify(v, null, 2) + "\n", { mode: 0o600 });
|
|
94
|
+
function fail(code, message, details) {
|
|
95
|
+
return Object.assign(oatsError(code, message), { details });
|
|
96
|
+
}
|
|
97
|
+
function realDir(path) {
|
|
98
|
+
if (!lstatSync(path).isDirectory())
|
|
99
|
+
throw fail(
|
|
100
|
+
"E_UPGRADE_INTEGRITY",
|
|
101
|
+
`${path} is not a real directory; respawn the instance`,
|
|
102
|
+
);
|
|
103
|
+
}
|
|
104
|
+
function safeHomePaths(home) {
|
|
105
|
+
realDir(home);
|
|
106
|
+
for (const p of [".oats", ".oats/modules", ".agents", ".agents/skills"])
|
|
107
|
+
realDir(join(home, p));
|
|
108
|
+
for (const p of ["instance.json", "AGENTS.md"])
|
|
109
|
+
if (!lstatSync(join(home, p)).isFile())
|
|
110
|
+
throw fail(
|
|
111
|
+
"E_UPGRADE_INTEGRITY",
|
|
112
|
+
`${p} is not a regular file; respawn the instance`,
|
|
113
|
+
);
|
|
114
|
+
const previous = join(home, ".oats/previous");
|
|
115
|
+
if (existsSync(previous)) realDir(previous);
|
|
116
|
+
}
|
|
117
|
+
function target(ctx, root, name, opts) {
|
|
118
|
+
const found = resolveInstance(ctx, root, name, opts);
|
|
119
|
+
const meta = identifiedHomeRecord(found.home).meta;
|
|
120
|
+
if (!object(meta?.modules) || !meta.workspace?.soul?.commit)
|
|
121
|
+
throw fail(
|
|
122
|
+
"E_UNSUPPORTED_MODE",
|
|
123
|
+
`${name} has no recorded workspace modules and soul commit; respawn the instance`,
|
|
124
|
+
);
|
|
125
|
+
safeHomePaths(found.home);
|
|
126
|
+
return { ...found, meta };
|
|
127
|
+
}
|
|
128
|
+
function stopped(home, name, opts, absentMeta) {
|
|
129
|
+
let session;
|
|
130
|
+
try {
|
|
131
|
+
session = inspectInstanceSession(home, { io: opts.io, absentMeta });
|
|
132
|
+
} catch {
|
|
133
|
+
/* unreadable is not stopped */
|
|
134
|
+
}
|
|
135
|
+
if (session?.running !== false)
|
|
136
|
+
throw fail(
|
|
137
|
+
"E_SESSION_RUNNING",
|
|
138
|
+
`${name}'s session is running or cannot be read; run oats instance stop ${name}, then upgrade, then oats session start --home ${home}`,
|
|
139
|
+
);
|
|
140
|
+
}
|
|
141
|
+
function unclaimed(home, name, own = false) {
|
|
142
|
+
if (existsSync(retirePendingMarkerPath(home)))
|
|
143
|
+
throw fail(
|
|
144
|
+
"E_INSTANCE_RETIRING",
|
|
145
|
+
`${name} is being retired; no modules were upgraded`,
|
|
146
|
+
);
|
|
147
|
+
if (!own) {
|
|
148
|
+
const held = homeClaimHolder(home);
|
|
149
|
+
if (held && held.state !== "gone")
|
|
150
|
+
throw lifecycleClaimRefusals("upgrade", name, home, held.lock).busy(
|
|
151
|
+
held.holder,
|
|
152
|
+
held.state === "unknown" ? held.reason : null,
|
|
153
|
+
);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
function hookCommand(manifest) {
|
|
157
|
+
const h = manifest.hooks?.upgrade;
|
|
158
|
+
return typeof h === "string" ? h : h?.command;
|
|
159
|
+
}
|
|
160
|
+
function runHook(phase, { home, meta, module, dir, to, root }) {
|
|
161
|
+
const cap = toCapabilityRows(
|
|
162
|
+
{
|
|
163
|
+
modules: [module],
|
|
164
|
+
payloads: meta.providers,
|
|
165
|
+
payloadOrigins: {
|
|
166
|
+
[module.name]:
|
|
167
|
+
meta.capabilityRuntime?.find((c) => c.id === module.name)
|
|
168
|
+
?.settingsOrigins ?? {},
|
|
169
|
+
},
|
|
170
|
+
},
|
|
171
|
+
home,
|
|
172
|
+
{ moduleDirs: { [module.name]: dir } },
|
|
173
|
+
)[0];
|
|
174
|
+
cap.dir = dir;
|
|
175
|
+
cap.hooks = materializedHookCommands(
|
|
176
|
+
{ ...cap, hooks: { upgrade: hookCommand(module.manifest) } },
|
|
177
|
+
home,
|
|
178
|
+
);
|
|
179
|
+
const env = lifecycleHookEnv("upgrade", cap, {
|
|
180
|
+
home,
|
|
181
|
+
instance: meta.instance,
|
|
182
|
+
agentName: meta.agent,
|
|
183
|
+
soulDir: meta.soulDir,
|
|
184
|
+
contextDir: meta.repo || dirname(root),
|
|
185
|
+
workspaceDir: dirname(root),
|
|
186
|
+
rootDir: root,
|
|
187
|
+
resolved: resolvedFromHome(home, meta),
|
|
188
|
+
priorMeta: meta.capabilityMeta || {},
|
|
189
|
+
extraEnv: {
|
|
190
|
+
OATS_UPGRADE_PHASE: phase,
|
|
191
|
+
OATS_UPGRADE_MODULE_DIR: join(home, ".oats/modules", module.name),
|
|
192
|
+
OATS_UPGRADE_FROM: JSON.stringify({
|
|
193
|
+
from: meta.modules[module.name].from,
|
|
194
|
+
commit: meta.modules[module.name].commit,
|
|
195
|
+
digest: meta.modules[module.name].digest,
|
|
196
|
+
}),
|
|
197
|
+
OATS_UPGRADE_TO: JSON.stringify(to),
|
|
198
|
+
},
|
|
199
|
+
});
|
|
200
|
+
let answer,
|
|
201
|
+
observedExitZero = false;
|
|
202
|
+
try {
|
|
203
|
+
const output = execSync(cap.hooks.upgrade, {
|
|
204
|
+
cwd: home,
|
|
205
|
+
env,
|
|
206
|
+
encoding: "utf8",
|
|
207
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
208
|
+
timeout: 120000,
|
|
209
|
+
maxBuffer: 1024 * 1024,
|
|
210
|
+
});
|
|
211
|
+
observedExitZero = true;
|
|
212
|
+
answer = JSON.parse(
|
|
213
|
+
output.trim().split("\n").filter(Boolean).at(-1) || "null",
|
|
214
|
+
);
|
|
215
|
+
} catch (cause) {
|
|
216
|
+
let reported;
|
|
217
|
+
try {
|
|
218
|
+
const output = JSON.parse(String(cause.stdout ?? "").trim().split("\n").filter(Boolean).at(-1) || "null");
|
|
219
|
+
if (typeof output?.warning === "string") reported = output.warning.trim();
|
|
220
|
+
} catch { /* stderr remains useful when the provider did not report JSON */ }
|
|
221
|
+
const diagnosis = String(reported || cause.stderr || cause.message || cause).trim().slice(0, 2048);
|
|
222
|
+
throw Object.assign(
|
|
223
|
+
fail(
|
|
224
|
+
"E_UPGRADE_REFUSED",
|
|
225
|
+
`${module.name} upgrade hook reported failure in ${phase}${diagnosis ? `: ${diagnosis}` : ""}; host effects are the provider's responsibility (a failed apply must compensate its own effects); respawn if it cannot adopt`,
|
|
226
|
+
{ capability: module.name, phase },
|
|
227
|
+
),
|
|
228
|
+
{
|
|
229
|
+
hookRefused:
|
|
230
|
+
!observedExitZero &&
|
|
231
|
+
Number.isInteger(cause.status) &&
|
|
232
|
+
cause.status > 0 &&
|
|
233
|
+
!cause.signal,
|
|
234
|
+
},
|
|
235
|
+
);
|
|
236
|
+
}
|
|
237
|
+
if (
|
|
238
|
+
!object(answer) ||
|
|
239
|
+
(phase === "plan"
|
|
240
|
+
? typeof answer.adopt !== "boolean"
|
|
241
|
+
: !object(answer.meta))
|
|
242
|
+
)
|
|
243
|
+
throw fail(
|
|
244
|
+
"E_UPGRADE_REFUSED",
|
|
245
|
+
`${module.name} upgrade hook returned an invalid ${phase} answer; expected ${phase === "plan" ? "{adopt: boolean}" : "{meta}"}; respawn if it cannot adopt`,
|
|
246
|
+
{ capability: module.name, phase },
|
|
247
|
+
);
|
|
248
|
+
return answer;
|
|
249
|
+
}
|
|
250
|
+
function adoption(home, meta, module, dir, to, root, undo, oldManifest) {
|
|
251
|
+
if (!hookCommand(module.manifest)) {
|
|
252
|
+
if (
|
|
253
|
+
undo ||
|
|
254
|
+
Object.hasOwn(meta.capabilityMeta || {}, module.name) ||
|
|
255
|
+
module.manifest.hooks?.spawn ||
|
|
256
|
+
module.manifest.hooks?.launch ||
|
|
257
|
+
oldManifest.hooks?.spawn ||
|
|
258
|
+
oldManifest.hooks?.launch
|
|
259
|
+
)
|
|
260
|
+
return {
|
|
261
|
+
decision: "refuse",
|
|
262
|
+
reason: `${module.name} does not declare an upgrade hook; respawn the instance to change it`,
|
|
263
|
+
};
|
|
264
|
+
return {
|
|
265
|
+
decision: "adopt",
|
|
266
|
+
reason: "skills/inject only; no provider state",
|
|
267
|
+
};
|
|
268
|
+
}
|
|
269
|
+
const answer = runHook("plan", { home, meta, module, dir, to, root });
|
|
270
|
+
return answer.adopt
|
|
271
|
+
? { decision: "adopt", reason: null }
|
|
272
|
+
: {
|
|
273
|
+
decision: "refuse",
|
|
274
|
+
reason: answer.reason || "provider refused adoption",
|
|
275
|
+
...(answer.remedy ? { remedy: answer.remedy } : {}),
|
|
276
|
+
};
|
|
277
|
+
}
|
|
278
|
+
function skillDiff(oldDir, newDir, name, oldManifest, newManifest) {
|
|
279
|
+
const rows = (manifest, dir) =>
|
|
280
|
+
new Map(
|
|
281
|
+
moduleSkills({}, { name, manifest }, dir).map((s) => [
|
|
282
|
+
s.name,
|
|
283
|
+
remote.contentDigest(join(dir, s.path)),
|
|
284
|
+
]),
|
|
285
|
+
);
|
|
286
|
+
const a = rows(oldManifest, oldDir),
|
|
287
|
+
b = rows(newManifest, newDir);
|
|
288
|
+
return {
|
|
289
|
+
added: [...b.keys()].filter((k) => !a.has(k)).sort(),
|
|
290
|
+
removed: [...a.keys()].filter((k) => !b.has(k)).sort(),
|
|
291
|
+
changed: [...b.keys()]
|
|
292
|
+
.filter((k) => a.has(k) && a.get(k) !== b.get(k))
|
|
293
|
+
.sort(),
|
|
294
|
+
};
|
|
295
|
+
}
|
|
296
|
+
function injectBytes(manifest, dir) {
|
|
297
|
+
const paths = typeof manifest.inject === "string" ? [manifest.inject] : [];
|
|
298
|
+
return paths.map((p) => {
|
|
299
|
+
const abs = resolve(dir, p),
|
|
300
|
+
rel = relative(dir, abs);
|
|
301
|
+
if (rel === ".." || rel.startsWith(`..${sep}`))
|
|
302
|
+
throw fail("E_UPGRADE_INTEGRITY", `inject path escapes ${dir}`);
|
|
303
|
+
return readFileSync(abs, "utf8");
|
|
304
|
+
});
|
|
305
|
+
}
|
|
306
|
+
function verifyPrevious(home, record, name) {
|
|
307
|
+
try {
|
|
308
|
+
if (!record || !/^[a-f0-9]{24}$/.test(record.receipt))
|
|
309
|
+
throw fail(
|
|
310
|
+
"E_UPGRADE_UNDO",
|
|
311
|
+
`${name} has no latest verified previous state; respawn the instance`,
|
|
312
|
+
);
|
|
313
|
+
const base = join(home, ".oats/previous", record.receipt);
|
|
314
|
+
realDir(base);
|
|
315
|
+
realDir(join(base, "modules"));
|
|
316
|
+
const dir = join(base, "modules", name);
|
|
317
|
+
realDir(dir);
|
|
318
|
+
if (
|
|
319
|
+
remote.contentDigest(dir, {
|
|
320
|
+
allowSymlinks: remote.OATS_ALIAS_SYMLINK,
|
|
321
|
+
}) !== record.digest
|
|
322
|
+
)
|
|
323
|
+
throw fail(
|
|
324
|
+
"E_UPGRADE_UNDO",
|
|
325
|
+
`${name}'s previous copy no longer verifies; respawn the instance`,
|
|
326
|
+
);
|
|
327
|
+
const receipt = readUpgradeReceipts(home)
|
|
328
|
+
.map((row) => row.receipt)
|
|
329
|
+
.find((r) => r.receipt === record.receipt && r.status === "complete");
|
|
330
|
+
for (const file of ["instance.json", "AGENTS.md"])
|
|
331
|
+
if (
|
|
332
|
+
!receipt?.previousDigests?.[file] ||
|
|
333
|
+
fileDigest(join(base, file)) !== receipt.previousDigests[file]
|
|
334
|
+
)
|
|
335
|
+
throw fail(
|
|
336
|
+
"E_UPGRADE_UNDO",
|
|
337
|
+
`${name}'s previous ${file} no longer verifies; respawn the instance`,
|
|
338
|
+
);
|
|
339
|
+
const meta = readJson(join(base, "instance.json"));
|
|
340
|
+
const { previous, ...saved } = meta.modules?.[name] || {};
|
|
341
|
+
const { receipt: previousReceipt, ...expected } = record;
|
|
342
|
+
if (hash(saved) !== hash(expected))
|
|
343
|
+
throw fail(
|
|
344
|
+
"E_UPGRADE_UNDO",
|
|
345
|
+
`${name}'s previous record no longer verifies; respawn the instance`,
|
|
346
|
+
);
|
|
347
|
+
return { dir, record: meta.modules[name], meta };
|
|
348
|
+
} catch (error) {
|
|
349
|
+
if (error.code === "E_UPGRADE_UNDO") throw error;
|
|
350
|
+
throw fail(
|
|
351
|
+
"E_UPGRADE_UNDO",
|
|
352
|
+
`${name}'s previous copy is missing or cannot be verified; respawn the instance`,
|
|
353
|
+
);
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
function cleanupPending(home) {
|
|
357
|
+
for (const { receipt } of readUpgradeReceipts(home)) {
|
|
358
|
+
if (
|
|
359
|
+
receipt.action === "upgrade" &&
|
|
360
|
+
receipt.status === "complete" &&
|
|
361
|
+
receipt.steps?.cleaned === false
|
|
362
|
+
)
|
|
363
|
+
throw fail(
|
|
364
|
+
"E_UPGRADE_CLEANUP",
|
|
365
|
+
`the previous upgrade of ${receipt.instance} is committed but staging cleanup remains; retry oats instance upgrade ${receipt.instance}${receipt.undo ? " --undo" : ""} --plan-revision ${receipt.planRevision} --idempotency-key ${receipt.idempotencyKey} before planning another move`,
|
|
366
|
+
);
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
function finishCleanup(home, path, receipt) {
|
|
370
|
+
try {
|
|
371
|
+
if (!receipt.steps.event) {
|
|
372
|
+
receipt.step = "event";
|
|
373
|
+
writeJson(path, receipt);
|
|
374
|
+
// A crash after append but before the receipt must not duplicate the event.
|
|
375
|
+
if (
|
|
376
|
+
!readEvents(home, { limit: 2000 }).events.some(
|
|
377
|
+
(e) =>
|
|
378
|
+
e.kind === "modules-upgraded" &&
|
|
379
|
+
e.data?.receipt === receipt.receipt,
|
|
380
|
+
)
|
|
381
|
+
) {
|
|
382
|
+
const event = appendEvent(home, {
|
|
383
|
+
kind: "modules-upgraded",
|
|
384
|
+
data: {
|
|
385
|
+
receipt: receipt.receipt,
|
|
386
|
+
modules: receipt.modules.map((m) => ({
|
|
387
|
+
capability: m.capability,
|
|
388
|
+
from: m.from,
|
|
389
|
+
to: m.to,
|
|
390
|
+
})),
|
|
391
|
+
},
|
|
392
|
+
});
|
|
393
|
+
if (!event.ok)
|
|
394
|
+
throw fail(
|
|
395
|
+
"E_UPGRADE_EVENT",
|
|
396
|
+
`could not record modules-upgraded: ${event.reason}`,
|
|
397
|
+
);
|
|
398
|
+
}
|
|
399
|
+
receipt.steps.event = true;
|
|
400
|
+
writeJson(path, receipt);
|
|
401
|
+
}
|
|
402
|
+
rmSync(join(home, ".oats", `.staging-upgrade-${receipt.receipt}`), {
|
|
403
|
+
recursive: true,
|
|
404
|
+
force: true,
|
|
405
|
+
});
|
|
406
|
+
const complete = {
|
|
407
|
+
...receipt,
|
|
408
|
+
steps: { ...receipt.steps, cleaned: true },
|
|
409
|
+
step: "complete",
|
|
410
|
+
};
|
|
411
|
+
writeJson(path, complete);
|
|
412
|
+
return complete;
|
|
413
|
+
} catch (error) {
|
|
414
|
+
throw fail(
|
|
415
|
+
"E_UPGRADE_CLEANUP",
|
|
416
|
+
`${receipt.instance} upgrade is committed; staging cleanup remains (${error.code || "unavailable"}). Retry oats instance upgrade ${receipt.instance}${receipt.undo ? " --undo" : ""} --plan-revision ${receipt.planRevision} --idempotency-key ${receipt.idempotencyKey}; no hooks or copies will run`,
|
|
417
|
+
{ receipt: receipt.receipt, step: "cleanup" },
|
|
418
|
+
);
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
/** Build the exact frozen composition, leaving unchanged modules at their recorded bytes. */
|
|
422
|
+
async function prepare(ctx, root, name, opts, { own = false } = {}) {
|
|
423
|
+
const { home, meta } = target(ctx, root, name, opts);
|
|
424
|
+
unclaimed(home, name, own);
|
|
425
|
+
assertNoPartialUpgrade(home);
|
|
426
|
+
cleanupPending(home);
|
|
427
|
+
const previous = join(home, ".oats/previous");
|
|
428
|
+
if (existsSync(previous)) for (const entry of readdirSync(previous)) {
|
|
429
|
+
if (!/^[a-f0-9]{24}$/.test(entry)) throw fail("E_UPGRADE_INTEGRITY", `unexpected previous-state entry ${entry}; inspect it before retrying`);
|
|
430
|
+
}
|
|
431
|
+
stopped(home, name, opts);
|
|
432
|
+
const homeChangedSinceSpawn = retirementHomeChanged(home, { transientHomePaths: own ? [".oats-start.lock"] : [] });
|
|
433
|
+
const deployment = dirname(root),
|
|
434
|
+
lock = readLock(deployment);
|
|
435
|
+
const scratch = mkdtempSync(join(tmpdir(), "oats-upgrade-plan-"));
|
|
436
|
+
try {
|
|
437
|
+
const modules = [],
|
|
438
|
+
existingModules = {},
|
|
439
|
+
hookTargets = {},
|
|
440
|
+
moving = [],
|
|
441
|
+
kept = [],
|
|
442
|
+
packages = new Map(),
|
|
443
|
+
restored = {};
|
|
444
|
+
const previousReceipts = [
|
|
445
|
+
...new Set(
|
|
446
|
+
Object.values(meta.modules)
|
|
447
|
+
.map((m) => m.previous?.receipt)
|
|
448
|
+
.filter(
|
|
449
|
+
(id) =>
|
|
450
|
+
typeof id === "string" &&
|
|
451
|
+
/^[a-f0-9]{24}$/.test(id) &&
|
|
452
|
+
existsSync(join(home, ".oats/previous", id)),
|
|
453
|
+
),
|
|
454
|
+
),
|
|
455
|
+
];
|
|
456
|
+
if (opts.undo && previousReceipts.length > 1)
|
|
457
|
+
throw fail(
|
|
458
|
+
"E_UPGRADE_UNDO",
|
|
459
|
+
"more than one previous move remains; finish the pending upgrade or respawn",
|
|
460
|
+
);
|
|
461
|
+
const latestPrevious = previousReceipts[0];
|
|
462
|
+
const ids = [
|
|
463
|
+
...new Set([
|
|
464
|
+
...(meta.capabilityRuntime || []).map((c) => c.id),
|
|
465
|
+
...Object.keys(meta.modules),
|
|
466
|
+
]),
|
|
467
|
+
];
|
|
468
|
+
for (const id of ids) {
|
|
469
|
+
if (!CAP.test(id) || !Object.hasOwn(meta.modules, id))
|
|
470
|
+
throw fail(
|
|
471
|
+
"E_UPGRADE_INTEGRITY",
|
|
472
|
+
`invalid module ${id}; respawn the instance`,
|
|
473
|
+
);
|
|
474
|
+
const recorded = meta.modules[id],
|
|
475
|
+
oldDir = join(home, ".oats/modules", id);
|
|
476
|
+
realDir(oldDir);
|
|
477
|
+
const oldManifest = readJson(join(oldDir, "oats.json"));
|
|
478
|
+
const base = {
|
|
479
|
+
name: id,
|
|
480
|
+
from: recorded.from,
|
|
481
|
+
digest: recorded.digest,
|
|
482
|
+
manifest: oldManifest,
|
|
483
|
+
};
|
|
484
|
+
let next = null,
|
|
485
|
+
dir = null,
|
|
486
|
+
to = null;
|
|
487
|
+
const entry = lock.packages[recorded.from?.package];
|
|
488
|
+
if (
|
|
489
|
+
recorded.from?.kind === "package" &&
|
|
490
|
+
opts.undo &&
|
|
491
|
+
recorded.previous &&
|
|
492
|
+
(!latestPrevious || recorded.previous.receipt === latestPrevious)
|
|
493
|
+
) {
|
|
494
|
+
const prev = verifyPrevious(home, recorded.previous, id);
|
|
495
|
+
dir = prev.dir;
|
|
496
|
+
restored[id] = {
|
|
497
|
+
contribution: prev.meta.launch?.hooks?.contributions?.find(
|
|
498
|
+
(c) => c.capability === id,
|
|
499
|
+
),
|
|
500
|
+
env: prev.meta.launch?.hooks?.env || {},
|
|
501
|
+
};
|
|
502
|
+
next = {
|
|
503
|
+
name: id,
|
|
504
|
+
from: prev.record.from,
|
|
505
|
+
digest: prev.record.digest,
|
|
506
|
+
manifest: readJson(join(dir, "oats.json")),
|
|
507
|
+
};
|
|
508
|
+
to = {
|
|
509
|
+
...prev.record.from,
|
|
510
|
+
commit: prev.record.commit,
|
|
511
|
+
digest: prev.record.digest,
|
|
512
|
+
};
|
|
513
|
+
} else if (
|
|
514
|
+
recorded.from?.kind === "package" &&
|
|
515
|
+
!opts.undo &&
|
|
516
|
+
entry &&
|
|
517
|
+
entry.capabilities.includes(id) &&
|
|
518
|
+
entry.commit !== recorded.commit
|
|
519
|
+
) {
|
|
520
|
+
const pkgid = recorded.from.package;
|
|
521
|
+
if (!packages.has(pkgid)) {
|
|
522
|
+
const found = await lockedPackageCapabilities(pkgid, entry, {
|
|
523
|
+
catalog: opts.catalog ?? officialPackageCatalog(),
|
|
524
|
+
remoteOptions: opts.remoteOptions,
|
|
525
|
+
});
|
|
526
|
+
const tree = join(scratch, `package-${packages.size}`);
|
|
527
|
+
await remote.fetchRemoteTree(
|
|
528
|
+
found.ref,
|
|
529
|
+
entry.commit,
|
|
530
|
+
entry.path,
|
|
531
|
+
tree,
|
|
532
|
+
{ ...opts.remoteOptions, allowSymlinks: remote.OATS_ALIAS_SYMLINK },
|
|
533
|
+
);
|
|
534
|
+
const digest = remote.contentDigest(tree, {
|
|
535
|
+
allowSymlinks: remote.OATS_ALIAS_SYMLINK,
|
|
536
|
+
});
|
|
537
|
+
if (digest !== entry.integrity)
|
|
538
|
+
throw fail(
|
|
539
|
+
"E_PACKAGE_INTEGRITY",
|
|
540
|
+
`package ${pkgid} does not match locked integrity`,
|
|
541
|
+
{ package: pkgid, expected: entry.integrity, actual: digest },
|
|
542
|
+
);
|
|
543
|
+
packages.set(pkgid, { ...found, tree });
|
|
544
|
+
}
|
|
545
|
+
const pkg = packages.get(pkgid),
|
|
546
|
+
cap = lockedCapability(id, pkgid, entry, pkg.capabilities);
|
|
547
|
+
next = {
|
|
548
|
+
name: id,
|
|
549
|
+
from: {
|
|
550
|
+
kind: "package",
|
|
551
|
+
package: pkgid,
|
|
552
|
+
version: entry.version,
|
|
553
|
+
commit: entry.commit,
|
|
554
|
+
integrity: entry.integrity,
|
|
555
|
+
repoKey: remote.parseRepoRef(pkg.ref).key,
|
|
556
|
+
},
|
|
557
|
+
dir: cap.dir,
|
|
558
|
+
manifest: cap.manifest,
|
|
559
|
+
};
|
|
560
|
+
dir = join(pkg.tree, relative(entry.path, cap.dir));
|
|
561
|
+
to = clone(entry);
|
|
562
|
+
}
|
|
563
|
+
if (!next) {
|
|
564
|
+
modules.push(base);
|
|
565
|
+
existingModules[id] = oldDir;
|
|
566
|
+
kept.push({
|
|
567
|
+
capability: id,
|
|
568
|
+
reason:
|
|
569
|
+
recorded.from?.kind === "member"
|
|
570
|
+
? "member module"
|
|
571
|
+
: !entry
|
|
572
|
+
? "package no longer locked"
|
|
573
|
+
: opts.undo
|
|
574
|
+
? "not part of the latest previous move"
|
|
575
|
+
: !entry.capabilities.includes(id)
|
|
576
|
+
? "package no longer provides capability"
|
|
577
|
+
: "current",
|
|
578
|
+
});
|
|
579
|
+
continue;
|
|
580
|
+
}
|
|
581
|
+
const compatibility = kernelCompatibility(next.manifest);
|
|
582
|
+
if (compatibility && compatibility.ok === false)
|
|
583
|
+
throw fail(
|
|
584
|
+
"E_UPGRADE_REFUSED",
|
|
585
|
+
`${id} is incompatible with this kernel; upgrade the kernel before its modules`,
|
|
586
|
+
);
|
|
587
|
+
next.digest = remote.contentDigest(dir, {
|
|
588
|
+
allowSymlinks: remote.OATS_ALIAS_SYMLINK,
|
|
589
|
+
});
|
|
590
|
+
modules.push(next);
|
|
591
|
+
existingModules[id] = dir;
|
|
592
|
+
const provider = adoption(home, meta, next, dir, to, root, !!opts.undo, oldManifest);
|
|
593
|
+
hookTargets[id] = to;
|
|
594
|
+
moving.push({
|
|
595
|
+
capability: id,
|
|
596
|
+
from: {
|
|
597
|
+
version: recorded.from.version,
|
|
598
|
+
commit: recorded.commit,
|
|
599
|
+
digest: recorded.digest,
|
|
600
|
+
},
|
|
601
|
+
to: {
|
|
602
|
+
version: next.from.version,
|
|
603
|
+
commit: next.from.commit,
|
|
604
|
+
integrity: next.from.integrity,
|
|
605
|
+
},
|
|
606
|
+
skills: skillDiff(oldDir, dir, id, oldManifest, next.manifest),
|
|
607
|
+
inject:
|
|
608
|
+
JSON.stringify(injectBytes(oldManifest, oldDir)) !==
|
|
609
|
+
JSON.stringify(injectBytes(next.manifest, dir)),
|
|
610
|
+
hooks:
|
|
611
|
+
JSON.stringify(oldManifest.hooks || {}) !==
|
|
612
|
+
JSON.stringify(next.manifest.hooks || {}),
|
|
613
|
+
provider,
|
|
614
|
+
});
|
|
615
|
+
}
|
|
616
|
+
if (opts.undo && !moving.length)
|
|
617
|
+
throw fail(
|
|
618
|
+
"E_UPGRADE_UNDO",
|
|
619
|
+
`${name} has no previous move to undo; respawn the instance`,
|
|
620
|
+
);
|
|
621
|
+
const soul = meta.workspace.soul,
|
|
622
|
+
path = soul.package?.path || memberSoulPath(meta.agent);
|
|
623
|
+
let body;
|
|
624
|
+
try {
|
|
625
|
+
body = (
|
|
626
|
+
await remote.readRemoteFile(
|
|
627
|
+
refForKey(soul.repoKey),
|
|
628
|
+
soul.commit,
|
|
629
|
+
`${path}/AGENTS.md`,
|
|
630
|
+
opts.remoteOptions,
|
|
631
|
+
)
|
|
632
|
+
).bytes.toString("utf8");
|
|
633
|
+
} catch {
|
|
634
|
+
throw fail(
|
|
635
|
+
"E_UPGRADE_SOUL",
|
|
636
|
+
`${name}'s soul body cannot be read at recorded commit ${soul.commit}; restore access to that commit or respawn`,
|
|
637
|
+
);
|
|
638
|
+
}
|
|
639
|
+
const resolution = {
|
|
640
|
+
resolutionApi: 1,
|
|
641
|
+
modules,
|
|
642
|
+
payloads: meta.providers || {},
|
|
643
|
+
payloadOrigins: Object.fromEntries(
|
|
644
|
+
(meta.capabilityRuntime || []).map((c) => [
|
|
645
|
+
c.id,
|
|
646
|
+
c.settingsOrigins || {},
|
|
647
|
+
]),
|
|
648
|
+
),
|
|
649
|
+
};
|
|
650
|
+
resolution.revision = revisionOf({
|
|
651
|
+
modules: modules.map((m) => ({ name: m.name, from: m.from })),
|
|
652
|
+
soul,
|
|
653
|
+
});
|
|
654
|
+
const composition = composeInstanceAgentsMd(
|
|
655
|
+
meta.soulDir,
|
|
656
|
+
meta.repo,
|
|
657
|
+
meta.agent,
|
|
658
|
+
meta.work,
|
|
659
|
+
meta.kind,
|
|
660
|
+
{ resolution },
|
|
661
|
+
);
|
|
662
|
+
const blocks = composition.blocks.filter(
|
|
663
|
+
(b) => !b.source.startsWith("capability:"),
|
|
664
|
+
);
|
|
665
|
+
let memberDrift = [];
|
|
666
|
+
if (Object.values(meta.modules).some((m) => m.from.kind === "member")) {
|
|
667
|
+
const local = loadLocal(deployment).local;
|
|
668
|
+
const discovery = await discoverOrStandalone(local, {
|
|
669
|
+
deployment,
|
|
670
|
+
lock,
|
|
671
|
+
remoteOptions: opts.remoteOptions,
|
|
672
|
+
});
|
|
673
|
+
memberDrift = driftOf(meta, discovery, { lock }).filter(
|
|
674
|
+
(r) => r.from?.kind === "member" && r.status !== "current",
|
|
675
|
+
);
|
|
676
|
+
}
|
|
677
|
+
const facts = {
|
|
678
|
+
instance: meta.instance,
|
|
679
|
+
createdAt: meta.createdAt,
|
|
680
|
+
undo: !!opts.undo,
|
|
681
|
+
modules: meta.modules,
|
|
682
|
+
capabilityMeta: meta.capabilityMeta || {},
|
|
683
|
+
providers: meta.providers || {},
|
|
684
|
+
launch: meta.launch,
|
|
685
|
+
body,
|
|
686
|
+
blocks,
|
|
687
|
+
moving,
|
|
688
|
+
kept,
|
|
689
|
+
lock,
|
|
690
|
+
};
|
|
691
|
+
const plan = {
|
|
692
|
+
lifecycleApi: 1,
|
|
693
|
+
action: "upgrade",
|
|
694
|
+
instance: name,
|
|
695
|
+
home,
|
|
696
|
+
undo: !!opts.undo,
|
|
697
|
+
modules: moving,
|
|
698
|
+
kept,
|
|
699
|
+
memberDrift,
|
|
700
|
+
homeChangedSinceSpawn,
|
|
701
|
+
planRevision: hash(facts),
|
|
702
|
+
};
|
|
703
|
+
return {
|
|
704
|
+
plan,
|
|
705
|
+
home,
|
|
706
|
+
meta,
|
|
707
|
+
resolution,
|
|
708
|
+
existingModules,
|
|
709
|
+
hookTargets,
|
|
710
|
+
soulAgentsMd: body,
|
|
711
|
+
blocks,
|
|
712
|
+
lock,
|
|
713
|
+
scratch,
|
|
714
|
+
restored,
|
|
715
|
+
};
|
|
716
|
+
} catch (e) {
|
|
717
|
+
rmSync(scratch, { recursive: true, force: true });
|
|
718
|
+
throw e;
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
export async function planUpgrade(ctx, root, name, opts = {}) {
|
|
722
|
+
const p = await prepare(ctx, root, name, opts);
|
|
723
|
+
try {
|
|
724
|
+
return p.plan;
|
|
725
|
+
} finally {
|
|
726
|
+
rmSync(p.scratch, { recursive: true, force: true });
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
function derivedMetadata(p, tx, receipt) {
|
|
731
|
+
const { meta, resolution, home } = p,
|
|
732
|
+
outcome = tx.outcome;
|
|
733
|
+
const moving = new Set(receipt.modules.map((m) => m.capability));
|
|
734
|
+
const rows = toCapabilityRows(resolution, home, {
|
|
735
|
+
moduleDirs: Object.fromEntries(
|
|
736
|
+
resolution.modules.map((m) => [
|
|
737
|
+
m.name,
|
|
738
|
+
join(tx.staging, "modules", m.name),
|
|
739
|
+
]),
|
|
740
|
+
),
|
|
741
|
+
});
|
|
742
|
+
for (const row of rows) {
|
|
743
|
+
const stagedDir = join(tx.staging, "modules", row.id);
|
|
744
|
+
row.dir = stagedDir;
|
|
745
|
+
row.hooks = Object.fromEntries(
|
|
746
|
+
Object.entries(materializedHookCommands(row, home)).map(([e, cmd]) => [
|
|
747
|
+
e,
|
|
748
|
+
cmd.split(shq(stagedDir).slice(1, -1)).join(shq(join(home, ".oats/modules", row.id)).slice(1, -1)),
|
|
749
|
+
]),
|
|
750
|
+
);
|
|
751
|
+
row.skills = outcome.skills
|
|
752
|
+
.filter((s) => s.module === row.id)
|
|
753
|
+
.map((s) => s.path);
|
|
754
|
+
row.inject = row.manifest.inject
|
|
755
|
+
? join(home, ".oats/modules", row.id, row.manifest.inject)
|
|
756
|
+
: undefined;
|
|
757
|
+
}
|
|
758
|
+
const modules = clone(outcome.instanceJson.modules);
|
|
759
|
+
for (const [id, old] of Object.entries(meta.modules)) {
|
|
760
|
+
if (!moving.has(id)) modules[id] = clone(old);
|
|
761
|
+
else {
|
|
762
|
+
const { previous, ...from } = old;
|
|
763
|
+
modules[id].previous = { ...from, receipt: receipt.receipt };
|
|
764
|
+
}
|
|
765
|
+
}
|
|
766
|
+
const soulSkills = (meta.skills || []).filter((s) => s.source === "soul");
|
|
767
|
+
for (const skill of soulSkills) {
|
|
768
|
+
if (!/^(?!\.+$)[^/\\\0]+$/.test(skill.name))
|
|
769
|
+
throw fail("E_UPGRADE_INTEGRITY", "invalid recorded soul skill name");
|
|
770
|
+
if (
|
|
771
|
+
outcome.skills.some(
|
|
772
|
+
(s) => s.name.toLowerCase() === skill.name.toLowerCase(),
|
|
773
|
+
)
|
|
774
|
+
)
|
|
775
|
+
throw fail(
|
|
776
|
+
"E_SKILL_DUPLICATE",
|
|
777
|
+
`soul skill ${skill.name} collides with a module skill`,
|
|
778
|
+
);
|
|
779
|
+
copyTreeSafe(
|
|
780
|
+
join(home, ".agents/skills", skill.name),
|
|
781
|
+
join(tx.staging, "skills", skill.name),
|
|
782
|
+
);
|
|
783
|
+
}
|
|
784
|
+
const skills = [
|
|
785
|
+
...soulSkills,
|
|
786
|
+
...outcome.skills.map((s) => ({
|
|
787
|
+
name: s.name,
|
|
788
|
+
source: `module:${s.module}`,
|
|
789
|
+
})),
|
|
790
|
+
];
|
|
791
|
+
const instructions = outcome.blocks.map(({ source, file }) => ({
|
|
792
|
+
source,
|
|
793
|
+
file,
|
|
794
|
+
}));
|
|
795
|
+
const capabilities = rows.map((cap) => ({
|
|
796
|
+
id: cap.id,
|
|
797
|
+
layer: cap.layer,
|
|
798
|
+
command: cap.command,
|
|
799
|
+
origin: cap.origin,
|
|
800
|
+
level: cap.level,
|
|
801
|
+
settings: cap.settings,
|
|
802
|
+
settingsOrigins: cap.settingsOrigins,
|
|
803
|
+
provenance: cap.provenance,
|
|
804
|
+
skills: cap.skills,
|
|
805
|
+
hooks: Object.keys(cap.hooks),
|
|
806
|
+
trusted: !!cap.trust?.trusted,
|
|
807
|
+
...(cap.environment.length ? { environment: cap.environment } : {}),
|
|
808
|
+
...(cap.environmentNamespaces.length
|
|
809
|
+
? { environmentNamespaces: cap.environmentNamespaces }
|
|
810
|
+
: {}),
|
|
811
|
+
}));
|
|
812
|
+
const capabilityRuntime = rows.map((cap) => ({
|
|
813
|
+
id: cap.id,
|
|
814
|
+
layer: cap.layer,
|
|
815
|
+
level: cap.level,
|
|
816
|
+
settings: cap.settings,
|
|
817
|
+
settingsOrigins: cap.settingsOrigins,
|
|
818
|
+
hooks: cap.hooks,
|
|
819
|
+
requiredHooks: cap.requiredHooks,
|
|
820
|
+
environment: cap.environment,
|
|
821
|
+
environmentNamespaces: cap.environmentNamespaces,
|
|
822
|
+
missingRequires: cap.missingRequires,
|
|
823
|
+
trust: cap.trust,
|
|
824
|
+
executable: cap.executable,
|
|
825
|
+
}));
|
|
826
|
+
const expected = [
|
|
827
|
+
...(meta.composition?.expected || [])
|
|
828
|
+
.filter((r) => r.source === "soul")
|
|
829
|
+
.map((r) => ({ ...r, path: r.resolved })),
|
|
830
|
+
...planInstanceResources({
|
|
831
|
+
resolved: {
|
|
832
|
+
capabilities: rows.map((row) => ({ ...row, planned: true })),
|
|
833
|
+
},
|
|
834
|
+
agent: { name: meta.agent },
|
|
835
|
+
contextDir: meta.repo,
|
|
836
|
+
composition: { blocks: p.blocks },
|
|
837
|
+
}),
|
|
838
|
+
];
|
|
839
|
+
for (const resource of expected) {
|
|
840
|
+
if (resource.deferred !== "materialize") continue;
|
|
841
|
+
const row = rows.find((r) => r.id === resource.module);
|
|
842
|
+
if (resource.type === "injection") resource.path = row.inject;
|
|
843
|
+
if (resource.type === "skill-tree") {
|
|
844
|
+
resource.path = join(home, ".agents/skills");
|
|
845
|
+
resource.entries = row.skills.map((path) => path.split(sep).at(-1));
|
|
846
|
+
}
|
|
847
|
+
}
|
|
848
|
+
for (const block of outcome.blocks.filter((b) =>
|
|
849
|
+
b.source.startsWith("capability:"),
|
|
850
|
+
))
|
|
851
|
+
expected.push({
|
|
852
|
+
type: "instruction-block",
|
|
853
|
+
source: block.source,
|
|
854
|
+
declared: block.file,
|
|
855
|
+
path: block.file,
|
|
856
|
+
materialized: true,
|
|
857
|
+
});
|
|
858
|
+
const composition = {
|
|
859
|
+
...meta.composition,
|
|
860
|
+
expected: expected.map((r) => ({
|
|
861
|
+
type: r.type,
|
|
862
|
+
source: r.source,
|
|
863
|
+
declared: r.declared,
|
|
864
|
+
resolved: r.path,
|
|
865
|
+
origin: r.origin,
|
|
866
|
+
level: r.level,
|
|
867
|
+
...(r.deferred ? { deferred: r.deferred } : {}),
|
|
868
|
+
})),
|
|
869
|
+
materialized: {
|
|
870
|
+
...meta.composition?.materialized,
|
|
871
|
+
skills: [
|
|
872
|
+
...(meta.composition?.materialized?.skills || []).filter(
|
|
873
|
+
(s) => s.source === "soul",
|
|
874
|
+
),
|
|
875
|
+
...outcome.skills.map((s) => ({
|
|
876
|
+
name: s.name,
|
|
877
|
+
source: `module:${s.module}`,
|
|
878
|
+
from: join(home, s.from),
|
|
879
|
+
})),
|
|
880
|
+
],
|
|
881
|
+
instructions,
|
|
882
|
+
},
|
|
883
|
+
};
|
|
884
|
+
let launch = meta.launch;
|
|
885
|
+
if (launch?.hooks) {
|
|
886
|
+
let contributions = clone(launch.hooks.contributions || []);
|
|
887
|
+
const env = { ...launch.hooks.env };
|
|
888
|
+
for (const row of rows.filter((r) => moving.has(r.id))) {
|
|
889
|
+
const existing = contributions.find((c) => c.capability === row.id);
|
|
890
|
+
// Undo restores the saved contribution as data; no launch hook runs here.
|
|
891
|
+
const restore = p.restored?.[row.id];
|
|
892
|
+
if (restore) {
|
|
893
|
+
for (const name of existing?.env || []) delete env[name];
|
|
894
|
+
contributions = contributions.filter((c) => c.capability !== row.id);
|
|
895
|
+
if (restore.contribution) {
|
|
896
|
+
contributions.push(clone(restore.contribution));
|
|
897
|
+
for (const name of restore.contribution.env || [])
|
|
898
|
+
env[name] = restore.env[name];
|
|
899
|
+
}
|
|
900
|
+
}
|
|
901
|
+
const contribution = contributions.find((c) => c.capability === row.id);
|
|
902
|
+
if (!row.hooks.launch) {
|
|
903
|
+
for (const name of contribution?.env || []) delete env[name];
|
|
904
|
+
contributions = contributions.filter((c) => c.capability !== row.id);
|
|
905
|
+
} else if (contribution) {
|
|
906
|
+
Object.assign(contribution, {
|
|
907
|
+
settings: row.settings,
|
|
908
|
+
settingsOrigins: row.settingsOrigins,
|
|
909
|
+
trust: {
|
|
910
|
+
trusted: !!row.trust?.trusted,
|
|
911
|
+
integrity: row.trust?.integrity || null,
|
|
912
|
+
},
|
|
913
|
+
});
|
|
914
|
+
}
|
|
915
|
+
}
|
|
916
|
+
const args = {},
|
|
917
|
+
owners = new Map();
|
|
918
|
+
for (const c of contributions) {
|
|
919
|
+
for (const name of c.env || []) {
|
|
920
|
+
if (owners.has(name) && owners.get(name) !== c.capability)
|
|
921
|
+
throw fail(
|
|
922
|
+
"E_UPGRADE_REFUSED",
|
|
923
|
+
`${name} would have two launch environment owners; respawn the instance`,
|
|
924
|
+
);
|
|
925
|
+
owners.set(name, c.capability);
|
|
926
|
+
}
|
|
927
|
+
for (const [harness, text] of Object.entries(c.launch || {}))
|
|
928
|
+
if (text)
|
|
929
|
+
args[harness] = `${args[harness] ? args[harness] + " " : ""}${text}`;
|
|
930
|
+
}
|
|
931
|
+
launch = {
|
|
932
|
+
...launch,
|
|
933
|
+
hooks: { ...launch.hooks, launch: args, env, contributions },
|
|
934
|
+
};
|
|
935
|
+
}
|
|
936
|
+
return {
|
|
937
|
+
...meta,
|
|
938
|
+
modules,
|
|
939
|
+
capabilities,
|
|
940
|
+
capabilityRuntime,
|
|
941
|
+
skills,
|
|
942
|
+
instructions,
|
|
943
|
+
composition,
|
|
944
|
+
launch,
|
|
945
|
+
resolutionRevision: resolution.revision,
|
|
946
|
+
};
|
|
947
|
+
}
|
|
948
|
+
function keepPrevious(home, receipt, meta) {
|
|
949
|
+
const root = join(home, ".oats/previous");
|
|
950
|
+
if (existsSync(root)) realDir(root);
|
|
951
|
+
else mkdirSync(root, { mode: 0o700 });
|
|
952
|
+
const dest = join(root, receipt.receipt);
|
|
953
|
+
mkdirSync(join(dest, "modules"), { recursive: true, mode: 0o700 });
|
|
954
|
+
for (const row of receipt.modules) {
|
|
955
|
+
const src = join(home, ".oats/modules", row.capability),
|
|
956
|
+
to = join(dest, "modules", row.capability);
|
|
957
|
+
copyTreeSafe(src, to);
|
|
958
|
+
const comparison = treeDisagreement(src, to);
|
|
959
|
+
if (
|
|
960
|
+
remote.contentDigest(to, { allowSymlinks: remote.OATS_ALIAS_SYMLINK }) !==
|
|
961
|
+
meta.modules[row.capability].digest ||
|
|
962
|
+
!comparison.complete ||
|
|
963
|
+
comparison.entries.length
|
|
964
|
+
)
|
|
965
|
+
throw fail(
|
|
966
|
+
"E_UPGRADE_INTEGRITY",
|
|
967
|
+
`previous copy of ${row.capability} does not verify`,
|
|
968
|
+
);
|
|
969
|
+
}
|
|
970
|
+
receipt.previousDigests = {};
|
|
971
|
+
for (const file of ["instance.json", "AGENTS.md"]) {
|
|
972
|
+
copyTreeSafe(join(home, file), join(dest, file));
|
|
973
|
+
receipt.previousDigests[file] = fileDigest(join(dest, file));
|
|
974
|
+
if (!readFileSync(join(home, file)).equals(readFileSync(join(dest, file))))
|
|
975
|
+
throw fail(
|
|
976
|
+
"E_UPGRADE_INTEGRITY",
|
|
977
|
+
`previous copy of ${file} does not verify`,
|
|
978
|
+
);
|
|
979
|
+
}
|
|
980
|
+
}
|
|
981
|
+
function partial(receipt, error) {
|
|
982
|
+
const pending = receipt.modules
|
|
983
|
+
.filter((m) => !receipt.steps.hooks.includes(m.capability))
|
|
984
|
+
.map((m) => m.capability);
|
|
985
|
+
return fail(
|
|
986
|
+
"E_UPGRADE_PARTIAL",
|
|
987
|
+
`${receipt.instance} upgrade is partial at ${receipt.step}${pending.length ? ` (pending modules: ${pending.join(", ")})` : ""}: ${error.message}. Retry oats instance upgrade ${receipt.instance}${receipt.undo ? " --undo" : ""} --plan-revision ${receipt.planRevision} --idempotency-key ${receipt.idempotencyKey}; if it cannot finish, respawn the instance`,
|
|
988
|
+
{
|
|
989
|
+
receipt: receipt.receipt,
|
|
990
|
+
step: receipt.step,
|
|
991
|
+
completed: receipt.steps,
|
|
992
|
+
pending,
|
|
993
|
+
},
|
|
994
|
+
);
|
|
995
|
+
}
|
|
996
|
+
function reclaimUpgradeMutex(home, name) {
|
|
997
|
+
const path = join(home, ".oats-start.lock");
|
|
998
|
+
let stat;
|
|
999
|
+
try {
|
|
1000
|
+
stat = lstatSync(path);
|
|
1001
|
+
} catch (error) {
|
|
1002
|
+
if (error.code === "ENOENT") return;
|
|
1003
|
+
throw error;
|
|
1004
|
+
}
|
|
1005
|
+
if (!stat.isFile())
|
|
1006
|
+
throw fail(
|
|
1007
|
+
"E_SESSION_RUNNING",
|
|
1008
|
+
`${name} has a start in progress; its directory mutex is never reclaimed by upgrade`,
|
|
1009
|
+
);
|
|
1010
|
+
rmSync(path);
|
|
1011
|
+
}
|
|
1012
|
+
function releaseUpgradeMutex(home, identity) {
|
|
1013
|
+
if (!identity) return;
|
|
1014
|
+
const path = join(home, ".oats-start.lock");
|
|
1015
|
+
let stat;
|
|
1016
|
+
try {
|
|
1017
|
+
stat = lstatSync(path);
|
|
1018
|
+
} catch (error) {
|
|
1019
|
+
if (error.code === "ENOENT") return;
|
|
1020
|
+
throw error;
|
|
1021
|
+
}
|
|
1022
|
+
if (stat.isFile() && stat.dev === identity.dev && stat.ino === identity.ino)
|
|
1023
|
+
rmSync(path);
|
|
1024
|
+
}
|
|
1025
|
+
/** Apply a fenced plan, or continue its exact staged versions after provider adoption.
|
|
1026
|
+
* Receipt progress is written before each irreversible operation; hooks must be
|
|
1027
|
+
* idempotent so an interrupted invocation can safely be retried. */
|
|
1028
|
+
export async function applyUpgrade(ctx, root, name, opts = {}) {
|
|
1029
|
+
if (
|
|
1030
|
+
typeof opts.planRevision !== "string" ||
|
|
1031
|
+
!opts.planRevision ||
|
|
1032
|
+
typeof opts.idempotencyKey !== "string" ||
|
|
1033
|
+
!KEY.test(opts.idempotencyKey)
|
|
1034
|
+
)
|
|
1035
|
+
throw fail(
|
|
1036
|
+
"E_BAD_ARGS",
|
|
1037
|
+
"upgrade needs --plan-revision <rev> and --idempotency-key <key> (1–128 safe characters)",
|
|
1038
|
+
);
|
|
1039
|
+
const { home } = resolveInstance(ctx, root, name, opts);
|
|
1040
|
+
realDir(home);
|
|
1041
|
+
realDir(join(home, ".oats"));
|
|
1042
|
+
const path = receiptPath(home, opts.idempotencyKey);
|
|
1043
|
+
let stored =
|
|
1044
|
+
readUpgradeReceipts(home).find((row) => row.path === path)?.receipt || null;
|
|
1045
|
+
const checkReceipt = () => {
|
|
1046
|
+
if (
|
|
1047
|
+
stored &&
|
|
1048
|
+
(stored.action !== "upgrade" ||
|
|
1049
|
+
stored.instance !== name ||
|
|
1050
|
+
stored.home !== home ||
|
|
1051
|
+
!/^[a-f0-9]{24}$/.test(stored.receipt) ||
|
|
1052
|
+
stored.undo !== !!opts.undo ||
|
|
1053
|
+
stored.planRevision !== opts.planRevision)
|
|
1054
|
+
)
|
|
1055
|
+
throw fail(
|
|
1056
|
+
"E_IDEMPOTENCY_CONFLICT",
|
|
1057
|
+
"this idempotency key belongs to another upgrade plan; use its original arguments or another key",
|
|
1058
|
+
);
|
|
1059
|
+
};
|
|
1060
|
+
checkReceipt();
|
|
1061
|
+
if (stored?.status !== "partial") target(ctx, root, name, opts);
|
|
1062
|
+
if (stored?.status === "complete") {
|
|
1063
|
+
const claim = claimHomeFor("upgrade", name, home);
|
|
1064
|
+
try {
|
|
1065
|
+
// The receipt already records the invocation's final state, so a stale
|
|
1066
|
+
// upgrade file may be released even when its harness is running.
|
|
1067
|
+
reclaimUpgradeMutex(home, name);
|
|
1068
|
+
if (stored.steps?.cleaned === false)
|
|
1069
|
+
return { ...finishCleanup(home, path, stored), replayed: true };
|
|
1070
|
+
writeJson(path, stored);
|
|
1071
|
+
return { ...stored, replayed: true };
|
|
1072
|
+
} finally {
|
|
1073
|
+
releaseHomeClaim(claim);
|
|
1074
|
+
}
|
|
1075
|
+
}
|
|
1076
|
+
const holding = claimHomeFor("upgrade", name, home);
|
|
1077
|
+
let mutexIdentity,
|
|
1078
|
+
p,
|
|
1079
|
+
tx,
|
|
1080
|
+
receipt = stored,
|
|
1081
|
+
forwardOnly = !!(
|
|
1082
|
+
stored?.steps?.hooks?.length ||
|
|
1083
|
+
stored?.uncertain?.length ||
|
|
1084
|
+
stored?.hooks?.inFlight
|
|
1085
|
+
);
|
|
1086
|
+
try {
|
|
1087
|
+
unclaimed(home, name, true);
|
|
1088
|
+
if (stored?.status === "partial" && stored.hooks?.inFlight) {
|
|
1089
|
+
receipt.uncertain = [
|
|
1090
|
+
...new Set([...(receipt.uncertain || []), stored.hooks.inFlight]),
|
|
1091
|
+
];
|
|
1092
|
+
forwardOnly = true;
|
|
1093
|
+
// Unknown is not a refusal. Make that boundary durable before any retry
|
|
1094
|
+
// can inspect staging or run another hook, even if its retry later fails.
|
|
1095
|
+
writeJson(path, receipt);
|
|
1096
|
+
}
|
|
1097
|
+
stopped(home, name, opts, stored?.priorMeta);
|
|
1098
|
+
// One path, two atomic shapes: start owns a mkdir directory; upgrade owns
|
|
1099
|
+
// an exclusive regular file. Under our lifecycle claim a prior upgrade
|
|
1100
|
+
// cannot still run, so even an empty interrupted wx file is reclaimable.
|
|
1101
|
+
// A directory or symlink is never reclaimed by this act.
|
|
1102
|
+
reclaimUpgradeMutex(home, name);
|
|
1103
|
+
const startMutex = join(home, ".oats-start.lock");
|
|
1104
|
+
let fd;
|
|
1105
|
+
try {
|
|
1106
|
+
fd = openSync(startMutex, "wx", 0o600);
|
|
1107
|
+
mutexIdentity = fstatSync(fd);
|
|
1108
|
+
writeFileSync(
|
|
1109
|
+
fd,
|
|
1110
|
+
JSON.stringify({
|
|
1111
|
+
action: "upgrade",
|
|
1112
|
+
instance: name,
|
|
1113
|
+
home,
|
|
1114
|
+
planRevision: opts.planRevision,
|
|
1115
|
+
idempotencyKey: opts.idempotencyKey,
|
|
1116
|
+
undo: !!opts.undo,
|
|
1117
|
+
}) + "\n",
|
|
1118
|
+
);
|
|
1119
|
+
} catch (error) {
|
|
1120
|
+
if (error.code === "EEXIST")
|
|
1121
|
+
throw fail(
|
|
1122
|
+
"E_SESSION_RUNNING",
|
|
1123
|
+
`${name} has a start in progress; wait for it to finish before upgrading`,
|
|
1124
|
+
);
|
|
1125
|
+
throw error;
|
|
1126
|
+
} finally {
|
|
1127
|
+
if (fd !== undefined) closeSync(fd);
|
|
1128
|
+
}
|
|
1129
|
+
stored =
|
|
1130
|
+
readUpgradeReceipts(home).find((row) => row.path === path)?.receipt ||
|
|
1131
|
+
null;
|
|
1132
|
+
checkReceipt();
|
|
1133
|
+
receipt = stored;
|
|
1134
|
+
if (stored?.status === "complete")
|
|
1135
|
+
return {
|
|
1136
|
+
...(stored.steps?.cleaned === false
|
|
1137
|
+
? finishCleanup(home, path, stored)
|
|
1138
|
+
: stored),
|
|
1139
|
+
replayed: true,
|
|
1140
|
+
};
|
|
1141
|
+
if (stored?.status === "partial") {
|
|
1142
|
+
if (
|
|
1143
|
+
!Array.isArray(stored.steps?.hooks) ||
|
|
1144
|
+
!object(stored.priorMeta) ||
|
|
1145
|
+
!object(stored.resolution) ||
|
|
1146
|
+
!Array.isArray(stored.resolution.modules) ||
|
|
1147
|
+
!object(stored.nextMeta) ||
|
|
1148
|
+
!Array.isArray(stored.modules)
|
|
1149
|
+
)
|
|
1150
|
+
throw fail(
|
|
1151
|
+
"E_UPGRADE_PARTIAL",
|
|
1152
|
+
"the partial upgrade receipt cannot be resumed safely; inspect its recorded state or respawn the instance",
|
|
1153
|
+
);
|
|
1154
|
+
forwardOnly = !!(
|
|
1155
|
+
stored.steps.hooks.length ||
|
|
1156
|
+
stored.uncertain?.length ||
|
|
1157
|
+
stored.hooks?.inFlight
|
|
1158
|
+
);
|
|
1159
|
+
if (!stored.steps.cleaned)
|
|
1160
|
+
tx = await stageMaterialize(null, home, {
|
|
1161
|
+
staging: join(home, ".oats", `.staging-upgrade-${stored.receipt}`),
|
|
1162
|
+
resume: true,
|
|
1163
|
+
});
|
|
1164
|
+
} else {
|
|
1165
|
+
p = await prepare(ctx, root, name, opts, { own: true });
|
|
1166
|
+
if (p.home !== home)
|
|
1167
|
+
throw fail(
|
|
1168
|
+
"E_PLAN_STALE",
|
|
1169
|
+
"instance address changed; review a fresh plan",
|
|
1170
|
+
);
|
|
1171
|
+
if (p.plan.planRevision !== opts.planRevision)
|
|
1172
|
+
throw Object.assign(
|
|
1173
|
+
fail(
|
|
1174
|
+
"E_PLAN_STALE",
|
|
1175
|
+
`the upgrade plan changed (${opts.planRevision} → ${p.plan.planRevision}); review the fresh plan`,
|
|
1176
|
+
),
|
|
1177
|
+
{ plan: p.plan },
|
|
1178
|
+
);
|
|
1179
|
+
const refusals = p.plan.modules.filter(
|
|
1180
|
+
(m) => m.provider.decision === "refuse",
|
|
1181
|
+
);
|
|
1182
|
+
if (refusals.length)
|
|
1183
|
+
throw fail(
|
|
1184
|
+
"E_UPGRADE_REFUSED",
|
|
1185
|
+
refusals
|
|
1186
|
+
.map(
|
|
1187
|
+
(m) =>
|
|
1188
|
+
`${m.capability}: ${m.provider.reason}${m.provider.remedy ? `; ${m.provider.remedy}` : ""}`,
|
|
1189
|
+
)
|
|
1190
|
+
.join("\n"),
|
|
1191
|
+
{ modules: refusals },
|
|
1192
|
+
);
|
|
1193
|
+
const id = hash({
|
|
1194
|
+
home,
|
|
1195
|
+
key: opts.idempotencyKey,
|
|
1196
|
+
revision: opts.planRevision,
|
|
1197
|
+
});
|
|
1198
|
+
if (!p.plan.modules.length) {
|
|
1199
|
+
const complete = {
|
|
1200
|
+
lifecycleApi: 1,
|
|
1201
|
+
action: "upgrade",
|
|
1202
|
+
status: "complete",
|
|
1203
|
+
instance: name,
|
|
1204
|
+
home,
|
|
1205
|
+
undo: !!opts.undo,
|
|
1206
|
+
idempotencyKey: opts.idempotencyKey,
|
|
1207
|
+
planRevision: opts.planRevision,
|
|
1208
|
+
receipt: id,
|
|
1209
|
+
modules: [],
|
|
1210
|
+
at: new Date().toISOString(),
|
|
1211
|
+
};
|
|
1212
|
+
writeJson(path, complete);
|
|
1213
|
+
return complete;
|
|
1214
|
+
}
|
|
1215
|
+
// No receipt means no hook was invoked. An interrupted preparation is
|
|
1216
|
+
// disposable under this claim; the same key can stage its plan again.
|
|
1217
|
+
rmSync(join(home, ".oats", `.staging-upgrade-${id}`), {
|
|
1218
|
+
recursive: true,
|
|
1219
|
+
force: true,
|
|
1220
|
+
});
|
|
1221
|
+
rmSync(join(home, ".oats/previous", id), {
|
|
1222
|
+
recursive: true,
|
|
1223
|
+
force: true,
|
|
1224
|
+
});
|
|
1225
|
+
receipt = {
|
|
1226
|
+
lifecycleApi: 1,
|
|
1227
|
+
action: "upgrade",
|
|
1228
|
+
status: "partial",
|
|
1229
|
+
instance: name,
|
|
1230
|
+
home,
|
|
1231
|
+
undo: !!opts.undo,
|
|
1232
|
+
idempotencyKey: opts.idempotencyKey,
|
|
1233
|
+
planRevision: opts.planRevision,
|
|
1234
|
+
receipt: id,
|
|
1235
|
+
at: new Date().toISOString(),
|
|
1236
|
+
modules: p.plan.modules,
|
|
1237
|
+
homeChangedSinceSpawn: p.plan.homeChangedSinceSpawn,
|
|
1238
|
+
hookTargets: p.hookTargets,
|
|
1239
|
+
hooks: { inFlight: null },
|
|
1240
|
+
uncertain: [],
|
|
1241
|
+
steps: {
|
|
1242
|
+
hooks: [],
|
|
1243
|
+
metadata: false,
|
|
1244
|
+
swapped: false,
|
|
1245
|
+
baseline: false,
|
|
1246
|
+
event: false,
|
|
1247
|
+
cleaned: false,
|
|
1248
|
+
},
|
|
1249
|
+
step: "stage",
|
|
1250
|
+
resolution: p.resolution,
|
|
1251
|
+
priorMeta: p.meta,
|
|
1252
|
+
};
|
|
1253
|
+
tx = await stageMaterialize(p.resolution, home, {
|
|
1254
|
+
replace: true,
|
|
1255
|
+
staging: join(home, ".oats", `.staging-upgrade-${id}`),
|
|
1256
|
+
existingModules: p.existingModules,
|
|
1257
|
+
soulAgentsMd: p.soulAgentsMd,
|
|
1258
|
+
blocks: p.blocks,
|
|
1259
|
+
lock: p.lock,
|
|
1260
|
+
});
|
|
1261
|
+
receipt.nextMeta = derivedMetadata(p, tx, receipt);
|
|
1262
|
+
tx.updateInstance(receipt.nextMeta);
|
|
1263
|
+
receipt.step = "previous";
|
|
1264
|
+
keepPrevious(home, receipt, p.meta);
|
|
1265
|
+
const baseline = findRetirementBaseline(home);
|
|
1266
|
+
if (existsSync(baseline))
|
|
1267
|
+
copyTreeSafe(baseline, join(tx.staging, "retirement-baseline.json"));
|
|
1268
|
+
// All replacement bytes now belong to the durable staging transaction.
|
|
1269
|
+
// Drop temporary planning copies before a killed resumable invocation can
|
|
1270
|
+
// strand them outside the receipt's staging tree.
|
|
1271
|
+
rmSync(p.scratch, { recursive: true, force: true });
|
|
1272
|
+
// A durable partial fence precedes the hook. If the process dies before
|
|
1273
|
+
// recording its success, retry re-runs that idempotent hook, never restores.
|
|
1274
|
+
writeJson(path, receipt);
|
|
1275
|
+
}
|
|
1276
|
+
const save = () => writeJson(path, receipt);
|
|
1277
|
+
for (const row of receipt.modules) {
|
|
1278
|
+
if (receipt.steps.hooks.includes(row.capability)) continue;
|
|
1279
|
+
const module = receipt.resolution.modules.find(
|
|
1280
|
+
(m) => m.name === row.capability,
|
|
1281
|
+
);
|
|
1282
|
+
if (!hookCommand(module.manifest)) continue;
|
|
1283
|
+
const moduleDirectory = join(tx.staging, "modules", module.name);
|
|
1284
|
+
const manifest = readJson(join(moduleDirectory, "oats.json"));
|
|
1285
|
+
if (
|
|
1286
|
+
manifest.capability !== module.name ||
|
|
1287
|
+
remote.contentDigest(moduleDirectory, {
|
|
1288
|
+
allowSymlinks: remote.OATS_ALIAS_SYMLINK,
|
|
1289
|
+
}) !== receipt.nextMeta.modules[module.name].digest
|
|
1290
|
+
)
|
|
1291
|
+
throw fail(
|
|
1292
|
+
"E_UPGRADE_INTEGRITY",
|
|
1293
|
+
`${module.name}'s staged copy no longer verifies; respawn if it cannot finish`,
|
|
1294
|
+
);
|
|
1295
|
+
module.manifest = manifest;
|
|
1296
|
+
if (!hookCommand(module.manifest)) continue;
|
|
1297
|
+
receipt.step = `hook ${row.capability}`;
|
|
1298
|
+
receipt.hooks = { ...(receipt.hooks || {}), inFlight: module.name };
|
|
1299
|
+
save();
|
|
1300
|
+
let answer;
|
|
1301
|
+
try {
|
|
1302
|
+
answer = runHook("apply", {
|
|
1303
|
+
home,
|
|
1304
|
+
meta: receipt.priorMeta,
|
|
1305
|
+
module,
|
|
1306
|
+
dir: join(tx.staging, "modules", module.name),
|
|
1307
|
+
to: receipt.hookTargets?.[row.capability] ?? row.to,
|
|
1308
|
+
root,
|
|
1309
|
+
});
|
|
1310
|
+
} catch (error) {
|
|
1311
|
+
if (error.hookRefused === true) {
|
|
1312
|
+
receipt.hooks.inFlight = null;
|
|
1313
|
+
receipt.hooks.refused = module.name;
|
|
1314
|
+
try {
|
|
1315
|
+
save();
|
|
1316
|
+
} catch (writeError) {
|
|
1317
|
+
// Without a durable outcome the marker remains authoritative.
|
|
1318
|
+
receipt.hooks.inFlight = module.name;
|
|
1319
|
+
forwardOnly = true;
|
|
1320
|
+
throw writeError;
|
|
1321
|
+
}
|
|
1322
|
+
} else {
|
|
1323
|
+
receipt.uncertain = [
|
|
1324
|
+
...new Set([...(receipt.uncertain || []), module.name]),
|
|
1325
|
+
];
|
|
1326
|
+
forwardOnly = true;
|
|
1327
|
+
save();
|
|
1328
|
+
}
|
|
1329
|
+
throw error;
|
|
1330
|
+
}
|
|
1331
|
+
forwardOnly = true;
|
|
1332
|
+
receipt.nextMeta.capabilityMeta = {
|
|
1333
|
+
...receipt.nextMeta.capabilityMeta,
|
|
1334
|
+
[module.name]: answer.meta,
|
|
1335
|
+
};
|
|
1336
|
+
if (answer.warning)
|
|
1337
|
+
receipt.warnings = [...(receipt.warnings || []), answer.warning];
|
|
1338
|
+
receipt.steps.hooks.push(module.name);
|
|
1339
|
+
receipt.hooks.inFlight = null;
|
|
1340
|
+
delete receipt.hooks.refused;
|
|
1341
|
+
save();
|
|
1342
|
+
}
|
|
1343
|
+
if (!receipt.steps.swapped) {
|
|
1344
|
+
receipt.step = "swap";
|
|
1345
|
+
save();
|
|
1346
|
+
if (!receipt.steps.metadata) {
|
|
1347
|
+
tx.updateInstance(receipt.nextMeta);
|
|
1348
|
+
receipt.steps.metadata = true;
|
|
1349
|
+
save();
|
|
1350
|
+
}
|
|
1351
|
+
tx.commit({ preserveOnFailure: forwardOnly, retainStaging: true });
|
|
1352
|
+
receipt.steps.swapped = true;
|
|
1353
|
+
save();
|
|
1354
|
+
}
|
|
1355
|
+
// Only one previous move survives. The current backups remain ordinary
|
|
1356
|
+
// home content and count against an unchanged dirty retirement baseline.
|
|
1357
|
+
const previous = join(home, ".oats/previous");
|
|
1358
|
+
const history = tx ? join(tx.staging, "previous-history") : null;
|
|
1359
|
+
for (const entry of readdirSync(previous))
|
|
1360
|
+
if (entry !== receipt.receipt) {
|
|
1361
|
+
if (!/^[a-f0-9]{24}$/.test(entry))
|
|
1362
|
+
throw fail(
|
|
1363
|
+
"E_UPGRADE_INTEGRITY",
|
|
1364
|
+
`unexpected previous-state entry ${entry}; inspect it before retrying`,
|
|
1365
|
+
);
|
|
1366
|
+
mkdirSync(history, { recursive: true });
|
|
1367
|
+
renameSync(join(previous, entry), join(history, entry));
|
|
1368
|
+
}
|
|
1369
|
+
if (!receipt.steps.baseline) {
|
|
1370
|
+
receipt.step = "baseline";
|
|
1371
|
+
save();
|
|
1372
|
+
rebaseUpgradeRetirementBaseline(home, {
|
|
1373
|
+
homeChangedSinceSpawn: receipt.homeChangedSinceSpawn !== false,
|
|
1374
|
+
});
|
|
1375
|
+
receipt.steps.baseline = true;
|
|
1376
|
+
save();
|
|
1377
|
+
}
|
|
1378
|
+
const complete = {
|
|
1379
|
+
...receipt,
|
|
1380
|
+
status: "complete",
|
|
1381
|
+
step: "cleanup",
|
|
1382
|
+
steps: { ...receipt.steps, cleaned: false },
|
|
1383
|
+
completedAt: new Date().toISOString(),
|
|
1384
|
+
};
|
|
1385
|
+
delete complete.hookTargets;
|
|
1386
|
+
delete complete.resolution;
|
|
1387
|
+
delete complete.priorMeta;
|
|
1388
|
+
delete complete.nextMeta;
|
|
1389
|
+
// Publishing this receipt is the commit. Only committed moves emit success.
|
|
1390
|
+
// Garbage collection cannot undo a fully composed home; a same-key retry
|
|
1391
|
+
// after this point finishes event publication and staging cleanup only.
|
|
1392
|
+
writeJson(path, complete);
|
|
1393
|
+
receipt = complete;
|
|
1394
|
+
return finishCleanup(home, path, receipt);
|
|
1395
|
+
} catch (error) {
|
|
1396
|
+
if (receipt?.status === "complete") throw error;
|
|
1397
|
+
if (
|
|
1398
|
+
receipt?.status === "partial" &&
|
|
1399
|
+
(forwardOnly || receipt.steps?.hooks?.length)
|
|
1400
|
+
) {
|
|
1401
|
+
try {
|
|
1402
|
+
writeJson(path, receipt);
|
|
1403
|
+
} catch {
|
|
1404
|
+
/* the pre-hook fence remains authoritative */
|
|
1405
|
+
}
|
|
1406
|
+
throw partial(receipt, error);
|
|
1407
|
+
}
|
|
1408
|
+
if (tx && existsSync(tx.staging)) {
|
|
1409
|
+
const history = join(tx.staging, "previous-history");
|
|
1410
|
+
if (existsSync(history))
|
|
1411
|
+
for (const entry of readdirSync(history))
|
|
1412
|
+
renameSync(join(history, entry), join(home, ".oats/previous", entry));
|
|
1413
|
+
const baseline = join(tx.staging, "retirement-baseline.json");
|
|
1414
|
+
if (existsSync(baseline))
|
|
1415
|
+
writeFileAtomic(findRetirementBaseline(home), readFileSync(baseline), { mode: 0o600 });
|
|
1416
|
+
tx.rollback();
|
|
1417
|
+
}
|
|
1418
|
+
if (receipt?.receipt) {
|
|
1419
|
+
rmSync(join(home, ".oats/previous", receipt.receipt), {
|
|
1420
|
+
recursive: true,
|
|
1421
|
+
force: true,
|
|
1422
|
+
});
|
|
1423
|
+
rmSync(path, { force: true });
|
|
1424
|
+
const previous = join(home, ".oats/previous");
|
|
1425
|
+
if (existsSync(previous) && readdirSync(previous).length === 0)
|
|
1426
|
+
rmSync(previous, { recursive: true });
|
|
1427
|
+
}
|
|
1428
|
+
appendEvent(
|
|
1429
|
+
home,
|
|
1430
|
+
{
|
|
1431
|
+
kind: "upgrade-refused",
|
|
1432
|
+
data: {
|
|
1433
|
+
step: receipt?.step || "plan",
|
|
1434
|
+
reason: String(error.message).slice(0, 2048),
|
|
1435
|
+
},
|
|
1436
|
+
},
|
|
1437
|
+
{ workspaceOnly: true },
|
|
1438
|
+
);
|
|
1439
|
+
throw error;
|
|
1440
|
+
} finally {
|
|
1441
|
+
if (p) rmSync(p.scratch, { recursive: true, force: true });
|
|
1442
|
+
releaseUpgradeMutex(home, mutexIdentity);
|
|
1443
|
+
releaseHomeClaim(holding);
|
|
1444
|
+
}
|
|
1445
|
+
}
|