cairn-ai 0.6.0 → 0.7.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.
@@ -1,19 +1,29 @@
1
1
  import { spawnSync } from "node:child_process";
2
- import { lstat, mkdir, readFile, writeFile } from "node:fs/promises";
3
- import { dirname, join } from "node:path";
2
+ import { realpathSync } from "node:fs";
3
+ import { lstat, mkdir, readFile, rmdir, writeFile } from "node:fs/promises";
4
+ import { dirname, join, resolve, sep } from "node:path";
4
5
  import { hasSetting, readSharedConfigSnapshot, removeCairnConfig, splitSections } from "./cairn-lifecycle-config.mjs";
5
6
  import {
6
7
  installedSkillLocatorPath, validRuntimeLocator, validateAntigravitySkills,
7
8
  } from "./cairn-lifecycle-mirror.mjs";
8
9
  import { createClaudeRegistration } from "./cairn-lifecycle-claude.mjs";
10
+ import { HOSTS, hostOfTarget, isHostSelection } from "./cairn-lifecycle-hosts.mjs";
11
+ import {
12
+ OWNERSHIP_SCHEMA_VERSION, RETAINED_RUNTIME_GRACE_MS, RETAINED_RUNTIME_IDS, RETAINED_RUNTIME_LIMIT,
13
+ compareVersions,
14
+ } from "./cairn-lifecycle-integrity.mjs";
15
+ import { AUTO_UPGRADE_EXIT } from "./cairn-update-state.mjs";
16
+
17
+ const VERSION_PATTERN = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
9
18
 
