@douyin-minigame/cli 0.6.1 → 0.8.0-alpha.20261204090540.dev
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/CHANGELOG.md +16 -0
- package/README.md +40 -21
- package/Third party software notice.json +15 -0
- package/dist/cli.js +114 -111
- package/dist/mintplay/capabilities/identity.json +40 -0
- package/dist/mintplay/capabilities/official.mpbundle +3471 -0
- package/dist/mintplay/dist/init.d.ts +2 -0
- package/dist/mintplay/dist/init.js +2250 -0
- package/dist/mintplay/dist/rename-no-replace-darwin-arm64 +0 -0
- package/dist/mintplay/dist/rename-no-replace-linux-x64 +0 -0
- package/dist/mintplay/dist/rename-no-replace-win32-x64.exe +0 -0
- package/dist/mintplay/package.json +5 -0
- package/package.json +2 -1
- package/skills/douyin-minigame/SKILL.md +82 -144
- package/skills/douyin-minigame/references/capabilities/ad-monetization.md +2 -2
- package/skills/douyin-minigame/references/capabilities/add-shortcut.md +2 -4
- package/skills/douyin-minigame/references/capabilities/customer-service.md +1 -3
- package/skills/douyin-minigame/references/capabilities/sidebar-retention.md +1 -3
- package/skills/douyin-minigame/references/capabilities/social-share.md +3 -5
- package/skills/douyin-minigame/references/capability-integration.md +38 -0
- package/skills/douyin-minigame/references/commands/ability.md +1 -4
- package/skills/douyin-minigame/references/commands/analytics.md +41 -31
- package/skills/douyin-minigame/references/commands/auth.md +19 -58
- package/skills/douyin-minigame/references/commands/feedback.md +22 -10
- package/skills/douyin-minigame/references/commands/game.md +2 -8
- package/skills/douyin-minigame/references/commands/growth.md +30 -36
- package/skills/douyin-minigame/references/commands/insight.md +6 -4
- package/skills/douyin-minigame/references/commands/mintplay.md +11 -0
- package/skills/douyin-minigame/references/commands/performance.md +27 -17
- package/skills/douyin-minigame/references/commands/publisher.md +20 -13
- package/skills/douyin-minigame/references/commands/revenue.md +30 -7
- package/skills/douyin-minigame/references/commands/update.md +26 -20
- package/skills/douyin-minigame/references/parameters.md +57 -31
|
@@ -0,0 +1,2250 @@
|
|
|
1
|
+
// dist/init/project-command.js
|
|
2
|
+
import fs4 from "node:fs";
|
|
3
|
+
import path4 from "node:path";
|
|
4
|
+
|
|
5
|
+
// dist/project.js
|
|
6
|
+
import fs3 from "node:fs";
|
|
7
|
+
import path3 from "node:path";
|
|
8
|
+
import os from "node:os";
|
|
9
|
+
import { randomUUID } from "node:crypto";
|
|
10
|
+
import { spawnSync as spawnSync2 } from "node:child_process";
|
|
11
|
+
|
|
12
|
+
// dist/contracts.js
|
|
13
|
+
import { createHash } from "node:crypto";
|
|
14
|
+
|
|
15
|
+
// dist/error.js
|
|
16
|
+
var MintPlayError = class extends Error {
|
|
17
|
+
code;
|
|
18
|
+
paths;
|
|
19
|
+
constructor(code, message, paths = []) {
|
|
20
|
+
super(message);
|
|
21
|
+
this.code = code;
|
|
22
|
+
this.paths = paths;
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
// dist/contracts.js
|
|
27
|
+
var sha = (bytes) => createHash("sha256").update(bytes).digest("hex");
|
|
28
|
+
var json = (value) => Buffer.from(JSON.stringify(value, null, 2) + "\n");
|
|
29
|
+
var order = (a, b) => Buffer.compare(Buffer.from(a), Buffer.from(b));
|
|
30
|
+
var hashPattern = /^[a-f0-9]{64}$/;
|
|
31
|
+
var execObservable = process.platform !== "win32";
|
|
32
|
+
var execFlag = (executable) => execObservable && executable ? 1 : 0;
|
|
33
|
+
var execMatches = (mode, executable) => !execObservable || Boolean(mode & 73) === executable;
|
|
34
|
+
var commitPattern = /^[a-f0-9]{40}$/;
|
|
35
|
+
var skillPattern = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
|
|
36
|
+
function fail(ok, message, code = 4) {
|
|
37
|
+
if (!ok)
|
|
38
|
+
throw new MintPlayError(code, message);
|
|
39
|
+
}
|
|
40
|
+
function relPath(value) {
|
|
41
|
+
fail(typeof value === "string" && value.length < 1024 && value.length > 0 && !value.includes("\\") && !/[\x00-\x1f\x7f:]/.test(value) && value.split("/").every((p) => p && p !== "." && p !== ".."), `Unsafe path: ${String(value)}`);
|
|
42
|
+
}
|
|
43
|
+
function exactKeys(o, keys, label) {
|
|
44
|
+
fail(o && typeof o === "object" && !Array.isArray(o) && Object.keys(o).sort().join(",") === keys.sort().join(","), `Unsupported ${label} schema`, 2);
|
|
45
|
+
}
|
|
46
|
+
var bundleFileLimit = 2e4;
|
|
47
|
+
var namespacePattern = /^[A-Za-z0-9][A-Za-z0-9._-]*(?:\/[A-Za-z0-9][A-Za-z0-9._-]*){1,3}$/;
|
|
48
|
+
var versionPattern = /^[0-9][A-Za-z0-9.+_-]{0,127}$/;
|
|
49
|
+
function validateAgentBuddySkills(value) {
|
|
50
|
+
fail(Array.isArray(value) && value.length < 100, "Invalid AgentBuddy skill list", 2);
|
|
51
|
+
const names = /* @__PURE__ */ new Set();
|
|
52
|
+
for (const item of value) {
|
|
53
|
+
const keys = ["name", "version", "sha256"];
|
|
54
|
+
if (item && typeof item === "object" && Object.hasOwn(item, "namespace"))
|
|
55
|
+
keys.push("namespace");
|
|
56
|
+
exactKeys(item, keys, "AgentBuddy skill");
|
|
57
|
+
fail(typeof item.name === "string" && item.name.length <= 64 && skillPattern.test(item.name) && !names.has(item.name), "Invalid or duplicate AgentBuddy skill name", 2);
|
|
58
|
+
if (keys.includes("namespace"))
|
|
59
|
+
fail(typeof item.namespace === "string" && item.namespace.length <= 200 && namespacePattern.test(item.namespace), "Invalid legacy AgentBuddy namespace", 2);
|
|
60
|
+
fail(typeof item.version === "string" && versionPattern.test(item.version) && typeof item.sha256 === "string" && hashPattern.test(item.sha256), "Invalid AgentBuddy skill version or digest", 2);
|
|
61
|
+
names.add(item.name);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
var agentBuddyRelease = (value) => `agentbuddy-${sha(json(value))}`;
|
|
65
|
+
function validateManifest(m) {
|
|
66
|
+
const keys = ["schema_version", "package_id", "release", "source", "profile", "skills", "files_manifest_sha256", "compatibility", "plugins", "distribution_rights"];
|
|
67
|
+
if (m && typeof m === "object" && Object.hasOwn(m, "agentbuddy"))
|
|
68
|
+
keys.push("agentbuddy");
|
|
69
|
+
exactKeys(m, keys, "manifest");
|
|
70
|
+
fail(m.schema_version === 1 && m.package_id === "mintplay-harness" && m.profile === "full" && typeof m.release === "string" && m.release.length < 200 && hashPattern.test(m.files_manifest_sha256), "Invalid manifest");
|
|
71
|
+
exactKeys(m.source, ["repository", "commit"], "source");
|
|
72
|
+
fail(commitPattern.test(m.source.commit) && typeof m.source.repository === "string" && (m.source.repository === "local-only" || /^(https:\/\/[^@?\s#]+|git@[^?\s#]+)$/.test(m.source.repository)), "Invalid source identity");
|
|
73
|
+
fail(Array.isArray(m.skills) && m.skills.length > 0 && m.skills.every((s) => typeof s === "string" && skillPattern.test(s)) && m.skills.join(",") === [...new Set(m.skills)].sort(order).join(","), "Invalid skill set");
|
|
74
|
+
if (keys.includes("agentbuddy")) {
|
|
75
|
+
exactKeys(m.agentbuddy, ["base_manifest_sha256", "skills"], "AgentBuddy lock");
|
|
76
|
+
const { base_manifest_sha256, skills } = m.agentbuddy;
|
|
77
|
+
validateAgentBuddySkills(skills);
|
|
78
|
+
fail(typeof base_manifest_sha256 === "string" && hashPattern.test(base_manifest_sha256) && skills.length > 0 && skills.every((s, i) => m.skills.includes(s.name) && (!i || order(skills[i - 1].name, s.name) < 0)) && m.release === agentBuddyRelease({ base_manifest_sha256, skills }), "Invalid AgentBuddy lock");
|
|
79
|
+
}
|
|
80
|
+
exactKeys(m.compatibility, ["node_min", "markdown_memory_sha256", "asset_ledger_version"], "compatibility");
|
|
81
|
+
fail(m.compatibility.node_min === 22 && hashPattern.test(m.compatibility.markdown_memory_sha256) && [2, null].includes(m.compatibility.asset_ledger_version), "Invalid compatibility");
|
|
82
|
+
exactKeys(m.plugins, ["identity", "source_codex_name", "source_claude_name"], "plugins");
|
|
83
|
+
fail(m.plugins.identity === "mintplay-harness" && ["source_codex_name", "source_claude_name"].every((k) => typeof m.plugins[k] === "string" && skillPattern.test(m.plugins[k])) && m.distribution_rights === "unverified", "Invalid plugin identity");
|
|
84
|
+
}
|
|
85
|
+
function validateFiles(value) {
|
|
86
|
+
fail(Array.isArray(value) && value.length > 0 && value.length < bundleFileLimit, "Invalid file list");
|
|
87
|
+
let previous = "";
|
|
88
|
+
for (const e of value) {
|
|
89
|
+
exactKeys(e, ["path", "sha256", "size", "executable"], "file");
|
|
90
|
+
relPath(e.path);
|
|
91
|
+
fail((e.path.startsWith("skills/") || ["NOTICE", "LICENSE", ".codex-plugin/plugin.json", ".claude-plugin/plugin.json"].includes(e.path)) && !e.path.split("/").some((p) => [".git", "__pycache__", "node_modules", ".DS_Store"].includes(p)) && !e.path.endsWith(".pyc") && hashPattern.test(e.sha256) && Number.isSafeInteger(e.size) && e.size >= 0 && typeof e.executable === "boolean" && (!previous || order(previous, e.path) < 0), "Invalid or unordered file entry");
|
|
92
|
+
previous = e.path;
|
|
93
|
+
}
|
|
94
|
+
const names = new Set(value.map((e) => e.path));
|
|
95
|
+
fail(value.every((e) => !e.path.split("/").slice(0, -1).some((_, i, p) => names.has(p.slice(0, i + 1).join("/")))), "File-directory collision");
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// dist/bundle.js
|
|
99
|
+
import fs from "node:fs";
|
|
100
|
+
import path from "node:path";
|
|
101
|
+
import { spawnSync } from "node:child_process";
|
|
102
|
+
var bundlePayloadLimit = 100 * 1024 * 1024;
|
|
103
|
+
var gitVersionChecked = false;
|
|
104
|
+
var git = (repo, args) => {
|
|
105
|
+
if (!gitVersionChecked) {
|
|
106
|
+
const version = spawnSync("git", ["--version"], { encoding: "utf8" }), match = /git version (\d+)\.(\d+)/.exec(version.stdout || "");
|
|
107
|
+
fail(version.status === 0 && match && (Number(match[1]) > 2 || Number(match[1]) === 2 && Number(match[2]) >= 47), "Local Git export requires Git 2.47+ with verified no-lazy-fetch support", 4);
|
|
108
|
+
gitVersionChecked = true;
|
|
109
|
+
}
|
|
110
|
+
const p = spawnSync("git", ["-C", repo, ...args], { maxBuffer: bundlePayloadLimit, env: { ...process.env, GIT_NO_REPLACE_OBJECTS: "1", GIT_NO_LAZY_FETCH: "1", GIT_OPTIONAL_LOCKS: "0", GIT_CONFIG_NOSYSTEM: "1" } });
|
|
111
|
+
if (p.status !== 0 || p.error)
|
|
112
|
+
throw new MintPlayError(4, `Git source unavailable: ${p.error?.message || p.stderr.toString().trim()}`);
|
|
113
|
+
return p.stdout;
|
|
114
|
+
};
|
|
115
|
+
function fromGit(repo, commit, options = {}, excludedSkills = []) {
|
|
116
|
+
fail(commitPattern.test(commit), "A full 40-character commit is required", 2);
|
|
117
|
+
const { audience, excludeSkills = [] } = typeof options === "string" ? { audience: options, excludeSkills: excludedSkills } : options;
|
|
118
|
+
fail(Array.isArray(excludeSkills), "Excluded skills must be an array", 2);
|
|
119
|
+
const excludedPrefixes = [];
|
|
120
|
+
for (const skill of excludeSkills) {
|
|
121
|
+
fail(skill !== "game-studio" && skill !== "_shared", "Cannot exclude game-studio or _shared", 2);
|
|
122
|
+
fail(typeof skill === "string" && skill.length <= 64 && skillPattern.test(skill), "Invalid excluded skill name", 2);
|
|
123
|
+
excludedPrefixes.push(`skills/${skill}/`);
|
|
124
|
+
}
|
|
125
|
+
fail(git(repo, ["rev-parse", "--verify", `${commit}^{commit}`]).toString().trim() === commit, "Commit mismatch");
|
|
126
|
+
const payload = /* @__PURE__ */ new Map();
|
|
127
|
+
const entries2 = [];
|
|
128
|
+
let total = 0;
|
|
129
|
+
const tree = git(repo, ["ls-tree", "-rz", commit, "--", "skills", "NOTICE", "LICENSE", ".codex-plugin/plugin.json", ".claude-plugin/plugin.json"]).toString("utf8");
|
|
130
|
+
const liveRegistration = /^skills\/platform-douyin-live\/templates\/(live-dev\/provenance|liveopen-js-sdk\/provenance(?:-[^/]+)?)\.json$/;
|
|
131
|
+
for (const row of tree.split("\0").filter(Boolean)) {
|
|
132
|
+
const match = /^(\d+) (\w+) ([a-f0-9]+)\t([\s\S]+)$/.exec(row);
|
|
133
|
+
fail(match, "Invalid Git tree");
|
|
134
|
+
const [, mode, type, oid, name] = match;
|
|
135
|
+
if (excludedPrefixes.some((prefix) => name.startsWith(prefix)))
|
|
136
|
+
continue;
|
|
137
|
+
relPath(name);
|
|
138
|
+
fail(type === "blob" && ["100644", "100755"].includes(mode), `Symlink or special source entry refused: ${name}`);
|
|
139
|
+
fail(!name.split("/").some((p) => ["__pycache__", "node_modules", ".DS_Store"].includes(p)) && !name.endsWith(".pyc"), `Non-distributable source entry: ${name}`);
|
|
140
|
+
if (audience === "public" && (name.startsWith("skills/platform-douyin-live/assets/gifts/") || name === "skills/platform-douyin-docs/references/mini-game-sources.md"))
|
|
141
|
+
continue;
|
|
142
|
+
let bytes = git(repo, ["cat-file", "blob", oid]);
|
|
143
|
+
if (audience === "public" && liveRegistration.test(name)) {
|
|
144
|
+
const metadata = JSON.parse(bytes.toString("utf8"));
|
|
145
|
+
const { date, scope, source: source2, sdkRuntimeIncluded, gameDistributionAllowed, productionAllowed, w2IndependentReview } = metadata.authorization;
|
|
146
|
+
metadata.authorization = { date, scope, source: source2, sdkRuntimeIncluded, gameDistributionAllowed, productionAllowed, w2IndependentReview };
|
|
147
|
+
bytes = json(metadata);
|
|
148
|
+
}
|
|
149
|
+
total += bytes.length;
|
|
150
|
+
fail(total <= bundlePayloadLimit, "Bundle exceeds size limit");
|
|
151
|
+
payload.set(name, bytes);
|
|
152
|
+
entries2.push({ path: name, sha256: sha(bytes), size: bytes.length, executable: mode === "100755" });
|
|
153
|
+
}
|
|
154
|
+
const skills = entries2.filter((e) => /^skills\/[^/]+\/SKILL\.md$/.test(e.path)).map((e) => e.path.split("/")[1]).sort(order);
|
|
155
|
+
fail(payload.has("skills/_shared/memory-spec.md") && skills.includes("game-studio"), "Full skills profile requires game-studio and shared memory");
|
|
156
|
+
const pluginName = (host) => {
|
|
157
|
+
const v = JSON.parse(payload.get(`.${host}-plugin/plugin.json`)?.toString() || "{}");
|
|
158
|
+
fail(typeof v.name === "string", `Missing ${host} plugin manifest`);
|
|
159
|
+
return v.name;
|
|
160
|
+
};
|
|
161
|
+
const repository = "local-only";
|
|
162
|
+
const asset = (payload.get("skills/asset-ledger/scripts/assetlib.py") ?? payload.get("skills/asset-pipeline/scripts/assetlib.py"))?.toString() || "";
|
|
163
|
+
const assetLedgerVersion = skills.includes("asset-delivery") || /(?:VERSION\s*=\s*2|["']version["']:\s*2)/.test(asset) ? 2 : null;
|
|
164
|
+
const manifest = {
|
|
165
|
+
schema_version: 1,
|
|
166
|
+
package_id: "mintplay-harness",
|
|
167
|
+
release: commit,
|
|
168
|
+
source: { repository, commit },
|
|
169
|
+
profile: "full",
|
|
170
|
+
skills,
|
|
171
|
+
files_manifest_sha256: "",
|
|
172
|
+
compatibility: { node_min: 22, markdown_memory_sha256: sha(payload.get("skills/_shared/memory-spec.md")), asset_ledger_version: assetLedgerVersion },
|
|
173
|
+
plugins: { identity: "mintplay-harness", source_codex_name: pluginName("codex"), source_claude_name: pluginName("claude") },
|
|
174
|
+
distribution_rights: "unverified"
|
|
175
|
+
};
|
|
176
|
+
entries2.sort((a, b) => order(a.path, b.path));
|
|
177
|
+
const filesBytes = json(entries2);
|
|
178
|
+
manifest.files_manifest_sha256 = sha(filesBytes);
|
|
179
|
+
return checkBundle(json(manifest), filesBytes, payload);
|
|
180
|
+
}
|
|
181
|
+
function checkBundle(manifestBytes, filesBytes, payload, expected) {
|
|
182
|
+
fail(manifestBytes.length <= 2 * 1024 * 1024 && filesBytes.length <= 2 * 1024 * 1024, "Oversized bundle metadata");
|
|
183
|
+
const digest = sha(manifestBytes);
|
|
184
|
+
fail(!expected || digest === expected, "Manifest digest mismatch");
|
|
185
|
+
let manifest, files;
|
|
186
|
+
try {
|
|
187
|
+
manifest = JSON.parse(manifestBytes.toString());
|
|
188
|
+
files = JSON.parse(filesBytes.toString());
|
|
189
|
+
} catch {
|
|
190
|
+
throw new MintPlayError(4, "Malformed bundle JSON");
|
|
191
|
+
}
|
|
192
|
+
validateManifest(manifest);
|
|
193
|
+
validateFiles(files);
|
|
194
|
+
fail(sha(filesBytes) === manifest.files_manifest_sha256, "File manifest digest mismatch");
|
|
195
|
+
fail(payload.size === files.length && files.every((e) => payload.has(e.path)), "Unlisted or missing payload");
|
|
196
|
+
let total = 0;
|
|
197
|
+
for (const e of files) {
|
|
198
|
+
const b = payload.get(e.path);
|
|
199
|
+
total += b.length;
|
|
200
|
+
fail(b.length === e.size && sha(b) === e.sha256, `Payload mismatch: ${e.path}`);
|
|
201
|
+
}
|
|
202
|
+
fail(total <= bundlePayloadLimit, "Bundle exceeds size limit");
|
|
203
|
+
const skills = files.filter((e) => /^skills\/[^/]+\/SKILL\.md$/.test(e.path)).map((e) => e.path.split("/")[1]).sort(order);
|
|
204
|
+
fail(skills.join(",") === manifest.skills.join(",") && payload.has("skills/_shared/memory-spec.md") && skills.includes("game-studio") && sha(payload.get("skills/_shared/memory-spec.md")) === manifest.compatibility.markdown_memory_sha256, "Profile or memory identity mismatch");
|
|
205
|
+
return { manifest, files, payload, manifestBytes, filesBytes, digest };
|
|
206
|
+
}
|
|
207
|
+
function base64(s) {
|
|
208
|
+
fail(typeof s === "string" && s.length % 4 === 0 && /^[A-Za-z0-9+/]*={0,2}$/.test(s), "Invalid base64");
|
|
209
|
+
const b = Buffer.from(s, "base64");
|
|
210
|
+
fail(b.toString("base64") === s, "Invalid base64");
|
|
211
|
+
return b;
|
|
212
|
+
}
|
|
213
|
+
function fromArchive(file, expected) {
|
|
214
|
+
const stat = fs.lstatSync(file);
|
|
215
|
+
fail(stat.isFile() && stat.size <= bundlePayloadLimit * 2, "Archive must be a bounded regular file");
|
|
216
|
+
let o;
|
|
217
|
+
try {
|
|
218
|
+
o = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
219
|
+
} catch {
|
|
220
|
+
throw new MintPlayError(4, "Invalid bundle archive");
|
|
221
|
+
}
|
|
222
|
+
exactKeys(o, ["format", "manifest", "files", "payload"], "archive");
|
|
223
|
+
fail(o.format === "mintplay-bundle-v1" && Array.isArray(o.payload) && o.payload.length < bundleFileLimit, "Unsupported archive");
|
|
224
|
+
const payload = /* @__PURE__ */ new Map();
|
|
225
|
+
for (const e of o.payload) {
|
|
226
|
+
exactKeys(e, ["path", "bytes"], "archive entry");
|
|
227
|
+
relPath(e.path);
|
|
228
|
+
fail(!payload.has(e.path), "Duplicate archive path");
|
|
229
|
+
payload.set(e.path, base64(e.bytes));
|
|
230
|
+
}
|
|
231
|
+
return checkBundle(base64(o.manifest), base64(o.files), payload, expected);
|
|
232
|
+
}
|
|
233
|
+
function writeBundle(bundle, root, afterFile) {
|
|
234
|
+
fail(!fs.existsSync(root), "Bundle destination already exists", 3);
|
|
235
|
+
fs.mkdirSync(root, { recursive: true });
|
|
236
|
+
fs.writeFileSync(path.join(root, "manifest.json"), bundle.manifestBytes, { flag: "wx" });
|
|
237
|
+
fs.writeFileSync(path.join(root, "files.json"), bundle.filesBytes, { flag: "wx" });
|
|
238
|
+
let index = 0;
|
|
239
|
+
for (const e of bundle.files) {
|
|
240
|
+
const target = path.join(root, e.path);
|
|
241
|
+
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
242
|
+
fs.writeFileSync(target, bundle.payload.get(e.path), { flag: "wx", mode: e.executable ? 493 : 420 });
|
|
243
|
+
afterFile?.(++index);
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
function isSkillBytecodeCache(directory, relative) {
|
|
247
|
+
if (!relative.startsWith("skills/") || !relative.endsWith("/__pycache__") || relative === "skills/__pycache__" || !fs.lstatSync(directory).isDirectory())
|
|
248
|
+
return false;
|
|
249
|
+
return fs.readdirSync(directory, { withFileTypes: true }).every((entry) => entry.isFile() && /^.+\.[\w-]+(?:\.opt-[a-zA-Z0-9]+)?\.pyc$/u.test(entry.name));
|
|
250
|
+
}
|
|
251
|
+
function readBundle(root, expected, mode = "strict") {
|
|
252
|
+
const payload = /* @__PURE__ */ new Map();
|
|
253
|
+
let manifestBytes, filesBytes;
|
|
254
|
+
const foundDirectories = [];
|
|
255
|
+
let totalBytes = 0, fileCount = 0;
|
|
256
|
+
const walk = (dir, rel = "") => {
|
|
257
|
+
fail(fs.lstatSync(dir).isDirectory(), `Not a regular bundle directory: ${rel}`);
|
|
258
|
+
for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
259
|
+
const r = rel ? `${rel}/${e.name}` : e.name;
|
|
260
|
+
relPath(r);
|
|
261
|
+
const f = path.join(dir, e.name);
|
|
262
|
+
if (e.isDirectory()) {
|
|
263
|
+
if (mode === "installed" && isSkillBytecodeCache(f, r))
|
|
264
|
+
continue;
|
|
265
|
+
fail(r === "skills" || r.startsWith("skills/") || [".codex-plugin", ".claude-plugin"].includes(r), `Unlisted directory: ${r}`);
|
|
266
|
+
foundDirectories.push(r);
|
|
267
|
+
walk(f, r);
|
|
268
|
+
} else {
|
|
269
|
+
fail(e.isFile(), `Symlink or special payload refused: ${r}`);
|
|
270
|
+
const stat = fs.lstatSync(f);
|
|
271
|
+
totalBytes += stat.size;
|
|
272
|
+
fileCount++;
|
|
273
|
+
fail(totalBytes <= bundlePayloadLimit + 4 * 1024 * 1024 && fileCount < bundleFileLimit + 2, "Oversized payload");
|
|
274
|
+
const bytes = fs.readFileSync(f);
|
|
275
|
+
if (r === "manifest.json")
|
|
276
|
+
manifestBytes = bytes;
|
|
277
|
+
else if (r === "files.json")
|
|
278
|
+
filesBytes = bytes;
|
|
279
|
+
else
|
|
280
|
+
payload.set(r, bytes);
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
};
|
|
284
|
+
walk(root);
|
|
285
|
+
fail(manifestBytes && filesBytes, "Missing bundle manifests");
|
|
286
|
+
const bundle = checkBundle(manifestBytes, filesBytes, payload, expected);
|
|
287
|
+
const directories = /* @__PURE__ */ new Set();
|
|
288
|
+
for (const e of bundle.files) {
|
|
289
|
+
const parts = e.path.split("/");
|
|
290
|
+
for (let i = 1; i < parts.length; i++)
|
|
291
|
+
directories.add(parts.slice(0, i).join("/"));
|
|
292
|
+
}
|
|
293
|
+
for (const dir of foundDirectories)
|
|
294
|
+
fail(directories.has(dir), `Unlisted directory: ${dir}`);
|
|
295
|
+
for (const e of bundle.files)
|
|
296
|
+
fail(execMatches(fs.lstatSync(path.join(root, e.path)).mode, e.executable), `Executable flag mismatch: ${e.path}`);
|
|
297
|
+
return bundle;
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
// dist/bundled.js
|
|
301
|
+
import fs2 from "node:fs";
|
|
302
|
+
import path2 from "node:path";
|
|
303
|
+
import { fileURLToPath } from "node:url";
|
|
304
|
+
var bundledArchive = fileURLToPath(new URL("../capabilities/official.mpbundle", import.meta.url));
|
|
305
|
+
var bundledReceipt = path2.join(path2.dirname(bundledArchive), "identity.json");
|
|
306
|
+
function officialBundle(expected) {
|
|
307
|
+
const dir = path2.dirname(bundledArchive);
|
|
308
|
+
fail(fs2.lstatSync(dir).isDirectory(), "Bundled capabilities must be a regular directory");
|
|
309
|
+
const stat = fs2.lstatSync(bundledReceipt);
|
|
310
|
+
fail(stat.isFile() && stat.size <= 2 * 1024 * 1024, "Invalid bundled identity file");
|
|
311
|
+
const identity2 = JSON.parse(fs2.readFileSync(bundledReceipt, "utf8"));
|
|
312
|
+
const keys = ["schema_version", "cli_version", "archive_sha256", "manifest_sha256", "source_commit", "cli_files"];
|
|
313
|
+
if (identity2 && typeof identity2 === "object" && Object.hasOwn(identity2, "audience"))
|
|
314
|
+
keys.push("audience");
|
|
315
|
+
exactKeys(identity2, keys, "bundled identity");
|
|
316
|
+
const pkg = JSON.parse(fs2.readFileSync(new URL("../package.json", import.meta.url), "utf8"));
|
|
317
|
+
fail(identity2.schema_version === 1 && identity2.cli_version === pkg.version && (!keys.includes("audience") || ["public", "internal"].includes(identity2.audience)) && hashPattern.test(identity2.archive_sha256) && hashPattern.test(identity2.manifest_sha256), "Bundled identity/version mismatch");
|
|
318
|
+
const bundle = fromArchive(bundledArchive, identity2.manifest_sha256);
|
|
319
|
+
fail(sha(fs2.readFileSync(bundledArchive)) === identity2.archive_sha256, "Bundled archive digest mismatch");
|
|
320
|
+
fail(bundle.manifest.source.commit === identity2.source_commit, "Bundled source commit mismatch");
|
|
321
|
+
for (const host of ["claude", "codex"]) {
|
|
322
|
+
const plugin = JSON.parse(bundle.payload.get(`.${host}-plugin/plugin.json`).toString());
|
|
323
|
+
fail(plugin.version === pkg.version, "CLI and official capability versions differ");
|
|
324
|
+
}
|
|
325
|
+
fail(!expected || bundle.digest === expected, "Installed CLI capabilities differ from the project lock; reinstall the matching CLI version or provide the exact --archive");
|
|
326
|
+
return bundle;
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
// dist/project.js
|
|
330
|
+
var ROOT = ".harness/mintplay";
|
|
331
|
+
var LOCK = ".harness/mintplay.lock.json";
|
|
332
|
+
var STATE = ".harness/.state/mintplay";
|
|
333
|
+
var MARKET = ".harness/.claude-plugin/marketplace.json";
|
|
334
|
+
var HOST = "host:claude/local-scope";
|
|
335
|
+
var IGNORE = "# MintPlay local state (managed)\n/.harness/.state/mintplay/\n/.harness/.claude-plugin/\n";
|
|
336
|
+
var AGENTS_BLOCK = "<!-- MintPlay harness (managed) -->\n## Game skills (MintPlay)\n\nThis project locks its game skills in `.harness/mintplay/skills/`. For game work, start with `.harness/mintplay/skills/game-studio/SKILL.md`; it owns project memory, verification and the order between skills. Read another skill when game-studio routes to it or its description in your skill list fits the current step (never an explicit-only skill unless the user invokes it), and only its SKILL.md until it points further. Whenever adding, modifying, or deleting game assets, use the installed asset delivery skill when available, or record the delivered files, specifications and sources in the project. A skill file already read in this session stays in context: do not reopen it; reread it only after the context was compacted or summarised.\n<!-- /MintPlay harness -->\n";
|
|
337
|
+
var BLOCKS = [
|
|
338
|
+
{ key: "ignore", file: ".gitignore", text: IGNORE, marker: "/.harness/.state/mintplay/", history: [] },
|
|
339
|
+
{ key: "agents", file: "AGENTS.md", text: AGENTS_BLOCK, marker: "<!-- MintPlay harness (managed) -->", history: [
|
|
340
|
+
// Published 0.4.0 (2f6cd3d); origin/main has no other AGENTS wording.
|
|
341
|
+
"<!-- MintPlay harness (managed) -->\n## Game skills (MintPlay)\n\nThis project locks its game skills in `.harness/mintplay/skills/`. For any request about the game, first read `.harness/mintplay/skills/game-studio/SKILL.md` and follow it; it routes to the other skills.\n<!-- /MintPlay harness -->\n",
|
|
342
|
+
// 75542c6 through 5a5cf04^: trigger-based reading, before the session-context sentence.
|
|
343
|
+
"<!-- MintPlay harness (managed) -->\n## Game skills (MintPlay)\n\nThis project locks its game skills in `.harness/mintplay/skills/`. For game work, start with `.harness/mintplay/skills/game-studio/SKILL.md`; read another skill only when that file names a trigger for it.\n<!-- /MintPlay harness -->\n",
|
|
344
|
+
// 5a5cf04 through 0.5.0-pre: session-context sentence, before independent asset-ledger trigger.
|
|
345
|
+
"<!-- MintPlay harness (managed) -->\n## Game skills (MintPlay)\n\nThis project locks its game skills in `.harness/mintplay/skills/`. For game work, start with `.harness/mintplay/skills/game-studio/SKILL.md`; read another skill only when that file names a trigger for it. A skill file already read in this session stays in context: do not reopen it; reread it only after the context was compacted or summarised.\n<!-- /MintPlay harness -->\n",
|
|
346
|
+
// Recognize managed texts issued before these branches merged.
|
|
347
|
+
"<!-- MintPlay harness (managed) -->\n## Game skills (MintPlay)\n\nThis project locks its game skills in `.harness/mintplay/skills/`. For game work, start with `.harness/mintplay/skills/game-studio/SKILL.md`; it owns project memory, verification and the order between skills. Read another skill when game-studio routes to it or its description in your skill list fits the current step (never an explicit-only skill unless the user invokes it), and only its SKILL.md until it points further. Whenever adding, modifying, or deleting game assets, also load `asset-delivery` to maintain project asset delivery and specs. A skill file already read in this session stays in context: do not reopen it; reread it only after the context was compacted or summarised.\n<!-- /MintPlay harness -->\n",
|
|
348
|
+
"<!-- MintPlay harness (managed) -->\n## Game skills (MintPlay)\n\nThis project locks its game skills in `.harness/mintplay/skills/`. For game work, start with `.harness/mintplay/skills/game-studio/SKILL.md`; read another skill only when that file names a trigger for it. Whenever adding, modifying, or deleting game assets, also load the `asset-delivery` skill to maintain project asset delivery and specs. A skill file already read in this session stays in context: do not reopen it; reread it only after the context was compacted or summarised.\n<!-- /MintPlay harness -->\n",
|
|
349
|
+
"<!-- MintPlay harness (managed) -->\n## Game skills (MintPlay)\n\nThis project locks its game skills in `.harness/mintplay/skills/`. For game work, start with `.harness/mintplay/skills/game-studio/SKILL.md`; it owns project memory, verification and the order between skills. Read another skill when game-studio routes to it or its description in your skill list fits the current step (never an explicit-only skill unless the user invokes it), and only its SKILL.md until it points further. Whenever adding, modifying, or deleting game assets, also load `.harness/mintplay/skills/asset-ledger/SKILL.md` to maintain the local asset ledger and runtime registry. A skill file already read in this session stays in context: do not reopen it; reread it only after the context was compacted or summarised.\n<!-- /MintPlay harness -->\n",
|
|
350
|
+
// 0.5.0 through 0.8.0: asset-ledger trigger before asset-delivery replaced it.
|
|
351
|
+
"<!-- MintPlay harness (managed) -->\n## Game skills (MintPlay)\n\nThis project locks its game skills in `.harness/mintplay/skills/`. For game work, start with `.harness/mintplay/skills/game-studio/SKILL.md`; read another skill only when that file names a trigger for it. Whenever adding, modifying, or deleting game assets, also load `.harness/mintplay/skills/asset-ledger/SKILL.md` to maintain the local asset ledger and runtime registry. A skill file already read in this session stays in context: do not reopen it; reread it only after the context was compacted or summarised.\n<!-- /MintPlay harness -->\n"
|
|
352
|
+
] }
|
|
353
|
+
];
|
|
354
|
+
var blockTexts = (b) => [b.text, ...b.history].flatMap((t) => [t, "\n" + t]);
|
|
355
|
+
var blockFor = (file) => BLOCKS.find((b) => b.file === file);
|
|
356
|
+
var blockOwned = (s, k) => s?.[`${k}_owned`] ?? null;
|
|
357
|
+
var blockCreated = (s, k) => s?.[`${k}_created`] ?? false;
|
|
358
|
+
var blockId = (s, k) => s?.[`${k}_identity`] ?? null;
|
|
359
|
+
function blockMigration(blk, state, text, id) {
|
|
360
|
+
const own = blockOwned(state, blk.key), previousId = blockId(state, blk.key);
|
|
361
|
+
if (!own || own === blk.text || own === "\n" + blk.text || !blockTexts(blk).includes(own) || !previousId || !id || !sameIdentity(previousId, id) || !text.endsWith(own))
|
|
362
|
+
return null;
|
|
363
|
+
const owned = (own.startsWith("\n") ? "\n" : "") + blk.text;
|
|
364
|
+
return { owned, text: text.slice(0, -own.length) + owned };
|
|
365
|
+
}
|
|
366
|
+
var supported = ["init", "sync", "status", "update", "remove"];
|
|
367
|
+
var activeWriters = /* @__PURE__ */ new Map();
|
|
368
|
+
var bundleIdentity = (m, digest) => ({ release: m.release, commit: m.source.commit, repository: m.source.repository, manifest_sha256: digest, profile: "full" });
|
|
369
|
+
var exists = (p) => {
|
|
370
|
+
try {
|
|
371
|
+
fs3.lstatSync(p);
|
|
372
|
+
return true;
|
|
373
|
+
} catch (e) {
|
|
374
|
+
if (e.code === "ENOENT")
|
|
375
|
+
return false;
|
|
376
|
+
throw e;
|
|
377
|
+
}
|
|
378
|
+
};
|
|
379
|
+
var nativeRename = path3.join(import.meta.dirname, `rename-no-replace-${process.platform}-${process.arch}${process.platform === "win32" ? ".exe" : ""}`);
|
|
380
|
+
var writablePlatform = ["darwin", "linux", "win32"].includes(process.platform);
|
|
381
|
+
var creationFenceMs = process.platform === "linux" ? 20 : process.platform === "win32" ? 40 : 0;
|
|
382
|
+
function creationFence(root) {
|
|
383
|
+
if (creationFenceMs) {
|
|
384
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, creationFenceMs);
|
|
385
|
+
activeWriter(root);
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
var rmOptions = (recursive) => process.platform === "win32" ? { recursive, maxRetries: 10, retryDelay: 100 } : { recursive };
|
|
389
|
+
var linkRoot = null;
|
|
390
|
+
function linkTarget(p) {
|
|
391
|
+
const raw = fs3.readlinkSync(p);
|
|
392
|
+
if (process.platform !== "win32")
|
|
393
|
+
return raw;
|
|
394
|
+
if (linkRoot && path3.win32.isAbsolute(raw))
|
|
395
|
+
return "../../" + path3.relative(linkRoot, raw).split(path3.sep).join("/");
|
|
396
|
+
return raw.split("\\").join("/");
|
|
397
|
+
}
|
|
398
|
+
function createLink(root, rel, target, location) {
|
|
399
|
+
if (process.platform !== "win32") {
|
|
400
|
+
fs3.symlinkSync(target, location);
|
|
401
|
+
return;
|
|
402
|
+
}
|
|
403
|
+
try {
|
|
404
|
+
fs3.symlinkSync(target, location, "dir");
|
|
405
|
+
} catch (e) {
|
|
406
|
+
if (!["EPERM", "EACCES"].includes(e.code || ""))
|
|
407
|
+
throw e;
|
|
408
|
+
fs3.symlinkSync(path3.resolve(path3.dirname(boundary(root, rel)), ...target.split("/")), location, "junction");
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
function requireExclusiveRename() {
|
|
412
|
+
fail(exists(nativeRename) && fs3.lstatSync(nativeRename).isFile(), "This package lacks an exclusive-rename helper for the current platform; write operations are unavailable", 5);
|
|
413
|
+
const p = spawnSync2(nativeRename, ["--probe"], { encoding: "utf8" });
|
|
414
|
+
fail(p.status === 0 && !p.error, "Exclusive-rename helper is unavailable; no write transaction started", 5);
|
|
415
|
+
}
|
|
416
|
+
function renameExclusive(source2, destination) {
|
|
417
|
+
const p = spawnSync2(nativeRename, [source2, destination], { encoding: "utf8" });
|
|
418
|
+
if (p.status !== 0 || p.error)
|
|
419
|
+
throw new MintPlayError(p.status === 3 ? 3 : 5, `${p.stderr?.trim() || p.error?.message || "Exclusive rename failed"}: ${destination}`, [destination]);
|
|
420
|
+
}
|
|
421
|
+
var readJson = (p) => {
|
|
422
|
+
fail(fs3.lstatSync(p).isFile() && fs3.lstatSync(p).size < 2 * 1024 * 1024, `Not a bounded regular JSON file: ${p}`, 2);
|
|
423
|
+
try {
|
|
424
|
+
return JSON.parse(fs3.readFileSync(p, "utf8"));
|
|
425
|
+
} catch {
|
|
426
|
+
throw new MintPlayError(2, `Invalid JSON: ${p}`);
|
|
427
|
+
}
|
|
428
|
+
};
|
|
429
|
+
function statIdentity(s) {
|
|
430
|
+
return { dev: s.dev, ino: s.ino, birthtime: s.birthtimeMs };
|
|
431
|
+
}
|
|
432
|
+
function identity(p) {
|
|
433
|
+
return statIdentity(fs3.lstatSync(p));
|
|
434
|
+
}
|
|
435
|
+
function sameIdentity(a, b) {
|
|
436
|
+
return a.dev === b.dev && a.ino === b.ino && a.birthtime === b.birthtime;
|
|
437
|
+
}
|
|
438
|
+
function staleWriter(root) {
|
|
439
|
+
const guard = boundary(root, `${STATE}/write.lock`);
|
|
440
|
+
if (!exists(guard))
|
|
441
|
+
return null;
|
|
442
|
+
try {
|
|
443
|
+
fail(fs3.lstatSync(guard).isDirectory() && !fs3.lstatSync(guard).isSymbolicLink(), "Writer record is not a directory", 5);
|
|
444
|
+
const file = path3.join(guard, "owner.json");
|
|
445
|
+
fail(exists(file) && fs3.lstatSync(file).isFile() && fs3.lstatSync(file).size < 2 * 1024 * 1024, "Writer owner is still being created or is untrusted", 5);
|
|
446
|
+
const proof = { directory: identity(guard), owner: identity(file), owner_signature: signature(file) }, owner = readJson(file);
|
|
447
|
+
exactKeys(owner, ["schema_version", "pid", "token", "project", "directory", "self"], "write lock");
|
|
448
|
+
fail(owner.schema_version === 2 && Number.isInteger(owner.pid) && owner.pid > 0 && typeof owner.token === "string" && owner.token.length === 36 && sameIdentity(owner.project, identity(root)) && sameIdentity(owner.directory, proof.directory) && sameIdentity(owner.self, proof.owner), "Writer owner cannot be safely verified or has been recreated", 5);
|
|
449
|
+
fail(fs3.readdirSync(guard).join(",") === "owner.json" && sameIdentity(proof.directory, identity(guard)) && sameIdentity(proof.owner, identity(file)) && proof.owner_signature === signature(file), "Writer record changed during inspection", 5);
|
|
450
|
+
try {
|
|
451
|
+
process.kill(owner.pid, 0);
|
|
452
|
+
throw new MintPlayError(5, "Another writer holds this project lock");
|
|
453
|
+
} catch (e) {
|
|
454
|
+
if (e.code !== "ESRCH")
|
|
455
|
+
throw new MintPlayError(5, "Writer is live or its exit cannot be safely established");
|
|
456
|
+
}
|
|
457
|
+
return { ...proof, pid: owner.pid, token: owner.token };
|
|
458
|
+
} catch (e) {
|
|
459
|
+
throw new MintPlayError(5, `Project writer is busy or untrusted: ${e.message}`);
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
function sameWriter(a, b) {
|
|
463
|
+
return sameIdentity(a.directory, b.directory) && sameIdentity(a.owner, b.owner) && a.owner_signature === b.owner_signature && a.pid === b.pid && a.token === b.token;
|
|
464
|
+
}
|
|
465
|
+
function activeWriter(root) {
|
|
466
|
+
const proof = activeWriters.get(root);
|
|
467
|
+
fail(proof, "No process-owned write capability", 5);
|
|
468
|
+
const guard = boundary(root, `${STATE}/write.lock`), file = path3.join(guard, "owner.json");
|
|
469
|
+
fail(exists(guard) && fs3.lstatSync(guard).isDirectory() && sameIdentity(proof.directory, identity(guard)) && exists(file) && fs3.lstatSync(file).isFile() && fs3.lstatSync(file).size < 2 * 1024 * 1024 && sameIdentity(proof.owner, identity(file)) && signature(file) === proof.owner_signature, "Writer ownership changed; preserving lock and transaction evidence", 5);
|
|
470
|
+
}
|
|
471
|
+
function signature(p, snapshotRoot) {
|
|
472
|
+
if (!exists(p))
|
|
473
|
+
return null;
|
|
474
|
+
const stat = fs3.lstatSync(p);
|
|
475
|
+
if (stat.isSymbolicLink())
|
|
476
|
+
return sha("link:" + linkTarget(p));
|
|
477
|
+
if (stat.isFile())
|
|
478
|
+
return sha(`file:${execFlag(Boolean(stat.mode & 73))}:` + sha(fs3.readFileSync(p)));
|
|
479
|
+
if (stat.isDirectory()) {
|
|
480
|
+
const entries2 = [];
|
|
481
|
+
for (const name of fs3.readdirSync(p).sort()) {
|
|
482
|
+
const child = path3.join(p, name);
|
|
483
|
+
if (snapshotRoot && name === "__pycache__" && isSkillBytecodeCache(child, path3.relative(snapshotRoot, child).split(path3.sep).join("/")))
|
|
484
|
+
continue;
|
|
485
|
+
entries2.push(`${name}:${signature(child, snapshotRoot)}`);
|
|
486
|
+
}
|
|
487
|
+
return sha("dir:" + entries2.join("\n"));
|
|
488
|
+
}
|
|
489
|
+
throw new MintPlayError(3, `Special file refused: ${p}`, [p]);
|
|
490
|
+
}
|
|
491
|
+
function ownedSignature(file, rel) {
|
|
492
|
+
return signature(file, rel === ROOT ? file : void 0);
|
|
493
|
+
}
|
|
494
|
+
function boundary(root, rel) {
|
|
495
|
+
relPath(rel);
|
|
496
|
+
let p = root;
|
|
497
|
+
const parts = rel.split("/");
|
|
498
|
+
for (let i = 0; i < parts.length; i++) {
|
|
499
|
+
p = path3.join(p, parts[i]);
|
|
500
|
+
if (exists(p)) {
|
|
501
|
+
const s = fs3.lstatSync(p);
|
|
502
|
+
if (i < parts.length - 1)
|
|
503
|
+
fail(s.isDirectory() && !s.isSymbolicLink(), `Managed parent is not a regular directory: ${parts.slice(0, i + 1).join("/")}`, 3);
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
return p;
|
|
507
|
+
}
|
|
508
|
+
function verifyNewSlot(root, rel, descriptor, expected) {
|
|
509
|
+
const stat = fs3.fstatSync(descriptor), current = boundary(root, rel), visible = exists(current) ? fs3.lstatSync(current) : null;
|
|
510
|
+
fail(stat.isFile() && stat.nlink === 1 && stat.size === 0 && !(stat.mode & 73) && sameIdentity(expected, statIdentity(stat)) && visible?.isFile() && visible.nlink === 1 && sameIdentity(expected, statIdentity(visible)), "New metadata slot changed or has hard-link aliases; preserving user content", 3);
|
|
511
|
+
}
|
|
512
|
+
function writeNewBytes(root, rel, bytes) {
|
|
513
|
+
const descriptor = fs3.openSync(boundary(root, rel), "wx");
|
|
514
|
+
try {
|
|
515
|
+
const expected = statIdentity(fs3.fstatSync(descriptor));
|
|
516
|
+
verifyNewSlot(root, rel, descriptor, expected);
|
|
517
|
+
verifyNewSlot(root, rel, descriptor, expected);
|
|
518
|
+
fs3.writeFileSync(descriptor, bytes);
|
|
519
|
+
} finally {
|
|
520
|
+
fs3.closeSync(descriptor);
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
var hostDir = (agent) => agent === "codex" ? ".agents/skills" : ".claude/skills";
|
|
524
|
+
function entries(m, agents2) {
|
|
525
|
+
return agents2.flatMap((a) => ["_shared", ...m.skills].map((n) => ({ path: `${hostDir(a)}/${n}`, kind: "symlink", target: `../../.harness/mintplay/skills/${n}` })));
|
|
526
|
+
}
|
|
527
|
+
function makeLock(b, agents2, mode = "snapshot") {
|
|
528
|
+
return {
|
|
529
|
+
schema_version: 1,
|
|
530
|
+
package_id: "mintplay-harness",
|
|
531
|
+
manifest_sha256: b.digest,
|
|
532
|
+
manifest: b.manifest,
|
|
533
|
+
installation: mode === "plugin" ? { mode, root: ROOT, agents: agents2, adapter: "host-plugin-v1", link_type: "none" } : { mode, root: ROOT, agents: agents2, adapter: "project-skills-v1", link_type: "relative-symlink" },
|
|
534
|
+
managed_entries: mode === "plugin" ? [] : entries(b.manifest, agents2)
|
|
535
|
+
};
|
|
536
|
+
}
|
|
537
|
+
function validateLock(o) {
|
|
538
|
+
exactKeys(o, ["schema_version", "package_id", "manifest_sha256", "manifest", "installation", "managed_entries"], "project lock");
|
|
539
|
+
validateManifest(o.manifest);
|
|
540
|
+
fail(o.schema_version === 1 && o.package_id === "mintplay-harness" && hashPattern.test(o.manifest_sha256), "Invalid lock", 2);
|
|
541
|
+
exactKeys(o.installation, ["mode", "root", "agents", "adapter", "link_type"], "installation");
|
|
542
|
+
const plugin = o.installation.mode === "plugin";
|
|
543
|
+
fail((plugin ? o.installation.adapter === "host-plugin-v1" && o.installation.link_type === "none" && JSON.stringify(o.installation.agents) === '["claude"]' : o.installation.mode === "snapshot" && o.installation.adapter === "project-skills-v1" && o.installation.link_type === "relative-symlink") && o.installation.root === ROOT && Array.isArray(o.installation.agents) && o.installation.agents.length > 0 && o.installation.agents.length <= 2 && o.installation.agents.every((a) => ["codex", "claude"].includes(a)) && new Set(o.installation.agents).size === o.installation.agents.length, "Unsupported installation", 2);
|
|
544
|
+
fail(JSON.stringify(o.managed_entries) === JSON.stringify(plugin ? [] : entries(o.manifest, o.installation.agents)), "Lock cannot grant arbitrary paths", 2);
|
|
545
|
+
}
|
|
546
|
+
function managedPath(p) {
|
|
547
|
+
return [ROOT, LOCK, `${STATE}/state.json`, ".gitignore", "AGENTS.md", MARKET].includes(p) || /^(?:\.agents|\.claude)\/skills\/(?:_shared|[a-z0-9]+(?:-[a-z0-9]+)*)$/.test(p);
|
|
548
|
+
}
|
|
549
|
+
function validateCausality(s, root) {
|
|
550
|
+
fail(writablePlatform && Number.isFinite(s.self.birthtime) && s.self.birthtime > 0, "Reliable state birthtime is unavailable", 3);
|
|
551
|
+
for (const item of [...s.owned, ...s.created_dirs, ...BLOCKS.flatMap((b) => blockId(s, b.key) ? [blockId(s, b.key)] : [])])
|
|
552
|
+
fail(Number.isFinite(item.birthtime) && item.birthtime > 0 && item.birthtime < s.self.birthtime, "Ownership birthtime is not strictly earlier than the state object; precision or provenance is untrusted", 3);
|
|
553
|
+
for (const directory of s.created_dirs.filter((d) => d.path === ".agents/skills" || d.path === ".claude/skills")) {
|
|
554
|
+
const parent = boundary(root, directory.path);
|
|
555
|
+
if (!exists(parent))
|
|
556
|
+
continue;
|
|
557
|
+
const actual = fs3.lstatSync(parent);
|
|
558
|
+
if (!actual.isDirectory() || !sameIdentity(directory, statIdentity(actual)))
|
|
559
|
+
continue;
|
|
560
|
+
for (const entry of s.owned.filter((e) => path3.posix.dirname(e.path) === directory.path))
|
|
561
|
+
fail(entry.birthtime > actual.birthtimeMs, "Entry birthtime is not later than its unchanged CLI-created host parent; precision or provenance is untrusted", 3);
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
function validateState(s, root, lock, location = boundary(root, `${STATE}/state.json`)) {
|
|
565
|
+
exactKeys(s, ["schema_version", "installation_id", "project", "self", "lock_sha256", "owned", "created_dirs", "source", "ignore_owned", "ignore_created", "ignore_identity", "agents_owned", "agents_created", "agents_identity"], "state");
|
|
566
|
+
fail(s.schema_version === 2 && typeof s.installation_id === "string" && s.installation_id.length === 36 && hashPattern.test(s.lock_sha256) && Array.isArray(s.owned) && Array.isArray(s.created_dirs) && BLOCKS.every((b) => [null, ...blockTexts(b)].includes(s[`${b.key}_owned`]) && typeof s[`${b.key}_created`] === "boolean"), "Invalid local state", 2);
|
|
567
|
+
exactKeys(s.self, ["dev", "ino", "birthtime"], "state file identity");
|
|
568
|
+
fail(sameIdentity(s.self, identity(location)), "Local state file was recreated; refusing automatic adoption", 3);
|
|
569
|
+
exactKeys(s.project, ["dev", "ino", "birthtime"], "project identity");
|
|
570
|
+
fail(sameIdentity(s.project, identity(root)), "Local state belongs to another project; remove copied local state and explicitly adopt", 3);
|
|
571
|
+
for (const b of BLOCKS) {
|
|
572
|
+
const id = s[`${b.key}_identity`];
|
|
573
|
+
if (id !== null) {
|
|
574
|
+
exactKeys(id, ["dev", "ino", "birthtime"], `${b.key} block ownership`);
|
|
575
|
+
fail(["dev", "ino", "birthtime"].every((n) => typeof id[n] === "number"), "Invalid block identity", 2);
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
const valid = /* @__PURE__ */ new Set([ROOT, LOCK, ...lock.managed_entries.map((e) => e.path), ...lock.installation.mode === "plugin" ? [MARKET] : []]);
|
|
579
|
+
const names = /* @__PURE__ */ new Set();
|
|
580
|
+
for (const e of s.owned) {
|
|
581
|
+
exactKeys(e, ["path", "signature", "dev", "ino", "birthtime"], "ownership");
|
|
582
|
+
fail(valid.has(e.path) && !names.has(e.path) && hashPattern.test(e.signature) && ["dev", "ino", "birthtime"].every((k) => typeof e[k] === "number"), "Invalid ownership", 2);
|
|
583
|
+
names.add(e.path);
|
|
584
|
+
}
|
|
585
|
+
fail(names.size === valid.size, "Incomplete ownership inventory", 2);
|
|
586
|
+
const validDirs = /* @__PURE__ */ new Set([".harness", ".harness/.state", STATE, `${STATE}/transactions`, ".agents", ".agents/skills", ".claude", ".claude/skills", ".harness/.claude-plugin"]);
|
|
587
|
+
for (const d of s.created_dirs) {
|
|
588
|
+
exactKeys(d, ["path", "dev", "ino", "birthtime"], "directory ownership");
|
|
589
|
+
fail(validDirs.has(d.path) && ["dev", "ino", "birthtime"].every((k) => typeof d[k] === "number"), "Invalid directory ownership", 2);
|
|
590
|
+
}
|
|
591
|
+
if (s.source !== null) {
|
|
592
|
+
exactKeys(s.source, ["kind", "path"], "local source");
|
|
593
|
+
fail(["git", "archive"].includes(s.source.kind) && typeof s.source.path === "string" && path3.isAbsolute(s.source.path), "Invalid local source", 2);
|
|
594
|
+
}
|
|
595
|
+
validateCausality(s, root);
|
|
596
|
+
}
|
|
597
|
+
function source(o, state, expected) {
|
|
598
|
+
try {
|
|
599
|
+
let b, origin;
|
|
600
|
+
if (o.archive) {
|
|
601
|
+
origin = { kind: "archive", path: path3.resolve(o.archive) };
|
|
602
|
+
b = fromArchive(origin.path, expected);
|
|
603
|
+
} else if (o.source && o.commit) {
|
|
604
|
+
origin = { kind: "git", path: path3.resolve(o.source) };
|
|
605
|
+
b = fromGit(origin.path, o.commit);
|
|
606
|
+
} else if (o.source || o.command !== "sync" && o.commit)
|
|
607
|
+
throw new MintPlayError(2, "Git source requires --source and --commit");
|
|
608
|
+
else if (o.command === "sync" && state?.source && exists(state.source.path)) {
|
|
609
|
+
origin = state.source;
|
|
610
|
+
if (origin.kind === "archive")
|
|
611
|
+
b = fromArchive(origin.path, expected);
|
|
612
|
+
else {
|
|
613
|
+
fail(o.commit, "Missing locked Git commit", 4);
|
|
614
|
+
b = fromGit(origin.path, o.commit);
|
|
615
|
+
}
|
|
616
|
+
} else {
|
|
617
|
+
origin = { kind: "archive", path: bundledArchive };
|
|
618
|
+
b = officialBundle(expected);
|
|
619
|
+
}
|
|
620
|
+
if (expected && b.digest !== expected && origin.kind === "git" && o.commit) {
|
|
621
|
+
b = fromGit(origin.path, o.commit, "public");
|
|
622
|
+
}
|
|
623
|
+
fail(!expected || b.digest === expected, "Source differs from locked manifest");
|
|
624
|
+
return { bundle: b, origin };
|
|
625
|
+
} catch (e) {
|
|
626
|
+
if (e instanceof MintPlayError)
|
|
627
|
+
throw e;
|
|
628
|
+
throw new MintPlayError(4, e.message);
|
|
629
|
+
}
|
|
630
|
+
}
|
|
631
|
+
function agents(value) {
|
|
632
|
+
fail(["codex", "claude", "both"].includes(value || ""), "First init requires --agent codex|claude|both", 2);
|
|
633
|
+
return value === "both" ? ["codex", "claude"] : [value];
|
|
634
|
+
}
|
|
635
|
+
function duplicates(root, names, selected, plugin = false) {
|
|
636
|
+
const found = [];
|
|
637
|
+
const bases = plugin ? selected.map((a) => path3.join(root, hostDir(a))) : [];
|
|
638
|
+
for (const a of selected) {
|
|
639
|
+
bases.push(path3.join(os.homedir(), hostDir(a)));
|
|
640
|
+
if (a === "codex")
|
|
641
|
+
bases.push(path3.join(os.homedir(), ".codex/skills"));
|
|
642
|
+
let parent = path3.dirname(root);
|
|
643
|
+
while (parent !== root) {
|
|
644
|
+
bases.push(path3.join(parent, hostDir(a)));
|
|
645
|
+
if (parent === path3.dirname(parent))
|
|
646
|
+
break;
|
|
647
|
+
parent = path3.dirname(parent);
|
|
648
|
+
}
|
|
649
|
+
}
|
|
650
|
+
for (const base of new Set(bases))
|
|
651
|
+
for (const n of names)
|
|
652
|
+
if (exists(path3.join(base, n)))
|
|
653
|
+
found.push(path3.join(base, n));
|
|
654
|
+
return found;
|
|
655
|
+
}
|
|
656
|
+
function compatibility(root, old, next) {
|
|
657
|
+
const game = path3.join(root, ".game");
|
|
658
|
+
if (!exists(game) || fs3.readdirSync(game).length === 0)
|
|
659
|
+
return "not_applicable";
|
|
660
|
+
if (old.manifest.compatibility.markdown_memory_sha256 !== next.manifest.compatibility.markdown_memory_sha256)
|
|
661
|
+
return "unknown";
|
|
662
|
+
const inspect = (d) => fs3.readdirSync(d, { withFileTypes: true }).every((e) => {
|
|
663
|
+
if (e.isSymbolicLink())
|
|
664
|
+
return false;
|
|
665
|
+
const p = path3.join(d, e.name);
|
|
666
|
+
if (e.isDirectory())
|
|
667
|
+
return inspect(p);
|
|
668
|
+
if (!e.isFile())
|
|
669
|
+
return false;
|
|
670
|
+
if (!e.name.endsWith(".json"))
|
|
671
|
+
return true;
|
|
672
|
+
let value;
|
|
673
|
+
try {
|
|
674
|
+
value = JSON.parse(fs3.readFileSync(p, "utf8"));
|
|
675
|
+
} catch {
|
|
676
|
+
return false;
|
|
677
|
+
}
|
|
678
|
+
if (path3.relative(game, p).split(path3.sep).join("/") === "assets/manifest.json")
|
|
679
|
+
return value.version === 2 && Array.isArray(value.assets) && Array.isArray(value.generation_log) && next.manifest.compatibility.asset_ledger_version === 2;
|
|
680
|
+
return false;
|
|
681
|
+
});
|
|
682
|
+
return inspect(game) ? "compatible" : "unknown";
|
|
683
|
+
}
|
|
684
|
+
function validateJournal(j, root) {
|
|
685
|
+
exactKeys(j, ["schema_version", "token", "project", "operations", "stage"], "transaction");
|
|
686
|
+
fail(j.schema_version === 1 && typeof j.token === "string" && j.token.length === 36 && sameIdentity(j.project, identity(root)) && Array.isArray(j.operations) && j.operations.length < 200 && ["preparing", "prepared", "committed"].includes(j.stage), "Invalid recovery journal", 5);
|
|
687
|
+
const names = /* @__PURE__ */ new Set();
|
|
688
|
+
for (const o of j.operations) {
|
|
689
|
+
exactKeys(o, ["path", "before", "after", "before_id", "after_id", "after_manifest"], "transaction operation");
|
|
690
|
+
fail(managedPath(o.path) && !names.has(o.path) && [o.before, o.after].every((v) => v === null || typeof v === "string" && hashPattern.test(v)), "Recovery path or digest refused", 5);
|
|
691
|
+
fail(o.path === ROOT && o.after !== null ? typeof o.after_manifest === "string" && hashPattern.test(o.after_manifest) : o.after_manifest === null, "Invalid staged bundle identity", 5);
|
|
692
|
+
for (const k of ["before", "after"]) {
|
|
693
|
+
const id = o[k + "_id"];
|
|
694
|
+
if (o[k] === null)
|
|
695
|
+
fail(id === null, "Unexpected recovery identity", 5);
|
|
696
|
+
else if (k === "after" && j.stage === "preparing" && id === null)
|
|
697
|
+
continue;
|
|
698
|
+
else {
|
|
699
|
+
exactKeys(id, ["dev", "ino", "birthtime"], "recovery identity");
|
|
700
|
+
fail(["dev", "ino", "birthtime"].every((n) => typeof id[n] === "number"), "Invalid recovery identity", 5);
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
names.add(o.path);
|
|
704
|
+
boundary(root, o.path);
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
function atomicJson(root, file, value) {
|
|
708
|
+
const temp = file + ".tmp";
|
|
709
|
+
fail(!exists(temp), "Unexpected transaction temp file", 5);
|
|
710
|
+
writeNewBytes(root, path3.relative(root, temp).split(path3.sep).join("/"), json(value));
|
|
711
|
+
fs3.renameSync(temp, file);
|
|
712
|
+
}
|
|
713
|
+
function removeStoredObject(file, allowDirectory = true) {
|
|
714
|
+
const stat = fs3.lstatSync(file);
|
|
715
|
+
if (stat.isSymbolicLink())
|
|
716
|
+
fs3.unlinkSync(file);
|
|
717
|
+
else
|
|
718
|
+
fs3.rmSync(file, rmOptions(allowDirectory && stat.isDirectory()));
|
|
719
|
+
}
|
|
720
|
+
function removeVerified(p, expected) {
|
|
721
|
+
fail(signature(p) === expected, `Changed transaction content: ${p}`, 3);
|
|
722
|
+
removeStoredObject(p);
|
|
723
|
+
}
|
|
724
|
+
function bundleSignature(b) {
|
|
725
|
+
const fileMap = new Map(b.files.map((e) => [e.path, { bytes: b.payload.get(e.path), executable: e.executable }]));
|
|
726
|
+
fileMap.set("manifest.json", { bytes: b.manifestBytes, executable: false });
|
|
727
|
+
fileMap.set("files.json", { bytes: b.filesBytes, executable: false });
|
|
728
|
+
const digest = (prefix) => {
|
|
729
|
+
const children = new Set([...fileMap.keys()].filter((n) => n.startsWith(prefix)).map((n) => n.slice(prefix.length).split("/")[0]));
|
|
730
|
+
return sha("dir:" + Array.from(children).sort().map((name) => {
|
|
731
|
+
const n = prefix + name, e = fileMap.get(n);
|
|
732
|
+
return `${name}:${e ? sha(`file:${execFlag(e.executable)}:` + sha(e.bytes)) : digest(n + "/")}`;
|
|
733
|
+
}).join("\n"));
|
|
734
|
+
};
|
|
735
|
+
return digest("");
|
|
736
|
+
}
|
|
737
|
+
function validatePartialBundle(dir, b) {
|
|
738
|
+
const files = new Map(b.files.map((e) => [e.path, { bytes: b.payload.get(e.path), executable: e.executable }]));
|
|
739
|
+
files.set("manifest.json", { bytes: b.manifestBytes, executable: false });
|
|
740
|
+
files.set("files.json", { bytes: b.filesBytes, executable: false });
|
|
741
|
+
const dirs = /* @__PURE__ */ new Set();
|
|
742
|
+
for (const p of files.keys()) {
|
|
743
|
+
const a = p.split("/");
|
|
744
|
+
for (let i = 1; i < a.length; i++)
|
|
745
|
+
dirs.add(a.slice(0, i).join("/"));
|
|
746
|
+
}
|
|
747
|
+
const walk = (d, prefix = "") => {
|
|
748
|
+
fail(fs3.lstatSync(d).isDirectory(), "Staging directory replaced", 3);
|
|
749
|
+
for (const item of fs3.readdirSync(d, { withFileTypes: true })) {
|
|
750
|
+
const rel = prefix + item.name, p = path3.join(d, item.name);
|
|
751
|
+
if (item.isDirectory()) {
|
|
752
|
+
fail(dirs.has(rel), `Unknown staging directory: ${rel}`, 3);
|
|
753
|
+
walk(p, rel + "/");
|
|
754
|
+
} else {
|
|
755
|
+
const expected = files.get(rel);
|
|
756
|
+
fail(expected && item.isFile(), `Unknown staging entry: ${rel}`, 3);
|
|
757
|
+
fail(fs3.lstatSync(p).size <= expected.bytes.length, `Changed preparation size: ${rel}`, 3);
|
|
758
|
+
const bytes = fs3.readFileSync(p);
|
|
759
|
+
fail(bytes.equals(expected.bytes.subarray(0, bytes.length)) && execMatches(fs3.lstatSync(p).mode, expected.executable), `Changed preparation content: ${rel}`, 3);
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
};
|
|
763
|
+
walk(dir);
|
|
764
|
+
}
|
|
765
|
+
function validateMissingBaseline(dir, manifest, digest) {
|
|
766
|
+
const meta = fs3.readFileSync(path3.join(dir, "manifest.json")), fileBytes = fs3.readFileSync(path3.join(dir, "files.json"));
|
|
767
|
+
fail(sha(meta) === digest && JSON.stringify(JSON.parse(meta.toString())) === JSON.stringify(manifest), "Incomplete baseline manifest changed", 3);
|
|
768
|
+
const files = JSON.parse(fileBytes.toString());
|
|
769
|
+
validateFiles(files);
|
|
770
|
+
fail(sha(fileBytes) === manifest.files_manifest_sha256, "Incomplete baseline file list changed", 3);
|
|
771
|
+
const names = /* @__PURE__ */ new Set(["manifest.json", "files.json", ...files.map((e) => e.path)]), dirs = /* @__PURE__ */ new Set();
|
|
772
|
+
for (const n of names) {
|
|
773
|
+
const a = n.split("/");
|
|
774
|
+
for (let i = 1; i < a.length; i++)
|
|
775
|
+
dirs.add(a.slice(0, i).join("/"));
|
|
776
|
+
}
|
|
777
|
+
const walk = (d, prefix = "") => {
|
|
778
|
+
for (const e of fs3.readdirSync(d, { withFileTypes: true })) {
|
|
779
|
+
const n = prefix + e.name, p = path3.join(d, e.name);
|
|
780
|
+
if (e.isDirectory()) {
|
|
781
|
+
if (isSkillBytecodeCache(p, n))
|
|
782
|
+
continue;
|
|
783
|
+
fail(dirs.has(n), "Extra incomplete baseline directory", 3);
|
|
784
|
+
walk(p, n + "/");
|
|
785
|
+
} else
|
|
786
|
+
fail(e.isFile() && names.has(n), "Extra or special incomplete baseline entry", 3);
|
|
787
|
+
}
|
|
788
|
+
};
|
|
789
|
+
walk(dir);
|
|
790
|
+
let missing = 0;
|
|
791
|
+
for (const e of files) {
|
|
792
|
+
const p = path3.join(dir, e.path);
|
|
793
|
+
if (!exists(p)) {
|
|
794
|
+
missing++;
|
|
795
|
+
continue;
|
|
796
|
+
}
|
|
797
|
+
const s = fs3.lstatSync(p);
|
|
798
|
+
fail(s.isFile() && s.size === e.size && sha(fs3.readFileSync(p)) === e.sha256 && execMatches(s.mode, e.executable), "Incomplete baseline file was modified", 3);
|
|
799
|
+
}
|
|
800
|
+
fail(missing > 0, "Not a missing-file-only baseline", 3);
|
|
801
|
+
}
|
|
802
|
+
function recoverySemantics(root, active, j) {
|
|
803
|
+
if (j.stage === "preparing")
|
|
804
|
+
return;
|
|
805
|
+
const candidate = (o, side) => {
|
|
806
|
+
if (o[side] === null)
|
|
807
|
+
return null;
|
|
808
|
+
const i = j.operations.indexOf(o), locations = [path3.join(active, `${side === "before" ? "old" : "new"}-${i}`), boundary(root, o.path)];
|
|
809
|
+
return locations.find((p) => exists(p) && sameIdentity(o[`${side}_id`], identity(p)) && signature(p) === o[side]) || null;
|
|
810
|
+
};
|
|
811
|
+
const stateOp = j.operations.find((o) => o.path === `${STATE}/state.json`);
|
|
812
|
+
fail(stateOp, "Recovery lacks the initial state operation", 5);
|
|
813
|
+
const lockOp = j.operations.find((o) => o.path === LOCK);
|
|
814
|
+
const lockFiles = [boundary(root, LOCK), ...lockOp ? ["before", "after"].map((side) => candidate(lockOp, side)).filter((p) => p !== null) : []];
|
|
815
|
+
const locks = lockFiles.filter(exists).map((file) => {
|
|
816
|
+
const lock = readJson(file);
|
|
817
|
+
validateLock(lock);
|
|
818
|
+
return { file, lock, bytes: fs3.readFileSync(file) };
|
|
819
|
+
});
|
|
820
|
+
const loadState = (side) => {
|
|
821
|
+
if (stateOp[side] === null)
|
|
822
|
+
return null;
|
|
823
|
+
const file = candidate(stateOp, side);
|
|
824
|
+
fail(file, `Recovery state ${side} content or identity is unavailable`, 3);
|
|
825
|
+
const value = readJson(file), locked = locks.find((l) => sha(l.bytes) === value.lock_sha256);
|
|
826
|
+
fail(locked, "Recovery state has no independently valid project lock", 5);
|
|
827
|
+
validateState(value, root, locked.lock, file);
|
|
828
|
+
const lockOwnership = value.owned.find((o) => o.path === LOCK);
|
|
829
|
+
fail(locks.some((l) => sha(l.bytes) === value.lock_sha256 && sameIdentity(lockOwnership, identity(l.file)) && signature(l.file) === lockOwnership.signature), "Recovery state lock ownership differs from the actual lock object", 3);
|
|
830
|
+
for (const entry of locked.lock.managed_entries) {
|
|
831
|
+
const own = value.owned.find((o) => o.path === entry.path);
|
|
832
|
+
fail(own.signature === sha("link:" + entry.target), "Recovery state cannot grant a foreign entry signature", 5);
|
|
833
|
+
}
|
|
834
|
+
for (const own of value.owned)
|
|
835
|
+
if (!j.operations.some((o) => o.path === own.path)) {
|
|
836
|
+
const p = boundary(root, own.path);
|
|
837
|
+
fail(ownedSignature(p, own.path) === own.signature && sameIdentity(own, identity(p)), `Unchanged recovery ownership drift: ${own.path}`, 3);
|
|
838
|
+
}
|
|
839
|
+
for (const o of j.operations) {
|
|
840
|
+
const own = value.owned.find((e) => e.path === o.path);
|
|
841
|
+
if ([ROOT, LOCK, MARKET].includes(o.path) || /^(?:\.agents|\.claude)\/skills\//.test(o.path)) {
|
|
842
|
+
if (o[side] !== null) {
|
|
843
|
+
fail(own && sameIdentity(own, o[`${side}_id`]), `Recovery ${side} operation has no matching state ownership: ${o.path}`, 5);
|
|
844
|
+
if (o.path !== ROOT)
|
|
845
|
+
fail(own.signature === o[side], `Recovery ${side} content differs from state ownership: ${o.path}`, 5);
|
|
846
|
+
} else if (side === "after")
|
|
847
|
+
fail(!own, `Deleted operation still has new ownership: ${o.path}`, 5);
|
|
848
|
+
}
|
|
849
|
+
}
|
|
850
|
+
return value;
|
|
851
|
+
};
|
|
852
|
+
const previous = loadState("before"), next = loadState("after");
|
|
853
|
+
fail(previous || next, "Recovery has no valid installation state", 5);
|
|
854
|
+
if (previous && next)
|
|
855
|
+
fail(previous.installation_id === next.installation_id, "Recovery changes the installation lineage", 5);
|
|
856
|
+
for (const o of j.operations) {
|
|
857
|
+
if (o.before_id && o.after_id)
|
|
858
|
+
fail(!sameIdentity(o.before_id, o.after_id), "Recovery claims the same object as both original and replacement", 5);
|
|
859
|
+
if (o.before === null && o.after !== null && previous && next) {
|
|
860
|
+
const a = previous.owned.find((e) => e.path === o.path), b = next.owned.find((e) => e.path === o.path);
|
|
861
|
+
fail(!a || !b || !sameIdentity(a, b), "Recovery claims an unchanged owned object was newly created", 5);
|
|
862
|
+
}
|
|
863
|
+
}
|
|
864
|
+
for (const blk of BLOCKS) {
|
|
865
|
+
const k = blk.key, op = j.operations.find((o) => o.path === blk.file);
|
|
866
|
+
if (op) {
|
|
867
|
+
const before = op.before === null ? "" : candidate(op, "before"), after = op.after === null ? "" : candidate(op, "after");
|
|
868
|
+
fail(before !== null && after !== null, "Recovery block baseline or result is unavailable", 3);
|
|
869
|
+
const text = (p) => p === "" ? "" : (fail(fs3.lstatSync(p).isFile(), "Recovery block object is not a regular file", 3), fs3.readFileSync(p, "utf8"));
|
|
870
|
+
const a = text(before), b = text(after);
|
|
871
|
+
if (next) {
|
|
872
|
+
const suffix = (a && !a.endsWith("\n") ? "\n" : "") + blk.text, nid = blockId(next, k);
|
|
873
|
+
const migration = blockMigration(blk, previous, a, op.before_id);
|
|
874
|
+
const addition = !blockOwned(previous, k) && blockOwned(next, k) === suffix && blockCreated(next, k) === (op.before === null) && b === a + suffix && !a.includes(blk.marker);
|
|
875
|
+
const replacement = migration && blockOwned(next, k) === migration.owned && b === migration.text && blockCreated(next, k) === blockCreated(previous, k);
|
|
876
|
+
fail(nid && op.after_id && sameIdentity(nid, op.after_id) && (addition || replacement), "Recovery block operation is not the independently described managed-block addition or migration", 5);
|
|
877
|
+
} else {
|
|
878
|
+
const po = blockOwned(previous, k), pid = blockId(previous, k);
|
|
879
|
+
fail(po && pid && op.before_id && sameIdentity(pid, op.before_id) && a.endsWith(po) && b === a.slice(0, -po.length) && (op.after !== null || blockCreated(previous, k) && b === ""), "Recovery block operation cannot prove managed-block removal ownership", 5);
|
|
880
|
+
}
|
|
881
|
+
} else if (next && previous)
|
|
882
|
+
fail(blockOwned(next, k) === blockOwned(previous, k) && blockCreated(next, k) === blockCreated(previous, k) && JSON.stringify(blockId(next, k)) === JSON.stringify(blockId(previous, k)), "Recovery changes block ownership without a block operation", 5);
|
|
883
|
+
else if (next)
|
|
884
|
+
fail(blockOwned(next, k) === null && blockId(next, k) === null, "Recovery claims block ownership without a block operation", 5);
|
|
885
|
+
}
|
|
886
|
+
}
|
|
887
|
+
function ignoreText(file) {
|
|
888
|
+
fail(fs3.lstatSync(file).isFile() && fs3.lstatSync(file).size < 2 * 1024 * 1024, "Ignore baseline is not a bounded regular file", 3);
|
|
889
|
+
try {
|
|
890
|
+
return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(fs3.readFileSync(file));
|
|
891
|
+
} catch {
|
|
892
|
+
throw new MintPlayError(3, "Ignore baseline is not valid UTF-8; preserving it");
|
|
893
|
+
}
|
|
894
|
+
}
|
|
895
|
+
function preparingRoles(root, active, j, lockFiles, target) {
|
|
896
|
+
if (j.stage !== "preparing")
|
|
897
|
+
return;
|
|
898
|
+
const locks = lockFiles.filter(exists).map((file) => {
|
|
899
|
+
const lock = readJson(file);
|
|
900
|
+
validateLock(lock);
|
|
901
|
+
return { file, lock, bytes: fs3.readFileSync(file) };
|
|
902
|
+
});
|
|
903
|
+
for (let i = 0; i < j.operations.length; i++) {
|
|
904
|
+
const o = j.operations[i];
|
|
905
|
+
for (const [file, side] of [[boundary(root, o.path), "before"], [path3.join(active, `new-${i}`), "after"]]) {
|
|
906
|
+
if (!exists(file))
|
|
907
|
+
continue;
|
|
908
|
+
fail(o[side] !== null, "Unplanned preparation object; preserving it", 3);
|
|
909
|
+
const stat = fs3.lstatSync(file);
|
|
910
|
+
if (o.path === ROOT) {
|
|
911
|
+
fail(stat.isDirectory() && !stat.isSymbolicLink(), "Capability preparation is not a directory", 3);
|
|
912
|
+
if (side === "after") {
|
|
913
|
+
fail(target && target.digest === o.after_manifest && bundleSignature(target) === o.after, "Interrupted preparation requires the same verified target bundle", 4);
|
|
914
|
+
validatePartialBundle(file, target);
|
|
915
|
+
}
|
|
916
|
+
} else if (o.path === LOCK) {
|
|
917
|
+
fail(stat.isFile(), "Lock preparation is not a regular file", 3);
|
|
918
|
+
const lock = readJson(file);
|
|
919
|
+
validateLock(lock);
|
|
920
|
+
if (side === "after") {
|
|
921
|
+
const original = locks.find((l) => l.file === boundary(root, LOCK));
|
|
922
|
+
const expected = target || original && readBundle(boundary(root, ROOT), original.lock.manifest_sha256, "installed");
|
|
923
|
+
fail(expected && expected.digest === lock.manifest_sha256 && JSON.stringify(expected.manifest) === JSON.stringify(lock.manifest), "Staged lock does not describe an independently validated target package", 5);
|
|
924
|
+
}
|
|
925
|
+
} else if (o.path === `${STATE}/state.json`) {
|
|
926
|
+
fail(stat.isFile(), "State preparation is not a regular file", 3);
|
|
927
|
+
const state = readJson(file), locked = locks.find((l) => sha(l.bytes) === state.lock_sha256);
|
|
928
|
+
fail(locked, "State preparation has no validated lock baseline", 5);
|
|
929
|
+
validateState(state, root, locked.lock, file);
|
|
930
|
+
const own = state.owned.find((e) => e.path === LOCK);
|
|
931
|
+
fail(locks.some((l) => sha(l.bytes) === state.lock_sha256 && sameIdentity(own, identity(l.file)) && signature(l.file) === own.signature), "State preparation lock ownership differs from the actual lock object", 5);
|
|
932
|
+
for (const entry of locked.lock.managed_entries)
|
|
933
|
+
fail(state.owned.find((e) => e.path === entry.path)?.signature === sha("link:" + entry.target), "State preparation cannot grant foreign entry content", 5);
|
|
934
|
+
} else if (blockFor(o.path)) {
|
|
935
|
+
const blk = blockFor(o.path), k = blk.key;
|
|
936
|
+
const content = ignoreText(file);
|
|
937
|
+
if (side === "after") {
|
|
938
|
+
const dest = boundary(root, o.path), before = exists(dest) ? ignoreText(dest) : "";
|
|
939
|
+
const stateOp = j.operations.find((e) => e.path === `${STATE}/state.json`);
|
|
940
|
+
fail(stateOp, "Ignore preparation has no state operation", 5);
|
|
941
|
+
if (stateOp.after === null) {
|
|
942
|
+
const stateFile = boundary(root, `${STATE}/state.json`), state = readJson(stateFile), locked = locks.find((l) => sha(l.bytes) === state.lock_sha256);
|
|
943
|
+
fail(locked, "Ignore removal has no valid state lock", 5);
|
|
944
|
+
validateState(state, root, locked.lock, stateFile);
|
|
945
|
+
const so = blockOwned(state, k), sid = blockId(state, k);
|
|
946
|
+
fail(so && sid && sameIdentity(sid, identity(dest)) && before.endsWith(so) && content === before.slice(0, -so.length), "Block preparation cannot prove managed-block removal", 5);
|
|
947
|
+
} else if (before.includes(blk.marker)) {
|
|
948
|
+
const stateFile = boundary(root, `${STATE}/state.json`), state = readJson(stateFile), locked = locks.find((l) => sha(l.bytes) === state.lock_sha256);
|
|
949
|
+
fail(locked, "Block migration has no valid state lock", 5);
|
|
950
|
+
validateState(state, root, locked.lock, stateFile);
|
|
951
|
+
const migration = blockMigration(blk, state, before, identity(dest));
|
|
952
|
+
fail(migration && content === migration.text, "Block preparation cannot prove managed-block migration", 5);
|
|
953
|
+
} else
|
|
954
|
+
fail(content === before + (before && !before.endsWith("\n") ? "\n" : "") + blk.text, "Block preparation is not a managed-block addition", 5);
|
|
955
|
+
}
|
|
956
|
+
} else if (o.path === MARKET) {
|
|
957
|
+
fail(stat.isFile() && fs3.readFileSync(file).equals(marketBytes(root)), "Marketplace preparation is not the project-derived catalog", 3);
|
|
958
|
+
} else {
|
|
959
|
+
fail(stat.isSymbolicLink(), "Entry preparation is not a symbolic link", 3);
|
|
960
|
+
const manifest = target?.manifest || locks[0]?.lock.manifest;
|
|
961
|
+
fail(manifest, "Entry preparation has no validated manifest", 5);
|
|
962
|
+
const expected = entries(manifest, ["codex", "claude"]).find((e) => e.path === o.path);
|
|
963
|
+
fail(expected && linkTarget(file) === expected.target, "Entry preparation target is not from a validated installation", 5);
|
|
964
|
+
}
|
|
965
|
+
}
|
|
966
|
+
}
|
|
967
|
+
}
|
|
968
|
+
function recover(root, target, verifyOnly = false) {
|
|
969
|
+
const active = boundary(root, `${STATE}/transactions/active`);
|
|
970
|
+
if (!exists(active))
|
|
971
|
+
return;
|
|
972
|
+
if (!verifyOnly)
|
|
973
|
+
activeWriter(root);
|
|
974
|
+
fail(fs3.lstatSync(active).isDirectory(), "Transaction root refused", 5);
|
|
975
|
+
const j = readJson(path3.join(active, "journal.json"));
|
|
976
|
+
validateJournal(j, root);
|
|
977
|
+
const allowed = /* @__PURE__ */ new Set(["journal.json", ...j.operations.flatMap((_, i) => [`old-${i}`, `new-${i}`])]);
|
|
978
|
+
fail(fs3.readdirSync(active).every((n) => allowed.has(n)), "Unexpected transaction contents", 5);
|
|
979
|
+
const allowedPaths = /* @__PURE__ */ new Set([ROOT, LOCK, `${STATE}/state.json`, ".gitignore", "AGENTS.md"]);
|
|
980
|
+
let identities = 0;
|
|
981
|
+
const lockedManifests = /* @__PURE__ */ new Map();
|
|
982
|
+
const lockCandidates = [boundary(root, LOCK), ...j.operations.flatMap((o, i) => o.path === LOCK ? [path3.join(active, `old-${i}`), path3.join(active, `new-${i}`)] : [])];
|
|
983
|
+
for (const candidate of lockCandidates)
|
|
984
|
+
if (exists(candidate)) {
|
|
985
|
+
fail(fs3.lstatSync(candidate).isFile(), "Recovery lock object is not a regular file", 3);
|
|
986
|
+
let lock;
|
|
987
|
+
try {
|
|
988
|
+
const value = readJson(candidate);
|
|
989
|
+
validateLock(value);
|
|
990
|
+
lock = value;
|
|
991
|
+
} catch (e) {
|
|
992
|
+
throw new MintPlayError(5, `Recovery lock metadata is untrusted: ${e.message}`);
|
|
993
|
+
}
|
|
994
|
+
lockedManifests.set(lock.manifest_sha256, lock.manifest);
|
|
995
|
+
identities++;
|
|
996
|
+
for (const entry of lock.managed_entries)
|
|
997
|
+
allowedPaths.add(entry.path);
|
|
998
|
+
if (lock.installation.mode === "plugin")
|
|
999
|
+
allowedPaths.add(MARKET);
|
|
1000
|
+
}
|
|
1001
|
+
if (j.stage === "preparing" && target) {
|
|
1002
|
+
identities++;
|
|
1003
|
+
for (const entry of entries(target.manifest, ["codex", "claude"]))
|
|
1004
|
+
allowedPaths.add(entry.path);
|
|
1005
|
+
allowedPaths.add(MARKET);
|
|
1006
|
+
}
|
|
1007
|
+
fail(identities > 0 && j.operations.every((o) => allowedPaths.has(o.path)), "Recovery cannot grant paths outside validated installation manifests", 5);
|
|
1008
|
+
if (target)
|
|
1009
|
+
lockedManifests.set(target.digest, target.manifest);
|
|
1010
|
+
const independentLinks = /* @__PURE__ */ new Map();
|
|
1011
|
+
for (const manifest of lockedManifests.values())
|
|
1012
|
+
for (const entry of entries(manifest, ["codex", "claude"]))
|
|
1013
|
+
independentLinks.set(entry.path, sha("link:" + entry.target));
|
|
1014
|
+
for (const o of j.operations)
|
|
1015
|
+
if (independentLinks.has(o.path))
|
|
1016
|
+
fail([o.before, o.after].every((v) => v === null || v === independentLinks.get(o.path)), "Recovery link signature differs from independently validated installation paths", 5);
|
|
1017
|
+
try {
|
|
1018
|
+
preparingRoles(root, active, j, lockCandidates, target);
|
|
1019
|
+
} catch (e) {
|
|
1020
|
+
if (e instanceof MintPlayError && e.code === 2)
|
|
1021
|
+
throw new MintPlayError(5, `Untrusted preparation metadata: ${e.message}`);
|
|
1022
|
+
throw e;
|
|
1023
|
+
}
|
|
1024
|
+
for (let i = 0; i < j.operations.length; i++)
|
|
1025
|
+
if (j.operations[i].path === ROOT) {
|
|
1026
|
+
const o = j.operations[i];
|
|
1027
|
+
if (o.after_manifest !== null) {
|
|
1028
|
+
fail(lockedManifests.has(o.after_manifest), "Recovery target is not bound to a validated lock or supplied package", 5);
|
|
1029
|
+
if (target && target.digest === o.after_manifest)
|
|
1030
|
+
fail(bundleSignature(target) === o.after, "Recovery target digest was changed", 5);
|
|
1031
|
+
}
|
|
1032
|
+
for (const [candidate, kind] of [[path3.join(active, `old-${i}`), "old"], [path3.join(active, `new-${i}`), "new"], [boundary(root, ROOT), "destination"]]) {
|
|
1033
|
+
if (!exists(candidate) || j.stage === "preparing" && kind === "new")
|
|
1034
|
+
continue;
|
|
1035
|
+
try {
|
|
1036
|
+
const bytes = fs3.readFileSync(path3.join(candidate, "manifest.json")), digest = sha(bytes), manifest = lockedManifests.get(digest);
|
|
1037
|
+
fail(manifest, "Recovery package is not bound to an independent lock or supplied package", 5);
|
|
1038
|
+
const original = kind === "old" || kind === "destination" && o.before_id !== null && sameIdentity(o.before_id, identity(candidate)) && signature(candidate) === o.before;
|
|
1039
|
+
let checked;
|
|
1040
|
+
try {
|
|
1041
|
+
checked = readBundle(candidate, digest, original ? "installed" : "strict");
|
|
1042
|
+
} catch (e) {
|
|
1043
|
+
if (original) {
|
|
1044
|
+
validateMissingBaseline(candidate, manifest, digest);
|
|
1045
|
+
continue;
|
|
1046
|
+
}
|
|
1047
|
+
throw e;
|
|
1048
|
+
}
|
|
1049
|
+
fail(JSON.stringify(checked.manifest) === JSON.stringify(manifest), "Recovery package manifest differs from trusted identity", 5);
|
|
1050
|
+
if (kind === "new")
|
|
1051
|
+
fail(digest === o.after_manifest && bundleSignature(checked) === o.after, "Recovery staged package differs from target", 5);
|
|
1052
|
+
} catch (e) {
|
|
1053
|
+
throw new MintPlayError(e instanceof MintPlayError && e.code === 5 ? 5 : 3, `Recovery capability content is untrusted or modified: ${e.message}`, [candidate]);
|
|
1054
|
+
}
|
|
1055
|
+
}
|
|
1056
|
+
}
|
|
1057
|
+
recoverySemantics(root, active, j);
|
|
1058
|
+
if (j.stage === "preparing") {
|
|
1059
|
+
for (let i = 0; i < j.operations.length; i++) {
|
|
1060
|
+
const o = j.operations[i], dest = boundary(root, o.path), stage = path3.join(active, `new-${i}`);
|
|
1061
|
+
fail(signature(dest) === o.before && (!o.before_id || sameIdentity(o.before_id, identity(dest))), `Preparation baseline changed: ${o.path}`, 3);
|
|
1062
|
+
fail(!exists(path3.join(active, `old-${i}`)), "Unexpected preparation backup", 5);
|
|
1063
|
+
if (exists(stage)) {
|
|
1064
|
+
if (o.after_manifest) {
|
|
1065
|
+
fail(target && target.digest === o.after_manifest && bundleSignature(target) === o.after, "Retry with the same verified target bundle to recover interrupted preparation", 4);
|
|
1066
|
+
validatePartialBundle(stage, target);
|
|
1067
|
+
} else
|
|
1068
|
+
fail(signature(stage) === o.after, `Changed preparation file: ${o.path}`, 3);
|
|
1069
|
+
}
|
|
1070
|
+
}
|
|
1071
|
+
if (verifyOnly)
|
|
1072
|
+
return;
|
|
1073
|
+
for (let i = 0; i < j.operations.length; i++) {
|
|
1074
|
+
const stage = path3.join(active, `new-${i}`);
|
|
1075
|
+
if (exists(stage))
|
|
1076
|
+
removeStoredObject(stage);
|
|
1077
|
+
}
|
|
1078
|
+
fs3.unlinkSync(path3.join(active, "journal.json"));
|
|
1079
|
+
fs3.rmdirSync(active);
|
|
1080
|
+
return;
|
|
1081
|
+
}
|
|
1082
|
+
if (j.stage === "committed") {
|
|
1083
|
+
for (let i = 0; i < j.operations.length; i++) {
|
|
1084
|
+
const o = j.operations[i], dest = boundary(root, o.path);
|
|
1085
|
+
fail(signature(dest) === o.after && (!o.after_id || sameIdentity(o.after_id, identity(dest))), `Committed transaction drift: ${o.path}`, 3);
|
|
1086
|
+
const backup = path3.join(active, `old-${i}`);
|
|
1087
|
+
if (exists(backup)) {
|
|
1088
|
+
fail(o.before, "Unexpected backup", 5);
|
|
1089
|
+
fail(signature(backup) === o.before && sameIdentity(o.before_id, identity(backup)), "Backup changed", 3);
|
|
1090
|
+
}
|
|
1091
|
+
}
|
|
1092
|
+
if (verifyOnly)
|
|
1093
|
+
return;
|
|
1094
|
+
} else {
|
|
1095
|
+
for (let i = 0; i < j.operations.length; i++) {
|
|
1096
|
+
const o = j.operations[i], dest = boundary(root, o.path), backup = path3.join(active, `old-${i}`), staged = path3.join(active, `new-${i}`);
|
|
1097
|
+
const d = signature(dest), b = signature(backup), n = signature(staged);
|
|
1098
|
+
fail((b === null || b === o.before) && (n === null || n === o.after), `Recovery backup/stage drift: ${o.path}`, 3);
|
|
1099
|
+
if (b !== null)
|
|
1100
|
+
fail(sameIdentity(o.before_id, identity(backup)), `Recovery backup replaced: ${o.path}`, 3);
|
|
1101
|
+
if (n !== null)
|
|
1102
|
+
fail(sameIdentity(o.after_id, identity(staged)), `Recovery stage replaced: ${o.path}`, 3);
|
|
1103
|
+
fail(b !== null ? d === null || d === o.after : d === o.before || o.before === null && d === o.after, `Recovery destination drift: ${o.path}`, 3);
|
|
1104
|
+
if (d !== null)
|
|
1105
|
+
fail(sameIdentity(b !== null || o.before === null ? o.after_id : o.before_id, identity(dest)), `Recovery destination replaced: ${o.path}`, 3);
|
|
1106
|
+
if (o.before !== null && b === null)
|
|
1107
|
+
fail(d === o.before, `Missing recovery baseline: ${o.path}`, 3);
|
|
1108
|
+
}
|
|
1109
|
+
if (verifyOnly)
|
|
1110
|
+
return;
|
|
1111
|
+
const unswitch = (o, dest, staged) => {
|
|
1112
|
+
fail(signature(dest) === o.after, `Changed transaction content: ${dest}`, 3);
|
|
1113
|
+
if (exists(staged))
|
|
1114
|
+
removeVerified(dest, o.after);
|
|
1115
|
+
else
|
|
1116
|
+
renameExclusive(dest, staged);
|
|
1117
|
+
};
|
|
1118
|
+
for (let i = j.operations.length - 1; i >= 0; i--) {
|
|
1119
|
+
const o = j.operations[i], dest = boundary(root, o.path), backup = path3.join(active, `old-${i}`), staged = path3.join(active, `new-${i}`);
|
|
1120
|
+
if (exists(backup)) {
|
|
1121
|
+
if (exists(dest))
|
|
1122
|
+
unswitch(o, dest, staged);
|
|
1123
|
+
renameExclusive(backup, dest);
|
|
1124
|
+
} else if (o.before === null && exists(dest))
|
|
1125
|
+
unswitch(o, dest, staged);
|
|
1126
|
+
checkpoint("rollback-" + i);
|
|
1127
|
+
}
|
|
1128
|
+
}
|
|
1129
|
+
const done = boundary(root, `${STATE}/transactions/done-${j.token}`);
|
|
1130
|
+
fail(!exists(done), "Unexpected transaction residue", 5);
|
|
1131
|
+
renameExclusive(active, done);
|
|
1132
|
+
for (let i = 0; i < j.operations.length; i++)
|
|
1133
|
+
for (const [prefix, expected] of [["old", j.operations[i].before], ["new", j.operations[i].after]]) {
|
|
1134
|
+
const p = path3.join(done, `${prefix}-${i}`);
|
|
1135
|
+
if (exists(p)) {
|
|
1136
|
+
fail(expected, "Unexpected recovery file", 5);
|
|
1137
|
+
removeVerified(p, expected);
|
|
1138
|
+
checkpoint("cleanup-" + prefix + "-" + i);
|
|
1139
|
+
}
|
|
1140
|
+
}
|
|
1141
|
+
fs3.unlinkSync(path3.join(done, "journal.json"));
|
|
1142
|
+
fs3.rmdirSync(done);
|
|
1143
|
+
}
|
|
1144
|
+
function writeGuard(root, run, target, expectedWriter) {
|
|
1145
|
+
requireExclusiveRename();
|
|
1146
|
+
fail(writablePlatform && Number.isFinite(identity(root).birthtime) && identity(root).birthtime > 0, "Reliable project birthtime is unavailable; write operations are not supported", 5);
|
|
1147
|
+
const created = [];
|
|
1148
|
+
const dirs = [".harness", ".harness/.state", STATE, `${STATE}/transactions`];
|
|
1149
|
+
for (const d of dirs) {
|
|
1150
|
+
const p = boundary(root, d);
|
|
1151
|
+
if (!exists(p)) {
|
|
1152
|
+
fs3.mkdirSync(p);
|
|
1153
|
+
created.push({ path: d, ...identity(p) });
|
|
1154
|
+
}
|
|
1155
|
+
fail(fs3.lstatSync(p).isDirectory(), `Invalid state directory: ${d}`, 3);
|
|
1156
|
+
}
|
|
1157
|
+
const guard = boundary(root, `${STATE}/write.lock`);
|
|
1158
|
+
if (exists(guard)) {
|
|
1159
|
+
const current = staleWriter(root);
|
|
1160
|
+
fail(current, "Writer disappeared during inspection", 5);
|
|
1161
|
+
if (expectedWriter !== void 0)
|
|
1162
|
+
fail(expectedWriter && sameWriter(expectedWriter, current), "Stale writer identity changed after recovery preflight", 5);
|
|
1163
|
+
recover(root, target, true);
|
|
1164
|
+
const rechecked = staleWriter(root);
|
|
1165
|
+
fail(rechecked && sameWriter(current, rechecked), "Stale writer changed before takeover", 5);
|
|
1166
|
+
fs3.unlinkSync(path3.join(guard, "owner.json"));
|
|
1167
|
+
fs3.rmdirSync(guard);
|
|
1168
|
+
} else if (expectedWriter)
|
|
1169
|
+
fail(false, "Stale writer disappeared after recovery preflight", 5);
|
|
1170
|
+
try {
|
|
1171
|
+
fs3.mkdirSync(guard);
|
|
1172
|
+
} catch {
|
|
1173
|
+
throw new MintPlayError(5, "Concurrent project writer");
|
|
1174
|
+
}
|
|
1175
|
+
const directory = identity(guard), token = randomUUID(), descriptor = fs3.openSync(path3.join(guard, "owner.json"), "wx"), owner = statIdentity(fs3.fstatSync(descriptor));
|
|
1176
|
+
let bytes;
|
|
1177
|
+
try {
|
|
1178
|
+
checkpoint("writer-allocated");
|
|
1179
|
+
const unchanged = () => {
|
|
1180
|
+
fail(sameIdentity(directory, identity(boundary(root, `${STATE}/write.lock`))), "Writer allocation directory changed; preserving records", 3);
|
|
1181
|
+
verifyNewSlot(root, `${STATE}/write.lock/owner.json`, descriptor, owner);
|
|
1182
|
+
};
|
|
1183
|
+
unchanged();
|
|
1184
|
+
bytes = json({ schema_version: 2, pid: process.pid, token, project: identity(root), directory, self: owner });
|
|
1185
|
+
unchanged();
|
|
1186
|
+
fs3.writeFileSync(descriptor, bytes);
|
|
1187
|
+
} finally {
|
|
1188
|
+
fs3.closeSync(descriptor);
|
|
1189
|
+
}
|
|
1190
|
+
activeWriters.set(root, { directory, owner, owner_signature: sha("file:0:" + sha(bytes)), pid: process.pid, token });
|
|
1191
|
+
let completed;
|
|
1192
|
+
let cleanup = [];
|
|
1193
|
+
try {
|
|
1194
|
+
activeWriter(root);
|
|
1195
|
+
recover(root, target);
|
|
1196
|
+
const stateFile = boundary(root, `${STATE}/state.json`);
|
|
1197
|
+
if (exists(stateFile)) {
|
|
1198
|
+
const prior = readJson(stateFile), lock = readJson(boundary(root, LOCK));
|
|
1199
|
+
validateLock(lock);
|
|
1200
|
+
validateState(prior, root, lock);
|
|
1201
|
+
cleanup = prior.created_dirs;
|
|
1202
|
+
}
|
|
1203
|
+
completed = run(created);
|
|
1204
|
+
return completed;
|
|
1205
|
+
} finally {
|
|
1206
|
+
try {
|
|
1207
|
+
activeWriter(root);
|
|
1208
|
+
fs3.unlinkSync(path3.join(guard, "owner.json"));
|
|
1209
|
+
fs3.rmdirSync(guard);
|
|
1210
|
+
} finally {
|
|
1211
|
+
activeWriters.delete(root);
|
|
1212
|
+
}
|
|
1213
|
+
if (completed?.command === "remove" && completed.changed)
|
|
1214
|
+
for (const d of cleanup.sort((a, b) => b.path.length - a.path.length)) {
|
|
1215
|
+
const p = boundary(root, d.path);
|
|
1216
|
+
if (exists(p) && sameIdentity(d, identity(p)) && fs3.readdirSync(p).length === 0)
|
|
1217
|
+
fs3.rmdirSync(p);
|
|
1218
|
+
}
|
|
1219
|
+
}
|
|
1220
|
+
}
|
|
1221
|
+
function checkpoint(n) {
|
|
1222
|
+
if (process.env.MINTPLAY_TEST_EXIT_AFTER === String(n))
|
|
1223
|
+
process.exit(86);
|
|
1224
|
+
if (process.env.MINTPLAY_TEST_HOLD_AFTER === String(n)) {
|
|
1225
|
+
process.stderr.write(`MintPlay test checkpoint: ${n}
|
|
1226
|
+
`);
|
|
1227
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 1500);
|
|
1228
|
+
}
|
|
1229
|
+
}
|
|
1230
|
+
function transact(root, replacements, nextState, baseline) {
|
|
1231
|
+
activeWriter(root);
|
|
1232
|
+
const stateRel = `${STATE}/state.json`;
|
|
1233
|
+
if (nextState)
|
|
1234
|
+
replacements.set(stateRel, json(nextState));
|
|
1235
|
+
const active = boundary(root, `${STATE}/transactions/active`);
|
|
1236
|
+
fail(!exists(active), "Transaction not recovered", 5);
|
|
1237
|
+
fs3.mkdirSync(active);
|
|
1238
|
+
const ops = [];
|
|
1239
|
+
const token = randomUUID();
|
|
1240
|
+
let j = { schema_version: 1, token, project: identity(root), operations: ops, stage: "preparing" };
|
|
1241
|
+
try {
|
|
1242
|
+
for (const [rel, value] of replacements) {
|
|
1243
|
+
fail(managedPath(rel), "Invalid transaction path", 2);
|
|
1244
|
+
const dest = boundary(root, rel);
|
|
1245
|
+
const before = baseline.get(rel) || { signature: null, identity: null };
|
|
1246
|
+
fail(signature(dest) === before.signature && (!before.identity || sameIdentity(before.identity, identity(dest))), `Changed since preflight: ${rel}`, 3);
|
|
1247
|
+
ops.push({
|
|
1248
|
+
path: rel,
|
|
1249
|
+
before: before.signature,
|
|
1250
|
+
before_id: before.identity,
|
|
1251
|
+
after_id: null,
|
|
1252
|
+
after: value === null ? null : Buffer.isBuffer(value) ? sha("file:0:" + sha(value)) : typeof value === "string" ? sha("link:" + value) : bundleSignature(value),
|
|
1253
|
+
after_manifest: value !== null && !Buffer.isBuffer(value) && typeof value !== "string" ? value.digest : null
|
|
1254
|
+
});
|
|
1255
|
+
}
|
|
1256
|
+
atomicJson(root, path3.join(active, "journal.json"), j);
|
|
1257
|
+
let index = 0;
|
|
1258
|
+
for (const [rel, plannedValue] of replacements) {
|
|
1259
|
+
fail(managedPath(rel), "Invalid transaction path", 2);
|
|
1260
|
+
activeWriter(root);
|
|
1261
|
+
let value = plannedValue;
|
|
1262
|
+
const staged = path3.join(active, `new-${index}`);
|
|
1263
|
+
if (rel === stateRel && nextState) {
|
|
1264
|
+
nextState.owned = nextState.owned.map((e) => {
|
|
1265
|
+
const op = ops.find((o) => o.path === e.path);
|
|
1266
|
+
if (op) {
|
|
1267
|
+
fail(op.after !== null && op.after_id !== null, "Missing planned ownership", 5);
|
|
1268
|
+
return { path: e.path, signature: op.after, ...op.after_id };
|
|
1269
|
+
}
|
|
1270
|
+
const p = boundary(root, e.path);
|
|
1271
|
+
fail(ownedSignature(p, e.path) === e.signature && sameIdentity(e, identity(p)), `Unchanged ownership drift: ${e.path}`, 3);
|
|
1272
|
+
return e;
|
|
1273
|
+
});
|
|
1274
|
+
for (const blk of BLOCKS) {
|
|
1275
|
+
const op = ops.find((o) => o.path === blk.file);
|
|
1276
|
+
if (blockOwned(nextState, blk.key) && op) {
|
|
1277
|
+
fail(op.after_id, "Missing planned block ownership", 5);
|
|
1278
|
+
nextState[`${blk.key}_identity`] = op.after_id;
|
|
1279
|
+
}
|
|
1280
|
+
}
|
|
1281
|
+
creationFence(root);
|
|
1282
|
+
const slot = boundary(root, `${STATE}/transactions/active/new-${index}`), descriptor = fs3.openSync(slot, "wx");
|
|
1283
|
+
try {
|
|
1284
|
+
nextState.self = statIdentity(fs3.fstatSync(descriptor));
|
|
1285
|
+
checkpoint("state-allocated");
|
|
1286
|
+
activeWriter(root);
|
|
1287
|
+
const unchanged = () => verifyNewSlot(root, `${STATE}/transactions/active/new-${index}`, descriptor, nextState.self);
|
|
1288
|
+
unchanged();
|
|
1289
|
+
value = json(nextState);
|
|
1290
|
+
ops[index].after = sha("file:0:" + sha(value));
|
|
1291
|
+
ops[index].after_id = nextState.self;
|
|
1292
|
+
atomicJson(root, path3.join(active, "journal.json"), j);
|
|
1293
|
+
unchanged();
|
|
1294
|
+
fs3.writeFileSync(descriptor, value);
|
|
1295
|
+
} finally {
|
|
1296
|
+
fs3.closeSync(descriptor);
|
|
1297
|
+
}
|
|
1298
|
+
} else if (value !== null) {
|
|
1299
|
+
if (Buffer.isBuffer(value))
|
|
1300
|
+
writeNewBytes(root, `${STATE}/transactions/active/new-${index}`, value);
|
|
1301
|
+
else if (typeof value === "string")
|
|
1302
|
+
createLink(root, rel, value, staged);
|
|
1303
|
+
else
|
|
1304
|
+
writeBundle(value, staged, (n) => {
|
|
1305
|
+
activeWriter(root);
|
|
1306
|
+
if (process.env.MINTPLAY_TEST_EXIT_PREPARE_AT === String(n))
|
|
1307
|
+
process.exit(86);
|
|
1308
|
+
});
|
|
1309
|
+
}
|
|
1310
|
+
fail(signature(staged) === ops[index].after, "Prepared contents differ from plan", 4);
|
|
1311
|
+
ops[index].after_id = exists(staged) ? identity(staged) : null;
|
|
1312
|
+
index++;
|
|
1313
|
+
}
|
|
1314
|
+
if (nextState)
|
|
1315
|
+
validateCausality(nextState, root);
|
|
1316
|
+
activeWriter(root);
|
|
1317
|
+
j.stage = "prepared";
|
|
1318
|
+
atomicJson(root, path3.join(active, "journal.json"), j);
|
|
1319
|
+
checkpoint(0);
|
|
1320
|
+
activeWriter(root);
|
|
1321
|
+
if (nextState) {
|
|
1322
|
+
for (const own of nextState.owned)
|
|
1323
|
+
if (!replacements.has(own.path)) {
|
|
1324
|
+
const p = boundary(root, own.path);
|
|
1325
|
+
fail(ownedSignature(p, own.path) === own.signature && sameIdentity(own, identity(p)), `Unchanged ownership drift before switch: ${own.path}`, 3);
|
|
1326
|
+
}
|
|
1327
|
+
}
|
|
1328
|
+
for (let i = 0; i < ops.length; i++) {
|
|
1329
|
+
activeWriter(root);
|
|
1330
|
+
const o = ops[i], dest = boundary(root, o.path);
|
|
1331
|
+
fail(signature(dest) === o.before && (!o.before_id || sameIdentity(o.before_id, identity(dest))), `Changed after preflight: ${o.path}`, 3);
|
|
1332
|
+
if (o.before !== null)
|
|
1333
|
+
renameExclusive(dest, path3.join(active, `old-${i}`));
|
|
1334
|
+
checkpoint(i * 2 + 1);
|
|
1335
|
+
activeWriter(root);
|
|
1336
|
+
if (o.after !== null)
|
|
1337
|
+
renameExclusive(path3.join(active, `new-${i}`), dest);
|
|
1338
|
+
checkpoint(i * 2 + 2);
|
|
1339
|
+
}
|
|
1340
|
+
if (nextState)
|
|
1341
|
+
for (const e of nextState.owned) {
|
|
1342
|
+
const p = boundary(root, e.path);
|
|
1343
|
+
fail(ownedSignature(p, e.path) === e.signature && sameIdentity(e, identity(p)), `Planned ownership changed before commit: ${e.path}`, 3);
|
|
1344
|
+
}
|
|
1345
|
+
activeWriter(root);
|
|
1346
|
+
j.stage = "committed";
|
|
1347
|
+
atomicJson(root, path3.join(active, "journal.json"), j);
|
|
1348
|
+
checkpoint("committed");
|
|
1349
|
+
recover(root);
|
|
1350
|
+
} catch (e) {
|
|
1351
|
+
if (exists(path3.join(active, "journal.json")))
|
|
1352
|
+
recover(root, [...replacements.values()].find((v) => v !== null && !Buffer.isBuffer(v) && typeof v !== "string"));
|
|
1353
|
+
else if (exists(active) && fs3.readdirSync(active).length === 0)
|
|
1354
|
+
fs3.rmdirSync(active);
|
|
1355
|
+
throw e;
|
|
1356
|
+
}
|
|
1357
|
+
}
|
|
1358
|
+
var claudeBin = () => process.env.MINTPLAY_CLAUDE_BIN || "claude";
|
|
1359
|
+
var marketName = (root) => "mintplay-" + sha(root).slice(0, 12);
|
|
1360
|
+
var pluginId = (root) => `mintplay-harness@${marketName(root)}`;
|
|
1361
|
+
function marketBytes(root) {
|
|
1362
|
+
return json({ name: marketName(root), owner: { name: "MintPlay" }, plugins: [{ name: "mintplay-harness", source: "./mintplay", description: "MintPlay harness locked by this project" }] });
|
|
1363
|
+
}
|
|
1364
|
+
function boundedJson(file, label) {
|
|
1365
|
+
if (!exists(file))
|
|
1366
|
+
return null;
|
|
1367
|
+
fail(fs3.lstatSync(file).isFile() && fs3.lstatSync(file).size < 4 * 1024 * 1024, `${label} is not a bounded regular file`, 3);
|
|
1368
|
+
try {
|
|
1369
|
+
return JSON.parse(fs3.readFileSync(file, "utf8"));
|
|
1370
|
+
} catch {
|
|
1371
|
+
throw new MintPlayError(3, `${label} is not valid JSON; preserving it`);
|
|
1372
|
+
}
|
|
1373
|
+
}
|
|
1374
|
+
function claudeHost(root) {
|
|
1375
|
+
const settingsFile = boundary(root, ".claude/settings.local.json"), settings = boundedJson(settingsFile, "Claude local settings") || {};
|
|
1376
|
+
const name = marketName(root), expected = path3.join(root, ".harness");
|
|
1377
|
+
const known = boundedJson(path3.join(process.env.MINTPLAY_CLAUDE_PLUGIN_HOME || path3.join(os.homedir(), ".claude/plugins"), "known_marketplaces.json"), "Claude marketplace registry") || {};
|
|
1378
|
+
const declared = settings.extraKnownMarketplaces?.[name]?.source?.path ?? null, user = known[name]?.source?.path ?? null, enabled = settings.enabledPlugins?.[pluginId(root)] === true;
|
|
1379
|
+
const foreign = [declared, user].find((v) => v !== null && v !== expected) ?? null;
|
|
1380
|
+
return { registered: enabled && declared === expected && user === expected, enabled, declared, user, foreign: foreign ? `marketplace ${name} points at ${foreign}, not ${expected}` : null, settings_signature: signature(settingsFile) };
|
|
1381
|
+
}
|
|
1382
|
+
function claudeRun(root, args) {
|
|
1383
|
+
const p = spawnSync2(claudeBin(), args, { cwd: root, encoding: "utf8", timeout: 18e4, stdio: ["ignore", "pipe", "pipe"] });
|
|
1384
|
+
const last = (p.stdout || "").trim().split("\n").filter(Boolean).at(-1);
|
|
1385
|
+
let outcome = null;
|
|
1386
|
+
try {
|
|
1387
|
+
outcome = JSON.parse(last || "");
|
|
1388
|
+
} catch {
|
|
1389
|
+
}
|
|
1390
|
+
if (p.error || p.status !== 0 || outcome?.outcome !== "ok")
|
|
1391
|
+
throw new MintPlayError(1, `Claude Code host command failed (claude ${args.join(" ")}): ${outcome?.message || p.error?.message || (p.stderr || "").trim().slice(0, 400)}; snapshot retained, rerun sync`);
|
|
1392
|
+
}
|
|
1393
|
+
function hostRegister(root) {
|
|
1394
|
+
let h = claudeHost(root);
|
|
1395
|
+
fail(!h.foreign, h.foreign, 3);
|
|
1396
|
+
if (h.declared === null || h.user === null)
|
|
1397
|
+
claudeRun(root, ["plugin", "marketplace", "add", "./.harness", "--scope", "local", "--json"]);
|
|
1398
|
+
h = claudeHost(root);
|
|
1399
|
+
if (!h.enabled)
|
|
1400
|
+
claudeRun(root, ["plugin", "install", pluginId(root), "--scope", "local", "--json"]);
|
|
1401
|
+
h = claudeHost(root);
|
|
1402
|
+
fail(h.registered, "Claude Code did not record the project-local plugin registration", 1);
|
|
1403
|
+
}
|
|
1404
|
+
function hostUnregister(root) {
|
|
1405
|
+
let h = claudeHost(root);
|
|
1406
|
+
fail(!h.foreign, h.foreign, 3);
|
|
1407
|
+
if (h.enabled)
|
|
1408
|
+
claudeRun(root, ["plugin", "uninstall", pluginId(root), "--scope", "local", "--json"]);
|
|
1409
|
+
h = claudeHost(root);
|
|
1410
|
+
if (h.declared !== null || h.user !== null)
|
|
1411
|
+
claudeRun(root, ["plugin", "marketplace", "remove", marketName(root), "--scope", "local", "--json"]);
|
|
1412
|
+
h = claudeHost(root);
|
|
1413
|
+
fail(!h.enabled && h.declared === null && h.user === null, "Claude Code still records this project registration", 1);
|
|
1414
|
+
}
|
|
1415
|
+
function sessionRecordValid(root, lock, state, r) {
|
|
1416
|
+
try {
|
|
1417
|
+
exactKeys(r, ["schema_version", "host", "project", "installation_id", "lock_sha256", "plugin_id", "loaded_path", "manifest_sha256", "session_id", "host_version", "captured_at", "duplicates"], "session record");
|
|
1418
|
+
} catch {
|
|
1419
|
+
return "unsupported record schema";
|
|
1420
|
+
}
|
|
1421
|
+
if (r.schema_version !== 1 || r.host !== "claude")
|
|
1422
|
+
return "unsupported host or schema";
|
|
1423
|
+
if (typeof r.session_id !== "string" || !/^[A-Za-z0-9-]{8,}$/.test(r.session_id) || typeof r.host_version !== "string" || !r.host_version || typeof r.captured_at !== "string" || !Number.isFinite(Date.parse(r.captured_at)) || Date.parse(r.captured_at) > Date.now() + 6e4)
|
|
1424
|
+
return "record lacks a plausible host session identity or capture time";
|
|
1425
|
+
if (!Array.isArray(r.duplicates) || r.duplicates.length)
|
|
1426
|
+
return `record shows duplicate skill sources: ${JSON.stringify(r.duplicates)}`;
|
|
1427
|
+
if (r.project !== root || r.plugin_id !== pluginId(root) || r.loaded_path !== path3.join(root, ROOT))
|
|
1428
|
+
return "record belongs to another project, plugin identity or path";
|
|
1429
|
+
if (r.manifest_sha256 !== lock.manifest_sha256)
|
|
1430
|
+
return "record is stale: it was captured for a different locked manifest";
|
|
1431
|
+
if (!state || r.installation_id !== state.installation_id || r.lock_sha256 !== state.lock_sha256)
|
|
1432
|
+
return "record is stale: it belongs to an earlier installation or lock of this project";
|
|
1433
|
+
return null;
|
|
1434
|
+
}
|
|
1435
|
+
function liveSession(root, lock) {
|
|
1436
|
+
const p = spawnSync2(claudeBin(), ["-p", "--model", "haiku", "--no-session-persistence", "--max-turns", "1", "--strict-mcp-config", "--mcp-config", '{"mcpServers":{}}', "--output-format", "stream-json", "--verbose", "Reply with the single word ok."], { cwd: root, encoding: "utf8", timeout: 18e4, stdio: ["ignore", "pipe", "pipe"] });
|
|
1437
|
+
let init = null;
|
|
1438
|
+
for (const line of (p.stdout || "").split("\n")) {
|
|
1439
|
+
try {
|
|
1440
|
+
const r = JSON.parse(line);
|
|
1441
|
+
if (r.type === "system" && r.subtype === "init") {
|
|
1442
|
+
init = r;
|
|
1443
|
+
break;
|
|
1444
|
+
}
|
|
1445
|
+
} catch {
|
|
1446
|
+
}
|
|
1447
|
+
}
|
|
1448
|
+
fail(init, `Claude Code session did not start: ${(p.stderr || p.error?.message || "").trim().slice(0, 300)}`, 1);
|
|
1449
|
+
const mine = (init.plugins || []).filter((x) => x.source === pluginId(root));
|
|
1450
|
+
const ns = mine.length === 1 ? String(mine[0].name || "") : "", wanted = /* @__PURE__ */ new Set(["_shared", ...lock.manifest.skills]), seen = /* @__PURE__ */ new Map(), duplicates2 = [];
|
|
1451
|
+
for (const skill of init.skills || []) {
|
|
1452
|
+
const base = String(skill).split(":").at(-1);
|
|
1453
|
+
if (!wanted.has(base))
|
|
1454
|
+
continue;
|
|
1455
|
+
seen.set(skill, (seen.get(skill) || 0) + 1);
|
|
1456
|
+
if (skill !== `${ns}:${base}`)
|
|
1457
|
+
duplicates2.push(skill);
|
|
1458
|
+
}
|
|
1459
|
+
for (const [skill, n] of seen)
|
|
1460
|
+
if (n > 1)
|
|
1461
|
+
duplicates2.push(`${skill} x${n}`);
|
|
1462
|
+
for (const other of init.plugins || [])
|
|
1463
|
+
if (other.source !== pluginId(root) && (other.name === ns || String(other.source || "").startsWith("mintplay-harness@")))
|
|
1464
|
+
duplicates2.push(`plugin ${other.source} at ${other.path}`);
|
|
1465
|
+
const st = readJson(boundary(root, `${STATE}/state.json`));
|
|
1466
|
+
return {
|
|
1467
|
+
schema_version: 1,
|
|
1468
|
+
host: "claude",
|
|
1469
|
+
project: root,
|
|
1470
|
+
installation_id: st.installation_id,
|
|
1471
|
+
lock_sha256: st.lock_sha256,
|
|
1472
|
+
duplicates: [...new Set(duplicates2)].sort(),
|
|
1473
|
+
plugin_id: pluginId(root),
|
|
1474
|
+
loaded_path: mine.length === 1 ? mine[0].path : "(not loaded)",
|
|
1475
|
+
manifest_sha256: mine.length === 1 && mine[0].path === path3.join(root, ROOT) && exists(boundary(root, `${ROOT}/manifest.json`)) ? sha(fs3.readFileSync(boundary(root, `${ROOT}/manifest.json`))) : "(not loaded)",
|
|
1476
|
+
session_id: String(init.session_id || ""),
|
|
1477
|
+
host_version: String(init.claude_code_version || ""),
|
|
1478
|
+
captured_at: (/* @__PURE__ */ new Date()).toISOString()
|
|
1479
|
+
};
|
|
1480
|
+
}
|
|
1481
|
+
function check(root, lock, state) {
|
|
1482
|
+
const missing = [], conflicts = [], unowned = [];
|
|
1483
|
+
let bundle;
|
|
1484
|
+
const snapshot = boundary(root, ROOT);
|
|
1485
|
+
if (!exists(snapshot))
|
|
1486
|
+
missing.push(ROOT);
|
|
1487
|
+
else {
|
|
1488
|
+
try {
|
|
1489
|
+
bundle = readBundle(snapshot, lock.manifest_sha256, "installed");
|
|
1490
|
+
fail(JSON.stringify(bundle.manifest) === JSON.stringify(lock.manifest), "Lock manifest content differs");
|
|
1491
|
+
} catch (e) {
|
|
1492
|
+
try {
|
|
1493
|
+
fail(fs3.lstatSync(snapshot).isDirectory(), "Snapshot type changed", 3);
|
|
1494
|
+
const m = boundary(root, `${ROOT}/manifest.json`), f = boundary(root, `${ROOT}/files.json`);
|
|
1495
|
+
fail(fs3.lstatSync(m).isFile() && fs3.lstatSync(f).isFile(), "Manifest type changed");
|
|
1496
|
+
fail(sha(fs3.readFileSync(m)) === lock.manifest_sha256 && JSON.stringify(readJson(m)) === JSON.stringify(lock.manifest), "Snapshot manifest drift");
|
|
1497
|
+
const files = readJson(f);
|
|
1498
|
+
validateFiles(files);
|
|
1499
|
+
fail(sha(fs3.readFileSync(f)) === lock.manifest.files_manifest_sha256, "File manifest drift");
|
|
1500
|
+
const names = /* @__PURE__ */ new Set(["manifest.json", "files.json", ...files.map((e2) => e2.path)]), dirs = /* @__PURE__ */ new Set();
|
|
1501
|
+
for (const n of names) {
|
|
1502
|
+
const parts = n.split("/");
|
|
1503
|
+
for (let i = 1; i < parts.length; i++)
|
|
1504
|
+
dirs.add(parts.slice(0, i).join("/"));
|
|
1505
|
+
}
|
|
1506
|
+
const walk = (d, r = "") => {
|
|
1507
|
+
for (const item of fs3.readdirSync(d, { withFileTypes: true })) {
|
|
1508
|
+
const n = r ? `${r}/${item.name}` : item.name, p = path3.join(d, item.name);
|
|
1509
|
+
if (item.isDirectory()) {
|
|
1510
|
+
if (isSkillBytecodeCache(p, n))
|
|
1511
|
+
continue;
|
|
1512
|
+
fail(dirs.has(n), `Extra directory ${n}`);
|
|
1513
|
+
walk(p, n);
|
|
1514
|
+
} else
|
|
1515
|
+
fail(item.isFile() && names.has(n), `Extra or special entry ${n}`);
|
|
1516
|
+
}
|
|
1517
|
+
};
|
|
1518
|
+
walk(snapshot);
|
|
1519
|
+
const absent = [];
|
|
1520
|
+
for (const entry of files) {
|
|
1521
|
+
const p = boundary(root, `${ROOT}/${entry.path}`);
|
|
1522
|
+
if (!exists(p))
|
|
1523
|
+
absent.push(`${ROOT}/${entry.path}`);
|
|
1524
|
+
else {
|
|
1525
|
+
const s = fs3.lstatSync(p);
|
|
1526
|
+
fail(s.isFile() && s.size === entry.size && sha(fs3.readFileSync(p)) === entry.sha256 && execMatches(s.mode, entry.executable), `Changed file ${entry.path}`);
|
|
1527
|
+
}
|
|
1528
|
+
}
|
|
1529
|
+
fail(absent.length, "Not a missing-file-only snapshot");
|
|
1530
|
+
missing.push(...absent);
|
|
1531
|
+
} catch {
|
|
1532
|
+
conflicts.push(`${ROOT}: ${e.message}`);
|
|
1533
|
+
}
|
|
1534
|
+
}
|
|
1535
|
+
}
|
|
1536
|
+
for (const entry of lock.managed_entries) {
|
|
1537
|
+
const p = boundary(root, entry.path);
|
|
1538
|
+
if (!exists(p)) {
|
|
1539
|
+
missing.push(entry.path);
|
|
1540
|
+
continue;
|
|
1541
|
+
}
|
|
1542
|
+
if (!fs3.lstatSync(p).isSymbolicLink() || linkTarget(p) !== entry.target) {
|
|
1543
|
+
conflicts.push(`${entry.path}: foreign entry`);
|
|
1544
|
+
continue;
|
|
1545
|
+
}
|
|
1546
|
+
const owned = state?.owned.find((e) => e.path === entry.path);
|
|
1547
|
+
if (!owned)
|
|
1548
|
+
unowned.push(entry.path);
|
|
1549
|
+
else if (!sameIdentity(owned, identity(p)) || owned.signature !== signature(p))
|
|
1550
|
+
conflicts.push(`${entry.path}: ownership identity changed`);
|
|
1551
|
+
}
|
|
1552
|
+
if (lock.installation.mode === "plugin") {
|
|
1553
|
+
const p = boundary(root, MARKET);
|
|
1554
|
+
if (!exists(p))
|
|
1555
|
+
missing.push(MARKET);
|
|
1556
|
+
else if (!fs3.lstatSync(p).isFile() || !fs3.readFileSync(p).equals(marketBytes(root)))
|
|
1557
|
+
conflicts.push(`${MARKET}: foreign or edited catalog`);
|
|
1558
|
+
else {
|
|
1559
|
+
const owned = state?.owned.find((e) => e.path === MARKET);
|
|
1560
|
+
if (!owned)
|
|
1561
|
+
unowned.push(MARKET);
|
|
1562
|
+
else if (!sameIdentity(owned, identity(p)) || owned.signature !== signature(p))
|
|
1563
|
+
conflicts.push(`${MARKET}: ownership identity changed`);
|
|
1564
|
+
}
|
|
1565
|
+
const h = claudeHost(root);
|
|
1566
|
+
if (h.foreign)
|
|
1567
|
+
conflicts.push(`${HOST}: ${h.foreign}`);
|
|
1568
|
+
else if (!h.registered)
|
|
1569
|
+
missing.push(HOST);
|
|
1570
|
+
}
|
|
1571
|
+
if (state) {
|
|
1572
|
+
if (state.lock_sha256 !== sha(fs3.readFileSync(boundary(root, LOCK))))
|
|
1573
|
+
conflicts.push(`${LOCK}: changed outside CLI`);
|
|
1574
|
+
for (const name of [ROOT, LOCK])
|
|
1575
|
+
if (exists(boundary(root, name))) {
|
|
1576
|
+
const owned = state.owned.find((e) => e.path === name);
|
|
1577
|
+
if (!owned)
|
|
1578
|
+
unowned.push(name);
|
|
1579
|
+
else if (!sameIdentity(owned, identity(boundary(root, name))) || owned.signature !== ownedSignature(boundary(root, name), name) && !(name === ROOT && missing.some((p) => p.startsWith(ROOT + "/"))))
|
|
1580
|
+
conflicts.push(`${name}: modified or replaced`);
|
|
1581
|
+
}
|
|
1582
|
+
} else if (exists(snapshot))
|
|
1583
|
+
unowned.push(ROOT, LOCK);
|
|
1584
|
+
return { bundle, missing, conflicts, unowned };
|
|
1585
|
+
}
|
|
1586
|
+
function destructivePlan(root, replacements, baseline, state, remove, plugin = false) {
|
|
1587
|
+
const items = [];
|
|
1588
|
+
for (const rel of [...replacements.keys()].sort()) {
|
|
1589
|
+
const before = baseline.get(rel);
|
|
1590
|
+
if (!before?.signature || !before.identity)
|
|
1591
|
+
continue;
|
|
1592
|
+
const value = replacements.get(rel), stat = fs3.lstatSync(boundary(root, rel));
|
|
1593
|
+
items.push({
|
|
1594
|
+
path: rel,
|
|
1595
|
+
action: value === null ? "delete" : "replace",
|
|
1596
|
+
kind: stat.isSymbolicLink() ? "symlink" : stat.isFile() ? "file" : "directory",
|
|
1597
|
+
target: stat.isSymbolicLink() ? linkTarget(boundary(root, rel)) : null,
|
|
1598
|
+
signature: before.signature,
|
|
1599
|
+
...before.identity,
|
|
1600
|
+
after: value === null ? null : Buffer.isBuffer(value) ? sha("file:0:" + sha(value)) : typeof value === "string" ? sha("link:" + value) : bundleSignature(value)
|
|
1601
|
+
});
|
|
1602
|
+
}
|
|
1603
|
+
const directories = remove ? (state?.created_dirs || []).filter((d) => {
|
|
1604
|
+
const p = boundary(root, d.path);
|
|
1605
|
+
return exists(p) && fs3.lstatSync(p).isDirectory() && sameIdentity(d, identity(p));
|
|
1606
|
+
}).map((d) => ({ path: d.path, dev: d.dev, ino: d.ino, birthtime: d.birthtime })).sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0) : [];
|
|
1607
|
+
const host = plugin && remove ? { host: "claude", scope: "local", plugin_id: pluginId(root), marketplace: marketName(root), source_path: path3.join(root, ".harness") } : null;
|
|
1608
|
+
const body = { schema_version: 1, project: identity(root), items, directories, host };
|
|
1609
|
+
return { ...body, digest: sha(JSON.stringify(body)) };
|
|
1610
|
+
}
|
|
1611
|
+
function abandonedPlan(root) {
|
|
1612
|
+
const items = [];
|
|
1613
|
+
const add = (rel) => {
|
|
1614
|
+
const p = boundary(root, rel);
|
|
1615
|
+
if (!exists(p))
|
|
1616
|
+
return;
|
|
1617
|
+
const st = fs3.lstatSync(p);
|
|
1618
|
+
items.push({ path: rel, action: "delete", kind: st.isSymbolicLink() ? "symlink" : st.isFile() ? "file" : "directory", target: st.isSymbolicLink() ? linkTarget(p) : null, signature: signature(p), ...statIdentity(st), after: null });
|
|
1619
|
+
};
|
|
1620
|
+
for (const rel of [ROOT, LOCK, ".harness/.claude-plugin"])
|
|
1621
|
+
add(rel);
|
|
1622
|
+
const stateDir = boundary(root, STATE);
|
|
1623
|
+
if (exists(stateDir)) {
|
|
1624
|
+
fail(fs3.lstatSync(stateDir).isDirectory(), "MintPlay state path is not a directory; preserving it", 3);
|
|
1625
|
+
for (const n of fs3.readdirSync(stateDir).sort())
|
|
1626
|
+
add(`${STATE}/${n}`);
|
|
1627
|
+
}
|
|
1628
|
+
for (const dir of [".agents/skills", ".claude/skills"]) {
|
|
1629
|
+
const d = boundary(root, dir);
|
|
1630
|
+
if (!exists(d) || !fs3.lstatSync(d).isDirectory())
|
|
1631
|
+
continue;
|
|
1632
|
+
for (const n of fs3.readdirSync(d).sort()) {
|
|
1633
|
+
const rel = `${dir}/${n}`, p = path3.join(d, n);
|
|
1634
|
+
if (fs3.lstatSync(p).isSymbolicLink() && linkTarget(p) === `../../${ROOT}/skills/${n}`)
|
|
1635
|
+
add(rel);
|
|
1636
|
+
}
|
|
1637
|
+
}
|
|
1638
|
+
const blocks = [];
|
|
1639
|
+
for (const blk of BLOCKS) {
|
|
1640
|
+
const f = boundary(root, blk.file);
|
|
1641
|
+
if (!exists(f) || !fs3.lstatSync(f).isFile())
|
|
1642
|
+
continue;
|
|
1643
|
+
const t = ignoreText(f);
|
|
1644
|
+
const block = [blk.text, ...blk.history].find((x) => t === x || t.endsWith("\n" + x)) ?? null;
|
|
1645
|
+
if (block)
|
|
1646
|
+
blocks.push({ file: blk.file, signature: signature(f), block });
|
|
1647
|
+
}
|
|
1648
|
+
const h = claudeHost(root);
|
|
1649
|
+
fail(!h.foreign, h.foreign, 3);
|
|
1650
|
+
const host = h.enabled || h.declared || h.user ? { host: "claude", scope: "local", plugin_id: pluginId(root), marketplace: marketName(root), source_path: path3.join(root, ".harness") } : null;
|
|
1651
|
+
const body = { schema_version: 1, mode: "abandoned", project: identity(root), items, blocks, host, host_state: host ? { enabled: h.enabled, declared: h.declared, user: h.user } : null };
|
|
1652
|
+
return { items, blocks, host, digest: sha(JSON.stringify(body)) };
|
|
1653
|
+
}
|
|
1654
|
+
function liveOwner(file) {
|
|
1655
|
+
if (!exists(file) || !fs3.lstatSync(file).isFile() || fs3.lstatSync(file).size === 0)
|
|
1656
|
+
return;
|
|
1657
|
+
let pid = 0;
|
|
1658
|
+
try {
|
|
1659
|
+
pid = JSON.parse(fs3.readFileSync(file, "utf8")).pid;
|
|
1660
|
+
} catch {
|
|
1661
|
+
}
|
|
1662
|
+
if (Number.isInteger(pid) && pid > 0) {
|
|
1663
|
+
let alive = true;
|
|
1664
|
+
try {
|
|
1665
|
+
process.kill(pid, 0);
|
|
1666
|
+
} catch (e) {
|
|
1667
|
+
alive = e.code !== "ESRCH";
|
|
1668
|
+
}
|
|
1669
|
+
fail(!alive, `A MintPlay writer (pid ${pid}) is still running; wait for it to finish`, 5);
|
|
1670
|
+
}
|
|
1671
|
+
}
|
|
1672
|
+
function removeAbandoned(root, o, result) {
|
|
1673
|
+
liveOwner(boundary(root, `${STATE}/write.lock/owner.json`));
|
|
1674
|
+
const plan = abandonedPlan(root);
|
|
1675
|
+
result.confirmation = { schema_version: 1, digest: plan.digest, project: identity(root), items: plan.items, directories: [], host: plan.host };
|
|
1676
|
+
result.changes = [...plan.items.map((i) => i.path), ...plan.blocks.map((b) => `${b.file} (managed block)`), ...plan.host ? [`${HOST}: ${plan.host.plugin_id}`] : []];
|
|
1677
|
+
result.warnings.push("Abandoned-installation removal: confirm only after checking that no other MintPlay process is running; files inside .harness/mintplay (including local skill edits) are deleted.");
|
|
1678
|
+
if (!plan.items.length && !plan.blocks.length && !plan.host) {
|
|
1679
|
+
result.next_actions.push("Nothing to remove");
|
|
1680
|
+
return result;
|
|
1681
|
+
}
|
|
1682
|
+
if (o.dry_run)
|
|
1683
|
+
return result;
|
|
1684
|
+
if (!o.confirm) {
|
|
1685
|
+
result.next_actions.push(`Review the listed objects, then rerun with --abandoned --confirm ${plan.digest}`);
|
|
1686
|
+
throw new MintPlayError(1, `Abandoned removal requires --confirm ${plan.digest} after a --dry-run review`, plan.items.map((i) => i.path));
|
|
1687
|
+
}
|
|
1688
|
+
fail(o.confirm === plan.digest, "Confirmed plan differs from the current objects; preview again", 3);
|
|
1689
|
+
requireExclusiveRename();
|
|
1690
|
+
const harness = boundary(root, ".harness");
|
|
1691
|
+
if (!exists(harness))
|
|
1692
|
+
fs3.mkdirSync(harness);
|
|
1693
|
+
fail(fs3.lstatSync(harness).isDirectory(), ".harness is not a directory; preserving it", 3);
|
|
1694
|
+
const quarantine = boundary(root, `.harness/.mintplay-abandoned-${randomUUID()}`);
|
|
1695
|
+
fs3.mkdirSync(quarantine);
|
|
1696
|
+
const kept = [], moved = /* @__PURE__ */ new Map();
|
|
1697
|
+
const take = (item, index) => {
|
|
1698
|
+
const p = boundary(root, item.path);
|
|
1699
|
+
if (!exists(p)) {
|
|
1700
|
+
kept.push(`${item.path} (disappeared)`);
|
|
1701
|
+
return null;
|
|
1702
|
+
}
|
|
1703
|
+
const q = path3.join(quarantine, String(index));
|
|
1704
|
+
renameExclusive(p, q);
|
|
1705
|
+
moved.set(item.path, q);
|
|
1706
|
+
if (!(sameIdentity(item, identity(q)) && signature(q) === item.signature)) {
|
|
1707
|
+
kept.push(`${item.path} -> ${path3.relative(root, q)}`);
|
|
1708
|
+
return null;
|
|
1709
|
+
}
|
|
1710
|
+
return q;
|
|
1711
|
+
};
|
|
1712
|
+
const ordered = [...plan.items].map((item, i) => ({ item, i })).sort((a, b) => b.item.path.length - a.item.path.length);
|
|
1713
|
+
const lockItem = ordered.find((x) => x.item.path === `${STATE}/write.lock`);
|
|
1714
|
+
let guard = null;
|
|
1715
|
+
try {
|
|
1716
|
+
if (lockItem) {
|
|
1717
|
+
const q = take(lockItem.item, lockItem.i);
|
|
1718
|
+
if (q)
|
|
1719
|
+
removeStoredObject(q, lockItem.item.kind === "directory");
|
|
1720
|
+
}
|
|
1721
|
+
for (const d of [".harness/.state", STATE]) {
|
|
1722
|
+
const p = boundary(root, d);
|
|
1723
|
+
if (!exists(p))
|
|
1724
|
+
fs3.mkdirSync(p);
|
|
1725
|
+
}
|
|
1726
|
+
guard = boundary(root, `${STATE}/write.lock`);
|
|
1727
|
+
try {
|
|
1728
|
+
fs3.mkdirSync(guard);
|
|
1729
|
+
} catch {
|
|
1730
|
+
guard = null;
|
|
1731
|
+
throw new MintPlayError(5, "Another writer started; nothing further removed");
|
|
1732
|
+
}
|
|
1733
|
+
fs3.writeFileSync(path3.join(guard, "owner.json"), json({ schema_version: 2, pid: process.pid, token: randomUUID(), mode: "abandoned-removal" }), { flag: "wx" });
|
|
1734
|
+
checkpoint("abandoned-guarded");
|
|
1735
|
+
if (plan.host)
|
|
1736
|
+
hostUnregister(root);
|
|
1737
|
+
for (const { item, i } of ordered) {
|
|
1738
|
+
if (item === lockItem?.item)
|
|
1739
|
+
continue;
|
|
1740
|
+
const q = take(item, i);
|
|
1741
|
+
if (q)
|
|
1742
|
+
removeStoredObject(q, item.kind === "directory");
|
|
1743
|
+
checkpoint("abandoned-" + item.path);
|
|
1744
|
+
}
|
|
1745
|
+
for (const blk of plan.blocks) {
|
|
1746
|
+
const f = boundary(root, blk.file), q = path3.join(quarantine, `block-${blk.file}`);
|
|
1747
|
+
if (exists(f)) {
|
|
1748
|
+
renameExclusive(f, q);
|
|
1749
|
+
const t = ignoreText(q);
|
|
1750
|
+
if (signature(q) !== blk.signature)
|
|
1751
|
+
kept.push(`${blk.file} -> ${path3.relative(root, q)} (changed after confirmation)`);
|
|
1752
|
+
else {
|
|
1753
|
+
try {
|
|
1754
|
+
fs3.writeFileSync(f, t.slice(0, -blk.block.length), { flag: "wx" });
|
|
1755
|
+
fs3.unlinkSync(q);
|
|
1756
|
+
} catch {
|
|
1757
|
+
kept.push(`${blk.file} -> ${path3.relative(root, q)} (a new ${blk.file} appeared)`);
|
|
1758
|
+
}
|
|
1759
|
+
}
|
|
1760
|
+
}
|
|
1761
|
+
}
|
|
1762
|
+
} finally {
|
|
1763
|
+
if (guard && exists(path3.join(guard, "owner.json")))
|
|
1764
|
+
fs3.unlinkSync(path3.join(guard, "owner.json"));
|
|
1765
|
+
if (guard && exists(guard) && fs3.readdirSync(guard).length === 0)
|
|
1766
|
+
fs3.rmdirSync(guard);
|
|
1767
|
+
for (const d of [STATE, ".harness/.state"]) {
|
|
1768
|
+
const p = boundary(root, d);
|
|
1769
|
+
if (exists(p) && fs3.lstatSync(p).isDirectory() && fs3.readdirSync(p).length === 0)
|
|
1770
|
+
fs3.rmdirSync(p);
|
|
1771
|
+
}
|
|
1772
|
+
if (exists(quarantine) && fs3.readdirSync(quarantine).length === 0)
|
|
1773
|
+
fs3.rmdirSync(quarantine);
|
|
1774
|
+
const h = boundary(root, ".harness");
|
|
1775
|
+
if (exists(h) && fs3.lstatSync(h).isDirectory() && fs3.readdirSync(h).length === 0)
|
|
1776
|
+
fs3.rmdirSync(h);
|
|
1777
|
+
}
|
|
1778
|
+
result.changed = true;
|
|
1779
|
+
result.package_state = "missing";
|
|
1780
|
+
result.integration_state = "missing";
|
|
1781
|
+
if (kept.length)
|
|
1782
|
+
throw new MintPlayError(3, `Changed after confirmation, kept for review: ${kept.join(", ")}`, kept);
|
|
1783
|
+
return result;
|
|
1784
|
+
}
|
|
1785
|
+
function pendingTarget(root, o) {
|
|
1786
|
+
const journal = readJson(boundary(root, `${STATE}/transactions/active/journal.json`));
|
|
1787
|
+
validateJournal(journal, root);
|
|
1788
|
+
if (journal.stage !== "preparing")
|
|
1789
|
+
return void 0;
|
|
1790
|
+
if (o.command === "sync") {
|
|
1791
|
+
const lockPath = boundary(root, LOCK);
|
|
1792
|
+
if (!journal.operations.some((op) => op.path === ROOT && op.after_manifest) || !exists(lockPath))
|
|
1793
|
+
return void 0;
|
|
1794
|
+
const lock = readJson(lockPath);
|
|
1795
|
+
validateLock(lock);
|
|
1796
|
+
const statePath = boundary(root, `${STATE}/state.json`);
|
|
1797
|
+
let state;
|
|
1798
|
+
if (exists(statePath)) {
|
|
1799
|
+
const value = readJson(statePath);
|
|
1800
|
+
validateState(value, root, lock);
|
|
1801
|
+
state = value;
|
|
1802
|
+
}
|
|
1803
|
+
return source({ ...o, commit: lock.manifest.source.commit }, state, lock.manifest_sha256).bundle;
|
|
1804
|
+
}
|
|
1805
|
+
if (o.archive || o.source && o.commit || o.command === "init" || o.command === "update" && !o.agent)
|
|
1806
|
+
return source(o).bundle;
|
|
1807
|
+
return void 0;
|
|
1808
|
+
}
|
|
1809
|
+
function execute(o, underGuard = false, guardCreated = []) {
|
|
1810
|
+
fail(supported.includes(o.command), "Unknown command", 2);
|
|
1811
|
+
let root;
|
|
1812
|
+
try {
|
|
1813
|
+
root = fs3.realpathSync(path3.resolve(o.project));
|
|
1814
|
+
fail(fs3.lstatSync(root).isDirectory(), "Project must be an existing directory", 2);
|
|
1815
|
+
} catch (e) {
|
|
1816
|
+
if (e instanceof MintPlayError)
|
|
1817
|
+
throw e;
|
|
1818
|
+
throw new MintPlayError(2, "Project must be an existing directory");
|
|
1819
|
+
}
|
|
1820
|
+
if (underGuard)
|
|
1821
|
+
activeWriter(root);
|
|
1822
|
+
linkRoot = root;
|
|
1823
|
+
const result = { schema_version: 1, command: o.command, project: root, ok: true, changed: false, dry_run: o.dry_run, package_state: "missing", integration_state: "missing", session_state: "not_checked", tool_state: "not_checked", compatibility: "not_checked", bundle_identity: null, target_identity: null, changes: [], conflicts: [], warnings: ["Session/tools and unknown plugin duplicate sources not checked; static installation is not session loading."], next_actions: [], confirmation: null };
|
|
1824
|
+
for (const p of [ROOT, LOCK, `${STATE}/state.json`, `${STATE}/transactions/active`, `${STATE}/write.lock`, ".gitignore", "AGENTS.md"])
|
|
1825
|
+
boundary(root, p);
|
|
1826
|
+
if (o.abandoned) {
|
|
1827
|
+
fail(o.command === "remove", "--abandoned applies to remove only", 2);
|
|
1828
|
+
return removeAbandoned(root, o, result);
|
|
1829
|
+
}
|
|
1830
|
+
const transactions = boundary(root, `${STATE}/transactions`);
|
|
1831
|
+
if (exists(transactions) && fs3.lstatSync(transactions).isDirectory()) {
|
|
1832
|
+
const residue = fs3.readdirSync(transactions).filter((n) => n.startsWith("done-"));
|
|
1833
|
+
if (residue.length)
|
|
1834
|
+
result.warnings.push(`Interrupted cleanup residue retained for review: ${residue.map((n) => `${STATE}/transactions/${n}`).join(", ")}`);
|
|
1835
|
+
}
|
|
1836
|
+
const pending = exists(boundary(root, `${STATE}/transactions/active`)), busy = exists(boundary(root, `${STATE}/write.lock`));
|
|
1837
|
+
if ((pending || busy) && !underGuard && (o.command === "status" || o.dry_run))
|
|
1838
|
+
throw new MintPlayError(5, "Pending transaction or writer; dry-run/status never recovers");
|
|
1839
|
+
if ((pending || busy) && !underGuard) {
|
|
1840
|
+
const observedWriter = busy ? staleWriter(root) : null, target = pending ? pendingTarget(root, o) : void 0;
|
|
1841
|
+
if (pending)
|
|
1842
|
+
recover(root, target, true);
|
|
1843
|
+
checkpoint("recovery-prechecked");
|
|
1844
|
+
return writeGuard(root, (created2) => execute(o, true, created2), target, observedWriter);
|
|
1845
|
+
}
|
|
1846
|
+
const lockPath = boundary(root, LOCK);
|
|
1847
|
+
let lock, state;
|
|
1848
|
+
if (exists(lockPath)) {
|
|
1849
|
+
fail(fs3.lstatSync(lockPath).isFile(), "Lock is not a regular file", 2);
|
|
1850
|
+
lock = readJson(lockPath);
|
|
1851
|
+
validateLock(lock);
|
|
1852
|
+
}
|
|
1853
|
+
if (lock)
|
|
1854
|
+
result.bundle_identity = bundleIdentity(lock.manifest, lock.manifest_sha256);
|
|
1855
|
+
const statePath = boundary(root, `${STATE}/state.json`);
|
|
1856
|
+
if (exists(statePath)) {
|
|
1857
|
+
fail(lock && fs3.lstatSync(statePath).isFile(), "Orphan or invalid state", 2);
|
|
1858
|
+
state = readJson(statePath);
|
|
1859
|
+
validateState(state, root, lock);
|
|
1860
|
+
}
|
|
1861
|
+
const baseline = /* @__PURE__ */ new Map();
|
|
1862
|
+
for (const rel of [ROOT, LOCK, `${STATE}/state.json`, ".gitignore", "AGENTS.md", MARKET, ...lock?.managed_entries.map((e) => e.path) || []]) {
|
|
1863
|
+
const p = boundary(root, rel);
|
|
1864
|
+
baseline.set(rel, { signature: o.command === "status" ? ownedSignature(p, rel) : signature(p), identity: exists(p) ? identity(p) : null });
|
|
1865
|
+
}
|
|
1866
|
+
if (underGuard)
|
|
1867
|
+
checkpoint("preflight");
|
|
1868
|
+
fail(!o.integration || ["snapshot", "plugin"].includes(o.integration), "Unsupported integration", 2);
|
|
1869
|
+
const mode = lock ? lock.installation.mode : o.integration || "snapshot", plugin = mode === "plugin";
|
|
1870
|
+
if (lock && o.integration)
|
|
1871
|
+
fail(o.integration === mode, "Switching integration backend is not supported; remove and init again", 2);
|
|
1872
|
+
fail(!plugin || process.platform !== "win32", "The Claude Code Plugin backend is not supported on Windows; use the default project skills (omit --integration)", 1);
|
|
1873
|
+
if (plugin && o.agent)
|
|
1874
|
+
fail(o.agent === "claude", "Codex Plugin backend is blocked: Codex 0.166 plugin enablement is user-global and cannot be scoped per project; no snapshot fallback. Codex uses the default project skills (omit --integration or pass --integration snapshot)", 1);
|
|
1875
|
+
if (o.refresh_local) {
|
|
1876
|
+
fail(plugin, "Local refresh applies to the Plugin backend; snapshot modifications remain protected", 1);
|
|
1877
|
+
fail(o.command === "sync", "Use sync --refresh-local", 2);
|
|
1878
|
+
}
|
|
1879
|
+
if (!lock && o.command === "status") {
|
|
1880
|
+
result.next_actions.push("Run init --agent codex|claude|both to use the CLI-bundled official capabilities and project skills.");
|
|
1881
|
+
return result;
|
|
1882
|
+
}
|
|
1883
|
+
if (!lock && o.command !== "init")
|
|
1884
|
+
throw new MintPlayError(1, "No MintPlay lock; use init");
|
|
1885
|
+
const checked = lock ? check(root, lock, state) : { bundle: void 0, missing: [], conflicts: [], unowned: [] };
|
|
1886
|
+
if (plugin && !lock) {
|
|
1887
|
+
const h = claudeHost(root);
|
|
1888
|
+
if (h.foreign)
|
|
1889
|
+
checked.conflicts.push(`${HOST}: ${h.foreign}`);
|
|
1890
|
+
}
|
|
1891
|
+
if (lock) {
|
|
1892
|
+
const dup = duplicates(root, lock.manifest.skills, lock.installation.agents, plugin);
|
|
1893
|
+
checked.conflicts.push(...dup.map((p) => `Duplicate skill source: ${p}`));
|
|
1894
|
+
}
|
|
1895
|
+
result.package_state = checked.conflicts.some((c) => c.startsWith(ROOT)) ? "modified" : checked.bundle ? "clean" : "missing";
|
|
1896
|
+
result.integration_state = checked.conflicts.length ? "conflict" : checked.unowned.length ? "unowned" : checked.missing.length ? "missing" : lock ? "ready" : "missing";
|
|
1897
|
+
result.conflicts = checked.conflicts;
|
|
1898
|
+
if (plugin)
|
|
1899
|
+
result.warnings.push("Claude Code loads the plugin from this project's .harness/mintplay in place; a new session is needed to load changes.");
|
|
1900
|
+
if (o.command === "status" && (o.check_session || o.session_record)) {
|
|
1901
|
+
fail(plugin && lock, "Session evidence applies to the Claude Code Plugin backend", 1);
|
|
1902
|
+
fail(!(o.check_session && o.session_record), "Choose --check-session or --session-record", 2);
|
|
1903
|
+
if (o.check_session) {
|
|
1904
|
+
fail(result.package_state === "clean" && result.integration_state === "ready", "Session check needs a clean, registered installation", 1);
|
|
1905
|
+
const record = liveSession(root, lock), problem = sessionRecordValid(root, lock, state, record);
|
|
1906
|
+
result.session_state = record.duplicates.length ? "duplicate" : problem ? "not_loaded" : "loaded";
|
|
1907
|
+
if (problem)
|
|
1908
|
+
result.warnings.push(problem);
|
|
1909
|
+
result.session_record = record;
|
|
1910
|
+
if (o.record_out) {
|
|
1911
|
+
const out = path3.resolve(o.record_out);
|
|
1912
|
+
fail(!out.startsWith(path3.join(root, ".harness") + path3.sep), "Record output must be outside .harness", 2);
|
|
1913
|
+
fs3.writeFileSync(out, json(record), { flag: "wx" });
|
|
1914
|
+
}
|
|
1915
|
+
} else {
|
|
1916
|
+
const record = boundedJson(path3.resolve(o.session_record), "Session record"), problem = sessionRecordValid(root, lock, state, record);
|
|
1917
|
+
if (!problem)
|
|
1918
|
+
result.warnings.push("Imported session record is an unauthenticated local claim; use --check-session for live evidence");
|
|
1919
|
+
result.session_state = problem ? "record_rejected" : result.package_state === "clean" ? "recorded_loaded" : "record_rejected";
|
|
1920
|
+
if (problem)
|
|
1921
|
+
result.warnings.push(problem);
|
|
1922
|
+
else if (result.package_state !== "clean")
|
|
1923
|
+
result.warnings.push("record no longer matches the current package content");
|
|
1924
|
+
}
|
|
1925
|
+
result.ok = result.package_state === "clean" && result.integration_state === "ready" && ["loaded", "recorded_loaded"].includes(result.session_state);
|
|
1926
|
+
return result;
|
|
1927
|
+
}
|
|
1928
|
+
if (o.command === "status") {
|
|
1929
|
+
result.ok = result.package_state === "clean" && result.integration_state === "ready";
|
|
1930
|
+
return result;
|
|
1931
|
+
}
|
|
1932
|
+
if (o.refresh_local) {
|
|
1933
|
+
const others = checked.conflicts.filter((c) => !c.startsWith(ROOT));
|
|
1934
|
+
fail(!others.length, others.join("\n"), 3);
|
|
1935
|
+
fail(!checked.missing.length && !checked.unowned.length, "Installation incomplete; run sync first", 1);
|
|
1936
|
+
result.package_state = checked.bundle ? "clean" : "modified";
|
|
1937
|
+
result.integration_state = "ready";
|
|
1938
|
+
result.ok = true;
|
|
1939
|
+
result.next_actions.push("Project-derived skill edits are already the plugin source for this project only; start a new Claude Code session to load them.");
|
|
1940
|
+
return result;
|
|
1941
|
+
}
|
|
1942
|
+
if (checked.conflicts.length)
|
|
1943
|
+
throw new MintPlayError(3, checked.conflicts.join("\n"), checked.conflicts);
|
|
1944
|
+
if (checked.unowned.length && !(o.command === "sync" && o.adopt_existing))
|
|
1945
|
+
throw new MintPlayError(3, "Existing entries have no local ownership; preview sync --adopt-existing", checked.unowned);
|
|
1946
|
+
const addAgents = Boolean(o.agents_md) && !state?.agents_owned;
|
|
1947
|
+
const migrateBlocks = ["sync", "update"].includes(o.command) && BLOCKS.some((blk) => {
|
|
1948
|
+
const file = boundary(root, blk.file);
|
|
1949
|
+
return exists(file) && fs3.lstatSync(file).isFile() && blockMigration(blk, state, ignoreText(file), identity(file)) !== null;
|
|
1950
|
+
});
|
|
1951
|
+
let b = checked.bundle;
|
|
1952
|
+
let next = lock;
|
|
1953
|
+
let selectedSource = state?.source || null;
|
|
1954
|
+
if (o.command === "init") {
|
|
1955
|
+
const selected = agents(o.agent), resolved = source(o);
|
|
1956
|
+
b = resolved.bundle;
|
|
1957
|
+
selectedSource = resolved.origin;
|
|
1958
|
+
next = makeLock(b, selected, mode);
|
|
1959
|
+
result.target_identity = bundleIdentity(b.manifest, b.digest);
|
|
1960
|
+
if (lock) {
|
|
1961
|
+
fail(JSON.stringify(next) === JSON.stringify(lock), "Already initialized differently; use update", 3);
|
|
1962
|
+
fail(!checked.missing.length, "Incomplete installation; use sync", 1);
|
|
1963
|
+
if (!addAgents)
|
|
1964
|
+
return result;
|
|
1965
|
+
}
|
|
1966
|
+
} else if (o.command === "update") {
|
|
1967
|
+
fail(!checked.missing.length, "Incomplete installation; sync before update", 1);
|
|
1968
|
+
if (o.source || o.archive || o.commit || !o.agent) {
|
|
1969
|
+
const resolved = source(o);
|
|
1970
|
+
b = resolved.bundle;
|
|
1971
|
+
selectedSource = resolved.origin;
|
|
1972
|
+
}
|
|
1973
|
+
fail(b, "Missing installed bundle", 1);
|
|
1974
|
+
next = makeLock(b, o.agent ? agents(o.agent) : lock.installation.agents, mode);
|
|
1975
|
+
result.target_identity = bundleIdentity(b.manifest, b.digest);
|
|
1976
|
+
if (b.digest !== lock.manifest_sha256)
|
|
1977
|
+
fail(b.manifest.release !== lock.manifest.release && (b.manifest.source.repository !== lock.manifest.source.repository || b.manifest.source.commit !== lock.manifest.source.commit || JSON.stringify(b.manifest.agentbuddy?.skills) !== JSON.stringify(lock.manifest.agentbuddy?.skills)), "Same release or source identity has a different digest; refusing ambiguous replacement", 4);
|
|
1978
|
+
result.compatibility = compatibility(root, lock, b);
|
|
1979
|
+
fail(result.compatibility !== "unknown", "Existing .game memory compatibility is unknown; update refused without migration", 1);
|
|
1980
|
+
if (JSON.stringify(next) === JSON.stringify(lock) && !addAgents && !migrateBlocks)
|
|
1981
|
+
return result;
|
|
1982
|
+
} else if (o.command === "sync") {
|
|
1983
|
+
if (!b) {
|
|
1984
|
+
const resolved = source({ ...o, commit: lock.manifest.source.commit }, state, lock.manifest_sha256);
|
|
1985
|
+
b = resolved.bundle;
|
|
1986
|
+
selectedSource = resolved.origin;
|
|
1987
|
+
}
|
|
1988
|
+
fail(b.digest === lock.manifest_sha256, "Source identity mismatch", 4);
|
|
1989
|
+
if (!checked.missing.length && !checked.unowned.length && !addAgents && !migrateBlocks)
|
|
1990
|
+
return result;
|
|
1991
|
+
}
|
|
1992
|
+
if (o.command !== "remove")
|
|
1993
|
+
fail(b && next, "Missing target bundle", 4);
|
|
1994
|
+
const nextEntries = next?.managed_entries || [], oldEntries = lock?.managed_entries || [];
|
|
1995
|
+
const replacements = /* @__PURE__ */ new Map();
|
|
1996
|
+
if (o.command === "remove") {
|
|
1997
|
+
fail(!checked.missing.filter((m) => m !== HOST).length, "Incomplete owned content; sync before remove", 3);
|
|
1998
|
+
if (plugin)
|
|
1999
|
+
replacements.set(MARKET, null);
|
|
2000
|
+
replacements.set(ROOT, null);
|
|
2001
|
+
for (const e of oldEntries)
|
|
2002
|
+
replacements.set(e.path, null);
|
|
2003
|
+
replacements.set(LOCK, null);
|
|
2004
|
+
replacements.set(`${STATE}/state.json`, null);
|
|
2005
|
+
} else {
|
|
2006
|
+
if (!checked.bundle || b.digest !== lock?.manifest_sha256)
|
|
2007
|
+
replacements.set(ROOT, b);
|
|
2008
|
+
for (const e of oldEntries)
|
|
2009
|
+
if (!nextEntries.some((n) => n.path === e.path))
|
|
2010
|
+
replacements.set(e.path, null);
|
|
2011
|
+
for (const e of nextEntries) {
|
|
2012
|
+
const p = boundary(root, e.path);
|
|
2013
|
+
if (!oldEntries.some((n) => n.path === e.path) && exists(p))
|
|
2014
|
+
throw new MintPlayError(3, `Foreign entry: ${e.path}`, [e.path]);
|
|
2015
|
+
if (!exists(p))
|
|
2016
|
+
replacements.set(e.path, e.target);
|
|
2017
|
+
}
|
|
2018
|
+
if (plugin && !exists(boundary(root, MARKET)))
|
|
2019
|
+
replacements.set(MARKET, marketBytes(root));
|
|
2020
|
+
const duplicate = duplicates(root, b.manifest.skills, next.installation.agents, plugin);
|
|
2021
|
+
fail(!duplicate.length, `Duplicate skill sources: ${duplicate.join(", ")}`, 3);
|
|
2022
|
+
if (!lock || sha(json(next)) !== sha(fs3.readFileSync(lockPath)))
|
|
2023
|
+
replacements.set(LOCK, json(next));
|
|
2024
|
+
}
|
|
2025
|
+
if (!lock) {
|
|
2026
|
+
for (const rel of [ROOT, LOCK, statePath])
|
|
2027
|
+
if (exists(rel === statePath ? rel : boundary(root, rel)))
|
|
2028
|
+
throw new MintPlayError(3, `Existing unmanaged path: ${rel}`);
|
|
2029
|
+
}
|
|
2030
|
+
const blockState = {};
|
|
2031
|
+
for (const blk of BLOCKS) {
|
|
2032
|
+
const k = blk.key, file = boundary(root, blk.file);
|
|
2033
|
+
fail(!exists(file) || fs3.lstatSync(file).isFile(), `${blk.file} is not a regular file`, 3);
|
|
2034
|
+
const text = exists(file) ? ignoreText(file) : "";
|
|
2035
|
+
let own = blockOwned(state, k);
|
|
2036
|
+
const made2 = state ? blockCreated(state, k) : !exists(file);
|
|
2037
|
+
const wanted = k === "ignore" || own !== null || Boolean(o.agents_md);
|
|
2038
|
+
if (o.command === "remove") {
|
|
2039
|
+
const id = blockId(state, k);
|
|
2040
|
+
if (own && id && exists(file) && sameIdentity(id, identity(file)) && text.endsWith(own)) {
|
|
2041
|
+
const remaining = text.slice(0, -own.length);
|
|
2042
|
+
replacements.set(blk.file, made2 && !remaining ? null : Buffer.from(remaining));
|
|
2043
|
+
} else if (own)
|
|
2044
|
+
result.warnings.push(`Edited or replaced MintPlay ${blk.file} block retained.`);
|
|
2045
|
+
} else if (migrateBlocks && own) {
|
|
2046
|
+
const migration = blockMigration(blk, state, text, exists(file) ? identity(file) : null);
|
|
2047
|
+
if (migration) {
|
|
2048
|
+
own = migration.owned;
|
|
2049
|
+
replacements.set(blk.file, Buffer.from(migration.text));
|
|
2050
|
+
}
|
|
2051
|
+
} else if (wanted && !own && !text.includes(blk.marker)) {
|
|
2052
|
+
own = (text && !text.endsWith("\n") ? "\n" : "") + blk.text;
|
|
2053
|
+
replacements.set(blk.file, Buffer.from(text + own));
|
|
2054
|
+
}
|
|
2055
|
+
blockState[k] = { owned: own, created: k === "ignore" ? made2 : state && blockOwned(state, k) !== null ? made2 : !exists(file) };
|
|
2056
|
+
}
|
|
2057
|
+
result.changes = [...replacements.keys(), ...o.command === "remove" ? [] : [`${STATE}/state.json`]];
|
|
2058
|
+
fail(replacements.size + (o.command === "remove" ? 0 : 1) < 200, "Installation exceeds supported transaction path limit", 2);
|
|
2059
|
+
if (o.command === "remove" || [...replacements].some(([rel, v]) => v === null && /^(?:\.agents|\.claude)\//.test(rel))) {
|
|
2060
|
+
const plan = destructivePlan(root, replacements, baseline, state, o.command === "remove", plugin);
|
|
2061
|
+
result.confirmation = plan;
|
|
2062
|
+
if (o.confirm)
|
|
2063
|
+
fail(o.confirm === plan.digest, "Confirmed plan differs from the current objects; preview again and confirm the listed entries", 3);
|
|
2064
|
+
else if (!o.dry_run) {
|
|
2065
|
+
result.next_actions.push(`Review the listed entries, then rerun with --confirm ${plan.digest}`);
|
|
2066
|
+
throw new MintPlayError(1, `Deleting managed entries requires explicit confirmation of the current objects; preview with --dry-run, then pass --confirm ${plan.digest}`, plan.items.map((i) => i.path));
|
|
2067
|
+
}
|
|
2068
|
+
}
|
|
2069
|
+
if (o.dry_run)
|
|
2070
|
+
return result;
|
|
2071
|
+
if (!underGuard)
|
|
2072
|
+
return writeGuard(root, (created2) => execute(o, true, created2));
|
|
2073
|
+
const created = [...state?.created_dirs || [], ...guardCreated];
|
|
2074
|
+
const dirs = /* @__PURE__ */ new Set([".harness", ".harness/.state", STATE, ...plugin && o.command !== "remove" ? [".harness/.claude-plugin"] : [], ...nextEntries.flatMap((e) => [e.path.split("/")[0], e.path.split("/").slice(0, 2).join("/")])]);
|
|
2075
|
+
let made = false;
|
|
2076
|
+
for (const dir of dirs) {
|
|
2077
|
+
const p = boundary(root, dir);
|
|
2078
|
+
if (!exists(p)) {
|
|
2079
|
+
fs3.mkdirSync(p);
|
|
2080
|
+
made = true;
|
|
2081
|
+
created.push({ path: dir, ...identity(p) });
|
|
2082
|
+
}
|
|
2083
|
+
}
|
|
2084
|
+
if (made && process.platform === "win32")
|
|
2085
|
+
creationFence(root);
|
|
2086
|
+
checkpoint("host-dirs-created");
|
|
2087
|
+
const nextState = o.command === "remove" ? null : {
|
|
2088
|
+
schema_version: 2,
|
|
2089
|
+
installation_id: state?.installation_id || randomUUID(),
|
|
2090
|
+
project: identity(root),
|
|
2091
|
+
self: { dev: 0, ino: 0, birthtime: 0 },
|
|
2092
|
+
lock_sha256: sha(json(next)),
|
|
2093
|
+
owned: [ROOT, LOCK, ...nextEntries.map((e) => e.path), ...plugin ? [MARKET] : []].map((p) => {
|
|
2094
|
+
const before = baseline.get(p);
|
|
2095
|
+
const digest = p === ROOT && checked.bundle && !replacements.has(ROOT) ? bundleSignature(checked.bundle) : before?.signature;
|
|
2096
|
+
return { path: p, signature: digest || "", ...before?.identity || { dev: 0, ino: 0, birthtime: 0 } };
|
|
2097
|
+
}),
|
|
2098
|
+
created_dirs: created,
|
|
2099
|
+
source: selectedSource,
|
|
2100
|
+
ignore_owned: blockState.ignore.owned,
|
|
2101
|
+
ignore_created: blockState.ignore.created,
|
|
2102
|
+
ignore_identity: state?.ignore_identity || null,
|
|
2103
|
+
agents_owned: blockState.agents.owned,
|
|
2104
|
+
agents_created: blockState.agents.created,
|
|
2105
|
+
agents_identity: state?.agents_identity || null
|
|
2106
|
+
};
|
|
2107
|
+
if (plugin && o.command === "remove") {
|
|
2108
|
+
activeWriter(root);
|
|
2109
|
+
hostUnregister(root);
|
|
2110
|
+
checkpoint("host-unregistered");
|
|
2111
|
+
}
|
|
2112
|
+
transact(root, replacements, nextState, baseline);
|
|
2113
|
+
if (plugin && o.command !== "remove") {
|
|
2114
|
+
activeWriter(root);
|
|
2115
|
+
checkpoint("before-host-register");
|
|
2116
|
+
hostRegister(root);
|
|
2117
|
+
}
|
|
2118
|
+
if (o.command === "remove")
|
|
2119
|
+
for (const d of [...created].sort((a, b2) => b2.path.length - a.path.length)) {
|
|
2120
|
+
const p = boundary(root, d.path);
|
|
2121
|
+
if (exists(p) && sameIdentity(d, identity(p)) && fs3.readdirSync(p).length === 0)
|
|
2122
|
+
fs3.rmdirSync(p);
|
|
2123
|
+
}
|
|
2124
|
+
result.changed = true;
|
|
2125
|
+
result.package_state = o.command === "remove" ? "missing" : "clean";
|
|
2126
|
+
result.integration_state = o.command === "remove" ? "missing" : "ready";
|
|
2127
|
+
result.bundle_identity = o.command === "remove" ? null : bundleIdentity(next.manifest, next.manifest_sha256);
|
|
2128
|
+
return result;
|
|
2129
|
+
}
|
|
2130
|
+
|
|
2131
|
+
// dist/init/project-command.js
|
|
2132
|
+
function reportCommandError(argv, e) {
|
|
2133
|
+
const error = e instanceof MintPlayError ? e : new MintPlayError(1, e.message);
|
|
2134
|
+
const projectArg = argv.indexOf("--project");
|
|
2135
|
+
const requested = path4.resolve(projectArg >= 0 ? argv[projectArg + 1] || "." : ".");
|
|
2136
|
+
let project = requested;
|
|
2137
|
+
try {
|
|
2138
|
+
project = fs4.realpathSync(requested);
|
|
2139
|
+
} catch {
|
|
2140
|
+
}
|
|
2141
|
+
const r = {
|
|
2142
|
+
schema_version: 1,
|
|
2143
|
+
command: argv[0] || "",
|
|
2144
|
+
project,
|
|
2145
|
+
ok: false,
|
|
2146
|
+
changed: false,
|
|
2147
|
+
dry_run: argv.includes("--dry-run"),
|
|
2148
|
+
package_state: "not_checked",
|
|
2149
|
+
integration_state: "not_checked",
|
|
2150
|
+
session_state: "not_checked",
|
|
2151
|
+
tool_state: "not_checked",
|
|
2152
|
+
compatibility: "not_checked",
|
|
2153
|
+
bundle_identity: null,
|
|
2154
|
+
target_identity: null,
|
|
2155
|
+
changes: [],
|
|
2156
|
+
conflicts: error.paths,
|
|
2157
|
+
warnings: [],
|
|
2158
|
+
next_actions: [error.message],
|
|
2159
|
+
confirmation: null
|
|
2160
|
+
};
|
|
2161
|
+
if (argv.includes("--json"))
|
|
2162
|
+
process.stdout.write(JSON.stringify(r) + "\n");
|
|
2163
|
+
else
|
|
2164
|
+
console.error(error.message);
|
|
2165
|
+
return error.code;
|
|
2166
|
+
}
|
|
2167
|
+
function runProjectCommand(argv) {
|
|
2168
|
+
const wantsJson = argv.includes("--json");
|
|
2169
|
+
if (Number(process.versions.node.split(".")[0]) < 22)
|
|
2170
|
+
throw new MintPlayError(2, "Node 22 or newer is required");
|
|
2171
|
+
const o = {
|
|
2172
|
+
command: argv[0],
|
|
2173
|
+
project: process.cwd(),
|
|
2174
|
+
dry_run: false,
|
|
2175
|
+
adopt_existing: false,
|
|
2176
|
+
refresh_local: false
|
|
2177
|
+
};
|
|
2178
|
+
const strings = {
|
|
2179
|
+
"--project": "project",
|
|
2180
|
+
"--agent": "agent",
|
|
2181
|
+
"--integration": "integration",
|
|
2182
|
+
"--source": "source",
|
|
2183
|
+
"--commit": "commit",
|
|
2184
|
+
"--archive": "archive",
|
|
2185
|
+
"--confirm": "confirm",
|
|
2186
|
+
"--session-record": "session_record",
|
|
2187
|
+
"--record-out": "record_out"
|
|
2188
|
+
};
|
|
2189
|
+
const flags = {
|
|
2190
|
+
"--dry-run": "dry_run",
|
|
2191
|
+
"--adopt-existing": "adopt_existing",
|
|
2192
|
+
"--refresh-local": "refresh_local",
|
|
2193
|
+
"--check-session": "check_session",
|
|
2194
|
+
"--abandoned": "abandoned",
|
|
2195
|
+
"--agents-md": "agents_md"
|
|
2196
|
+
};
|
|
2197
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2198
|
+
for (let i = 1; i < argv.length; i++) {
|
|
2199
|
+
const a = argv[i];
|
|
2200
|
+
if (seen.has(a))
|
|
2201
|
+
throw new MintPlayError(2, `Duplicate option: ${a}`);
|
|
2202
|
+
seen.add(a);
|
|
2203
|
+
if (a === "--json")
|
|
2204
|
+
continue;
|
|
2205
|
+
else if (flags[a])
|
|
2206
|
+
o[flags[a]] = true;
|
|
2207
|
+
else if (strings[a]) {
|
|
2208
|
+
const v = argv[++i];
|
|
2209
|
+
if (!v || v.startsWith("--"))
|
|
2210
|
+
throw new MintPlayError(2, `Missing value: ${a}`);
|
|
2211
|
+
o[strings[a]] = v;
|
|
2212
|
+
} else
|
|
2213
|
+
throw new MintPlayError(2, `Unknown option: ${a}`);
|
|
2214
|
+
}
|
|
2215
|
+
if (o.archive && (o.source || o.commit))
|
|
2216
|
+
throw new MintPlayError(2, "Choose archive or Git source, not both");
|
|
2217
|
+
if (o.confirm && !/^[a-f0-9]{64}$/.test(o.confirm))
|
|
2218
|
+
throw new MintPlayError(2, "--confirm requires a 64-character plan digest");
|
|
2219
|
+
if (o.agent && !["codex", "claude", "both"].includes(o.agent))
|
|
2220
|
+
throw new MintPlayError(2, "Unsupported agent");
|
|
2221
|
+
if (o.command === "init" && !o.agent)
|
|
2222
|
+
throw new MintPlayError(2, "init requires --agent codex|claude|both");
|
|
2223
|
+
if (o.command === "init" && o.source && !o.commit || o.command === "update" && o.source && !o.commit)
|
|
2224
|
+
throw new MintPlayError(2, "Git init/update requires --commit");
|
|
2225
|
+
const r = execute(o);
|
|
2226
|
+
process.stdout.write(wantsJson ? JSON.stringify(r) + "\n" : `${r.command}: ${r.ok ? "ok" : "not ready"} ${r.project}
|
|
2227
|
+
Version ${r.bundle_identity?.release || "(not installed)"}
|
|
2228
|
+
Package ${r.package_state}; integration ${r.integration_state}; session ${r.session_state}
|
|
2229
|
+
${r.changes.join("\n")}
|
|
2230
|
+
${r.confirmation ? `Confirm these current objects:
|
|
2231
|
+
${r.confirmation.items.map((i) => ` ${i.action} ${i.kind} ${i.path}${i.target ? " -> " + i.target : ""} (dev ${i.dev} ino ${i.ino})`).join("\n")}
|
|
2232
|
+
Plan digest ${r.confirmation.digest}
|
|
2233
|
+
` : ""}`);
|
|
2234
|
+
if (!wantsJson && r.warnings.length)
|
|
2235
|
+
console.error(r.warnings.join("\n"));
|
|
2236
|
+
return r.ok ? 0 : 1;
|
|
2237
|
+
}
|
|
2238
|
+
|
|
2239
|
+
// dist/init/index.js
|
|
2240
|
+
function runInitCommand(args) {
|
|
2241
|
+
const argv = ["init", ...args];
|
|
2242
|
+
try {
|
|
2243
|
+
return runProjectCommand(argv);
|
|
2244
|
+
} catch (error) {
|
|
2245
|
+
return reportCommandError(argv, error);
|
|
2246
|
+
}
|
|
2247
|
+
}
|
|
2248
|
+
export {
|
|
2249
|
+
runInitCommand
|
|
2250
|
+
};
|