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.
@@ -0,0 +1,98 @@
1
+ import { createInterface } from "node:readline";
2
+
3
+ // Hosts Cairn can install into, in canonical order. The ownership manifest records a non-empty subset in this order.
4
+ export const HOSTS = ["codex", "claude", "antigravity"];
5
+ const HOST_LABELS = { codex: "Codex", claude: "Claude Code", antigravity: "Antigravity" };
6
+ const PROMPT_ATTEMPTS = 3;
7
+
8
+ export function isHostSelection(hosts) {
9
+ return Array.isArray(hosts) && hosts.length > 0 && hosts.length <= HOSTS.length
10
+ && hosts.every((host, index) => HOSTS.includes(host) && (index === 0 || HOSTS.indexOf(hosts[index - 1]) < HOSTS.indexOf(host)));
11
+ }
12
+
13
+ // `all` or a comma-separated list of host ids; the result is in canonical order. Missing, empty, unknown, and
14
+ // duplicate values are rejected so nothing is locked or staged for a selection the user did not mean.
15
+ export function parseHostsOption(value) {
16
+ if (typeof value !== "string" || value.length === 0) throw new Error(`Invalid --hosts value: ${value === undefined ? "missing" : "empty"}`);
17
+ if (value === "all") return [...HOSTS];
18
+ const names = value.split(",").map((name) => name.trim());
19
+ const seen = new Set();
20
+ for (const name of names) {
21
+ if (name.length === 0) throw new Error(`Invalid --hosts value: ${value} (empty host name)`);
22
+ if (!HOSTS.includes(name)) throw new Error(`Invalid --hosts value: ${value} (unknown host ${name}; use all or ${HOSTS.join(",")})`);
23
+ if (seen.has(name)) throw new Error(`Invalid --hosts value: ${value} (duplicate host ${name})`);
24
+ seen.add(name);
25
+ }
26
+ return HOSTS.filter((host) => seen.has(host));
27
+ }
28
+
29
+ // The host a managed or journal-only target belongs to; `core` targets are installed for every selection.
30
+ export function hostOfTarget(id) {
31
+ if (id === "runtime" || id === "ownership" || id === "legacy-ownership" || id.startsWith("retired-runtime-")) return "core";
32
+ if (["codex-source", "marketplace", "codex-runtime", "codex-config", "previous-codex-runtime", "legacy-root-codex-source", "legacy-root-marketplace"].includes(id)
33
+ || id.startsWith("retired-codex-runtime-")) return "codex";
34
+ if (id.startsWith("claude-") || id === "legacy-root-claude-plugin") return "claude";
35
+ if (/^(?:legacy-)?(?:ide|cli)-/.test(id)) return "antigravity";
36
+ return null;
37
+ }
38
+
39
+ export function hostLabels(hosts) {
40
+ return hosts.map((host) => HOST_LABELS[host]).join(", ");
41
+ }
42
+
43
+ function promptText(ko) {
44
+ return ko ? [
45
+ "Cairn을 설치할 호스트를 선택하세요.",
46
+ " 1) 전체 — Codex, Claude Code, Antigravity (기본)",
47
+ " 2) Claude Code만",
48
+ " 3) Codex만",
49
+ " 4) Antigravity만",
50
+ "번호를 입력하거나 호스트 이름을 쉼표로 구분해 입력하세요 (codex,claude,antigravity) [1]: ",
51
+ ] : [
52
+ "Select the hosts to install Cairn into.",
53
+ " 1) All — Codex, Claude Code, Antigravity (default)",
54
+ " 2) Claude Code only",
55
+ " 3) Codex only",
56
+ " 4) Antigravity only",
57
+ "Enter a number, or host names separated by commas (codex,claude,antigravity) [1]: ",
58
+ ];
59
+ }
60
+
61
+ export function parseHostsAnswer(answer) {
62
+ const value = answer.trim();
63
+ const choices = { "": HOSTS, 1: HOSTS, 2: ["claude"], 3: ["codex"], 4: ["antigravity"] };
64
+ if (Object.hasOwn(choices, value)) return [...choices[value]];
65
+ return parseHostsOption(value);
66
+ }
67
+
68
+ // Asks once, re-asks after an invalid answer, and gives up after three attempts or at end of input. An empty answer
69
+ // selects every host. The caller asks before taking the lifecycle lock, so a waiting prompt never blocks another run.
70
+ export async function promptHosts({ input, output, ko = false }) {
71
+ const lines = promptText(ko);
72
+ const question = lines.at(-1);
73
+ const reader = createInterface({ input, terminal: false });
74
+ const answers = reader[Symbol.asyncIterator]();
75
+ try {
76
+ output.write(lines.join("\n"));
77
+ for (let attempt = 1; attempt <= PROMPT_ATTEMPTS; attempt += 1) {
78
+ if (attempt > 1) output.write(question);
79
+ const next = await answers.next();
80
+ if (next.done) {
81
+ output.write("\n");
82
+ break;
83
+ }
84
+ try {
85
+ const hosts = parseHostsAnswer(next.value);
86
+ output.write(ko
87
+ ? `선택한 호스트: ${hostLabels(hosts)}. 나중에 바꾸려면: cairn install --hosts <목록>\n`
88
+ : `Selected hosts: ${hostLabels(hosts)}. To change later: cairn install --hosts <list>\n`);
89
+ return hosts;
90
+ } catch {
91
+ output.write(ko ? `잘못된 입력입니다: ${next.value.trim()}\n` : `Invalid selection: ${next.value.trim()}\n`);
92
+ }
93
+ }
94
+ } finally {
95
+ reader.close();
96
+ }
97
+ throw new Error("No valid host selection was entered.");
98
+ }
@@ -2,18 +2,41 @@ import { createHash } from "node:crypto";
2
2
  import { lstat, readFile, readdir } from "node:fs/promises";