10
19
  export function createCommands(context) {
11
20
  const {
12
21
  antigravityCliHome, antigravityHome, claudeHome, claudeHomeOverridden, claudePluginMarketplaceRoot,
13
- claudeRuntimeLocatorPath, codexHome, marketplaceName, configPath, installedPluginRoot, installedRuntimeLocatorPath,
22
+ claudeRuntimeLocatorPath, codexCacheRoot, codexHome, codexRuntimeRoot, marketplaceName, configPath,
23
+ installRoot, installedPluginRoot, layout, legacy, legacyLayout,
14
24
  marketplaceJsonPath, ownershipPath, phases, pluginName, pluginRoot,
15
- pruneUninstallScaffolds, releaseVersion, samePath, skillNames, t, transaction,
16
- versionedPluginRoot, staging, integrity,
25
+ pruneUninstallScaffolds, releaseVersion, runtimeRoot, skillNames, t, transaction,
26
+ staging, integrity,
17
27
  } = context;
18
28
  const {
19
29
  createTransaction, finishTransaction, recoverInterruptedTransaction,
@@ -21,101 +31,282 @@ export function createCommands(context) {
21
31
  } = transaction;
22
32
  const { legacyMigrationTargets, stageInstall } = staging;
23
33
  const claudeRegistration = createClaudeRegistration({
24
- claudeHome, claudeHomeOverridden, marketplaceRoot: claudePluginMarketplaceRoot, marketplaceName, pluginName,
34
+ claudeHome, claudeHomeOverridden, marketplaceRoot: claudePluginMarketplaceRoot,
35
+ legacyMarketplaceRoot: legacyLayout?.claudePluginMarketplaceRoot, marketplaceName, pluginName, releaseVersion,
25
36
  });
26
37
  const {
27
- adoptLegacy, anyManagedArtifactExists, assertOwnershipDigests,
38
+ anyManagedArtifactExists, assertOwnershipDigests,
28
39
  assertTargetsReplaceable, ownershipDigestsValid, readOwnership, targetDigest,
29
- targetRecord, validateOwnershipShape, versionedRuntimeRoot,
40
+ targetRecord, validateOwnershipShape, withoutMissingRetained,
30
41
  } = integrity;
31
- async function install(mode) {
32
- if (samePath(pluginRoot, installedPluginRoot) || samePath(pluginRoot, versionedPluginRoot)) {
42
+ // Legacy-layout records that live in a different place after migration; the transaction removes the old copy.
43
+ const legacyRootRemovals = {
44
+ "codex-source": "legacy-root-codex-source", marketplace: "legacy-root-marketplace", "claude-plugin": "legacy-root-claude-plugin",
45
+ };
46
+ // `selection` is the --hosts value or the prompt answer; without one an upgrade keeps the recorded hosts and a first
47
+ // install takes every host. `auto` is `upgrade --auto` from the auto-upgrade runner. `allowDowngrade` lets this CLI
48
+ // replace an installation of a newer version.
49
+ async function install(mode, { hosts: selection = null, auto = false, allowDowngrade = false } = {}) {
50
+ if (isInsidePath(installRoot, pluginRoot) || isInsidePath(codexCacheRoot, pluginRoot)) {
33
51
  throw new Error("Run install or upgrade from the Cairn package/global source, not from the installed cache.");
34
52
  }
35
- await recoverInterruptedTransaction();
53
+ await recoverInterruptedTransactions();
54
+ await assertSingleOwnershipManifest();
55
+ // Checked under the lifecycle lock: an automatic upgrade only moves an existing installation forward, so a runner
56
+ // that started before an uninstall finished installs nothing.
57
+ if (auto && (await readJson(ownershipPath).catch(() => null))?.schemaVersion !== OWNERSHIP_SCHEMA_VERSION) {
58
+ throw new Error("auto-upgrade requires an existing installation");
59
+ }
60
+ // An older CLI (an old global install, an old npx cache) would otherwise move a newer installation back, and the
61
+ // auto-upgrade runner would move it forward again.
62
+ const installedVersion = await recordedVersion();
63
+ if (!allowDowngrade && installedVersion && compareVersions(installedVersion, releaseVersion) > 0) {
64
+ throw new Error(`Installed Cairn ${installedVersion} is newer than this CLI ${releaseVersion}; run the newer CLI, or pass --allow-downgrade to install ${releaseVersion}`);
65
+ }
36
66
  const transaction = await createTransaction();
67
+ let migration = null;
68
+ let unregisteredClaude = false;
69
+ let hosts = [...HOSTS];
70
+ let droppedHosts = false;
37
71
  try {
38
- const targets = await stageInstall(transaction.stageRoot);
39
- if (process.env.CAIRN_TEST_CRASH_AFTER_STAGE === "1") process.exit(87);
40
- targets.push(...await legacyMigrationTargets());
41
72
  let ownership = await readOwnership();
73
+ if (ownership) validateOwnershipShape(ownership);
74
+ // A retained runtime that is already gone needs no removal and is no longer recorded.
75
+ if (ownership) ownership = await withoutMissingRetained(ownership);
76
+ hosts = selection ?? (ownership ? ownership.hosts : hosts);
77
+ droppedHosts = Boolean(ownership) && ownership.hosts.some((host) => !hosts.includes(host));
78
+ const targets = await stageInstall(transaction.stageRoot, hosts);
79
+ if (process.env.CAIRN_TEST_CRASH_AFTER_STAGE === "1") process.exit(87);
80
+ if (hosts.includes("antigravity")) targets.push(...await legacyMigrationTargets());
81
+ let retained = [];
42
82
  if (ownership) {
43
- validateOwnershipShape(ownership);
44
83
  await assertOwnershipDigests(ownership);
45
- if (ownership.version !== releaseVersion) {
46
- targets.push({
47
- id: "previous-codex-runtime",
48
- phase: "cleanup",
49
- path: versionedRuntimeRoot(ownership.version),
50
- type: "tree",
51
- operation: "remove",
52
- });
84
+ const retention = planRetention(ownership, new Date(), hosts);
85
+ targets.push(...retention.removals);
86
+ retained = retention.retained;
87
+ targets.push(...await deselectedHostTargets(ownership, hosts, transaction));
88
+ } else {
89
+ // A 0.6.0-layout installation is validated by the legacy stack and moved here in this same transaction.
90
+ ownership = await legacy.integrity.readOwnership();
91
+ if (ownership) {
92
+ legacy.integrity.validateOwnershipShape(ownership);
93
+ await legacy.integrity.assertOwnershipDigests(ownership);
94
+ migration = { manifest: true };
95
+ } else {
96
+ const legacyTargets = legacyLayoutTargets(targets);
97
+ if (await anyManagedArtifactExists([...targets, ...legacyTargets])) {
98
+ ownership = await legacy.integrity.adoptLegacy(legacyTargets, transaction);
99
+ migration = { manifest: false };
100
+ }
101
+ }
102
+ if (migration) {
103
+ // A legacy installation had every host; it moves as a whole, and a narrower selection follows in a later run.
104
+ if (hosts.length !== HOSTS.length) {
105
+ throw new Error(`Invalid --hosts value: ${hosts.join(",")} (a legacy installation migrates with every host; run cairn upgrade first, then choose hosts)`);
106
+ }
107
+ targets.push(...legacyRemovalTargets(ownership));
53
108
  }
54
109
  }
55
- else if (await anyManagedArtifactExists(targets)) ownership = await adoptLegacy(targets, transaction);
56
110
  await assertTargetsReplaceable(targets, ownership);
111
+ // Like uninstall, a deselected Claude Code plugin is unregistered before its files are removed; a rollback
112
+ // restores the files and then the registration.
113
+ if (ownership?.hosts?.includes("claude") && !hosts.includes("claude")) {
114
+ unregisteredClaude = claudeRegistration.unregister().unregistered;
115
+ }
57
116
  for (const phase of phases) {
58
117
  for (const target of targets.filter((candidate) => candidate.phase === phase)) {
59
118
  if (target.operation === "remove") await removeManagedTarget(target, transaction);
60
119
  else await replaceTarget(target, transaction);
61
120
  }
62
121
  injectFailure(`after-${phase}`);
122
+ if (process.env.CAIRN_TEST_CRASH_AFTER_PHASE === phase) process.exit(88);
63
123
  }
64
124
  const records = [];
65
- for (const target of targets.filter((candidate) => candidate.operation !== "remove")) records.push(await targetRecord(target));
125
+ for (const target of targets.filter((candidate) => candidate.operation !== "remove" && !candidate.deselected)) records.push(await targetRecord(target));
66
126
  const nextOwnership = {
67
- schemaVersion: 1,
127
+ schemaVersion: OWNERSHIP_SCHEMA_VERSION,
68
128
  plugin: pluginName,
69
129
  version: releaseVersion,
70
130
  transactionId: transaction.id,
71
131
  installedAt: new Date().toISOString(),
132
+ origin: await exists(join(pluginRoot, ".git")) ? "checkout" : "package",
133
+ hosts: [...hosts],
72
134
  targets: records,
135
+ retained,
73
136
  };
74
137
  const ownershipStage = join(transaction.stageRoot, "lifecycle.json");
75
138
  await mkdir(dirname(ownershipStage), { recursive: true });
76
139
  await writeFile(ownershipStage, `${JSON.stringify(nextOwnership, null, 2)}\n`);
77
140
  await replaceTarget({ id: "ownership", phase: "manifest", path: ownershipPath, staged: ownershipStage, type: "file" }, transaction);
141
+ if (migration?.manifest) {
142
+ await removeManagedTarget({ id: "legacy-ownership", phase: "manifest", path: legacyLayout.ownershipPath, type: "file" }, transaction);
143
+ }
78
144
  await finishTransaction(transaction);
79
145
  console.log(t(mode === "upgrade" ? "upgradeComplete" : "installComplete"));
80
- console.log(`Codex plugin source: ${installedPluginRoot}`);
81
- console.log(`Codex versioned runtime: ${versionedPluginRoot}`);
146
+ console.log(`Cairn runtime: ${runtimeRoot}`);
147
+ if (nextOwnership.hosts.includes("codex")) {
148
+ console.log(`Codex plugin source: ${installedPluginRoot}`);
149
+ console.log(`Codex versioned runtime: ${codexRuntimeRoot}`);
150
+ }
82
151
  console.log(`Ownership manifest: ${ownershipPath}`);
83
152
  } catch (error) {
84
- if (transaction.state !== "committed") await rollback(transaction);
153
+ if (transaction.state !== "committed") {
154
+ await rollback(transaction);
155
+ if (unregisteredClaude) {
156
+ try { claudeRegistration.register(); } catch (registrationError) { console.error(`Claude Code plugin re-registration failed: ${registrationError.message}`); }
157
+ }
158
+ }
85
159
  throw error;
86
160
  }
87
- reportClaudeRegistration();
161
+ if (hosts.includes("claude")) reportClaudeRegistration({ auto, migrated: Boolean(migration) });
162
+ if (migration) await pruneLegacyScaffolds();
163
+ // Removing a host can leave its empty scaffolds (Codex marketplace and cache directories); only empty ones go.
164
+ if (droppedHosts) await pruneUninstallScaffolds();
165
+ injectFailure("after-commit");
166
+ }
167
+
168
+ // The version a current or 0.6.0-layout manifest records, or null when there is none or it is unreadable (the
169
+ // manifest checks that follow report that).
170
+ async function recordedVersion() {
171
+ for (const path of [ownershipPath, legacyLayout?.ownershipPath].filter(Boolean)) {
172
+ const version = (await readJson(path).catch(() => null))?.version;
173
+ if (typeof version === "string" && VERSION_PATTERN.test(version)) return version;
174
+ }
175
+ return null;
176
+ }
177
+
178
+ // Records of hosts that are no longer selected are removed under their own ids, so assertTargetsReplaceable compares
179
+ // them with the manifest and refuses modified ones. The shared config keeps everything but Cairn's sections, as in
180
+ // uninstall, and a Codex cache runtime from another version is removed through its journal-only id.
181
+ async function deselectedHostTargets(ownership, hosts, transaction) {
182
+ const removals = [];
183
+ for (const record of ownership.targets) {
184
+ const host = hostOfTarget(record.id);
185
+ if (host === "core" || hosts.includes(host)) continue;
186
+ if (record.type === "config") {
187
+ if (!(await exists(record.path))) continue;
188
+ const snapshot = await readSharedConfigSnapshot(record.path);
189
+ const staged = join(transaction.stageRoot, "deselected-config.toml");
190
+ await mkdir(dirname(staged), { recursive: true });
191
+ await writeFile(staged, removeCairnConfig(snapshot.text));
192
+ removals.push({ id: record.id, phase: record.phase, path: record.path, staged, type: record.type, configSourceDigest: snapshot.digest, deselected: true });
193
+ } else if (record.id === "codex-runtime" && record.path !== codexRuntimeRoot) {
194
+ removals.push({ id: "previous-codex-runtime", phase: "cleanup", path: record.path, type: record.type, operation: "remove", ownedBy: record.id });
195
+ } else {
196
+ removals.push({ id: record.id, phase: record.phase, path: record.path, type: record.type, operation: "remove" });
197
+ }
198
+ }
199
+ return removals;
200
+ }
201
+
202
+ function hostsOf(ownership) {
203
+ return isHostSelection(ownership?.hosts) ? ownership.hosts : [...HOSTS];
204
+ }
205
+
206
+ // A version change retains the previous runtimes for sessions that still run them, except a Codex cache copy that is
207
+ // not older than the release: Codex loads the highest cached version, so that copy would replace the release. Retained
208
+ // runtimes past the grace period, beyond the per-id limit (oldest first), or no longer older than a Codex release are
209
+ // removed in cleanup; the release's own retained runtime becomes the installed target again.
210
+ // Without Codex in the selection there is no codex-runtime record to retain, and Codex runtimes retained earlier are
211
+ // removed in this run.
212
+ function planRetention(ownership, now, hosts) {
213
+ const removals = [];
214
+ const candidates = [];
215
+ const retiredAt = now.toISOString();
216
+ const keepsCodex = hosts.includes("codex");
217
+ if (ownership.version !== releaseVersion) {
218
+ for (const id of RETAINED_RUNTIME_IDS) {
219
+ const record = ownership.targets.find((candidate) => candidate.id === id);
220
+ // A codex-runtime record of a deselected Codex is removed by deselectedHostTargets.
221
+ if (!record || (id === "codex-runtime" && !keepsCodex)) continue;
222
+ if (id === "codex-runtime" && compareVersions(ownership.version, releaseVersion) >= 0) {
223
+ removals.push({ id: "previous-codex-runtime", phase: "cleanup", path: record.path, type: "tree", operation: "remove", ownedBy: id });
224
+ } else {
225
+ candidates.push({ entry: { id, version: ownership.version, path: record.path, installedDigest: record.installedDigest, retiredAt }, retiring: true });
226
+ }
227
+ }
228
+ }
229
+ for (const entry of ownership.retained) {
230
+ if (entry.id === "codex-runtime" && !keepsCodex) {
231
+ removals.push(retiredRuntimeTarget(entry, "cleanup"));
232
+ continue;
233
+ }
234
+ if (entry.version === releaseVersion) continue;
235
+ const expired = now.getTime() - Date.parse(entry.retiredAt) >= RETAINED_RUNTIME_GRACE_MS;
236
+ const shadowsRelease = entry.id === "codex-runtime" && compareVersions(entry.version, releaseVersion) >= 0;
237
+ if (expired || shadowsRelease) removals.push(retiredRuntimeTarget(entry, "cleanup"));
238
+ else candidates.push({ entry, retiring: false });
239
+ }
240
+ const retained = [];
241
+ for (const id of RETAINED_RUNTIME_IDS) {
242
+ const newestFirst = candidates.filter(({ entry }) => entry.id === id).sort((left, right) => (right.retiring - left.retiring)
243
+ || (Date.parse(right.entry.retiredAt) - Date.parse(left.entry.retiredAt)) || compareVersions(right.entry.version, left.entry.version));
244
+ for (const [index, { entry, retiring }] of newestFirst.entries()) {
245
+ if (index < RETAINED_RUNTIME_LIMIT) retained.push(entry);
246
+ else if (!retiring) removals.push(retiredRuntimeTarget(entry, "cleanup"));
247
+ }
248
+ }
249
+ return { removals, retained: retained.sort((left, right) => Date.parse(left.retiredAt) - Date.parse(right.retiredAt)) };
250
+ }
251
+
252
+ function retiredRuntimeTarget(entry, phase) {
253
+ return { id: `retired-${entry.id}-${entry.version}`, phase, path: entry.path, type: "tree", operation: "remove", retained: entry };
88
254
  }
89
255
 
90
256
  // Files are committed first; registering with Claude Code is idempotent, and a failure leaves the files
91
257
  // installed with a manual command to finish, instead of rolling back a working Codex/Antigravity install.
92
- function reportClaudeRegistration() {
93
- const manual = `claude plugin marketplace add ${JSON.stringify(claudePluginMarketplaceRoot)} && claude plugin install ${claudeRegistration.pluginId} --scope user`;
258
+ // A missing claude CLI is only advice (exit 0), except under `upgrade --auto`. Under `--auto` every Claude Code step
259
+ // left to the user exits AUTO_UPGRADE_EXIT.manual so the runner can tell it from other errors; a foreign `cairn`
260
+ // marketplace is not Cairn's to change and exits 0 as in a manual upgrade.
261
+ function reportClaudeRegistration({ auto = false, migrated = false } = {}) {
262
+ const register = `claude plugin marketplace add ${JSON.stringify(claudePluginMarketplaceRoot)} && claude plugin install ${claudeRegistration.pluginId} --scope user`;
263
+ // After a migration the 0.6.0-layout registration still points at the removed directory, and `marketplace add`
264
+ // fails on the name until it is removed.
265
+ const replaceLegacy = `claude plugin marketplace remove ${marketplaceName} && ${register}`;
266
+ const failedExit = auto ? AUTO_UPGRADE_EXIT.manual : 1;
94
267
  try {
95
268
  const result = claudeRegistration.register();
96
269
  if (result.registered) {
97
270
  console.log(`Claude Code plugin: ${claudeRegistration.pluginId} (${claudePluginMarketplaceRoot})`);
271
+ if (result.cacheRefresh && !result.cacheRefresh.refreshed) {
272
+ const refresh = `claude plugin marketplace update ${marketplaceName} && claude plugin update ${claudeRegistration.pluginId} --scope user`;
273
+ console.log(`Claude Code plugin cache refresh failed: ${result.cacheRefresh.reason}. To finish: ${refresh}`);
274
+ process.exitCode = failedExit;
275
+ }
98
276
  return;
99
277
  }
278
+ const manual = result.cliMissing && migrated ? replaceLegacy : register;
100
279
  console.log(`Claude Code plugin not registered: ${result.reason}. To register: ${manual}`);
280
+ if (auto && result.cliMissing) process.exitCode = AUTO_UPGRADE_EXIT.manual;
101
281
  } catch (error) {
282
+ // The 0.6.0-layout registration could not be removed, so the manual steps start by removing it.
283
+ const manual = error.legacyMarketplace ? replaceLegacy : register;
102
284
  console.log(`Claude Code plugin registration failed: ${error.message}. To register: ${manual}`);
103
- process.exitCode = 1;
285
+ process.exitCode = failedExit;
104
286
  }
105
287
  }
106
288
 
107
289
  async function uninstall() {
108
- await recoverInterruptedTransaction();
109
- const ownership = await readOwnership({ required: true });
110
- validateOwnershipShape(ownership, { required: true });
290
+ await recoverInterruptedTransactions();
291
+ if (legacy) {
292
+ await assertSingleOwnershipManifest();
293
+ // A 0.6.0-layout installation is removed in place by the legacy stack instead of being migrated first.
294
+ if (!(await exists(ownershipPath)) && await exists(legacyLayout.ownershipPath)) return legacy.commands.uninstall();
295
+ }
296
+ const recorded = await readOwnership({ required: true });
297
+ validateOwnershipShape(recorded, { required: true });
298
+ // A retained runtime that is already gone is not a conflict and has nothing left to remove.
299
+ const ownership = await withoutMissingRetained(recorded);
111
300
  const conflicts = [];
112
- for (const record of ownership.targets) {
301
+ const retiredRuntimes = (ownership.retained ?? []).map((entry) => retiredRuntimeTarget(entry, "core"));
302
+ for (const record of [...ownership.targets, ...retiredRuntimes.map((target) => ({ ...target, installedDigest: target.retained.installedDigest }))]) {
113
303
  const current = await targetDigest(record.path, record.type);
114
304
  if (record.type !== "config" && current !== record.installedDigest) conflicts.push(record.path);
115
305
  }
116
306
  if (conflicts.length > 0) throw new Error(`Refusing to uninstall modified managed artifacts: ${conflicts.join(", ")}`);
117
307
  // Unregister before removing files so Claude Code never points at a deleted plugin; a failure aborts with nothing changed.
118
- const unregistered = claudeRegistration.unregister().unregistered;
308
+ // Without Claude Code in the selection the claude CLI is never run.
309
+ const unregistered = hostsOf(ownership).includes("claude") ? claudeRegistration.unregister().unregistered : false;
119
310
  const transaction = await createTransaction();
120
311
  try {
121
312
  const configRecord = ownership.targets.find((record) => record.type === "config");
@@ -131,7 +322,10 @@ async function uninstall() {
131
322
  for (const record of ownership.targets.filter((candidate) => candidate.phase === phase).reverse()) await removeManagedTarget(record, transaction);
132
323
  }
133
324
  injectFailure("uninstall-after-external");
134
- for (const record of ownership.targets.filter((candidate) => candidate.phase === "codex").reverse()) await removeManagedTarget(record, transaction);
325
+ for (const phase of ["codex", "core"]) {
326
+ for (const record of ownership.targets.filter((candidate) => candidate.phase === phase).reverse()) await removeManagedTarget(record, transaction);
327
+ }
328
+ for (const target of retiredRuntimes) await removeManagedTarget(target, transaction);
135
329
  injectFailure("uninstall-after-codex");
136
330
  await removeManagedTarget({ id: "ownership", phase: "manifest", path: ownershipPath, type: "file" }, transaction);
137
331
  injectFailure("uninstall-after-ownership");
@@ -151,53 +345,80 @@ async function uninstall() {
151
345
  console.log(t("uninstallComplete"));
152
346
  }
153
347
 
348
+ // Only the selected hosts are checked, and only their host CLIs are run; without a valid manifest every host is checked.
349
+ // Version-dependent paths follow the installed version, so a CLI of another version checks the installation as it is.
154
350
  async function doctor() {
155
351
  const checks = [];
156
352
  const ownership = await readOwnership();
353
+ const hosts = hostsOf(ownership);
354
+ const selected = (host) => hosts.includes(host);
355
+ console.log(`Hosts: ${hosts.join(",")}`);
356
+ const installedVersion = typeof ownership?.version === "string" && VERSION_PATTERN.test(ownership.version) ? ownership.version : releaseVersion;
357
+ if (installedVersion !== releaseVersion) console.log(`CLI version ${releaseVersion} differs from installed version ${installedVersion}`);
358
+ const runtimeRoot = layout.runtimeRootFor(installedVersion);
359
+ const codexRuntimeRoot = layout.codexRuntimeRootFor(installedVersion);
360
+ const installedRuntimeLocatorPath = join(runtimeRoot, ".cairn-runtime.json");
157
361
  checks.push(["source", await exists(join(pluginRoot, ".codex-plugin", "plugin.json"))]);
158
362
  checks.push(["ownership manifest", Boolean(ownership)]);
159
363
  checks.push(["ownership digests", await ownershipDigestsValid(ownership)]);
160
- checks.push(["custom marketplace source", await exists(join(installedPluginRoot, ".codex-plugin", "plugin.json"))]);
161
- checks.push(["versioned runtime", await exists(join(versionedPluginRoot, ".codex-plugin", "plugin.json"))]);
162
- checks.push(["marketplace", await exists(marketplaceJsonPath)]);
163
- checks.push(["installed hooks manifest field", (await readJson(join(versionedPluginRoot, ".codex-plugin", "plugin.json")))?.hooks === "./hooks/hooks.json"]);
164
- checks.push(["hooks file", await exists(join(versionedPluginRoot, "hooks", "hooks.json"))]);
165
- checks.push(["installed runtime locator", await validRuntimeLocator(installedRuntimeLocatorPath, versionedPluginRoot)]);
166
- checks.push(["installed skill locators", (await Promise.all(skillNames().map((name) => validRuntimeLocator(installedSkillLocatorPath(versionedPluginRoot, name), versionedPluginRoot)))).every(Boolean)]);
167
- checks.push(["installed CLI script", await exists(join(versionedPluginRoot, "scripts", "cairn.mjs"))]);
168
- checks.push(["installed plan template", await exists(join(versionedPluginRoot, "templates", "work-plan.md"))]);
169
- checks.push(["installed model guidance", await exists(join(versionedPluginRoot, "docs", "model-guidance", "codex.md"))]);
170
- const config = (await readSharedConfigSnapshot(configPath)).text;
171
- checks.push(["config marketplace", splitSections(config).some((section) => section.header === "marketplaces.cairn")]);
172
- checks.push(["config plugin enabled", hasSetting(config, 'plugins."cairn@cairn"', "enabled", "true")]);
173
- checks.push(["Claude runtime locator", await validRuntimeLocator(claudeRuntimeLocatorPath, versionedPluginRoot)]);
174
- const claudePluginManifest = await readJson(join(claudePluginMarketplaceRoot, pluginName, ".claude-plugin", "plugin.json"));
175
- checks.push(["Claude plugin files", claudePluginManifest?.version === releaseVersion
176
- && await exists(join(claudePluginMarketplaceRoot, ".claude-plugin", "marketplace.json"))
177
- && await exists(join(claudePluginMarketplaceRoot, pluginName, "hooks", "hooks.json"))]);
178
- let claudeStatus = null;
179
- try { claudeStatus = claudeRegistration.status(); } catch { claudeStatus = null; }
180
- checks.push(["Claude plugin registered", Boolean(claudeStatus?.marketplace && claudeStatus.installed)]);
181
- checks.push(["Claude plugin enabled", Boolean(claudeStatus?.enabled)]);
182
- checks.push(["Antigravity IDE skills", await exists(join(antigravityHome, "skills", "cairn-plan", "SKILL.md"))]);
183
- checks.push(["Antigravity CLI flat skills", await exists(join(antigravityCliHome, "skills", "cairn-plan.md"))]);
184
-
185
- const codexStatus = hostJson(["plugin", "list", "--json"], { CODEX_HOME: codexHome });
186
- const codexEntry = findPluginStatus(codexStatus, "cairn@cairn");
187
- checks.push(["Codex plugin installed", Boolean(codexEntry?.installed)]);
188
- checks.push(["Codex plugin enabled", Boolean(codexEntry?.enabled)]);
189
- checks.push(["Codex plugin version", codexEntry?.version === releaseVersion]);
190
-
191
- const featureResult = spawnSync("codex", ["features", "list"], { encoding: "utf8", env: { ...process.env, CODEX_HOME: codexHome } });
192
- const featureStates = featureResult.status === 0 && !featureResult.error ? parseCodexFeatureList(featureResult.stdout) : null;
193
- checks.push(["Codex feature plugins", featureStates?.plugins === true]);
194
- checks.push(["Codex feature hooks", featureStates?.hooks === true]);
195
- checks.push(["Codex feature multi_agent", featureStates?.multi_agent === true]);
196
-
197
- const agy = spawnSync("agy", ["--version"], { encoding: "utf8", env: process.env });
198
- checks.push(["Antigravity CLI readiness", !agy.error && agy.status === 0 && /^\d+\.\d+\.\d+/.test(agy.stdout.trim())]);
199
- checks.push(["Antigravity CLI skill validation", await validateAntigravitySkills(antigravityCliHome, skillNames(), versionedPluginRoot)]);
364
+ if (selected("codex")) checks.push(["custom marketplace source", await exists(join(installedPluginRoot, ".codex-plugin", "plugin.json"))]);
365
+ checks.push(["canonical runtime", await exists(join(runtimeRoot, ".codex-plugin", "plugin.json"))]);
366
+ if (selected("codex")) {
367
+ checks.push(["versioned runtime", await exists(join(codexRuntimeRoot, ".codex-plugin", "plugin.json"))]);
368
+ checks.push(["marketplace", await exists(marketplaceJsonPath)]);
369
+ checks.push(["installed hooks manifest field", (await readJson(join(codexRuntimeRoot, ".codex-plugin", "plugin.json")))?.hooks === "./hooks/hooks.json"]);
370
+ checks.push(["hooks file", await exists(join(codexRuntimeRoot, "hooks", "hooks.json"))]);
371
+ }
372
+ checks.push(["installed runtime locator", await validRuntimeLocator(installedRuntimeLocatorPath, runtimeRoot)]);
373
+ checks.push(["installed skill locators", (await Promise.all(skillNames().map((name) => validRuntimeLocator(installedSkillLocatorPath(runtimeRoot, name), runtimeRoot)))).every(Boolean)]);
374
+ checks.push(["installed CLI script", await exists(join(runtimeRoot, "scripts", "cairn.mjs"))]);
375
+ checks.push(["installed plan template", await exists(join(runtimeRoot, "templates", "work-plan.md"))]);
376
+ checks.push(["installed model guidance", await exists(join(runtimeRoot, "docs", "model-guidance", "codex.md"))]);
377
+ if (selected("codex")) {
378
+ const config = (await readSharedConfigSnapshot(configPath)).text;
379
+ checks.push(["config marketplace", splitSections(config).some((section) => section.header === "marketplaces.cairn")]);
380
+ checks.push(["config plugin enabled", hasSetting(config, 'plugins."cairn@cairn"', "enabled", "true")]);
381
+ }
382
+ if (selected("claude")) {
383
+ checks.push(["Claude runtime locator", await validRuntimeLocator(claudeRuntimeLocatorPath, runtimeRoot)]);
384
+ const claudePluginManifest = await readJson(join(claudePluginMarketplaceRoot, pluginName, ".claude-plugin", "plugin.json"));
385
+ checks.push(["Claude plugin files", claudePluginManifest?.version === installedVersion
386
+ && await exists(join(claudePluginMarketplaceRoot, ".claude-plugin", "marketplace.json"))
387
+ && await exists(join(claudePluginMarketplaceRoot, pluginName, "hooks", "hooks.json"))]);
388
+ let claudeStatus = null;
389
+ try { claudeStatus = claudeRegistration.status(); } catch { claudeStatus = null; }
390
+ checks.push(["Claude plugin registered", Boolean(claudeStatus?.marketplace && claudeStatus.installed)]);
391
+ checks.push(["Claude plugin enabled", Boolean(claudeStatus?.enabled)]);
392
+ checks.push(["Claude plugin cache version", claudeStatus?.version === installedVersion]);
393
+ }
394
+ if (selected("antigravity")) {
395
+ checks.push(["Antigravity IDE skills", await exists(join(antigravityHome, "skills", "cairn-plan", "SKILL.md"))]);
396
+ checks.push(["Antigravity CLI flat skills", await exists(join(antigravityCliHome, "skills", "cairn-plan.md"))]);
397
+ }
398
+
399
+ if (selected("codex")) {
400
+ const codexStatus = hostJson(["plugin", "list", "--json"], { CODEX_HOME: codexHome });
401
+ const codexEntry = findPluginStatus(codexStatus, "cairn@cairn");
402
+ checks.push(["Codex plugin installed", Boolean(codexEntry?.installed)]);
403
+ checks.push(["Codex plugin enabled", Boolean(codexEntry?.enabled)]);
404
+ checks.push(["Codex plugin version", codexEntry?.version === installedVersion]);
405
+
406
+ const featureResult = spawnSync("codex", ["features", "list"], { encoding: "utf8", env: { ...process.env, CODEX_HOME: codexHome } });
407
+ const featureStates = featureResult.status === 0 && !featureResult.error ? parseCodexFeatureList(featureResult.stdout) : null;
408
+ checks.push(["Codex feature plugins", featureStates?.plugins === true]);
409
+ checks.push(["Codex feature hooks", featureStates?.hooks === true]);
410
+ checks.push(["Codex feature multi_agent", featureStates?.multi_agent === true]);
411
+ }
412
+
413
+ if (selected("antigravity")) {
414
+ const agy = spawnSync("agy", ["--version"], { encoding: "utf8", env: process.env });
415
+ checks.push(["Antigravity CLI readiness", !agy.error && agy.status === 0 && /^\d+\.\d+\.\d+/.test(agy.stdout.trim())]);
416
+ checks.push(["Antigravity CLI skill validation", await validateAntigravitySkills(antigravityCliHome, skillNames(), runtimeRoot)]);
417
+ }
200
418
  for (const [name, ok] of checks) console.log(`${ok ? "OK" : "FAIL"} ${name}`);
419
+ if (!ownership && legacyLayout && await exists(legacyLayout.ownershipPath)) {
420
+ console.log(`Legacy installation found at ${legacyLayout.installRoot}; run cairn upgrade to migrate`);
421
+ }
201
422
  if (checks.some(([, ok]) => !ok)) process.exitCode = 1;
202
423
  }
203
424
 
@@ -206,6 +427,61 @@ async function doctor() {
206
427
  if (process.env.CAIRN_TEST_FAIL_PHASE === point) throw new Error(`Injected lifecycle failure: ${point}`);
207
428
  }
208
429
 
430
+ // The legacy journal is recovered first so the legacy manifest and artifacts are whole before the current
431
+ // journal (which may hold a migration that moved them) is rolled back.
432
+ async function recoverInterruptedTransactions() {
433
+ if (legacy) await legacy.transaction.recoverInterruptedTransaction();
434
+ await recoverInterruptedTransaction();
435
+ }
436
+
437
+ async function assertSingleOwnershipManifest() {
438
+ if (await exists(ownershipPath) && await exists(legacyLayout.ownershipPath)) {
439
+ throw new Error(`Both legacy and current ownership manifests exist: ${legacyLayout.ownershipPath}, ${ownershipPath}`);
440
+ }
441
+ }
442
+
443
+ // The 0.6.0 layout used the same ids at other paths. Its adoption checks run against those paths; ids without a
444
+ // legacy counterpart (the canonical runtime) are skipped.
445
+ function legacyLayoutTargets(targets) {
446
+ const mapped = [];
447
+ for (const target of targets) {
448
+ const expected = legacy.integrity.expectedManagedTarget(target.id);
449
+ if (expected) mapped.push({ ...target, path: expected.path });
450
+ }
451
+ return mapped;
452
+ }
453
+
454
+ function legacyRemovalTargets(ownership) {
455
+ const removals = ownership.targets.filter((record) => Object.hasOwn(legacyRootRemovals, record.id)).map((record) => ({
456
+ id: legacyRootRemovals[record.id], phase: "cleanup", path: record.path, type: record.type, operation: "remove", ownedBy: record.id,
457
+ }));
458
+ // Runtime retention does not apply to a migration: the legacy runtime is the Codex cache copy.
459
+ if (ownership.version !== releaseVersion && ownership.targets.some((record) => record.id === "codex-runtime")) {
460
+ removals.push({ id: "previous-codex-runtime", phase: "cleanup", path: layout.codexRuntimeRootFor(ownership.version), type: "tree", operation: "remove", ownedBy: "codex-runtime" });
461
+ }
462
+ return removals;
463
+ }
464
+
465
+ // Only empty directories are removed, so unmanaged children keep their parents; the legacy state root and the
466
+ // legacy root itself are pruned after the legacy lock is released.
467
+ async function pruneLegacyScaffolds() {
468
+ for (const path of [
469
+ join(legacyLayout.marketplaceRoot, "plugins"), join(legacyLayout.marketplaceRoot, ".agents", "plugins"),
470
+ join(legacyLayout.marketplaceRoot, ".agents"), legacyLayout.transactionRoot,
471
+ ]) {
472
+ try { await rmdir(path); }
473
+ catch (error) { if (!["ENOENT", "ENOTEMPTY", "EEXIST"].includes(error?.code)) throw error; }
474
+ }
475
+ }
476
+
477
+ // The installed copies live under the install root or the Codex cache; comparing real paths keeps a symlinked
478
+ // temp or home directory from hiding that the CLI was started from one of them.
479
+ function isInsidePath(root, candidate) {
480
+ const real = (path) => { try { return realpathSync(path); } catch { return resolve(path); } };
481
+ const [base, path] = [real(root), real(candidate)];
482
+ return path === base || path.startsWith(`${base}${sep}`);
483
+ }
484
+
209
485
  function hostJson(args, extraEnv = {}) {
210
486
  const result = spawnSync("codex", args, { encoding: "utf8", env: { ...process.env, ...extraEnv } });
211
487
  if (result.error || result.status !== 0) return null;