cairn-ai 0.5.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.
- package/.agents/workflows/cairn-doctor.md +4 -1
- package/.agents/workflows/cairn-install.md +3 -1
- package/.agents/workflows/cairn-memory.md +2 -2
- package/.agents/workflows/cairn-plan.md +2 -2
- package/.agents/workflows/cairn-review.md +1 -1
- package/.agents/workflows/cairn-uninstall.md +3 -1
- package/.agents/workflows/cairn-upgrade.md +3 -1
- package/.agents/workflows/cairn-work.md +2 -2
- package/.claude/agents/explorer.md +1 -1
- package/.claude/agents/worker.md +1 -1
- package/.codex-plugin/plugin.json +2 -2
- package/README.de.md +46 -8
- package/README.es.md +46 -8
- package/README.fr.md +46 -8
- package/README.ja.md +46 -8
- package/README.ko.md +51 -15
- package/README.md +51 -15
- package/README.pt.md +46 -8
- package/README.zh.md +46 -8
- package/agents/explorer.md +1 -1
- package/agents/worker.md +1 -1
- package/commands/cairn-doctor.md +4 -1
- package/commands/cairn-install.md +11 -5
- package/commands/cairn-memory.md +2 -2
- package/commands/cairn-plan.md +2 -2
- package/commands/cairn-review.md +1 -1
- package/commands/cairn-uninstall.md +9 -4
- package/commands/cairn-upgrade.md +8 -1
- package/commands/cairn-work.md +2 -2
- package/package.json +2 -2
- package/scripts/cairn-auto-upgrade.mjs +334 -0
- package/scripts/cairn-cleanup.mjs +142 -15
- package/scripts/cairn-goal-cli.mjs +50 -4
- package/scripts/cairn-goal-history.mjs +316 -0
- package/scripts/cairn-goal-operations-evidence.mjs +2 -2
- package/scripts/cairn-goal-operations.mjs +11 -3
- package/scripts/cairn-goal.mjs +3 -0
- package/scripts/cairn-index.mjs +1052 -0
- package/scripts/cairn-lifecycle-claude.mjs +64 -18
- package/scripts/cairn-lifecycle-commands.mjs +355 -79
- package/scripts/cairn-lifecycle-hosts.mjs +98 -0
- package/scripts/cairn-lifecycle-integrity.mjs +106 -33
- package/scripts/cairn-lifecycle-layout.mjs +69 -0
- package/scripts/cairn-lifecycle-staging.mjs +45 -30
- package/scripts/cairn-lifecycle-transaction-journal.mjs +50 -7
- package/scripts/cairn-lifecycle.mjs +148 -45
- package/scripts/cairn-paths.mjs +12 -0
- package/scripts/cairn-safe-fs.mjs +7 -2
- package/scripts/cairn-state-context.mjs +126 -10
- package/scripts/cairn-state-init.mjs +11 -68
- package/scripts/cairn-state.mjs +63 -19
- package/scripts/cairn-update-state.mjs +219 -0
- package/scripts/cairn.mjs +68 -26
- package/skills/cairn-memory/SKILL.md +4 -4
- package/skills/cairn-plan/SKILL.md +2 -2
- package/skills/cairn-plan/delegation.md +2 -1
- package/skills/cairn-plan/planning-rules.md +10 -0
- package/skills/cairn-review/SKILL.md +3 -1
- package/skills/cairn-work/SKILL.md +1 -1
- package/skills/cairn-work/delegation.md +2 -1
- package/skills/cairn-work/verification.md +15 -1
- package/templates/MEMORY.md +4 -6
- package/templates/PLAN.md +2 -15
- package/templates/domain-memory.md +2 -0
- package/templates/work-plan.md +3 -1
package/commands/cairn-review.md
CHANGED
|
@@ -9,7 +9,7 @@ Goal: review completed work against plan, memory, policy, and evidence.
|
|
|
9
9
|
Procedure:
|
|
10
10
|
|
|
11
11
|
1. Every agent reads project-root `MEMORY.md` when present and continues without repository memory when absent before review work, then reads the plan task and available memory inputs.
|
|
12
|
-
2. Check changed files, tool readiness evidence, and verification evidence. Inspect test, fixture, and verification-command diffs and reject any weakening without a recorded plan reason. For defect fixes, confirm the same-rule sweep was performed and its result recorded.
|
|
12
|
+
2. Check changed files, tool readiness evidence, and verification evidence. Inspect test, fixture, and verification-command diffs and reject any weakening without a recorded plan reason. For defect fixes, confirm the same-rule sweep was performed and its result recorded. Confirm the plan's Evidence has a filled `Memory promotion:` line (`docs/memory/<domain>.md` or `none: <reason>`) and that the installed Cairn CLI's `memory check --root <repoRoot>` and `plan check --root <repoRoot>` exit 0. A `none: <reason>` decision is acceptable: do not create a note or demand one; flag a missing or placeholder line, or a named note that does not exist.
|
|
13
13
|
3. Delegate independent read-only review to `explorer` when it materially improves speed or quality; use `worker` only for scoped verification reruns or QA artifacts. When subagent tools are available, each agent may recursively delegate bounded sub-tasks to subagents. Tell every delegated agent and child subagent to read the project-root `MEMORY.md` before work, keep scope, and preserve others' edits.
|
|
14
14
|
4. Report findings first, ordered by severity, with file and line references. If no issues are found, say so clearly and mention remaining test gaps or residual risk.
|
|
15
15
|
5. Record review evidence in `docs/plan/<topic>.md` and as the goal-level final review evidence record before completing the goal.
|
|
@@ -8,15 +8,20 @@ Run from the published or global package:
|
|
|
8
8
|
bunx cairn-ai@latest uninstall
|
|
9
9
|
```
|
|
10
10
|
|
|
11
|
-
The custom marketplace ownership manifest is authoritative. Uninstall
|
|
11
|
+
The custom marketplace ownership manifest is authoritative. Uninstall first compares every non-config managed destination with its recorded installed digest and refuses the whole uninstall, changing nothing, if any managed artifact was modified or removed. Otherwise it removes or restores the managed destinations; unmanaged targets and their parent directories are preserved. A failure rolls back the transaction.
|
|
12
12
|
|
|
13
13
|
Managed items:
|
|
14
14
|
|
|
15
15
|
- Cairn marketplace, plugin, and hook trust state blocks in `~/.codex/config.toml`.
|
|
16
|
-
- `~/.
|
|
16
|
+
- `~/.cairn/install/` (ownership manifest, canonical and retained runtimes, Codex marketplace source, Claude Code marketplace).
|
|
17
|
+
- `$CODEX_HOME/plugins/cache/cairn` (Codex versioned runtime cache and retained copies).
|
|
18
|
+
- The Claude Code plugin `cairn@cairn` registration.
|
|
19
|
+
- Auto-upgrade state in `~/.cairn/update/`.
|
|
17
20
|
- Claude Code `cairn-*` commands and agents mirror files.
|
|
18
21
|
- Antigravity IDE/CLI `cairn-*` skills and workflows mirror files.
|
|
19
22
|
|
|
20
|
-
|
|
23
|
+
Only the hosts recorded in the ownership manifest are touched. An installation made by Cairn 0.6.0 or earlier is removed in place without migrating.
|
|
21
24
|
|
|
22
|
-
|
|
25
|
+
After the transaction commits, Cairn removes empty managed scaffold directories bottom-up and removes `~/.cairn/install/` and `$CODEX_HOME/plugins/cache/cairn` only when empty, after releasing its own lifecycle lock. `~/.cairn/update/` loses its known state files and is removed when empty. A directory containing any unmanaged child is preserved; pruning never uses recursive deletion.
|
|
26
|
+
|
|
27
|
+
The source work folder, repository `MEMORY.md`, `PLAN.md`, `docs/`, and user-home Cairn goal state (`~/.cairn/projects/`) and settings (`~/.cairn/config.json`) are not deleted. The globally installed `cairn-ai` package, package-manager download caches, legacy backup files, and legacy shared settings not recorded by the current ownership manifest are also outside this command's scope and require a separate, explicit cleanup decision.
|
|
@@ -6,9 +6,10 @@ Run from the published or global package, not from the installed cache copy:
|
|
|
6
6
|
|
|
7
7
|
```sh
|
|
8
8
|
bunx cairn-ai@latest upgrade
|
|
9
|
+
bunx cairn-ai@latest upgrade --hosts codex,claude
|
|
9
10
|
```
|
|
10
11
|
|
|
11
|
-
The current custom marketplace lifecycle remains in use.
|
|
12
|
+
The current custom marketplace lifecycle remains in use. An installed copy (`~/.cairn/install/` or the Codex plugin cache) is a replacement target and must not upgrade itself.
|
|
12
13
|
|
|
13
14
|
Actions:
|
|
14
15
|
|
|
@@ -18,3 +19,9 @@ Actions:
|
|
|
18
19
|
- Refresh runtime locators for every installed surface.
|
|
19
20
|
- Stage and validate all candidates before commit; rollback committed phases in reverse order on failure.
|
|
20
21
|
- Preserve and report a conflict for modified, unmanaged, or invalid legacy artifacts.
|
|
22
|
+
- Keep the recorded hosts unless `--hosts` (`all` or a comma list of `codex`, `claude`, `antigravity`) changes them; deselected hosts are removed, and a modified artifact of a deselected host refuses the upgrade.
|
|
23
|
+
- Migrate an installation made by Cairn 0.6.0 or earlier (everything under `$CODEX_HOME/plugins/cache/cairn`) to `~/.cairn/install/` in one transaction, re-registering the Claude Code plugin from its new marketplace path. A failed or interrupted migration is restored; a legacy installation migrates with every host, so a narrower `--hosts` is refused until the next run. Restart sessions that were open during the migration.
|
|
24
|
+
- After a version change, keep the previous canonical runtime and Codex cache copy for 3 days (at most 3 of each); expired ones are removed by the next install or upgrade. A Codex cache copy at or above the new version is never kept, because Codex loads the highest cached version.
|
|
25
|
+
- When the Claude Code plugin cache holds a different version, run `claude plugin marketplace update cairn` and `claude plugin update cairn@cairn --scope user`. If that fails, keep the upgraded files, print those commands, and exit 1.
|
|
26
|
+
- Refuse, changing nothing, when the installed version is newer than this CLI; `--allow-downgrade` moves the installation to this CLI's version anyway.
|
|
27
|
+
- `upgrade --auto` is reserved for the auto-upgrade runner; it keeps the recorded hosts, never downgrades (it cannot be combined with `--allow-downgrade`), and refuses to run without an existing installation.
|
package/commands/cairn-work.md
CHANGED
|
@@ -18,7 +18,7 @@ Procedure:
|
|
|
18
18
|
6. Run module acceptance and surface integration through `goal verify -- ...`; `--kind "moduleAcceptance|surfaceIntegration"` records both from one run. Treat tool exit codes as authoritative and expand context only around failing tests. Heavy Path records explicit `Tests:` evidence.
|
|
19
19
|
7. Never edit, weaken, skip, or delete existing tests, fixtures, or verification commands to make a gate pass unless the plan records the contract change. Reproduce reported defects before fixing, and after a fix search for other implementations of the same rule or pattern.
|
|
20
20
|
8. Inspect package lifecycle scripts and run normal `npm pack --dry-run` by default. Content-producing or unknown lifecycle scripts must never use `--ignore-scripts`; only absent or proven content-neutral scripts may use it while the full check remains fresh.
|
|
21
|
-
9. Relevant mutation makes the current task's evidence stale; rerun it before completing the task. Do not rerun earlier tasks' checks; finish with one goal-level check through `goal finish -- ...`. Missing, failed, skipped, stale, or placeholder evidence never completes work. `goal stats` measures receipt reruns.
|
|
21
|
+
9. Relevant mutation makes the current task's evidence stale; rerun it before completing the task. Do not rerun earlier tasks' checks; finish with one goal-level check through `goal finish -- ...`. Missing, failed, skipped, stale, or placeholder evidence never completes work. `goal stats` measures receipt reruns; `goal stats --history` compares finished goals of the repository.
|
|
22
22
|
10. Read the skill's reference files only when needed: `cairn://skills/cairn-work/verification.md`, `cairn://skills/cairn-work/delegation.md`, `cairn://skills/cairn-work/recovery.md`, and `cairn://skills/cairn-work/heavy-path.md` (Heavy route only).
|
|
23
|
-
11. Update the plan, goal state, and `PLAN.md` only after evidence exists. Answer side questions briefly and resume unless explicitly asked to pause, stop, or switch.
|
|
23
|
+
11. Before `goal finish`, record the memory promotion decision in the plan's Evidence: `Memory promotion: docs/memory/<domain>.md` when the goal produced reusable repository knowledge (write the note with a `Summary:` line, then run `memory index --root <repoRoot>`), otherwise `Memory promotion: none: <reason>`. The line is required and the note is optional: do not create a note when nothing qualifies. Update the plan, goal state, and `PLAN.md` only after evidence exists. Answer side questions briefly and resume unless explicitly asked to pause, stop, or switch.
|
|
24
24
|
12. Use the OS locale for user-visible responses and generated or updated documentation, plans, and memory artifacts unless the user asks for another language.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "cairn-ai",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.0",
|
|
4
4
|
"description": "Token-efficient agent harness with tool readiness for Codex, Claude Code, and Antigravity",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": {
|
|
@@ -41,7 +41,7 @@
|
|
|
41
41
|
"README.*.md"
|
|
42
42
|
],
|
|
43
43
|
"scripts": {
|
|
44
|
-
"check": "node --check scripts/cairn.mjs && node --check scripts/cairn-paths.mjs && node --check scripts/cairn-safe-fs.mjs && node --check scripts/cairn-goal.mjs && node --check scripts/cairn-state.mjs && node --check scripts/cairn-cleanup.mjs && node --check scripts/cairn-lifecycle.mjs && node --check scripts/cairn-toolcheck.mjs && node -e \"JSON.parse(require('node:fs').readFileSync('package.json','utf8')); JSON.parse(require('node:fs').readFileSync('.codex-plugin/plugin.json','utf8')); JSON.parse(require('node:fs').readFileSync('hooks/hooks.json','utf8')); JSON.parse(require('node:fs').readFileSync('scripts/release-integrity-0.2.2.json','utf8'))\" && npm test",
|
|
44
|
+
"check": "node --check scripts/cairn.mjs && node --check scripts/cairn-paths.mjs && node --check scripts/cairn-safe-fs.mjs && node --check scripts/cairn-goal.mjs && node --check scripts/cairn-state.mjs && node --check scripts/cairn-cleanup.mjs && node --check scripts/cairn-lifecycle.mjs && node --check scripts/cairn-lifecycle-layout.mjs && node --check scripts/cairn-lifecycle-hosts.mjs && node --check scripts/cairn-update-state.mjs && node --check scripts/cairn-auto-upgrade.mjs && node --check scripts/cairn-toolcheck.mjs && node -e \"JSON.parse(require('node:fs').readFileSync('package.json','utf8')); JSON.parse(require('node:fs').readFileSync('.codex-plugin/plugin.json','utf8')); JSON.parse(require('node:fs').readFileSync('hooks/hooks.json','utf8')); JSON.parse(require('node:fs').readFileSync('scripts/release-integrity-0.2.2.json','utf8'))\" && npm test",
|
|
45
45
|
"test": "node --test",
|
|
46
46
|
"prepack": "npm run check"
|
|
47
47
|
},
|
|
@@ -0,0 +1,334 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { spawnSync } from "node:child_process";
|
|
3
|
+
import { realpathSync } from "node:fs";
|
|
4
|
+
import { lstat, mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
|
|
5
|
+
import { join, relative } from "node:path";
|
|
6
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
7
|
+
import { createLifecycleLock } from "./cairn-lifecycle-lock.mjs";
|
|
8
|
+
import { assertNoSymlinkComponents } from "./cairn-safe-fs.mjs";
|
|
9
|
+
import {
|
|
10
|
+
AUTO_UPGRADE_EXIT, UPDATE_PACKAGE_NAME, autoUpgradeSetting, emptyUpdateState, noticeRecord, readInstallManifest,
|
|
11
|
+
readJsonFile, readPendingNotice, readUpdateState, removeUpdateState, updatePaths, writeFileAtomic, writeJsonAtomic,
|
|
12
|
+
} from "./cairn-update-state.mjs";
|
|
13
|
+
|
|
14
|
+
// The detached auto-upgrade runner (`run`, started by the SessionStart hook) and the `cairn auto-upgrade` CLI.
|
|
15
|
+
// The runner is the old version and the package it installs is the new one. Only three things are fixed between
|
|
16
|
+
// versions: the `cairn-lifecycle.mjs upgrade --auto` call, `version` in CAIRN_HOME/install/lifecycle.json, and the
|
|
17
|
+
// meaning of the lifecycle exit code (0 done, AUTO_UPGRADE_EXIT.manual a Claude Code step left to the user, anything
|
|
18
|
+
// else not confirmed).
|
|
19
|
+
export const AUTO_UPGRADE_USAGE = "Usage: cairn auto-upgrade status|on|off|run";
|
|
20
|
+
const VIEW_TIMEOUT_MS = 30_000;
|
|
21
|
+
const INSTALL_TIMEOUT_MS = 120_000;
|
|
22
|
+
const LIFECYCLE_TIMEOUT_MS = 300_000;
|
|
23
|
+
const LOG_LIMIT_BYTES = 64 * 1024;
|
|
24
|
+
const HOUR_MS = 60 * 60 * 1000;
|
|
25
|
+
const DAY_MS = 24 * HOUR_MS;
|
|
26
|
+
const REGISTRY_VERSION = /^\d+\.\d+\.\d+$/;
|
|
27
|
+
const REGISTRY_VERSION_MAX_LENGTH = 32;
|
|
28
|
+
const LOCK_BUSY = "Timed out waiting for Cairn lifecycle lock";
|
|
29
|
+
|
|
30
|
+
class UsageError extends Error {}
|
|
31
|
+
|
|
32
|
+
if (isCliEntry()) {
|
|
33
|
+
try {
|
|
34
|
+
process.exitCode = await main(process.argv.slice(2));
|
|
35
|
+
} catch (error) {
|
|
36
|
+
console.error(`Cairn auto-upgrade error: ${error instanceof Error ? error.message : String(error)}`);
|
|
37
|
+
process.exitCode = error instanceof UsageError ? 2 : 1;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// Exit codes follow the root CLI: 0 success or help, 1 an execution error or a failed run, 2 a usage error.
|
|
42
|
+
export async function main(args, env = process.env) {
|
|
43
|
+
const [command, ...rest] = args;
|
|
44
|
+
if (command === undefined || command === "help" || command === "--help") {
|
|
45
|
+
console.log(AUTO_UPGRADE_USAGE);
|
|
46
|
+
return 0;
|
|
47
|
+
}
|
|
48
|
+
if (!["status", "on", "off", "run"].includes(command)) throw new UsageError(`unknown command: ${command}`);
|
|
49
|
+
if (rest.length > 0) throw new UsageError(`auto-upgrade ${command} does not accept arguments: ${rest.join(" ")}`);
|
|
50
|
+
if (command === "on" || command === "off") setAutoUpgrade(env, command === "on");
|
|
51
|
+
if (command !== "run") {
|
|
52
|
+
printJson(statusReport(env));
|
|
53
|
+
return 0;
|
|
54
|
+
}
|
|
55
|
+
const report = await runAutoUpgrade(env);
|
|
56
|
+
printJson(report);
|
|
57
|
+
return ["failed", "check-failed", "manual"].includes(report.result?.kind) ? 1 : 0;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function statusReport(env = process.env) {
|
|
61
|
+
const paths = updatePaths(env);
|
|
62
|
+
const setting = autoUpgradeSetting(env, paths);
|
|
63
|
+
const manifest = readInstallManifest(paths);
|
|
64
|
+
const state = readUpdateState(paths);
|
|
65
|
+
return {
|
|
66
|
+
enabled: setting.enabled,
|
|
67
|
+
source: setting.source,
|
|
68
|
+
installed: manifest,
|
|
69
|
+
lastCheckedAt: state?.lastCheckedAt ?? null,
|
|
70
|
+
latestSeen: state?.latestSeen ?? null,
|
|
71
|
+
nextAttemptAt: state?.nextAttemptAt ?? null,
|
|
72
|
+
consecutiveFailures: state?.consecutiveFailures ?? 0,
|
|
73
|
+
failedVersion: state?.failedVersion ?? null,
|
|
74
|
+
lastResult: state?.lastResult ?? null,
|
|
75
|
+
pendingNotice: readPendingNotice(paths),
|
|
76
|
+
config: paths.config,
|
|
77
|
+
statePath: paths.state,
|
|
78
|
+
log: paths.log,
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// Other config.json keys are kept. A config.json that is not a readable JSON object is left as it is.
|
|
83
|
+
function setAutoUpgrade(env, enabled) {
|
|
84
|
+
const paths = updatePaths(env);
|
|
85
|
+
const read = readJsonFile(paths.config);
|
|
86
|
+
const object = read.status === "ok" && read.value && typeof read.value === "object" && !Array.isArray(read.value);
|
|
87
|
+
if (read.status !== "missing" && !object) throw new Error(`${paths.config} is not a readable JSON object; fix or remove it`);
|
|
88
|
+
writeJsonAtomic(paths.config, { ...(object ? read.value : {}), autoUpgrade: enabled });
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export async function runAutoUpgrade(env = process.env) {
|
|
92
|
+
const paths = updatePaths(env);
|
|
93
|
+
if (!autoUpgradeSetting(env, paths).enabled) return { ran: false, reason: "disabled" };
|
|
94
|
+
if (!readInstallManifest(paths)) return { ran: false, reason: "not-installed" };
|
|
95
|
+
await assertNoSymlinkComponents(paths.home, paths.stage);
|
|
96
|
+
await mkdir(paths.root, { recursive: true });
|
|
97
|
+
// A held update.lock means another runner is working: exit without waiting. A lock left by a dead process is
|
|
98
|
+
// reclaimed by the lifecycle lock rules.
|
|
99
|
+
let report;
|
|
100
|
+
try {
|
|
101
|
+
report = await createLifecycleLock({ lifecycleLockPath: paths.lock })
|
|
102
|
+
.withLifecycleLock(() => runLocked(env, paths), { timeoutMs: 1, retryMs: 1 });
|
|
103
|
+
} catch (error) {
|
|
104
|
+
if (String(error?.message).startsWith(LOCK_BUSY)) return { ran: false, reason: "locked" };
|
|
105
|
+
throw error;
|
|
106
|
+
}
|
|
107
|
+
// An uninstall finished while this runner worked: its update state goes too, as uninstall would have removed it.
|
|
108
|
+
if (report.reason === "not-installed" && readJsonFile(paths.manifest).status === "missing") await removeUpdateState(env);
|
|
109
|
+
return report;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
async function runLocked(env, paths) {
|
|
113
|
+
// Read again under the lock: a lifecycle command or another runner may have changed the installation.
|
|
114
|
+
if (!autoUpgradeSetting(env, paths).enabled) return { ran: false, reason: "disabled" };
|
|
115
|
+
const manifest = readInstallManifest(paths);
|
|
116
|
+
if (!manifest) return { ran: false, reason: "not-installed" };
|
|
117
|
+
const now = new Date();
|
|
118
|
+
const previous = { ...emptyUpdateState(), ...(readUpdateState(paths) ?? {}) };
|
|
119
|
+
if (manifest.origin === "checkout") {
|
|
120
|
+
const state = { ...previous, lastCheckedAt: now.toISOString(), lastResult: result("skipped", now, manifest.version, null, "checkout-origin installation") };
|
|
121
|
+
writeJsonAtomic(paths.state, state);
|
|
122
|
+
return { ran: false, reason: "checkout", result: state.lastResult };
|
|
123
|
+
}
|
|
124
|
+
const log = [];
|
|
125
|
+
let state;
|
|
126
|
+
try {
|
|
127
|
+
const lookup = runNpm(["view", `${UPDATE_PACKAGE_NAME}@latest`, "version", "--json"], { cwd: paths.root, env, timeout: VIEW_TIMEOUT_MS });
|
|
128
|
+
log.push(logEntry("npm view", lookup));
|
|
129
|
+
const latest = registryVersion(lookup);
|
|
130
|
+
state = latest.error
|
|
131
|
+
? checkFailure(previous, { now, from: manifest.version, to: null, detail: latest.error })
|
|
132
|
+
: isNewer(latest.version, manifest.version)
|
|
133
|
+
? await upgradeTo(latest.version, { env, paths, manifest, previous, now, log })
|
|
134
|
+
: settled(previous, { now, kind: "current", from: manifest.version, to: latest.version });
|
|
135
|
+
} catch (error) {
|
|
136
|
+
// An unexpected error (a file system failure around the stage) is recorded like a lookup failure: no notice, and
|
|
137
|
+
// a backoff so the next sessions do not retry it at once.
|
|
138
|
+
const detail = `unexpected error: ${error instanceof Error ? error.message : String(error)}`;
|
|
139
|
+
log.push(detail);
|
|
140
|
+
state = checkFailure(previous, { now, from: manifest.version, to: null, detail });
|
|
141
|
+
}
|
|
142
|
+
if (state.uninstalled) return { ran: false, reason: "not-installed" };
|
|
143
|
+
try {
|
|
144
|
+
writeJsonAtomic(paths.state, state);
|
|
145
|
+
return { ran: true, result: state.lastResult };
|
|
146
|
+
} finally {
|
|
147
|
+
writeLog(paths.log, now, log);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
async function upgradeTo(target, { env, paths, manifest, previous, now, log }) {
|
|
152
|
+
const from = manifest.version;
|
|
153
|
+
await rm(paths.stage, { recursive: true, force: true });
|
|
154
|
+
await assertNoSymlinkComponents(paths.home, paths.stage);
|
|
155
|
+
await mkdir(paths.stage, { recursive: true });
|
|
156
|
+
// npm installs into the nearest package.json; without this one it would climb to CAIRN_HOME or the home directory.
|
|
157
|
+
await writeFile(join(paths.stage, "package.json"), `${JSON.stringify({ name: "cairn-auto-upgrade-stage", private: true }, null, 2)}\n`);
|
|
158
|
+
try {
|
|
159
|
+
// The stage is the cwd, so no path is passed to npm (npm.cmd splits paths with spaces on Windows).
|
|
160
|
+
const install = runNpm(["install", "--ignore-scripts", "--no-audit", "--no-fund", "--no-save", `${UPDATE_PACKAGE_NAME}@${target}`], {
|
|
161
|
+
cwd: paths.stage, env, timeout: INSTALL_TIMEOUT_MS,
|
|
162
|
+
});
|
|
163
|
+
log.push(logEntry("npm install", install));
|
|
164
|
+
if (install.error || install.status !== 0) {
|
|
165
|
+
return checkFailure(previous, { now, from, to: target, detail: `npm install failed: ${lastLine(install)}` });
|
|
166
|
+
}
|
|
167
|
+
const problem = await verifyStagedPackage(paths.stage, target);
|
|
168
|
+
if (problem) return upgradeFailure(previous, { paths, now, from, to: target, detail: `verification failed: ${problem}` });
|
|
169
|
+
const lifecycle = spawnSync(process.execPath, [join(paths.stage, "node_modules", UPDATE_PACKAGE_NAME, "scripts", "cairn-lifecycle.mjs"), "upgrade", "--auto"], {
|
|
170
|
+
cwd: paths.root, env, encoding: "utf8", timeout: LIFECYCLE_TIMEOUT_MS, windowsHide: true, maxBuffer: 16 * 1024 * 1024,
|
|
171
|
+
});
|
|
172
|
+
log.push(logEntry("cairn-lifecycle upgrade --auto", lifecycle));
|
|
173
|
+
// An uninstall finished while the package was staged (`upgrade --auto` then installs nothing): there is nothing
|
|
174
|
+
// left to upgrade or to report.
|
|
175
|
+
if (readJsonFile(paths.manifest).status === "missing") return { uninstalled: true };
|
|
176
|
+
const installed = readInstallManifest(paths);
|
|
177
|
+
// The manifest decides: the files moved to the target version or they did not.
|
|
178
|
+
if (installed?.version !== target) {
|
|
179
|
+
return upgradeFailure(previous, { paths, now, from, to: target, detail: `upgrade exited ${lifecycle.status ?? lifecycle.error?.code}: ${lastLine(lifecycle)}` });
|
|
180
|
+
}
|
|
181
|
+
if (lifecycle.status === 0 || lifecycle.status === AUTO_UPGRADE_EXIT.manual) {
|
|
182
|
+
const kind = lifecycle.status === 0 ? "updated" : "manual";
|
|
183
|
+
writeJsonAtomic(paths.notice, noticeRecord(kind, from, target, now.toISOString()));
|
|
184
|
+
return settled(previous, { now, kind, from, to: target, detail: kind === "manual" ? lastLine(lifecycle) : null });
|
|
185
|
+
}
|
|
186
|
+
// The files moved but the run failed after its commit: reported once like a failed upgrade. The next check finds
|
|
187
|
+
// the target version installed, so the upgrade is not retried.
|
|
188
|
+
return upgradeFailure(previous, { paths, now, from, to: target, detail: `upgrade exited ${lifecycle.status ?? lifecycle.error?.code} after its commit: ${lastLine(lifecycle)}` });
|
|
189
|
+
} finally {
|
|
190
|
+
// A stage that cannot be removed (a held file, a changed permission) must not hide the result; the next run
|
|
191
|
+
// removes it before staging again.
|
|
192
|
+
try { await rm(paths.stage, { recursive: true, force: true }); } catch (error) { log.push(`stage removal failed: ${error.message}`); }
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
function settled(previous, { now, kind, from, to, detail = null }) {
|
|
197
|
+
return {
|
|
198
|
+
...previous, lastCheckedAt: now.toISOString(), latestSeen: to, consecutiveFailures: 0, nextAttemptAt: null,
|
|
199
|
+
failedVersion: null, lastResult: result(kind, now, from, to, detail),
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// Lookup and install failures (offline, no npm, a registry error) back off 1h, 2h, … up to 24h without a notice.
|
|
204
|
+
function checkFailure(previous, { now, from, to, detail }) {
|
|
205
|
+
const failures = previous.lastResult?.kind === "check-failed" ? failureCount(previous) + 1 : 1;
|
|
206
|
+
return {
|
|
207
|
+
...previous, latestSeen: to ?? previous.latestSeen, consecutiveFailures: failures,
|
|
208
|
+
nextAttemptAt: new Date(now.getTime() + Math.min(HOUR_MS * 2 ** (failures - 1), DAY_MS)).toISOString(),
|
|
209
|
+
lastResult: result("check-failed", now, from, to, detail),
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
// A version that failed verification or the upgrade backs off 24h, 48h, … up to 7 days, with one notice per version.
|
|
214
|
+
// A newer release starts over.
|
|
215
|
+
function upgradeFailure(previous, { paths, now, from, to, detail }) {
|
|
216
|
+
const sameVersion = previous.failedVersion === to;
|
|
217
|
+
const failures = sameVersion && previous.lastResult?.kind === "failed" ? failureCount(previous) + 1 : 1;
|
|
218
|
+
if (!sameVersion) writeJsonAtomic(paths.notice, noticeRecord("failed", from, to, now.toISOString()));
|
|
219
|
+
return {
|
|
220
|
+
...previous, lastCheckedAt: now.toISOString(), latestSeen: to, consecutiveFailures: failures, failedVersion: to,
|
|
221
|
+
nextAttemptAt: new Date(now.getTime() + Math.min(DAY_MS * 2 ** (failures - 1), 7 * DAY_MS)).toISOString(),
|
|
222
|
+
lastResult: result("failed", now, from, to, detail),
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
function failureCount(state) {
|
|
227
|
+
return Number.isSafeInteger(state.consecutiveFailures) && state.consecutiveFailures > 0 ? state.consecutiveFailures : 0;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
function result(kind, now, from, to, detail) {
|
|
231
|
+
return { kind, at: now.toISOString(), from, to, detail };
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
// Only an exact x.y.z release of at most 32 characters is accepted; npm 12 may wrap it in an object.
|
|
235
|
+
function registryVersion(lookup) {
|
|
236
|
+
if (lookup.error || lookup.status !== 0) return { error: `npm view failed: ${lastLine(lookup)}` };
|
|
237
|
+
let value;
|
|
238
|
+
try { value = JSON.parse(lookup.stdout); } catch { return { error: "npm view did not return JSON" }; }
|
|
239
|
+
if (value && typeof value === "object" && !Array.isArray(value)) value = value.version;
|
|
240
|
+
if (typeof value !== "string" || value.length > REGISTRY_VERSION_MAX_LENGTH || !REGISTRY_VERSION.test(value)) {
|
|
241
|
+
return { error: `npm view returned an invalid version: ${String(JSON.stringify(value)).slice(0, 80)}` };
|
|
242
|
+
}
|
|
243
|
+
return { version: value };
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
// Strictly newer by major.minor.patch, or the same core release of an installed prerelease. Never a downgrade.
|
|
247
|
+
function isNewer(latest, installed) {
|
|
248
|
+
const match = /^(\d+)\.(\d+)\.(\d+)(-.+)?$/.exec(installed);
|
|
249
|
+
if (!match) return false;
|
|
250
|
+
const next = latest.split(".").map(BigInt);
|
|
251
|
+
const current = match.slice(1, 4).map(BigInt);
|
|
252
|
+
for (let index = 0; index < 3; index += 1) if (next[index] !== current[index]) return next[index] > current[index];
|
|
253
|
+
return Boolean(match[4]);
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
// The staged package must be exactly cairn-ai@<target> with no dependencies, symlinks, or special files.
|
|
257
|
+
async function verifyStagedPackage(stage, target) {
|
|
258
|
+
const modules = join(stage, "node_modules");
|
|
259
|
+
const packageRoot = join(modules, UPDATE_PACKAGE_NAME);
|
|
260
|
+
try {
|
|
261
|
+
for (const entry of (await readdir(modules)).sort()) {
|
|
262
|
+
if (!entry.startsWith(".") && entry !== UPDATE_PACKAGE_NAME) return `unexpected package in node_modules: ${entry}`;
|
|
263
|
+
}
|
|
264
|
+
const special = await firstSpecialEntry(packageRoot);
|
|
265
|
+
if (special) return `not a regular file or directory: ${relative(stage, special)}`;
|
|
266
|
+
const manifest = JSON.parse(await readFile(join(packageRoot, "package.json"), "utf8"));
|
|
267
|
+
if (manifest?.name !== UPDATE_PACKAGE_NAME || manifest.version !== target) {
|
|
268
|
+
return `package.json names ${manifest?.name}@${manifest?.version}, expected ${UPDATE_PACKAGE_NAME}@${target}`;
|
|
269
|
+
}
|
|
270
|
+
const plugin = JSON.parse(await readFile(join(packageRoot, ".codex-plugin", "plugin.json"), "utf8"));
|
|
271
|
+
if (plugin?.name !== "cairn" || plugin.version !== target) {
|
|
272
|
+
return `.codex-plugin/plugin.json names ${plugin?.name}@${plugin?.version}, expected cairn@${target}`;
|
|
273
|
+
}
|
|
274
|
+
if (!(await lstat(join(packageRoot, "scripts", "cairn-lifecycle.mjs"))).isFile()) return "scripts/cairn-lifecycle.mjs is not a regular file";
|
|
275
|
+
return null;
|
|
276
|
+
} catch (error) {
|
|
277
|
+
return error instanceof Error ? error.message : String(error);
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
async function firstSpecialEntry(path) {
|
|
282
|
+
const info = await lstat(path);
|
|
283
|
+
if (info.isFile()) return null;
|
|
284
|
+
if (!info.isDirectory()) return path;
|
|
285
|
+
for (const entry of (await readdir(path)).sort()) {
|
|
286
|
+
const found = await firstSpecialEntry(join(path, entry));
|
|
287
|
+
if (found) return found;
|
|
288
|
+
}
|
|
289
|
+
return null;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
// CAIRN_NPM_CLI follows the CAIRN_CLAUDE_CLI rule: a .mjs/.js stand-in runs through this Node binary, anything else
|
|
293
|
+
// is run directly (through the shell on Windows for npm.cmd).
|
|
294
|
+
function runNpm(args, { cwd, env, timeout }) {
|
|
295
|
+
const cli = env.CAIRN_NPM_CLI ?? "npm";
|
|
296
|
+
const options = { cwd, env, encoding: "utf8", timeout, windowsHide: true, maxBuffer: 16 * 1024 * 1024 };
|
|
297
|
+
if (/\.m?js$/.test(cli)) return spawnSync(process.execPath, [cli, ...args], options);
|
|
298
|
+
return spawnSync(cli, args, { ...options, shell: process.platform === "win32" });
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
function logEntry(label, run) {
|
|
302
|
+
return `$ ${label} (exit ${run.status ?? run.error?.code ?? run.signal ?? "unknown"})\n${run.stdout ?? ""}${run.stderr ?? ""}`;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
// The last run's npm and lifecycle output, keeping the end when it exceeds 64 KiB.
|
|
306
|
+
function writeLog(path, now, entries) {
|
|
307
|
+
try {
|
|
308
|
+
let text = `${now.toISOString()}\n${entries.join("\n")}\n`;
|
|
309
|
+
const bytes = Buffer.from(text, "utf8");
|
|
310
|
+
if (bytes.length > LOG_LIMIT_BYTES) text = bytes.subarray(bytes.length - LOG_LIMIT_BYTES).toString("utf8");
|
|
311
|
+
while (Buffer.byteLength(text, "utf8") > LOG_LIMIT_BYTES) text = text.slice(1);
|
|
312
|
+
writeFileAtomic(path, text);
|
|
313
|
+
} catch {
|
|
314
|
+
// The log is diagnostic only.
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
function lastLine(run) {
|
|
319
|
+
const text = [run.stderr, run.stdout].map((value) => String(value ?? "").trim()).find(Boolean) ?? run.error?.message ?? `exit ${run.status}`;
|
|
320
|
+
return text.split("\n").filter((line) => line.trim()).at(-1)?.trim().slice(0, 300) ?? "";
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
function printJson(value) {
|
|
324
|
+
console.log(JSON.stringify(value, null, 2));
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
function isCliEntry() {
|
|
328
|
+
if (!process.argv[1]) return false;
|
|
329
|
+
try {
|
|
330
|
+
return realpathSync(fileURLToPath(import.meta.url)) === realpathSync(process.argv[1]);
|
|
331
|
+
} catch {
|
|
332
|
+
return import.meta.url === pathToFileURL(process.argv[1]).href;
|
|
333
|
+
}
|
|
334
|
+
}
|
|
@@ -1,11 +1,17 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {
|
|
2
|
+
import { constants, readFileSync } from "node:fs";
|
|
3
|
+
import { lstat, open, readdir, rm, rmdir } from "node:fs/promises";
|
|
4
|
+
import { hostname } from "node:os";
|
|
3
5
|
import { join, resolve } from "node:path";
|
|
4
6
|
import { pathToFileURL } from "node:url";
|
|
5
7
|
import { reconcileWorktreeState } from "./cairn-goal.mjs";
|
|
6
|
-
import {
|
|
8
|
+
import { resolvePluginRoot, resolveRepoRoot } from "./cairn-paths.mjs";
|
|
9
|
+
import { lockOwnerIsDead, parseLockRecord } from "./cairn-safe-fs.mjs";
|
|
7
10
|
|
|
8
|
-
const
|
|
11
|
+
const staleLockPrefix = "state.lock.stale.";
|
|
12
|
+
const staleLockName = /^state\.lock\.stale\.(.+)\.[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
|
|
13
|
+
const MAX_LOCK_RECORD_BYTES = 4096;
|
|
14
|
+
const usage = "Usage: cairn cleanup [--root PATH] [--check | --yes]";
|
|
9
15
|
|
|
10
16
|
export async function cleanupProjectCairn({ root = process.cwd(), apply = false } = {}) {
|
|
11
17
|
const repoRoot = resolve(root);
|
|
@@ -14,7 +20,9 @@ export async function cleanupProjectCairn({ root = process.cwd(), apply = false
|
|
|
14
20
|
try {
|
|
15
21
|
rootStat = await lstat(legacyRoot);
|
|
16
22
|
} catch (error) {
|
|
17
|
-
if (error?.code === "ENOENT")
|
|
23
|
+
if (error?.code === "ENOENT") {
|
|
24
|
+
return { root: repoRoot, apply, known: [], unknown: [], removed: [], projectDirectoryRemoved: false, preservedReasons: {} };
|
|
25
|
+
}
|
|
18
26
|
throw error;
|
|
19
27
|
}
|
|
20
28
|
if (rootStat.isSymbolicLink()) throw new Error(`Legacy Cairn root must not be a symbolic link: ${legacyRoot}`);
|
|
@@ -23,21 +31,42 @@ export async function cleanupProjectCairn({ root = process.cwd(), apply = false
|
|
|
23
31
|
const entries = await readdir(legacyRoot, { withFileTypes: true });
|
|
24
32
|
const known = [];
|
|
25
33
|
const unknown = [];
|
|
34
|
+
const preservedReasons = {};
|
|
26
35
|
for (const entry of entries) {
|
|
27
|
-
|
|
36
|
+
if (entry.isFile() && isLockFileName(entry.name)) {
|
|
37
|
+
// Lock files are Cairn-owned only when their content is a lock record that may be removed.
|
|
38
|
+
const reason = await lockFileReason(join(legacyRoot, entry.name), entry.name);
|
|
39
|
+
if (reason === null) known.push(entry.name);
|
|
40
|
+
else {
|
|
41
|
+
unknown.push(entry.name);
|
|
42
|
+
preservedReasons[entry.name] = reason;
|
|
43
|
+
}
|
|
44
|
+
continue;
|
|
45
|
+
}
|
|
46
|
+
const isKnownFile = entry.isFile() && entry.name === "state.json";
|
|
28
47
|
const isKnownDirectory = entry.isDirectory() && entry.name === "tools";
|
|
29
48
|
(isKnownFile || isKnownDirectory ? known : unknown).push(entry.name);
|
|
30
49
|
}
|
|
31
|
-
if (!apply) return {
|
|
50
|
+
if (!apply) return cleanupResult({ repoRoot, apply, known, unknown, removed: [], projectDirectoryRemoved: false, preservedReasons });
|
|
32
51
|
|
|
33
52
|
if (known.includes("state.json")) await reconcileWorktreeState({ root: repoRoot });
|
|
34
53
|
const removed = [];
|
|
35
|
-
for (const name of known) {
|
|
54
|
+
for (const name of [...known]) {
|
|
36
55
|
const path = join(legacyRoot, name);
|
|
37
56
|
try {
|
|
38
57
|
const stat = await lstat(path);
|
|
39
58
|
const expectedType = name === "tools" ? stat.isDirectory() : stat.isFile();
|
|
40
59
|
if (!expectedType) continue;
|
|
60
|
+
if (isLockFileName(name)) {
|
|
61
|
+
// Judge the lock again right before removal; a lock that changed owner is preserved.
|
|
62
|
+
const reason = await lockFileReason(path, name);
|
|
63
|
+
if (reason !== null) {
|
|
64
|
+
known.splice(known.indexOf(name), 1);
|
|
65
|
+
unknown.push(name);
|
|
66
|
+
preservedReasons[name] = reason;
|
|
67
|
+
continue;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
41
70
|
await rm(path, { recursive: name === "tools", force: true });
|
|
42
71
|
removed.push(name);
|
|
43
72
|
} catch (error) {
|
|
@@ -51,17 +80,115 @@ export async function cleanupProjectCairn({ root = process.cwd(), apply = false
|
|
|
51
80
|
} catch (error) {
|
|
52
81
|
if (!["ENOENT", "ENOTEMPTY", "EEXIST"].includes(error?.code)) throw error;
|
|
53
82
|
}
|
|
54
|
-
return {
|
|
83
|
+
return cleanupResult({ repoRoot, apply, known, unknown, removed, projectDirectoryRemoved, preservedReasons });
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function cleanupResult({ repoRoot, apply, known, unknown, removed, projectDirectoryRemoved, preservedReasons }) {
|
|
87
|
+
return {
|
|
88
|
+
root: repoRoot,
|
|
89
|
+
apply,
|
|
90
|
+
known: known.sort(),
|
|
91
|
+
unknown: unknown.sort(),
|
|
92
|
+
removed: removed.sort(),
|
|
93
|
+
projectDirectoryRemoved,
|
|
94
|
+
preservedReasons: Object.fromEntries(Object.keys(preservedReasons).sort().map((name) => [name, preservedReasons[name]])),
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function isLockFileName(name) {
|
|
99
|
+
return name === "state.lock" || name.startsWith(staleLockPrefix);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// Returns null when the lock file may be removed, otherwise the reason it is preserved.
|
|
103
|
+
async function lockFileReason(path, name) {
|
|
104
|
+
let nonce = null;
|
|
105
|
+
if (name !== "state.lock") {
|
|
106
|
+
const match = staleLockName.exec(name);
|
|
107
|
+
if (!match) return "invalid-lock-record";
|
|
108
|
+
nonce = match[1];
|
|
109
|
+
}
|
|
110
|
+
const record = await readLockRecord(path);
|
|
111
|
+
if (!record) return "invalid-lock-record";
|
|
112
|
+
if (nonce !== null) return record.nonce === nonce ? null : "invalid-lock-record";
|
|
113
|
+
if (lockOwnerIsDead(record)) return null;
|
|
114
|
+
return record.hostname === hostname() ? "live-lock-owner" : "foreign-host-lock";
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
async function readLockRecord(path) {
|
|
118
|
+
let handle;
|
|
119
|
+
try {
|
|
120
|
+
// Never follow a link or block on a special file that replaced the inspected entry.
|
|
121
|
+
handle = await open(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
|
|
122
|
+
const stat = await handle.stat();
|
|
123
|
+
if (!stat.isFile() || stat.size > MAX_LOCK_RECORD_BYTES) return null;
|
|
124
|
+
const buffer = Buffer.alloc(MAX_LOCK_RECORD_BYTES + 1);
|
|
125
|
+
const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
|
|
126
|
+
if (bytesRead > MAX_LOCK_RECORD_BYTES) return null;
|
|
127
|
+
return parseLockRecord(buffer.subarray(0, bytesRead).toString("utf8"));
|
|
128
|
+
} catch {
|
|
129
|
+
return null;
|
|
130
|
+
} finally {
|
|
131
|
+
await handle?.close();
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
class CleanupUsageError extends Error {}
|
|
136
|
+
|
|
137
|
+
function parseCleanupArgs(args) {
|
|
138
|
+
const provided = new Set();
|
|
139
|
+
let explicitRoot = null;
|
|
140
|
+
for (let index = 0; index < args.length; index += 1) {
|
|
141
|
+
const argument = args[index];
|
|
142
|
+
if (["--help", "--version", "--check", "--yes"].includes(argument)) {
|
|
143
|
+
if (provided.has(argument)) throw new CleanupUsageError(`${argument} may only be provided once`);
|
|
144
|
+
provided.add(argument);
|
|
145
|
+
} else if (argument === "--root" || argument.startsWith("--root=")) {
|
|
146
|
+
if (explicitRoot !== null) throw new CleanupUsageError("--root may only be provided once");
|
|
147
|
+
const value = argument === "--root" ? args[index + 1] : argument.slice("--root=".length);
|
|
148
|
+
if (!value || value.startsWith("--")) throw new CleanupUsageError("--root requires a path");
|
|
149
|
+
explicitRoot = value;
|
|
150
|
+
if (argument === "--root") index += 1;
|
|
151
|
+
} else {
|
|
152
|
+
throw new CleanupUsageError(`unknown option: ${argument}`);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
if (provided.has("--help") && provided.has("--version")) throw new CleanupUsageError("--help and --version cannot be used together");
|
|
156
|
+
if (provided.has("--check") && provided.has("--yes")) throw new CleanupUsageError("--check and --yes cannot be used together");
|
|
157
|
+
const action = provided.has("--help") ? "help" : provided.has("--version") ? "version" : "cleanup";
|
|
158
|
+
return { action, explicitRoot, apply: provided.has("--yes") };
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
async function main(args) {
|
|
162
|
+
let options;
|
|
163
|
+
try {
|
|
164
|
+
options = parseCleanupArgs(args);
|
|
165
|
+
} catch (error) {
|
|
166
|
+
console.error(`Cairn cleanup error: ${firstLine(error)}`);
|
|
167
|
+
process.exitCode = 2;
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
if (options.action === "help") {
|
|
171
|
+
console.log(usage);
|
|
172
|
+
return;
|
|
173
|
+
}
|
|
174
|
+
if (options.action === "version") {
|
|
175
|
+
const { version } = JSON.parse(readFileSync(join(resolvePluginRoot(import.meta.url), "package.json"), "utf8"));
|
|
176
|
+
console.log(`cairn ${version}`);
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
try {
|
|
180
|
+
const repoRoot = resolveRepoRoot({ explicitRoot: options.explicitRoot });
|
|
181
|
+
console.log(JSON.stringify(await cleanupProjectCairn({ root: repoRoot, apply: options.apply }), null, 2));
|
|
182
|
+
} catch (error) {
|
|
183
|
+
console.error(`Cairn cleanup error: ${firstLine(error)}`);
|
|
184
|
+
process.exitCode = 1;
|
|
185
|
+
}
|
|
55
186
|
}
|
|
56
187
|
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
const apply = args.includes("--yes");
|
|
60
|
-
const unsupported = args.filter((value) => value !== "--yes" && value !== "--check");
|
|
61
|
-
if (unsupported.length > 0) throw new Error(`Unknown cleanup option: ${unsupported[0]}`);
|
|
62
|
-
console.log(JSON.stringify(await cleanupProjectCairn({ root: repoRoot, apply }), null, 2));
|
|
188
|
+
function firstLine(error) {
|
|
189
|
+
return String(error instanceof Error ? error.message : error).split(/\r?\n/)[0];
|
|
63
190
|
}
|
|
64
191
|
|
|
65
192
|
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
|
66
|
-
await main();
|
|
193
|
+
await main(process.argv.slice(2));
|
|
67
194
|
}
|