3
3
  import { basename, join, relative, sep } from "node:path";
4
4
  import { cairnConfigProjection, readSharedConfigSnapshot } from "./cairn-lifecycle-config.mjs";
5
+ import { HOSTS, hostOfTarget, isHostSelection } from "./cairn-lifecycle-hosts.mjs";
5
6
  import { createLegacyIntegrity } from "./cairn-lifecycle-legacy.mjs";
6
7
  import { antigravityRuntimeLocatorPath } from "./cairn-lifecycle-mirror.mjs";
7
8
 
9
+ export const OWNERSHIP_SCHEMA_VERSION = 2;
10
+ export const OWNERSHIP_ORIGINS = ["checkout", "package"];
11
+ // Runtimes a version change leaves behind stay for open sessions: at most this many per id, for this long.
12
+ export const RETAINED_RUNTIME_IDS = ["runtime", "codex-runtime"];
13
+ export const RETAINED_RUNTIME_LIMIT = 3;
14
+ export const RETAINED_RUNTIME_GRACE_MS = 3 * 24 * 60 * 60 * 1000;
15
+ const VERSION_PATTERN = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
16
+
17
+ // Orders release versions by major.minor.patch; a prerelease suffix compares equal to its release.
18
+ export function compareVersions(left, right) {
19
+ const parse = (value) => String(value).split("-")[0].split(".").map(Number);
20
+ const [a, b] = [parse(left), parse(right)];
21
+ for (let index = 0; index < 3; index += 1) if (a[index] !== b[index]) return a[index] - b[index];
22
+ return 0;
23
+ }
24
+
8
25
  export function createIntegrity(context) {
9
26
  const {
10
27
  antigravityCliHome, antigravityHome, claudeHome, claudePluginMarketplaceRoot, claudeRuntimeLocatorPath,
11
- commandNames, configPath, installedPluginRoot, legacyAntigravityHome,
12
- marketplaceJsonPath, marketplaceRoot, ownershipPath, phases, pluginName,
28
+ commandNames, configPath, installedPluginRoot, layout, legacyAntigravityHome,
29
+ marketplaceJsonPath, ownershipPath, phases, pluginName,
13
30
  releaseVersion, skillNames,
14
31
  } = context;
32
+ // The current layout writes schema 2; a legacy stack built from layout.legacy validates schema 1 unchanged.
33
+ const ownershipSchemaVersion = context.ownershipSchemaVersion ?? OWNERSHIP_SCHEMA_VERSION;
34
+ // A journal-only removal (previous runtime, legacy root) names the record it removes with `ownedBy` and must match
35
+ // that record's path, type, and digest. A record claimed that way moves away from its id, so the new target with the
36
+ // same id at a different path starts unowned. A retired-runtime removal carries its `retained` entry instead.
15
37
  async function assertTargetsReplaceable(targets, ownership) {
16
38
  const records = new Map((ownership?.targets ?? []).map((record) => [record.id, record]));
39
+ const moved = new Set(targets.filter((target) => target.ownedBy).map((target) => target.ownedBy));
17
40
  for (const target of targets) {
18
41
  if (!(await exists(target.path))) {
19
42
  target.preflightDigest = "missing";
@@ -21,26 +44,37 @@ async function assertTargetsReplaceable(targets, ownership) {
21
44
  }
22
45
  const current = await targetDigest(target.path, target.type);
23
46
  target.preflightDigest = current;
24
- if (target.id === "previous-codex-runtime") {
25
- const previous = records.get("codex-runtime");
26
- if (!previous || previous.path !== target.path || previous.type !== target.type) throw new Error("Previous runtime does not match ownership manifest.");
47
+ if (target.ownedBy || target.retained) {
48
+ const owner = target.retained ? { ...target.retained, type: "tree" } : records.get(target.ownedBy);
49
+ if (!owner || owner.path !== target.path || owner.type !== target.type) throw new Error(`Removal target does not match ownership manifest: ${target.id}`);
50
+ if (target.type !== "config" && current !== owner.installedDigest) throw new Error(`Managed artifact was modified: ${target.path}`);
51
+ continue;
52
+ }
53
+ const claimed = records.get(target.id);
54
+ const record = claimed && !(moved.has(target.id) && claimed.path !== target.path) ? claimed : undefined;
55
+ const versionedRuntime = target.id === "runtime" || target.id === "codex-runtime";
56
+ // After a version change the release's runtime is owned only when an earlier upgrade retained it. A removal
57
+ // (a deselected host's record) is checked against its own record below.
58
+ if (versionedRuntime && target.operation !== "remove" && ownership && ownership.version !== releaseVersion) {
59
+ const retained = (ownership.retained ?? []).find((entry) => entry.id === target.id && entry.version === releaseVersion);
60
+ if (!retained || retained.path !== target.path || target.type !== "tree") {
61
+ throw new Error(`Refusing to overwrite unmanaged current-version runtime: ${target.path}`);
62
+ }
63
+ if (current !== retained.installedDigest) throw new Error(`Managed artifact was modified: ${target.path}`);
27
64
  continue;
28
65
  }
29
- const record = records.get(target.id);
30
66
  if (!record) {
31
67
  if (target.type === "config" && cairnConfigProjection((await readSharedConfigSnapshot(target.path)).text).length === 0) continue;
68
+ if (claimed && versionedRuntime) throw new Error(`Refusing to overwrite unmanaged current-version runtime: ${target.path}`);
32
69
  throw new Error(`Refusing to overwrite unmanaged artifact: ${target.path}`);
33
70
  }
34
- if (target.id === "codex-runtime" && ownership?.version !== releaseVersion) {
35
- throw new Error(`Refusing to overwrite unmanaged current-version runtime: ${target.path}`);
36
- }
37
71
  if (record.path !== target.path || record.type !== target.type) throw new Error(`Ownership manifest target mismatch: ${target.id}`);
38
72
  if (target.type !== "config" && current !== record.installedDigest) throw new Error(`Managed artifact was modified: ${target.path}`);
39
73
  }
40
74
  }
41
75
 
42
76
  async function assertOwnershipDigests(ownership) {
43
- for (const record of ownership.targets) {
77
+ for (const record of [...ownership.targets, ...(ownership.retained ?? []).map((entry) => ({ ...entry, type: "tree" }))]) {
44
78
  const current = await targetDigest(record.path, record.type);
45
79
  if (record.type !== "config" && current !== record.installedDigest) {
46
80
  throw new Error(`Managed artifact was modified: ${record.path}`);
@@ -48,6 +82,16 @@ async function assertOwnershipDigests(ownership) {
48
82
  }
49
83
  }
50
84
 
85
+ // A retained runtime that no longer exists was removed outside Cairn (by Codex or the user) and counts as already
86
+ // gone: install, upgrade, and uninstall drop it from the manifest instead of removing or recording it, and doctor does
87
+ // not report it. One that exists with other content is still a modified managed artifact.
88
+ async function withoutMissingRetained(ownership) {
89
+ if (!Array.isArray(ownership?.retained)) return ownership;
90
+ const retained = [];
91
+ for (const entry of ownership.retained) if (await exists(entry.path)) retained.push(entry);
92
+ return { ...ownership, retained };
93
+ }
94
+
51
95
  async function targetRecord(target) {
52
96
  return { id: target.id, phase: target.phase, path: target.path, type: target.type, installedDigest: await targetDigest(target.path, target.type), previous: null };
53
97
  }
@@ -69,14 +113,39 @@ function validateOwnershipShape(ownership, { required = false } = {}) {
69
113
  if (required) throw new Error("Ownership manifest is required.");
70
114
  return;
71
115
  }
72
- if (!sameKeys(ownership, ["schemaVersion", "plugin", "version", "transactionId", "installedAt", "targets"])
73
- || ownership.schemaVersion !== 1 || ownership.plugin !== pluginName
74
- || typeof ownership.version !== "string" || !/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(ownership.version)
116
+ if (ownershipSchemaVersion === 1) {
117
+ if (!sameKeys(ownership, ["schemaVersion", "plugin", "version", "transactionId", "installedAt", "targets"])
118
+ || ownership.schemaVersion !== 1 || ownership.plugin !== pluginName
119
+ || typeof ownership.version !== "string" || !/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(ownership.version)
120
+ || typeof ownership.transactionId !== "string" || !/^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/i.test(ownership.transactionId)
121
+ || typeof ownership.installedAt !== "string" || Number.isNaN(Date.parse(ownership.installedAt))
122
+ || !Array.isArray(ownership.targets)) {
123
+ throw new Error("Ownership manifest schema or plugin identity is invalid.");
124
+ }
125
+ } else if (!sameKeys(ownership, ["schemaVersion", "plugin", "version", "transactionId", "installedAt", "origin", "hosts", "targets", "retained"])
126
+ || ownership.schemaVersion !== OWNERSHIP_SCHEMA_VERSION || ownership.plugin !== pluginName
127
+ || typeof ownership.version !== "string" || !VERSION_PATTERN.test(ownership.version)
75
128
  || typeof ownership.transactionId !== "string" || !/^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/i.test(ownership.transactionId)
76
129
  || typeof ownership.installedAt !== "string" || Number.isNaN(Date.parse(ownership.installedAt))
77
- || !Array.isArray(ownership.targets)) {
130
+ || !OWNERSHIP_ORIGINS.includes(ownership.origin)
131
+ || !isHostSelection(ownership.hosts)
132
+ || !Array.isArray(ownership.targets) || !Array.isArray(ownership.retained)) {
78
133
  throw new Error("Ownership manifest schema or plugin identity is invalid.");
79
134
  }
135
+ const retainedKeys = new Set();
136
+ for (const record of ownership.retained ?? []) {
137
+ if (!record || !sameKeys(record, ["id", "version", "path", "installedDigest", "retiredAt"])
138
+ || !RETAINED_RUNTIME_IDS.includes(record.id) || typeof record.version !== "string" || !VERSION_PATTERN.test(record.version)
139
+ || record.version === ownership.version || retainedKeys.has(`${record.id}\0${record.version}`)
140
+ || record.path !== retainedRuntimePath(record.id, record.version)
141
+ || typeof record.installedDigest !== "string" || !/^sha256:[a-f0-9]{64}$/.test(record.installedDigest)
142
+ || typeof record.retiredAt !== "string" || Number.isNaN(Date.parse(record.retiredAt))
143
+ || ownership.retained.filter((entry) => entry?.id === record.id).length > RETAINED_RUNTIME_LIMIT
144
+ || (record.id === "codex-runtime" && !ownership.hosts.includes("codex"))) {
145
+ throw new Error("Ownership manifest contains an invalid retained runtime.");
146
+ }
147
+ retainedKeys.add(`${record.id}\0${record.version}`);
148
+ }
80
149
  const ids = new Set();
81
150
  const paths = new Set();
82
151
  for (const record of ownership.targets) {
@@ -96,36 +165,41 @@ function validateOwnershipShape(ownership, { required = false } = {}) {
96
165
  ids.add(record.id);
97
166
  paths.add(record.path);
98
167
  }
99
- const requiredTargets = requiredOwnershipTargets(ownership.version);
168
+ // Schema 1 predates host selection and always held every host.
169
+ const hosts = ownershipSchemaVersion === 1 ? HOSTS : ownership.hosts;
170
+ const unselected = [...ids].find((id) => !hosts.includes(hostOfTarget(id)) && hostOfTarget(id) !== "core");
171
+ if (unselected) throw new Error(`Ownership manifest schema is inconsistent: ${unselected} belongs to a host that is not selected.`);
172
+ const requiredTargets = requiredOwnershipTargets(ownership.version, hosts);
100
173
  const optionalIds = new Set(requiredTargets.has("claude-plugin") ? [] : ["claude-plugin"]);
101
174
  if ([...ids].some((id) => !requiredTargets.has(id) && !optionalIds.has(id)) || [...requiredTargets.keys()].some((id) => !ids.has(id))) {
102
175
  throw new Error("Ownership manifest does not contain the complete managed target set.");
103
176
  }
104
177
  }
105
178
 
106
- const CLAUDE_PLUGIN_SINCE = "0.2.9";
107
-
108
- function compareVersions(left, right) {
109
- const parse = (value) => String(value).split("-")[0].split(".").map(Number);
110
- const [a, b] = [parse(left), parse(right)];
111
- for (let index = 0; index < 3; index += 1) if (a[index] !== b[index]) return a[index] - b[index];
112
- return 0;
179
+ function retainedRuntimePath(id, version) {
180
+ return id === "runtime" ? layout.runtimeRootFor(version) : layout.codexRuntimeRootFor(version);
113
181
  }
114
182
 
115
- function requiredOwnershipTargets(version = releaseVersion) {
183
+ const CLAUDE_PLUGIN_SINCE = "0.2.9";
184
+
185
+ // The core runtime is always required; every other required target belongs to one selected host.
186
+ function requiredOwnershipTargets(version = releaseVersion, hosts = HOSTS) {
116
187
  const ids = ["codex-source", "codex-runtime", "marketplace", "claude-runtime", "ide-runtime", "cli-runtime", "codex-config"];
117
- // Manifests written before the Claude Code plugin existed must stay valid so those installs can upgrade.
118
- if (compareVersions(version, CLAUDE_PLUGIN_SINCE) >= 0) ids.push("claude-plugin");
188
+ if (ownershipSchemaVersion !== 1) ids.unshift("runtime");
189
+ // Schema 1 manifests written before the Claude Code plugin existed must stay valid so those installs can upgrade.
190
+ if (ownershipSchemaVersion !== 1 || compareVersions(version, CLAUDE_PLUGIN_SINCE) >= 0) ids.push("claude-plugin");
119
191
  for (const name of commandNames()) ids.push(`claude-command-${name}`, `ide-workflow-${name}`, `cli-workflow-${name}`);
120
192
  for (const name of ["explorer", "worker"]) ids.push(`claude-agent-${name}`);
121
193
  for (const name of skillNames()) ids.push(`ide-skill-${name}`, `cli-skill-${name}`);
122
- return new Map(ids.map((id) => [id, expectedManagedTarget(id, version)]));
194
+ const selected = ids.filter((id) => hostOfTarget(id) === "core" || hosts.includes(hostOfTarget(id)));
195
+ return new Map(selected.map((id) => [id, expectedManagedTarget(id, version)]));
123
196
  }
124
197
 
125
198
  function expectedManagedTarget(id, version = releaseVersion) {
126
199
  const exact = {
200
+ ...(ownershipSchemaVersion === 1 ? {} : { runtime: { phase: "core", path: layout.runtimeRootFor(version), type: "tree" } }),
127
201
  "codex-source": { phase: "codex", path: installedPluginRoot, type: "tree" },
128
- "codex-runtime": { phase: "codex", path: versionedRuntimeRoot(version), type: "tree" },
202
+ "codex-runtime": { phase: "codex", path: layout.codexRuntimeRootFor(version), type: "tree" },
129
203
  marketplace: { phase: "codex", path: marketplaceJsonPath, type: "file" },
130
204
  "claude-runtime": { phase: "claude", path: claudeRuntimeLocatorPath, type: "file" },
131
205
  "claude-plugin": { phase: "claude", path: claudePluginMarketplaceRoot, type: "tree" },
@@ -151,11 +225,6 @@ function expectedManagedTarget(id, version = releaseVersion) {
151
225
  return null;
152
226
  }
153
227
 
154
- function versionedRuntimeRoot(version) {
155
- if (typeof version !== "string" || !/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(version)) throw new Error(`Invalid Cairn runtime version: ${version}`);
156
- return join(marketplaceRoot, pluginName, version);
157
- }
158
-
159
228
  async function anyManagedArtifactExists(targets) {
160
229
  for (const target of targets) {
161
230
  if (!(await exists(target.path))) continue;
@@ -207,6 +276,10 @@ function sha(value) {
207
276
  try {
208
277
  validateOwnershipShape(ownership, { required: true });
209
278
  for (const record of ownership.targets) if (await targetDigest(record.path, record.type) !== record.installedDigest) return false;
279
+ for (const record of ownership.retained ?? []) {
280
+ const digest = await targetDigest(record.path, "tree");
281
+ if (digest !== "missing" && digest !== record.installedDigest) return false;
282
+ }
210
283
  return true;
211
284
  } catch {
212
285
  return false;
@@ -217,7 +290,7 @@ function sha(value) {
217
290
  return {
218
291
  ...legacy, anyManagedArtifactExists, assertOwnershipDigests, assertRegularTree,
219
292
  assertTargetsReplaceable, expectedManagedTarget, ownershipDigestsValid, readOwnership,
220
- targetDigest, targetRecord, validateOwnershipShape, versionedRuntimeRoot,
293
+ targetDigest, targetRecord, validateOwnershipShape, withoutMissingRetained,
221
294
  };
222
295
 
223
296
  function sameKeys(value, expected) {
@@ -0,0 +1,69 @@
1
+ import { homedir } from "node:os";
2
+ import { join, resolve } from "node:path";
3
+ import { cairnHome, installRoot as cairnInstallRoot, installManifestPath } from "./cairn-paths.mjs";
4
+
5
+ const VERSION_PATTERN = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
6
+
7
+ // Path constants for the lifecycle. `current` is the <cairnHome>/install layout; `legacy` keeps the 0.6.0
8
+ // constants (everything under $CODEX_HOME/plugins/cache/cairn) byte for byte so a legacy stack can read it.
9
+ // Codex only treats cairn@cairn as installed when its own plugin cache holds cairn/<version>, so that host
10
+ // cache stays under CODEX_HOME in both layouts.
11
+ export function createLayout({ env = process.env, releaseVersion, marketplaceName = "cairn", pluginName = "cairn" }) {
12
+ if (typeof releaseVersion !== "string" || !VERSION_PATTERN.test(releaseVersion)) throw new Error(`Invalid Cairn release version: ${releaseVersion}`);
13
+ const homeRoot = env.HOME ?? env.USERPROFILE ?? homedir() ?? ".";
14
+ const codexHome = resolve(env.CODEX_HOME ?? join(homeRoot, ".codex"));
15
+ const cairnHomeRoot = cairnHome(env);
16
+ const codexCacheRoot = join(codexHome, "plugins", "cache", marketplaceName);
17
+ const codexRuntimeParent = join(codexCacheRoot, pluginName);
18
+ const shared = { cairnHomeRoot, codexHome, codexCacheRoot, codexRuntimeParent };
19
+
20
+ const installRoot = cairnInstallRoot(env);
21
+ const codexMarketplaceRoot = join(installRoot, "codex");
22
+ const current = layoutPaths({
23
+ ...shared,
24
+ installRoot,
25
+ stateRoot: installRoot,
26
+ ownershipPath: installManifestPath(env),
27
+ marketplaceRoot: codexMarketplaceRoot,
28
+ installedPluginRoot: join(codexMarketplaceRoot, "plugins", pluginName),
29
+ marketplaceJsonPath: join(codexMarketplaceRoot, ".agents", "plugins", "marketplace.json"),
30
+ claudePluginMarketplaceRoot: join(installRoot, "claude"),
31
+ runtimeParent: join(installRoot, "runtime"),
32
+ }, releaseVersion);
33
+
34
+ const legacyStateRoot = join(codexCacheRoot, ".cairn");
35
+ const legacy = layoutPaths({
36
+ ...shared,
37
+ installRoot: codexCacheRoot,
38
+ stateRoot: legacyStateRoot,
39
+ ownershipPath: join(legacyStateRoot, "lifecycle.json"),
40
+ marketplaceRoot: codexCacheRoot,
41
+ installedPluginRoot: join(codexCacheRoot, "plugins", pluginName),
42
+ marketplaceJsonPath: join(codexCacheRoot, ".agents", "plugins", "marketplace.json"),
43
+ claudePluginMarketplaceRoot: join(codexCacheRoot, "claude"),
44
+ // 0.6.0 locators point at the Codex cache runtime.
45
+ runtimeParent: codexRuntimeParent,
46
+ }, releaseVersion);
47
+
48
+ return { current, legacy };
49
+ }
50
+
51
+ function layoutPaths(paths, releaseVersion) {
52
+ const runtimeRootFor = (version) => versionedChild(paths.runtimeParent, version);
53
+ const codexRuntimeRootFor = (version) => versionedChild(paths.codexRuntimeParent, version);
54
+ return {
55
+ ...paths,
56
+ transactionPath: join(paths.stateRoot, "transaction.json"),
57
+ transactionRoot: join(paths.stateRoot, "transactions"),
58
+ lifecycleLockPath: join(paths.stateRoot, "lifecycle.lock"),
59
+ runtimeRoot: runtimeRootFor(releaseVersion),
60
+ codexRuntimeRoot: codexRuntimeRootFor(releaseVersion),
61
+ runtimeRootFor,
62
+ codexRuntimeRootFor,
63
+ };
64
+ }
65
+
66
+ function versionedChild(parent, version) {
67
+ if (typeof version !== "string" || !VERSION_PATTERN.test(version)) throw new Error(`Invalid Cairn runtime version: ${version}`);
68
+ return join(parent, version);
69
+ }
@@ -5,23 +5,47 @@ import {
5
5
  antigravityRuntimeLocatorPath, antigravitySkillLocatorPath, renderMirrorFile, writeLocator,
6
6
  } from "./cairn-lifecycle-mirror.mjs";
7
7
  import { stageClaudePlugin } from "./cairn-lifecycle-claude.mjs";
8
+ import { HOSTS } from "./cairn-lifecycle-hosts.mjs";
8
9
 
9
10
  export function createStaging(context) {
10
11
  const {
11
12
  agentNames, antigravityCliHome, antigravityHome, claudeHome, claudePluginMarketplaceRoot,
12
- claudeRuntimeLocatorPath, commandNames, releaseVersion, configPath, installedPluginRoot,
13
+ claudeRuntimeLocatorPath, codexRuntimeRoot, commandNames, releaseVersion, configPath, installedPluginRoot,
13
14
  legacyAntigravityHome, marketplaceJsonPath, marketplaceName, pluginName,
14
- pluginRoot, skillNames, updateConfig, versionedPluginRoot, assertRegularTree,
15
+ pluginRoot, runtimeRoot, skillNames, updateConfig, assertRegularTree,
15
16
  } = context;
16
- async function stageInstall(stageRoot) {
17
+ // The canonical runtime is always staged; each selected host adds its own targets (see cairn-lifecycle-hosts.mjs).
18
+ async function stageInstall(stageRoot, hosts = HOSTS) {
17
19
  const targets = [];
18
20
  const add = (id, phase, destination, staged, type = "tree", details = {}) => targets.push({ id, phase, path: destination, staged, type, ...details });
21
+ // Every copy carries locators to the canonical runtime, so mirrors and hooks never depend on a host cache.
22
+ const runtimeStage = join(stageRoot, "runtime");
23
+ await copyPluginCandidate(runtimeStage, runtimeRoot);
24
+ add("runtime", "core", runtimeRoot, runtimeStage);
25
+ if (hosts.includes("codex")) await stageCodex(stageRoot, add);
26
+ if (hosts.includes("claude")) await stageClaude(stageRoot, runtimeStage, add);
27
+ if (hosts.includes("antigravity")) {
28
+ await stageAntigravity(targets, stageRoot, runtimeStage, antigravityHome, "ide", false);
29
+ await stageAntigravity(targets, stageRoot, runtimeStage, antigravityCliHome, "cli", true);
30
+ }
31
+ if (hosts.includes("codex")) {
32
+ const configStage = join(stageRoot, "config.toml");
33
+ const hookStates = await trustedHookStates(runtimeStage);
34
+ const configSnapshot = await readSharedConfigSnapshot(configPath);
35
+ await writeFile(configStage, updateConfig(configSnapshot.text, hookStates));
36
+ add("codex-config", "config", configPath, configStage, "config", { configSourceDigest: configSnapshot.digest });
37
+ }
38
+ for (const target of targets) await assertRegularTree(target.staged);
39
+ return targets;
40
+ }
41
+
42
+ async function stageCodex(stageRoot, add) {
19
43
  const sourceStage = join(stageRoot, "codex-source");
20
- const runtimeStage = join(stageRoot, "codex-runtime");
21
- await copyPluginCandidate(sourceStage, versionedPluginRoot);
22
- await copyPluginCandidate(runtimeStage, versionedPluginRoot);
44
+ const codexRuntimeStage = join(stageRoot, "codex-runtime");
45
+ await copyPluginCandidate(sourceStage, runtimeRoot);
46
+ await copyPluginCandidate(codexRuntimeStage, runtimeRoot);
23
47
  add("codex-source", "codex", installedPluginRoot, sourceStage);
24
- add("codex-runtime", "codex", versionedPluginRoot, runtimeStage);
48
+ add("codex-runtime", "codex", codexRuntimeRoot, codexRuntimeStage);
25
49
 
26
50
  const marketplaceStage = join(stageRoot, "marketplace.json");
27
51
  await writeFile(marketplaceStage, `${JSON.stringify({
@@ -30,64 +54,55 @@ async function stageInstall(stageRoot) {
30
54
  plugins: [{ name: pluginName, source: { source: "local", path: "./plugins/cairn" }, policy: { installation: "AVAILABLE", authentication: "ON_INSTALL" }, category: "Productivity" }],
31
55
  }, null, 2)}\n`);
32
56
  add("marketplace", "codex", marketplaceJsonPath, marketplaceStage, "file");
57
+ }
33
58
 
59
+ async function stageClaude(stageRoot, runtimeStage, add) {
34
60
  const claudeLocator = join(stageRoot, "claude-runtime.json");
35
- await writeLocator(claudeLocator, versionedPluginRoot);
61
+ await writeLocator(claudeLocator, runtimeRoot);
36
62
  add("claude-runtime", "claude", claudeRuntimeLocatorPath, claudeLocator, "file");
37
63
  for (const name of commandNames()) {
38
64
  const staged = join(stageRoot, "claude-commands", `cairn-${name}.md`);
39
- await renderMirrorFile(join(runtimeStage, ".claude", "commands", `cairn-${name}.md`), staged, { locatorPath: claudeRuntimeLocatorPath, runtimeRoot: versionedPluginRoot });
65
+ await renderMirrorFile(join(runtimeStage, ".claude", "commands", `cairn-${name}.md`), staged, { locatorPath: claudeRuntimeLocatorPath, runtimeRoot });
40
66
  add(`claude-command-${name}`, "claude", join(claudeHome, "commands", `cairn-${name}.md`), staged, "file");
41
67
  }
42
68
  for (const name of agentNames()) {
43
69
  const staged = join(stageRoot, "claude-agents", `cairn-${name}.md`);
44
- await renderMirrorFile(join(runtimeStage, ".claude", "agents", `${name}.md`), staged, { locatorPath: claudeRuntimeLocatorPath, runtimeRoot: versionedPluginRoot });
70
+ await renderMirrorFile(join(runtimeStage, ".claude", "agents", `${name}.md`), staged, { locatorPath: claudeRuntimeLocatorPath, runtimeRoot });
45
71
  add(`claude-agent-${name}`, "claude", join(claudeHome, "agents", `cairn-${name}.md`), staged, "file");
46
72
  }
47
73
 
48
74
  const claudePluginStage = await stageClaudePlugin({
49
- stageRoot, runtimeStage, destinationRoot: claudePluginMarketplaceRoot, versionedPluginRoot,
75
+ stageRoot, runtimeStage, destinationRoot: claudePluginMarketplaceRoot, runtimeRoot,
50
76
  marketplaceName, pluginName, releaseVersion, skillNames: skillNames(),
51
77
  });
52
78
  add("claude-plugin", "claude", claudePluginMarketplaceRoot, claudePluginStage);
53
-
54
- await stageAntigravity(targets, stageRoot, runtimeStage, antigravityHome, "ide", false);
55
- await stageAntigravity(targets, stageRoot, runtimeStage, antigravityCliHome, "cli", true);
56
-
57
- const configStage = join(stageRoot, "config.toml");
58
- const hookStates = await trustedHookStates(runtimeStage);
59
- const configSnapshot = await readSharedConfigSnapshot(configPath);
60
- await writeFile(configStage, updateConfig(configSnapshot.text, hookStates));
61
- add("codex-config", "config", configPath, configStage, "config", { configSourceDigest: configSnapshot.digest });
62
- for (const target of targets) await assertRegularTree(target.staged);
63
- return targets;
64
79
  }
65
80
 
66
81
  async function stageAntigravity(targets, stageRoot, runtimeStage, destinationRoot, label, flatSkills) {
67
82
  const locatorPath = antigravityRuntimeLocatorPath(destinationRoot);
68
83
  const locatorStage = join(stageRoot, `${label}-runtime.json`);
69
- await writeLocator(locatorStage, versionedPluginRoot);
84
+ await writeLocator(locatorStage, runtimeRoot);
70
85
  targets.push({ id: `${label}-runtime`, phase: "antigravity", path: locatorPath, staged: locatorStage, type: "file" });
71
86
  for (const name of skillNames()) {
72
87
  if (flatSkills) {
73
88
  const staged = join(stageRoot, `${label}-skills`, `${name}.md`);
74
- await renderMirrorFile(join(runtimeStage, "skills", name, "SKILL.md"), staged, { locatorPath, runtimeRoot: versionedPluginRoot, includeLocatorNotice: true });
89
+ await renderMirrorFile(join(runtimeStage, "skills", name, "SKILL.md"), staged, { locatorPath, runtimeRoot, includeLocatorNotice: true });
75
90
  targets.push({ id: `${label}-skill-${name}`, phase: "antigravity", path: join(destinationRoot, "skills", `${name}.md`), staged, type: "file" });
76
91
  } else {
77
92
  const staged = join(stageRoot, `${label}-skills`, name);
78
93
  await cp(join(runtimeStage, "skills", name), staged, { recursive: true });
79
94
  await renderMirrorFile(join(runtimeStage, "skills", name, "SKILL.md"), join(staged, "SKILL.md"), {
80
95
  locatorPath: antigravitySkillLocatorPath(destinationRoot, name),
81
- runtimeRoot: versionedPluginRoot,
96
+ runtimeRoot,
82
97
  includeLocatorNotice: true,
83
98
  });
84
- await writeLocator(join(staged, "references", "cairn-runtime.json"), versionedPluginRoot);
99
+ await writeLocator(join(staged, "references", "cairn-runtime.json"), runtimeRoot);
85
100
  targets.push({ id: `${label}-skill-${name}`, phase: "antigravity", path: join(destinationRoot, "skills", name), staged, type: "tree" });
86
101
  }
87
102
  }
88
103
  for (const name of commandNames()) {
89
104
  const staged = join(stageRoot, `${label}-workflows`, `cairn-${name}.md`);
90
- await renderMirrorFile(join(runtimeStage, ".agents", "workflows", `cairn-${name}.md`), staged, { locatorPath, runtimeRoot: versionedPluginRoot });
105
+ await renderMirrorFile(join(runtimeStage, ".agents", "workflows", `cairn-${name}.md`), staged, { locatorPath, runtimeRoot });
91
106
  targets.push({ id: `${label}-workflow-${name}`, phase: "antigravity", path: join(destinationRoot, "workflows", `cairn-${name}.md`), staged, type: "file" });
92
107
  }
93
108
  }
@@ -104,14 +119,14 @@ async function legacyMigrationTargets() {
104
119
  return present;
105
120
  }
106
121
 
107
- async function copyPluginCandidate(destination, runtimeRoot) {
122
+ async function copyPluginCandidate(destination, locatorRoot) {
108
123
  await copyPluginTree(pluginRoot, destination);
109
124
  const manifestPath = join(destination, ".codex-plugin", "plugin.json");
110
125
  const manifest = JSON.parse(await readFile(manifestPath, "utf8"));
111
126
  manifest.hooks = "./hooks/hooks.json";
112
127
  await writeFile(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`);
113
- await writeLocator(join(destination, ".cairn-runtime.json"), runtimeRoot);
114
- for (const name of skillNames()) await writeLocator(join(destination, "skills", name, "references", "cairn-runtime.json"), runtimeRoot);
128
+ await writeLocator(join(destination, ".cairn-runtime.json"), locatorRoot);
129
+ for (const name of skillNames()) await writeLocator(join(destination, "skills", name, "references", "cairn-runtime.json"), locatorRoot);
115
130
  }
116
131
 
117
132
  async function copyPluginTree(source, destination) {
@@ -5,9 +5,24 @@ import { cairnConfigProjection, readSharedConfigSnapshot, removeCairnConfig } fr
5
5
 
6
6
  export function createTransactionJournal(context) {
7
7
  const {
8
- marketplaceRoot, ownershipPath, pluginName, releaseVersion, transactionPath,
8
+ layout, legacyLayout, ownershipPath, transactionPath,
9
9
  transactionRoot, expectedManagedTarget, targetDigest,
10
10
  } = context;
11
+ // Journal-only id that removes the Codex cache runtime a version change leaves behind when it is not retained.
12
+ const previousRuntimeParents = { "previous-codex-runtime": layout.codexRuntimeParent };
13
+ // The versioned runtimes of any release (the installation's, not only this CLI's): a rollback or recovery by a CLI
14
+ // of another version still has to read them. The legacy stack has no canonical `runtime` id.
15
+ const versionedRuntimeIds = ["runtime", "codex-runtime"];
16
+ // Journal-only ids that remove a retained runtime: `retired-<runtime|codex-runtime>-<version>`, during install
17
+ // cleanup or uninstall core. Only the current stack retains runtimes.
18
+ const retiredRuntimeRoots = legacyLayout ? { runtime: layout.runtimeRootFor, "codex-runtime": layout.codexRuntimeRootFor } : {};
19
+ // Journal-only ids that remove a migrated 0.6.0-layout installation. Only the current stack knows them.
20
+ const legacyRemovalTargets = legacyLayout ? {
21
+ "legacy-ownership": { phase: "manifest", path: legacyLayout.ownershipPath, type: "file" },
22
+ "legacy-root-codex-source": { phase: "cleanup", path: legacyLayout.installedPluginRoot, type: "tree" },
23
+ "legacy-root-marketplace": { phase: "cleanup", path: legacyLayout.marketplaceJsonPath, type: "file" },
24
+ "legacy-root-claude-plugin": { phase: "cleanup", path: legacyLayout.claudePluginMarketplaceRoot, type: "tree" },
25
+ } : {};
11
26
  async function createTransaction() {
12
27
  const id = randomUUID();
13
28
  const root = join(transactionRoot, id);
@@ -105,8 +120,14 @@ function validateTransactionJournal(journal, { strict = false } = {}) {
105
120
  for (const entry of journal.entries) {
106
121
  const expected = entry.id === "ownership"
107
122
  ? { phase: "manifest", path: ownershipPath, type: "file" }
108
- : entry.id === "previous-codex-runtime"
109
- ? previousRuntimeTarget(entry.path)
123
+ : Object.hasOwn(previousRuntimeParents, entry.id)
124
+ ? previousRuntimeTarget(previousRuntimeParents[entry.id], entry.path)
125
+ : Object.hasOwn(legacyRemovalTargets, entry.id)
126
+ ? (entry.operation === "remove" ? legacyRemovalTargets[entry.id] : null)
127
+ : typeof entry.id === "string" && entry.id.startsWith("retired-")
128
+ ? (entry.operation === "remove" ? retiredRuntimeTarget(entry.id, entry.phase) : null)
129
+ : versionedRuntimeIds.includes(entry.id)
130
+ ? versionedRuntimeTarget(entry.id, entry.path)
110
131
  : expectedManagedTarget(entry.id);
111
132
  if (!expected || expected.path !== entry.path || expected.phase !== entry.phase || expected.type !== entry.type
112
133
  || !["prepared", "applied"].includes(entry.status)
@@ -126,11 +147,33 @@ function validateTransactionJournal(journal, { strict = false } = {}) {
126
147
  }
127
148
  }
128
149
 
129
- function previousRuntimeTarget(path) {
130
- const parent = join(marketplaceRoot, pluginName);
150
+ // A direct `<version>` child of `parent`; the version is any release, because the journal may come from a CLI of
151
+ // another version than this one.
152
+ function previousRuntimeTarget(parent, path) {
153
+ const relation = versionedChild(parent, path);
154
+ return relation ? { phase: "cleanup", path: join(parent, relation), type: "tree" } : null;
155
+ }
156
+
157
+ // `runtime` and `codex-runtime` keep their phase and type; only the version directory may differ from this release.
158
+ function versionedRuntimeTarget(id, path) {
159
+ const expected = expectedManagedTarget(id);
160
+ if (!expected) return null;
161
+ const parent = dirname(expected.path);
162
+ const relation = versionedChild(parent, path);
163
+ return relation ? { ...expected, path: join(parent, relation) } : null;
164
+ }
165
+
166
+ function versionedChild(parent, path) {
167
+ if (typeof path !== "string") return null;
131
168
  const relation = relative(parent, resolve(path));
132
- if (!relation || relation.includes(sep) || !/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(relation) || relation === releaseVersion) return null;
133
- return { phase: "cleanup", path: join(parent, relation), type: "tree" };
169
+ if (!relation || relation.includes(sep) || !/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(relation)) return null;
170
+ return relation;
171
+ }
172
+
173
+ function retiredRuntimeTarget(id, phase) {
174
+ const match = /^retired-(runtime|codex-runtime)-(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)$/.exec(id);
175
+ if (!match || !Object.hasOwn(retiredRuntimeRoots, match[1]) || !["core", "cleanup"].includes(phase)) return null;
176
+ return { phase, path: retiredRuntimeRoots[match[1]](match[2]), type: "tree" };
134
177
  }
135
178
 
136
179
  function sameKeys(value, expected) {