joycraft 0.7.16 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +137 -156
- package/dist/cli.js +1593 -373
- package/dist/cli.js.map +1 -1
- package/dist/index.d.ts +4 -0
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -1
- package/dist/joycraft-release.json +1 -1
- package/package.json +9 -3
- package/payload/.agents/skills/joycraft-context/SKILL.md +36 -0
- package/payload/.agents/skills/joycraft-decompose/SKILL.md +68 -0
- package/payload/.agents/skills/joycraft-entry/SKILL.md +103 -0
- package/payload/.agents/skills/joycraft-implement/SKILL.md +106 -0
- package/payload/.agents/skills/joycraft-retro/SKILL.md +54 -0
- package/payload/.agents/skills/joycraft-retro/agents/openai.yaml +5 -0
- package/payload/.agents/skills/joycraft-session-end/SKILL.md +78 -0
- package/payload/.agents/skills/joycraft-testing/SKILL.md +60 -0
- package/payload/.agents/skills/joycraft-ui-slice/SKILL.md +59 -0
- package/payload/.agents/skills/joycraft-ui-slice/scripts/serve.mjs +97 -0
- package/payload/.agents/skills/joycraft-verify/SKILL.md +103 -0
- package/payload/.claude/agents/joycraft-implementer.md +31 -0
- package/payload/.claude/agents/joycraft-reviewer.md +30 -0
- package/payload/.joycraft/assets/artifacts/kit.css +102 -0
- package/payload/.joycraft/assets/artifacts/kit.js +301 -0
- package/payload/.joycraft/assets/artifacts/transports.js +236 -0
- package/payload/.joycraft/contracts/types.d.ts +185 -0
- package/payload/.joycraft/references/architecture.md +90 -0
- package/payload/.joycraft/references/archive.md +211 -0
- package/payload/.joycraft/references/artifacts.md +176 -0
- package/payload/.joycraft/references/completion.md +109 -0
- package/payload/.joycraft/references/context.md +80 -0
- package/payload/.joycraft/references/delivery.md +32 -0
- package/payload/.joycraft/references/dispatch.md +226 -0
- package/payload/.joycraft/references/recurring-failures.md +33 -0
- package/payload/.joycraft/references/retro.md +94 -0
- package/payload/.joycraft/references/setup.md +279 -0
- package/payload/.joycraft/references/testing.md +120 -0
- package/payload/.joycraft/references/update.md +44 -0
- package/payload/.joycraft/references/workflow.md +113 -0
- package/payload/.joycraft/references/worktrees.md +148 -0
- package/payload/.joycraft/runtime/archive.mjs +463 -0
- package/payload/.joycraft/runtime/artifacts/cli.mjs +61 -0
- package/payload/.joycraft/runtime/artifacts/decisions.mjs +214 -0
- package/payload/.joycraft/runtime/artifacts/model.mjs +161 -0
- package/payload/.joycraft/runtime/artifacts/preferences.mjs +127 -0
- package/payload/.joycraft/runtime/artifacts/render.mjs +21 -0
- package/payload/.joycraft/runtime/artifacts/server.mjs +40 -0
- package/payload/.joycraft/runtime/completion.mjs +300 -0
- package/payload/.joycraft/runtime/context/cli.mjs +75 -0
- package/payload/.joycraft/runtime/context/index.mjs +29 -0
- package/payload/.joycraft/runtime/context/search.mjs +149 -0
- package/payload/.joycraft/runtime/delivery.mjs +142 -0
- package/payload/.joycraft/runtime/dispatch-preflight.mjs +535 -0
- package/payload/.joycraft/runtime/dispatch-start.mjs +98 -0
- package/payload/.joycraft/runtime/evidence.mjs +137 -0
- package/payload/.joycraft/runtime/identity.mjs +486 -0
- package/payload/.joycraft/runtime/kickoff.mjs +174 -0
- package/payload/.joycraft/runtime/redact.mjs +9 -0
- package/payload/.joycraft/runtime/retro.mjs +151 -0
- package/payload/.joycraft/runtime/review-tools.json +34 -0
- package/payload/.joycraft/runtime/review-tools.mjs +331 -0
- package/payload/.joycraft/runtime/scope.mjs +129 -0
- package/payload/.joycraft/runtime/update-check.mjs +142 -0
- package/payload/.joycraft/templates/README.md +7 -0
- package/payload/.joycraft/templates/artifact.json +33 -0
- package/payload/.joycraft/templates/brief.md +35 -0
- package/payload/.joycraft/templates/decisions.md +13 -0
- package/payload/.joycraft/templates/project-context.md +36 -0
- package/payload/.joycraft/templates/queue.json +27 -0
- package/payload/.joycraft/templates/spec.md +39 -0
- package/payload/.joycraft/templates/ui-slice.html +71 -0
- package/payload/PIN +74 -0
- package/payload/scripts/export.mjs +301 -0
- package/payload/scripts/hook-paths.mjs +35 -0
- package/payload/scripts/legacy-hooks.mjs +128 -0
- package/payload/scripts/legacy-inventory.json +117 -0
- package/dist/chunk-35RQLGKM.js +0 -2167
- package/dist/chunk-35RQLGKM.js.map +0 -1
- package/dist/chunk-7BPB2IKY.js +0 -255
- package/dist/chunk-7BPB2IKY.js.map +0 -1
- package/dist/chunk-B73DPYYC.js +0 -377
- package/dist/chunk-B73DPYYC.js.map +0 -1
- package/dist/chunk-GTP7Z52K.js +0 -3942
- package/dist/chunk-GTP7Z52K.js.map +0 -1
- package/dist/chunk-K4AI6FKB.js +0 -417
- package/dist/chunk-K4AI6FKB.js.map +0 -1
- package/dist/chunk-KKDKC4FM.js +0 -115
- package/dist/chunk-KKDKC4FM.js.map +0 -1
- package/dist/chunk-OMFGDJW4.js +0 -97
- package/dist/chunk-OMFGDJW4.js.map +0 -1
- package/dist/chunk-Z5JFEGWG.js +0 -563
- package/dist/chunk-Z5JFEGWG.js.map +0 -1
- package/dist/init-MUB5CC6L.js +0 -60
- package/dist/init-MUB5CC6L.js.map +0 -1
- package/dist/init-autofix-2DMBO4QN.js +0 -122
- package/dist/init-autofix-2DMBO4QN.js.map +0 -1
- package/dist/install-manifest-EQHT4474.js +0 -37
- package/dist/install-manifest-EQHT4474.js.map +0 -1
- package/dist/release-artifact-4TL5L2ZY.js +0 -14
- package/dist/release-artifact-4TL5L2ZY.js.map +0 -1
- package/dist/release-resolver-P2H46QTU.js +0 -293
- package/dist/release-resolver-P2H46QTU.js.map +0 -1
- package/dist/telemetry-store-IBO5GRTA.js +0 -14
- package/dist/telemetry-store-IBO5GRTA.js.map +0 -1
- package/dist/update-LFLQTPUA.js +0 -19
- package/dist/update-LFLQTPUA.js.map +0 -1
- package/dist/update-check-YT765NE7.js +0 -36
- package/dist/update-check-YT765NE7.js.map +0 -1
- package/dist/upgrade-L5WERK4X.js +0 -28
- package/dist/upgrade-L5WERK4X.js.map +0 -1
package/dist/chunk-GTP7Z52K.js
DELETED
|
@@ -1,3942 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import {
|
|
3
|
-
CHECKER_SOURCE,
|
|
4
|
-
CODEX_SKILLS,
|
|
5
|
-
COPILOT_SKILLS,
|
|
6
|
-
OMP_SKILLS,
|
|
7
|
-
PI_AGENTS,
|
|
8
|
-
PI_EXTENSIONS,
|
|
9
|
-
PI_SCRIPTS,
|
|
10
|
-
PI_SKILLS,
|
|
11
|
-
SKILLS,
|
|
12
|
-
TEMPLATES
|
|
13
|
-
} from "./chunk-35RQLGKM.js";
|
|
14
|
-
import {
|
|
15
|
-
resolveUpdatePath
|
|
16
|
-
} from "./chunk-OMFGDJW4.js";
|
|
17
|
-
import {
|
|
18
|
-
adoptLegacyInstallation,
|
|
19
|
-
manifestDigest,
|
|
20
|
-
manifestPath,
|
|
21
|
-
normalizeManifestPath,
|
|
22
|
-
normalizedVendorHash,
|
|
23
|
-
parseInstallationManifest,
|
|
24
|
-
planGitignoreProfile,
|
|
25
|
-
rawFileHash,
|
|
26
|
-
readInstallationManifestInfo,
|
|
27
|
-
resolveGitignoreProfile,
|
|
28
|
-
sharedManifestIgnoreWarning,
|
|
29
|
-
validateManifest
|
|
30
|
-
} from "./chunk-Z5JFEGWG.js";
|
|
31
|
-
import {
|
|
32
|
-
DEFAULT_GITIGNORE_PROFILE,
|
|
33
|
-
HARNESSES,
|
|
34
|
-
LEGACY_CLAUDE_STATE_PATH,
|
|
35
|
-
LEGACY_VERSION_FILE,
|
|
36
|
-
STATE_PATH,
|
|
37
|
-
parseGitignoreProfile,
|
|
38
|
-
parseHarnessSelection,
|
|
39
|
-
readVersion,
|
|
40
|
-
resolveHarnesses,
|
|
41
|
-
sanitizeHarnesses
|
|
42
|
-
} from "./chunk-KKDKC4FM.js";
|
|
43
|
-
import {
|
|
44
|
-
compareStableVersions,
|
|
45
|
-
readUpdatePolicy
|
|
46
|
-
} from "./chunk-B73DPYYC.js";
|
|
47
|
-
import {
|
|
48
|
-
isVerifiedReleaseArtifact
|
|
49
|
-
} from "./chunk-7BPB2IKY.js";
|
|
50
|
-
|
|
51
|
-
// src/update.ts
|
|
52
|
-
import {
|
|
53
|
-
existsSync as existsSync8,
|
|
54
|
-
lstatSync as lstatSync3,
|
|
55
|
-
mkdirSync as mkdirSync3,
|
|
56
|
-
readFileSync as readFileSync8
|
|
57
|
-
} from "fs";
|
|
58
|
-
import { execFileSync } from "child_process";
|
|
59
|
-
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
60
|
-
import { join as join10, resolve, dirname as dirname3 } from "path";
|
|
61
|
-
|
|
62
|
-
// src/detect.ts
|
|
63
|
-
import { readFileSync, existsSync, readdirSync } from "fs";
|
|
64
|
-
import { join } from "path";
|
|
65
|
-
var WEB_FRAMEWORKS = /* @__PURE__ */ new Set(["Next.js", "Nuxt", "Remix", "React", "Vue", "Svelte"]);
|
|
66
|
-
var API_FRAMEWORKS = /* @__PURE__ */ new Set(["Express", "Fastify", "FastAPI", "Django", "Flask", "Gin", "Fiber", "Echo", "Actix", "Axum", "Rocket"]);
|
|
67
|
-
function buildTestingStrategy(backbone) {
|
|
68
|
-
switch (backbone) {
|
|
69
|
-
case "playwright":
|
|
70
|
-
return { backbone, testFormat: ".spec.ts", layers: ["ui", "api", "logic", "static"] };
|
|
71
|
-
case "maestro":
|
|
72
|
-
return { backbone, testFormat: ".yaml", layers: ["ui", "api", "logic", "static"] };
|
|
73
|
-
case "api":
|
|
74
|
-
return { backbone, testFormat: ".test.ts", layers: ["api", "logic", "static"] };
|
|
75
|
-
case "native":
|
|
76
|
-
return { backbone, testFormat: ".test.ts", layers: ["logic", "static"] };
|
|
77
|
-
}
|
|
78
|
-
}
|
|
79
|
-
function readFile(path) {
|
|
80
|
-
try {
|
|
81
|
-
return readFileSync(path, "utf-8");
|
|
82
|
-
} catch {
|
|
83
|
-
return null;
|
|
84
|
-
}
|
|
85
|
-
}
|
|
86
|
-
function detectNodeFramework(pkg) {
|
|
87
|
-
const allDeps = { ...pkg.dependencies, ...pkg.devDependencies };
|
|
88
|
-
if (allDeps["next"]) return "Next.js";
|
|
89
|
-
if (allDeps["nuxt"]) return "Nuxt";
|
|
90
|
-
if (allDeps["@remix-run/node"] || allDeps["@remix-run/react"]) return "Remix";
|
|
91
|
-
if (allDeps["express"]) return "Express";
|
|
92
|
-
if (allDeps["fastify"]) return "Fastify";
|
|
93
|
-
if (allDeps["react"]) return "React";
|
|
94
|
-
if (allDeps["vue"]) return "Vue";
|
|
95
|
-
if (allDeps["svelte"]) return "Svelte";
|
|
96
|
-
return void 0;
|
|
97
|
-
}
|
|
98
|
-
function detectNodeTestFramework(pkg) {
|
|
99
|
-
const allDeps = { ...pkg.dependencies, ...pkg.devDependencies };
|
|
100
|
-
if (allDeps["vitest"]) return "vitest";
|
|
101
|
-
if (allDeps["jest"]) return "jest";
|
|
102
|
-
if (allDeps["mocha"]) return "mocha";
|
|
103
|
-
return void 0;
|
|
104
|
-
}
|
|
105
|
-
function detectNodePackageManager(dir) {
|
|
106
|
-
if (existsSync(join(dir, "pnpm-lock.yaml"))) return "pnpm";
|
|
107
|
-
if (existsSync(join(dir, "yarn.lock"))) return "yarn";
|
|
108
|
-
if (existsSync(join(dir, "bun.lockb")) || existsSync(join(dir, "bun.lock"))) return "bun";
|
|
109
|
-
return "npm";
|
|
110
|
-
}
|
|
111
|
-
function detectNode(dir) {
|
|
112
|
-
const raw = readFile(join(dir, "package.json"));
|
|
113
|
-
if (raw === null) return null;
|
|
114
|
-
let pkg;
|
|
115
|
-
try {
|
|
116
|
-
pkg = JSON.parse(raw);
|
|
117
|
-
} catch {
|
|
118
|
-
return null;
|
|
119
|
-
}
|
|
120
|
-
const pm = detectNodePackageManager(dir);
|
|
121
|
-
const run = pm === "npm" ? "npm run" : pm;
|
|
122
|
-
const scripts = pkg.scripts ?? {};
|
|
123
|
-
const framework = detectNodeFramework(pkg);
|
|
124
|
-
const testFramework = detectNodeTestFramework(pkg);
|
|
125
|
-
const commands = {};
|
|
126
|
-
if (scripts.build) commands.build = `${run} build`;
|
|
127
|
-
else commands.build = `${run} build`;
|
|
128
|
-
if (scripts.test) commands.test = `${run} test`;
|
|
129
|
-
else if (testFramework) commands.test = `${run} test`;
|
|
130
|
-
else commands.test = `${pm === "npm" ? "npm" : pm} test`;
|
|
131
|
-
if (scripts.lint) commands.lint = `${run} lint`;
|
|
132
|
-
if (scripts.typecheck) commands.typecheck = `${run} typecheck`;
|
|
133
|
-
else if (pkg.devDependencies?.["typescript"]) {
|
|
134
|
-
commands.typecheck = "tsc --noEmit";
|
|
135
|
-
}
|
|
136
|
-
const allDeps = { ...pkg.dependencies, ...pkg.devDependencies };
|
|
137
|
-
let testingStrategy;
|
|
138
|
-
if (allDeps["react-native"]) {
|
|
139
|
-
testingStrategy = buildTestingStrategy("maestro");
|
|
140
|
-
} else if (framework && WEB_FRAMEWORKS.has(framework)) {
|
|
141
|
-
testingStrategy = buildTestingStrategy("playwright");
|
|
142
|
-
} else if (framework && API_FRAMEWORKS.has(framework)) {
|
|
143
|
-
testingStrategy = buildTestingStrategy("api");
|
|
144
|
-
} else {
|
|
145
|
-
testingStrategy = buildTestingStrategy("native");
|
|
146
|
-
}
|
|
147
|
-
return {
|
|
148
|
-
language: "node",
|
|
149
|
-
packageManager: pm,
|
|
150
|
-
commands,
|
|
151
|
-
framework,
|
|
152
|
-
testingStrategy
|
|
153
|
-
};
|
|
154
|
-
}
|
|
155
|
-
function detectPythonFramework(content) {
|
|
156
|
-
if (/fastapi/i.test(content)) return "FastAPI";
|
|
157
|
-
if (/django/i.test(content)) return "Django";
|
|
158
|
-
if (/flask/i.test(content)) return "Flask";
|
|
159
|
-
return void 0;
|
|
160
|
-
}
|
|
161
|
-
function detectPython(dir) {
|
|
162
|
-
const pyproject = readFile(join(dir, "pyproject.toml"));
|
|
163
|
-
if (pyproject !== null) {
|
|
164
|
-
const isPoetry = /\[tool\.poetry\]/.test(pyproject);
|
|
165
|
-
const isUv = existsSync(join(dir, "uv.lock"));
|
|
166
|
-
let pm;
|
|
167
|
-
let run;
|
|
168
|
-
if (isUv) {
|
|
169
|
-
pm = "uv";
|
|
170
|
-
run = "uv run";
|
|
171
|
-
} else if (isPoetry) {
|
|
172
|
-
pm = "poetry";
|
|
173
|
-
run = "poetry run";
|
|
174
|
-
} else {
|
|
175
|
-
pm = "pip";
|
|
176
|
-
run = "python -m";
|
|
177
|
-
}
|
|
178
|
-
const framework = detectPythonFramework(pyproject);
|
|
179
|
-
const hasPytest = /pytest/i.test(pyproject);
|
|
180
|
-
const testingStrategy = framework && API_FRAMEWORKS.has(framework) ? buildTestingStrategy("api") : buildTestingStrategy("native");
|
|
181
|
-
return {
|
|
182
|
-
language: "python",
|
|
183
|
-
packageManager: pm,
|
|
184
|
-
commands: {
|
|
185
|
-
build: `${pm === "poetry" ? "poetry" : pm} build`,
|
|
186
|
-
test: hasPytest ? `${run} pytest` : `${run} pytest`,
|
|
187
|
-
lint: `${run} ruff check .`
|
|
188
|
-
},
|
|
189
|
-
framework,
|
|
190
|
-
testingStrategy
|
|
191
|
-
};
|
|
192
|
-
}
|
|
193
|
-
const requirements = readFile(join(dir, "requirements.txt"));
|
|
194
|
-
if (requirements !== null) {
|
|
195
|
-
const framework = detectPythonFramework(requirements);
|
|
196
|
-
const testingStrategy = framework && API_FRAMEWORKS.has(framework) ? buildTestingStrategy("api") : buildTestingStrategy("native");
|
|
197
|
-
return {
|
|
198
|
-
language: "python",
|
|
199
|
-
packageManager: "pip",
|
|
200
|
-
commands: {
|
|
201
|
-
build: "pip install -e .",
|
|
202
|
-
test: "python -m pytest",
|
|
203
|
-
lint: "python -m ruff check ."
|
|
204
|
-
},
|
|
205
|
-
framework,
|
|
206
|
-
testingStrategy
|
|
207
|
-
};
|
|
208
|
-
}
|
|
209
|
-
return null;
|
|
210
|
-
}
|
|
211
|
-
function detectRust(dir) {
|
|
212
|
-
const cargo = readFile(join(dir, "Cargo.toml"));
|
|
213
|
-
if (cargo === null) return null;
|
|
214
|
-
let framework;
|
|
215
|
-
if (/actix-web/.test(cargo)) framework = "Actix";
|
|
216
|
-
else if (/axum/.test(cargo)) framework = "Axum";
|
|
217
|
-
else if (/rocket/.test(cargo)) framework = "Rocket";
|
|
218
|
-
const testingStrategy = framework && API_FRAMEWORKS.has(framework) ? buildTestingStrategy("api") : buildTestingStrategy("native");
|
|
219
|
-
return {
|
|
220
|
-
language: "rust",
|
|
221
|
-
packageManager: "cargo",
|
|
222
|
-
commands: {
|
|
223
|
-
build: "cargo build",
|
|
224
|
-
test: "cargo test",
|
|
225
|
-
lint: "cargo clippy"
|
|
226
|
-
},
|
|
227
|
-
framework,
|
|
228
|
-
testingStrategy
|
|
229
|
-
};
|
|
230
|
-
}
|
|
231
|
-
function detectGo(dir) {
|
|
232
|
-
const gomod = readFile(join(dir, "go.mod"));
|
|
233
|
-
if (gomod === null) return null;
|
|
234
|
-
let framework;
|
|
235
|
-
if (/github\.com\/gin-gonic\/gin/.test(gomod)) framework = "Gin";
|
|
236
|
-
else if (/github\.com\/gofiber\/fiber/.test(gomod)) framework = "Fiber";
|
|
237
|
-
else if (/github\.com\/labstack\/echo/.test(gomod)) framework = "Echo";
|
|
238
|
-
const testingStrategy = framework && API_FRAMEWORKS.has(framework) ? buildTestingStrategy("api") : buildTestingStrategy("native");
|
|
239
|
-
return {
|
|
240
|
-
language: "go",
|
|
241
|
-
packageManager: "go",
|
|
242
|
-
commands: {
|
|
243
|
-
build: "go build ./...",
|
|
244
|
-
test: "go test ./...",
|
|
245
|
-
lint: "golangci-lint run"
|
|
246
|
-
},
|
|
247
|
-
framework,
|
|
248
|
-
testingStrategy
|
|
249
|
-
};
|
|
250
|
-
}
|
|
251
|
-
function detectSwift(dir) {
|
|
252
|
-
const pkg = readFile(join(dir, "Package.swift"));
|
|
253
|
-
if (pkg === null) return null;
|
|
254
|
-
return {
|
|
255
|
-
language: "swift",
|
|
256
|
-
packageManager: "swift",
|
|
257
|
-
commands: {
|
|
258
|
-
build: "swift build",
|
|
259
|
-
test: "swift test"
|
|
260
|
-
},
|
|
261
|
-
testingStrategy: buildTestingStrategy("native")
|
|
262
|
-
};
|
|
263
|
-
}
|
|
264
|
-
function detectFlutter(dir) {
|
|
265
|
-
const pubspec = readFile(join(dir, "pubspec.yaml"));
|
|
266
|
-
if (pubspec === null) return null;
|
|
267
|
-
if (!/flutter/i.test(pubspec)) return null;
|
|
268
|
-
return {
|
|
269
|
-
language: "dart",
|
|
270
|
-
packageManager: "flutter",
|
|
271
|
-
commands: {
|
|
272
|
-
build: "flutter build",
|
|
273
|
-
test: "flutter test",
|
|
274
|
-
lint: "flutter analyze"
|
|
275
|
-
},
|
|
276
|
-
framework: "Flutter",
|
|
277
|
-
testingStrategy: buildTestingStrategy("maestro")
|
|
278
|
-
};
|
|
279
|
-
}
|
|
280
|
-
function detectXcode(dir) {
|
|
281
|
-
try {
|
|
282
|
-
const entries = readdirSync(dir);
|
|
283
|
-
const hasXcode = entries.some((e) => e.endsWith(".xcodeproj") || e.endsWith(".xcworkspace"));
|
|
284
|
-
if (!hasXcode) return null;
|
|
285
|
-
} catch {
|
|
286
|
-
return null;
|
|
287
|
-
}
|
|
288
|
-
return {
|
|
289
|
-
language: "swift",
|
|
290
|
-
packageManager: "xcode",
|
|
291
|
-
commands: {
|
|
292
|
-
build: "xcodebuild build",
|
|
293
|
-
test: "xcodebuild test"
|
|
294
|
-
},
|
|
295
|
-
testingStrategy: buildTestingStrategy("maestro")
|
|
296
|
-
};
|
|
297
|
-
}
|
|
298
|
-
function detectMakefile(dir) {
|
|
299
|
-
const makefile = readFile(join(dir, "Makefile"));
|
|
300
|
-
if (makefile === null) return null;
|
|
301
|
-
const commands = {};
|
|
302
|
-
commands.build = "make build";
|
|
303
|
-
if (/^test:/m.test(makefile)) commands.test = "make test";
|
|
304
|
-
if (/^lint:/m.test(makefile)) commands.lint = "make lint";
|
|
305
|
-
return {
|
|
306
|
-
language: "unknown",
|
|
307
|
-
packageManager: "make",
|
|
308
|
-
commands
|
|
309
|
-
};
|
|
310
|
-
}
|
|
311
|
-
function detectDockerfile(dir) {
|
|
312
|
-
if (!existsSync(join(dir, "Dockerfile"))) return null;
|
|
313
|
-
return {
|
|
314
|
-
language: "unknown",
|
|
315
|
-
packageManager: "docker",
|
|
316
|
-
commands: {
|
|
317
|
-
build: "docker build ."
|
|
318
|
-
}
|
|
319
|
-
};
|
|
320
|
-
}
|
|
321
|
-
async function detectStack(dir) {
|
|
322
|
-
const detectors = [
|
|
323
|
-
detectNode,
|
|
324
|
-
detectPython,
|
|
325
|
-
detectRust,
|
|
326
|
-
detectGo,
|
|
327
|
-
detectFlutter,
|
|
328
|
-
detectSwift,
|
|
329
|
-
detectXcode,
|
|
330
|
-
detectMakefile,
|
|
331
|
-
detectDockerfile
|
|
332
|
-
];
|
|
333
|
-
for (const detect of detectors) {
|
|
334
|
-
const result = detect(dir);
|
|
335
|
-
if (result) return result;
|
|
336
|
-
}
|
|
337
|
-
return { language: "unknown", packageManager: "", commands: {} };
|
|
338
|
-
}
|
|
339
|
-
|
|
340
|
-
// src/safeguard.ts
|
|
341
|
-
import { existsSync as existsSync2, readFileSync as readFileSync2, writeFileSync, mkdirSync } from "fs";
|
|
342
|
-
import { join as join2 } from "path";
|
|
343
|
-
function generateHookScript() {
|
|
344
|
-
return `#!/bin/bash
|
|
345
|
-
# Joycraft Safeguard \u2014 PreToolUse hook
|
|
346
|
-
# Blocks dangerous Bash commands. Exit 2 = block the action.
|
|
347
|
-
# Edit deny-patterns.txt to customize what's blocked.
|
|
348
|
-
#
|
|
349
|
-
# Claude Code passes no arguments: the hook payload arrives as JSON on stdin
|
|
350
|
-
# ({"tool_name":"Bash","tool_input":{"command":"..."},...}). The reason for a
|
|
351
|
-
# block goes to stderr, which is what the model sees on exit 2.
|
|
352
|
-
|
|
353
|
-
INPUT=$(cat)
|
|
354
|
-
|
|
355
|
-
if command -v jq >/dev/null 2>&1; then
|
|
356
|
-
TOOL_NAME=$(printf '%s' "$INPUT" | jq -r '.tool_name // empty' 2>/dev/null)
|
|
357
|
-
COMMAND=$(printf '%s' "$INPUT" | jq -r '.tool_input.command // .command // empty' 2>/dev/null)
|
|
358
|
-
else
|
|
359
|
-
# Fallback without jq: tolerate spaces around the colon and escaped quotes.
|
|
360
|
-
TOOL_NAME=$(printf '%s' "$INPUT" | grep -o '"tool_name"[[:space:]]*:[[:space:]]*"[^"]*"' | head -1 | sed 's/^"tool_name"[[:space:]]*:[[:space:]]*"//;s/"$//')
|
|
361
|
-
COMMAND=$(printf '%s' "$INPUT" | grep -o '"command"[[:space:]]*:[[:space:]]*"\\([^"\\\\]\\|\\\\.\\)*"' | head -1 | sed 's/^"command"[[:space:]]*:[[:space:]]*"//;s/"$//;s/\\\\"/"/g;s/\\\\\\\\/\\\\/g')
|
|
362
|
-
fi
|
|
363
|
-
|
|
364
|
-
# Only check Bash commands (the settings matcher already limits this hook to
|
|
365
|
-
# Bash; a payload that names another tool is passed through untouched).
|
|
366
|
-
if [ -n "$TOOL_NAME" ] && [ "$TOOL_NAME" != "Bash" ]; then
|
|
367
|
-
exit 0
|
|
368
|
-
fi
|
|
369
|
-
|
|
370
|
-
if [ -z "$COMMAND" ]; then
|
|
371
|
-
exit 0
|
|
372
|
-
fi
|
|
373
|
-
|
|
374
|
-
PATTERNS_FILE="$(dirname "$0")/deny-patterns.txt"
|
|
375
|
-
|
|
376
|
-
if [ ! -f "$PATTERNS_FILE" ]; then
|
|
377
|
-
exit 0
|
|
378
|
-
fi
|
|
379
|
-
|
|
380
|
-
while IFS= read -r pattern || [ -n "$pattern" ]; do
|
|
381
|
-
# Skip empty lines and comments
|
|
382
|
-
[ -z "$pattern" ] && continue
|
|
383
|
-
[[ "$pattern" == \\#* ]] && continue
|
|
384
|
-
|
|
385
|
-
if printf '%s' "$COMMAND" | grep -qEi "$pattern"; then
|
|
386
|
-
echo "Blocked by Joycraft Safeguard: command matches deny pattern '$pattern'" >&2
|
|
387
|
-
echo "Edit .claude/hooks/joycraft/deny-patterns.txt to modify blocked patterns." >&2
|
|
388
|
-
exit 2
|
|
389
|
-
fi
|
|
390
|
-
done < "$PATTERNS_FILE"
|
|
391
|
-
|
|
392
|
-
exit 0
|
|
393
|
-
`;
|
|
394
|
-
}
|
|
395
|
-
function generateDenyPatternsFile(customPatterns = []) {
|
|
396
|
-
const lines = [
|
|
397
|
-
"# Joycraft Safeguard \u2014 Deny Patterns",
|
|
398
|
-
"# One regex pattern per line. Lines starting with # are comments.",
|
|
399
|
-
"# Commands matching any pattern will be blocked (exit 2).",
|
|
400
|
-
"# Edit this file to customize what's blocked.",
|
|
401
|
-
"",
|
|
402
|
-
"# Destructive file operations",
|
|
403
|
-
"rm\\s+-rf\\s+/",
|
|
404
|
-
"rm\\s+-rf\\s+\\.",
|
|
405
|
-
"",
|
|
406
|
-
"# Dangerous git operations",
|
|
407
|
-
"git\\s+push\\s+--force",
|
|
408
|
-
"git\\s+push\\s+-f\\b",
|
|
409
|
-
"git\\s+reset\\s+--hard",
|
|
410
|
-
"",
|
|
411
|
-
"# SQL destruction",
|
|
412
|
-
"DROP\\s+TABLE",
|
|
413
|
-
"DROP\\s+DATABASE",
|
|
414
|
-
"TRUNCATE",
|
|
415
|
-
"",
|
|
416
|
-
"# System security",
|
|
417
|
-
"chmod\\s+777",
|
|
418
|
-
"curl.*\\|.*sh",
|
|
419
|
-
"wget.*\\|.*sh"
|
|
420
|
-
];
|
|
421
|
-
if (customPatterns.length > 0) {
|
|
422
|
-
lines.push("");
|
|
423
|
-
lines.push("# Project-specific patterns (from risk interview)");
|
|
424
|
-
for (const p of customPatterns) {
|
|
425
|
-
lines.push(p);
|
|
426
|
-
}
|
|
427
|
-
}
|
|
428
|
-
return lines.join("\n") + "\n";
|
|
429
|
-
}
|
|
430
|
-
|
|
431
|
-
// src/claude-session-start.ts
|
|
432
|
-
function generateClaudeSessionStartAdapter() {
|
|
433
|
-
return `// Joycraft update discovery adapter \u2014 runs on Claude Code session start
|
|
434
|
-
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
435
|
-
import { dirname, join } from 'node:path';
|
|
436
|
-
import { appendFileSync } from 'node:fs';
|
|
437
|
-
|
|
438
|
-
const root = join(dirname(fileURLToPath(import.meta.url)), '..', '..');
|
|
439
|
-
|
|
440
|
-
async function readHookEvent() {
|
|
441
|
-
if (process.stdin.isTTY) return {};
|
|
442
|
-
return new Promise((resolve) => {
|
|
443
|
-
let raw = '';
|
|
444
|
-
let settled = false;
|
|
445
|
-
const finish = () => {
|
|
446
|
-
if (settled) return;
|
|
447
|
-
settled = true;
|
|
448
|
-
clearTimeout(timer);
|
|
449
|
-
process.stdin.off('data', onData);
|
|
450
|
-
process.stdin.off('end', finish);
|
|
451
|
-
process.stdin.off('error', finish);
|
|
452
|
-
process.stdin.pause();
|
|
453
|
-
try {
|
|
454
|
-
const parsed = JSON.parse(raw);
|
|
455
|
-
resolve(parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {});
|
|
456
|
-
} catch {
|
|
457
|
-
resolve({});
|
|
458
|
-
}
|
|
459
|
-
};
|
|
460
|
-
const onData = (chunk) => {
|
|
461
|
-
raw += chunk;
|
|
462
|
-
// Claude sends one compact JSON event. Parsing immediately avoids
|
|
463
|
-
// waiting on a pipe that a host may keep open for the hook lifetime.
|
|
464
|
-
try { JSON.parse(raw); finish(); } catch { /* wait for more bytes */ }
|
|
465
|
-
};
|
|
466
|
-
const timer = setTimeout(finish, 250);
|
|
467
|
-
process.stdin.setEncoding('utf8');
|
|
468
|
-
process.stdin.on('data', onData);
|
|
469
|
-
process.stdin.on('end', finish);
|
|
470
|
-
process.stdin.on('error', finish);
|
|
471
|
-
process.stdin.resume();
|
|
472
|
-
});
|
|
473
|
-
}
|
|
474
|
-
|
|
475
|
-
try {
|
|
476
|
-
const event = await readHookEvent();
|
|
477
|
-
const eventSession = typeof event.session_id === 'string' ? event.session_id : undefined;
|
|
478
|
-
const session = eventSession
|
|
479
|
-
?? process.env.JOYCRAFT_SESSION_ID
|
|
480
|
-
?? \`parent-\${process.ppid}\`;
|
|
481
|
-
// Claude documents this append-only environment handoff for SessionStart:
|
|
482
|
-
// https://code.claude.com/docs/en/hooks#persist-environment-variables
|
|
483
|
-
if (process.env.CLAUDE_ENV_FILE) {
|
|
484
|
-
const assignment = "export JOYCRAFT_SESSION_ID='" + session.replaceAll("'", ${JSON.stringify(`'"'"'`)}) + "'\\n";
|
|
485
|
-
try { appendFileSync(process.env.CLAUDE_ENV_FILE, assignment, { mode: 0o600 }); } catch { /* continue without environment persistence */ }
|
|
486
|
-
}
|
|
487
|
-
const checker = await import(pathToFileURL(join(root, 'docs', '.joycraft', 'check.mjs')).href);
|
|
488
|
-
const result = await checker.checkForUpdate(root, { sessionId: session });
|
|
489
|
-
if (result?.display && result.availableVersion) {
|
|
490
|
-
console.log(\`Joycraft \${result.availableVersion} available (you have \${result.installedVersion ?? 'unknown'}). Finish the active skill, then run the update and restart or reinvoke the skill.\`);
|
|
491
|
-
checker.acknowledgeUpdate(root, { release: result.availableVersion, session });
|
|
492
|
-
}
|
|
493
|
-
} catch {
|
|
494
|
-
// Discovery must never block Claude's requested work.
|
|
495
|
-
}
|
|
496
|
-
`;
|
|
497
|
-
}
|
|
498
|
-
|
|
499
|
-
// src/model-profile.ts
|
|
500
|
-
var MODEL_PROFILE_TEMPLATE_KEY = "reference/model-profile-claude-fable-5-1.md";
|
|
501
|
-
var MODEL_PROFILE_PATH = `docs/templates/${MODEL_PROFILE_TEMPLATE_KEY}`;
|
|
502
|
-
var MODEL_PROFILE_HARNESSES = Object.freeze(["claude", "pi", "omp"]);
|
|
503
|
-
var MODEL_PROFILE_CONTEXT_MAP_ROW = `| \`${MODEL_PROFILE_PATH}\` | Working with Claude Fable 5.1 \u2014 finishing whole tasks, scope, progress updates, prose |`;
|
|
504
|
-
function selectsModelProfile(harnesses) {
|
|
505
|
-
return harnesses.some((harness) => MODEL_PROFILE_HARNESSES.includes(harness));
|
|
506
|
-
}
|
|
507
|
-
|
|
508
|
-
// src/bundle-inventory.ts
|
|
509
|
-
var vendor = (path, harness, content, options = {}) => ({
|
|
510
|
-
path,
|
|
511
|
-
harness,
|
|
512
|
-
kind: "vendor",
|
|
513
|
-
ownership: "managed",
|
|
514
|
-
active: true,
|
|
515
|
-
installable: true,
|
|
516
|
-
content,
|
|
517
|
-
...options
|
|
518
|
-
});
|
|
519
|
-
var createOnce = (path) => ({
|
|
520
|
-
path,
|
|
521
|
-
harness: "shared",
|
|
522
|
-
kind: "create-once",
|
|
523
|
-
ownership: "managed",
|
|
524
|
-
active: true,
|
|
525
|
-
installable: false
|
|
526
|
-
});
|
|
527
|
-
var patch = (path, harness, ownedKey, ownedRegion) => ({
|
|
528
|
-
path,
|
|
529
|
-
harness,
|
|
530
|
-
kind: "config-patch",
|
|
531
|
-
ownership: "managed",
|
|
532
|
-
active: true,
|
|
533
|
-
installable: false,
|
|
534
|
-
...ownedKey ? { ownedKey } : {},
|
|
535
|
-
...ownedRegion ? { ownedRegion } : {}
|
|
536
|
-
});
|
|
537
|
-
var TEMPLATE_HARNESS_GATES = {
|
|
538
|
-
// D6: keyed to the model, not the harness. The list lives in model-profile.ts
|
|
539
|
-
// so the memory-file pointer row is gated on exactly the same harnesses.
|
|
540
|
-
[MODEL_PROFILE_TEMPLATE_KEY]: MODEL_PROFILE_HARNESSES
|
|
541
|
-
};
|
|
542
|
-
function templateEntries(templates, selected2, gates = TEMPLATE_HARNESS_GATES) {
|
|
543
|
-
return Object.entries(templates).flatMap(([path, content]) => {
|
|
544
|
-
const gate = Object.prototype.hasOwnProperty.call(gates, path) ? gates[path] : void 0;
|
|
545
|
-
if (!gate) return [vendor(`docs/templates/${path}`, "shared", content)];
|
|
546
|
-
const owner = HARNESSES.find((harness) => gate.includes(harness) && selected2.includes(harness));
|
|
547
|
-
return owner ? [vendor(`docs/templates/${path}`, owner, content)] : [];
|
|
548
|
-
});
|
|
549
|
-
}
|
|
550
|
-
function mapVendorFiles(harness, root, files, options = void 0) {
|
|
551
|
-
return Object.entries(files).map(([name, content]) => {
|
|
552
|
-
const relative = name.endsWith(".md") && root.endsWith("/skills") ? `${name.slice(0, -3)}/SKILL.md` : name;
|
|
553
|
-
return vendor(`${root}/${relative}`, harness, content, options ?? (root.endsWith("/scripts/joycraft") && !name.endsWith("README.md") ? { executable: true, mode: 493 } : root.endsWith("/scripts/joycraft") ? { executable: false } : {}));
|
|
554
|
-
});
|
|
555
|
-
}
|
|
556
|
-
function getBundleInventory(selection = HARNESSES) {
|
|
557
|
-
const selected2 = sanitizeHarnesses(selection) ?? [...HARNESSES];
|
|
558
|
-
const wants = (harness) => selected2.includes(harness);
|
|
559
|
-
const entries = [
|
|
560
|
-
...templateEntries(TEMPLATES, selected2),
|
|
561
|
-
createOnce("CLAUDE.md"),
|
|
562
|
-
createOnce("AGENTS.md"),
|
|
563
|
-
vendor("docs/.joycraft/check.mjs", "shared", CHECKER_SOURCE, { executable: true, mode: 493 })
|
|
564
|
-
];
|
|
565
|
-
if (wants("claude")) {
|
|
566
|
-
entries.push(...mapVendorFiles("claude", ".claude/skills", SKILLS));
|
|
567
|
-
entries.push(
|
|
568
|
-
vendor(".claude/hooks/joycraft/block-dangerous.sh", "claude", generateHookScript(), { executable: true, mode: 493 }),
|
|
569
|
-
vendor(".claude/hooks/joycraft/deny-patterns.txt", "claude", generateDenyPatternsFile(), { executable: false }),
|
|
570
|
-
vendor(".claude/hooks/joycraft-version-check.mjs", "claude", generateClaudeSessionStartAdapter(), { executable: true, mode: 493 }),
|
|
571
|
-
patch(".claude/settings.json", "claude", void 0, "hooks.SessionStart[command=node .claude/hooks/joycraft-version-check.mjs]"),
|
|
572
|
-
patch(".claude/settings.json", "claude", void 0, "hooks.PreToolUse[command=.claude/hooks/joycraft/block-dangerous.sh]"),
|
|
573
|
-
patch(".claude/settings.json", "claude", "env.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS"),
|
|
574
|
-
patch(".claude/settings.json", "claude", void 0, "permissions.allow[joycraft-generated]"),
|
|
575
|
-
patch(".claude/settings.json", "claude", void 0, "permissions.deny[joycraft-generated]"),
|
|
576
|
-
patch(".claude/settings.json", "claude", "autoMemoryEnabled")
|
|
577
|
-
);
|
|
578
|
-
}
|
|
579
|
-
if (wants("codex")) entries.push(...mapVendorFiles("codex", ".agents/skills", CODEX_SKILLS));
|
|
580
|
-
if (wants("pi")) {
|
|
581
|
-
entries.push(...mapVendorFiles("pi", ".pi/skills", PI_SKILLS));
|
|
582
|
-
entries.push(...mapVendorFiles("pi", ".pi/scripts/joycraft", PI_SCRIPTS));
|
|
583
|
-
entries.push(...mapVendorFiles("pi", ".pi/extensions", PI_EXTENSIONS));
|
|
584
|
-
entries.push(...mapVendorFiles("pi", ".pi/agents", PI_AGENTS));
|
|
585
|
-
}
|
|
586
|
-
if (wants("copilot")) entries.push(...mapVendorFiles("copilot", ".github/skills", COPILOT_SKILLS));
|
|
587
|
-
if (wants("omp")) entries.push(...mapVendorFiles("omp", ".omp/skills", OMP_SKILLS));
|
|
588
|
-
return entries;
|
|
589
|
-
}
|
|
590
|
-
|
|
591
|
-
// src/update-patches.ts
|
|
592
|
-
var FORBIDDEN_JSON_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
|
|
593
|
-
var REGION_IDENTIFIER = /^[A-Za-z0-9][A-Za-z0-9._:/-]*$/;
|
|
594
|
-
function selectorKind(selector) {
|
|
595
|
-
if (!selector || typeof selector !== "object") {
|
|
596
|
-
return { kind: "invalid", reason: "Patch selector must be an object" };
|
|
597
|
-
}
|
|
598
|
-
const hasKey = selector.ownedKey !== void 0;
|
|
599
|
-
const hasRegion = selector.ownedRegion !== void 0;
|
|
600
|
-
if (hasKey === hasRegion) {
|
|
601
|
-
return { kind: "invalid", reason: "Patch selector must contain exactly one ownedKey or ownedRegion" };
|
|
602
|
-
}
|
|
603
|
-
if (hasKey) {
|
|
604
|
-
if (typeof selector.ownedKey !== "string") {
|
|
605
|
-
return { kind: "invalid", reason: "ownedKey must be a string" };
|
|
606
|
-
}
|
|
607
|
-
const parts = selector.ownedKey.split(".");
|
|
608
|
-
if (parts.length === 0 || parts.some((part) => part.length === 0 || FORBIDDEN_JSON_KEYS.has(part))) {
|
|
609
|
-
return { kind: "invalid", reason: "ownedKey contains an empty or prototype key segment" };
|
|
610
|
-
}
|
|
611
|
-
return { kind: "key", value: selector.ownedKey };
|
|
612
|
-
}
|
|
613
|
-
if (typeof selector.ownedRegion !== "string" || !REGION_IDENTIFIER.test(selector.ownedRegion)) {
|
|
614
|
-
return { kind: "invalid", reason: "ownedRegion is not a valid marker identifier" };
|
|
615
|
-
}
|
|
616
|
-
return { kind: "region", value: selector.ownedRegion };
|
|
617
|
-
}
|
|
618
|
-
function isJsonObject(value) {
|
|
619
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
620
|
-
}
|
|
621
|
-
function parseJsonObject(content) {
|
|
622
|
-
let value;
|
|
623
|
-
try {
|
|
624
|
-
value = JSON.parse(content);
|
|
625
|
-
} catch {
|
|
626
|
-
return { reason: "Current content is not valid JSON" };
|
|
627
|
-
}
|
|
628
|
-
if (!isJsonObject(value)) {
|
|
629
|
-
return { reason: "JSON patch paths require an object at the root" };
|
|
630
|
-
}
|
|
631
|
-
return { value };
|
|
632
|
-
}
|
|
633
|
-
function own(value, key) {
|
|
634
|
-
return Object.prototype.hasOwnProperty.call(value, key);
|
|
635
|
-
}
|
|
636
|
-
function readJsonValue(root, path) {
|
|
637
|
-
const parts = path.split(".");
|
|
638
|
-
let parent = root;
|
|
639
|
-
for (let index = 0; index < parts.length - 1; index += 1) {
|
|
640
|
-
if (!isJsonObject(parent)) {
|
|
641
|
-
return { status: "invalid", reason: `JSON path parent is not an object at ${parts[index]}` };
|
|
642
|
-
}
|
|
643
|
-
const part = parts[index];
|
|
644
|
-
if (!own(parent, part)) return { status: "missing" };
|
|
645
|
-
parent = parent[part];
|
|
646
|
-
}
|
|
647
|
-
if (!isJsonObject(parent)) {
|
|
648
|
-
return { status: "invalid", reason: "JSON path parent is not an object" };
|
|
649
|
-
}
|
|
650
|
-
const finalPart = parts[parts.length - 1];
|
|
651
|
-
if (!own(parent, finalPart)) return { status: "missing" };
|
|
652
|
-
const serialized = JSON.stringify(parent[finalPart]);
|
|
653
|
-
return serialized === void 0 ? { status: "invalid", reason: "Owned JSON value cannot be serialized" } : { status: "present", content: serialized };
|
|
654
|
-
}
|
|
655
|
-
function newlineOf(content) {
|
|
656
|
-
return content.includes("\r\n") ? "\r\n" : "\n";
|
|
657
|
-
}
|
|
658
|
-
function hasFinalNewline(content) {
|
|
659
|
-
return content.endsWith("\n") || content.endsWith("\r");
|
|
660
|
-
}
|
|
661
|
-
function normalizeNewlines(content, newline) {
|
|
662
|
-
return content.replace(/\r\n?|\n/g, newline);
|
|
663
|
-
}
|
|
664
|
-
function jsonIndent(content) {
|
|
665
|
-
const match = content.match(/(?:^|\r?\n)([ \t]+)(?=["}\]])/);
|
|
666
|
-
return match?.[1];
|
|
667
|
-
}
|
|
668
|
-
function serializePatchedJson(value, current) {
|
|
669
|
-
const indentation = jsonIndent(current);
|
|
670
|
-
const serialized = JSON.stringify(value, null, indentation);
|
|
671
|
-
const newline = newlineOf(current);
|
|
672
|
-
const withNewlines = normalizeNewlines(serialized, newline);
|
|
673
|
-
return hasFinalNewline(current) ? `${withNewlines}${newline}` : withNewlines;
|
|
674
|
-
}
|
|
675
|
-
function parseTarget(target) {
|
|
676
|
-
try {
|
|
677
|
-
return { value: JSON.parse(target) };
|
|
678
|
-
} catch {
|
|
679
|
-
return { reason: "Target content is not valid JSON" };
|
|
680
|
-
}
|
|
681
|
-
}
|
|
682
|
-
function escapeRegExp(value) {
|
|
683
|
-
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
684
|
-
}
|
|
685
|
-
function markerBounds(current, identifier) {
|
|
686
|
-
const opening = `<!-- ${identifier} -->`;
|
|
687
|
-
const closing = `<!-- /${identifier} -->`;
|
|
688
|
-
const openCount = countOccurrences(current, opening);
|
|
689
|
-
const closeCount = countOccurrences(current, closing);
|
|
690
|
-
const mentionPattern = new RegExp(`<!--\\s*/?\\s*${escapeRegExp(identifier)}\\s*-->`, "g");
|
|
691
|
-
const mentions = current.match(mentionPattern) ?? [];
|
|
692
|
-
if (mentions.length === 0) return { status: "missing" };
|
|
693
|
-
if (openCount !== 1 || closeCount !== 1 || mentions.length !== 2) {
|
|
694
|
-
return { status: "invalid", reason: "Owned region markers are duplicated or malformed" };
|
|
695
|
-
}
|
|
696
|
-
const openEnd = current.indexOf(opening) + opening.length;
|
|
697
|
-
const closeStart = current.indexOf(closing);
|
|
698
|
-
if (closeStart <= openEnd) {
|
|
699
|
-
return { status: "invalid", reason: "Owned region markers are in the wrong order" };
|
|
700
|
-
}
|
|
701
|
-
const newline = newlineOf(current);
|
|
702
|
-
const body = current.slice(openEnd, closeStart);
|
|
703
|
-
const hasLeadingBoundary = body.startsWith(newline);
|
|
704
|
-
const withoutLeading = hasLeadingBoundary ? body.slice(newline.length) : body;
|
|
705
|
-
const hasTrailingBoundary = withoutLeading.endsWith(newline);
|
|
706
|
-
return {
|
|
707
|
-
openEnd,
|
|
708
|
-
closeStart,
|
|
709
|
-
body: withoutLeading,
|
|
710
|
-
newline,
|
|
711
|
-
hasLeadingBoundary,
|
|
712
|
-
hasTrailingBoundary
|
|
713
|
-
};
|
|
714
|
-
}
|
|
715
|
-
function countOccurrences(content, needle) {
|
|
716
|
-
let count = 0;
|
|
717
|
-
let offset = 0;
|
|
718
|
-
while (true) {
|
|
719
|
-
const found = content.indexOf(needle, offset);
|
|
720
|
-
if (found < 0) return count;
|
|
721
|
-
count += 1;
|
|
722
|
-
offset = found + needle.length;
|
|
723
|
-
}
|
|
724
|
-
}
|
|
725
|
-
function readOwnedContent(current, selector) {
|
|
726
|
-
const selected2 = selectorKind(selector);
|
|
727
|
-
if (selected2.kind === "invalid") return { status: "invalid", reason: selected2.reason };
|
|
728
|
-
if (selected2.kind === "key") {
|
|
729
|
-
const parsed = parseJsonObject(current);
|
|
730
|
-
if ("reason" in parsed) return { status: "invalid", reason: parsed.reason };
|
|
731
|
-
return readJsonValue(parsed.value, selected2.value);
|
|
732
|
-
}
|
|
733
|
-
const markers = markerBounds(current, selected2.value);
|
|
734
|
-
if ("status" in markers) {
|
|
735
|
-
return markers.status === "missing" ? { status: "missing" } : { status: "invalid", reason: markers.reason };
|
|
736
|
-
}
|
|
737
|
-
return { status: "present", content: markers.body };
|
|
738
|
-
}
|
|
739
|
-
function applyOwnedContent(current, selector, target) {
|
|
740
|
-
const selected2 = selectorKind(selector);
|
|
741
|
-
if (selected2.kind === "invalid") return { ok: false, reason: selected2.reason };
|
|
742
|
-
if (current === void 0) return { ok: false, reason: "Current content is missing" };
|
|
743
|
-
if (selected2.kind === "key") {
|
|
744
|
-
const parsed = parseJsonObject(current);
|
|
745
|
-
if ("reason" in parsed) return { ok: false, reason: parsed.reason };
|
|
746
|
-
const parsedTarget = parseTarget(target);
|
|
747
|
-
if ("reason" in parsedTarget) return { ok: false, reason: parsedTarget.reason };
|
|
748
|
-
const parts = selected2.value.split(".");
|
|
749
|
-
let parent = parsed.value;
|
|
750
|
-
for (let index = 0; index < parts.length - 1; index += 1) {
|
|
751
|
-
if (!isJsonObject(parent)) {
|
|
752
|
-
return { ok: false, reason: `JSON path parent is not an object at ${parts[index]}` };
|
|
753
|
-
}
|
|
754
|
-
const part = parts[index];
|
|
755
|
-
if (!own(parent, part)) return { ok: false, reason: `JSON path does not exist: ${selected2.value}` };
|
|
756
|
-
parent = parent[part];
|
|
757
|
-
}
|
|
758
|
-
if (!isJsonObject(parent)) return { ok: false, reason: "JSON path parent is not an object" };
|
|
759
|
-
parent[parts[parts.length - 1]] = parsedTarget.value;
|
|
760
|
-
return { ok: true, content: serializePatchedJson(parsed.value, current) };
|
|
761
|
-
}
|
|
762
|
-
const markers = markerBounds(current, selected2.value);
|
|
763
|
-
if ("status" in markers) {
|
|
764
|
-
return {
|
|
765
|
-
ok: false,
|
|
766
|
-
reason: markers.status === "missing" ? "Owned region markers are missing" : markers.reason
|
|
767
|
-
};
|
|
768
|
-
}
|
|
769
|
-
const markerPattern = new RegExp(`<!--\\s*/?\\s*${escapeRegExp(selected2.value)}\\s*-->`);
|
|
770
|
-
if (markerPattern.test(target)) {
|
|
771
|
-
return { ok: false, reason: "Target content contains an owned region marker" };
|
|
772
|
-
}
|
|
773
|
-
let normalizedTarget = normalizeNewlines(target, markers.newline);
|
|
774
|
-
if (markers.hasLeadingBoundary && normalizedTarget.startsWith(markers.newline)) {
|
|
775
|
-
normalizedTarget = normalizedTarget.slice(markers.newline.length);
|
|
776
|
-
}
|
|
777
|
-
if (markers.hasTrailingBoundary && !normalizedTarget.endsWith(markers.newline)) {
|
|
778
|
-
normalizedTarget += markers.newline;
|
|
779
|
-
}
|
|
780
|
-
const content = `${current.slice(0, markers.openEnd)}${markers.hasLeadingBoundary ? markers.newline : ""}${normalizedTarget}${current.slice(markers.closeStart)}`;
|
|
781
|
-
return { ok: true, content };
|
|
782
|
-
}
|
|
783
|
-
|
|
784
|
-
// src/update-plan.ts
|
|
785
|
-
function bytes(value) {
|
|
786
|
-
return Buffer.isBuffer(value) ? Buffer.from(value) : value;
|
|
787
|
-
}
|
|
788
|
-
function text(value) {
|
|
789
|
-
return Buffer.isBuffer(value) ? value.toString("utf8") : value;
|
|
790
|
-
}
|
|
791
|
-
function contentOf(value) {
|
|
792
|
-
return typeof value === "object" && value !== null && "content" in value ? bytes(value.content) : bytes(value);
|
|
793
|
-
}
|
|
794
|
-
function cloneManifest(manifest) {
|
|
795
|
-
return {
|
|
796
|
-
...manifest,
|
|
797
|
-
files: Object.fromEntries(Object.entries(manifest.files).map(([path, file]) => [path, { ...file }]))
|
|
798
|
-
};
|
|
799
|
-
}
|
|
800
|
-
function normalized(value) {
|
|
801
|
-
return normalizedVendorHash(text(value));
|
|
802
|
-
}
|
|
803
|
-
function newlineStyle(value) {
|
|
804
|
-
return value.includes("\r\n") ? "\r\n" : "\n";
|
|
805
|
-
}
|
|
806
|
-
function preserveNewlines(target, current, executable) {
|
|
807
|
-
if (!current || executable || Buffer.isBuffer(target) || Buffer.isBuffer(current)) return bytes(target);
|
|
808
|
-
const style = newlineStyle(text(current));
|
|
809
|
-
if (style === "\n") return target;
|
|
810
|
-
return text(target).replace(/\r\n?/g, "\n").replace(/\n/g, "\r\n");
|
|
811
|
-
}
|
|
812
|
-
function diff(path, current, target) {
|
|
813
|
-
const oldLines = text(current).replace(/\r\n?/g, "\n").split("\n");
|
|
814
|
-
const newLines = text(target).replace(/\r\n?/g, "\n").split("\n");
|
|
815
|
-
const lines = [`--- ${path}`, `+++ ${path}`];
|
|
816
|
-
const size = Math.max(oldLines.length, newLines.length);
|
|
817
|
-
for (let i = 0; i < size; i += 1) {
|
|
818
|
-
if (oldLines[i] === newLines[i]) lines.push(` ${oldLines[i] ?? ""}`);
|
|
819
|
-
else {
|
|
820
|
-
if (oldLines[i] !== void 0) lines.push(`-${oldLines[i]}`);
|
|
821
|
-
if (newLines[i] !== void 0) lines.push(`+${newLines[i]}`);
|
|
822
|
-
}
|
|
823
|
-
}
|
|
824
|
-
return lines.join("\n");
|
|
825
|
-
}
|
|
826
|
-
function selected(options, path, kind) {
|
|
827
|
-
if (kind === "replace" || kind === "create" || kind === "adopt" || kind === "delete" || kind === "reconcile") return true;
|
|
828
|
-
if (kind === "repair") return (options.repair ?? []).includes(path);
|
|
829
|
-
return false;
|
|
830
|
-
}
|
|
831
|
-
function explicitReplacement(options, path) {
|
|
832
|
-
return (options.replaceCustomized ?? []).includes(path);
|
|
833
|
-
}
|
|
834
|
-
function targetPayload(entry) {
|
|
835
|
-
return entry.content;
|
|
836
|
-
}
|
|
837
|
-
function patchOutput(current, entries) {
|
|
838
|
-
const entry = entries[0];
|
|
839
|
-
if (entry.content === void 0) return { reason: "Config patch has no installable payload." };
|
|
840
|
-
const selector = { ...entry.ownedKey ? { ownedKey: entry.ownedKey } : {}, ...entry.ownedRegion ? { ownedRegion: entry.ownedRegion } : {} };
|
|
841
|
-
const result = applyOwnedContent(text(current), selector, text(entry.content));
|
|
842
|
-
if (!result.ok) return { reason: result.reason };
|
|
843
|
-
const fragment = readOwnedContent(result.content, selector);
|
|
844
|
-
if (fragment.status !== "present") return { reason: fragment.status === "invalid" ? fragment.reason : "Patched owned content is missing." };
|
|
845
|
-
return { content: result.content, fragment: fragment.content };
|
|
846
|
-
}
|
|
847
|
-
function trustedHash(path, options) {
|
|
848
|
-
const catalogue = options.catalogue?.find((entry) => entry.path === path);
|
|
849
|
-
return catalogue?.vendorHash;
|
|
850
|
-
}
|
|
851
|
-
function addFile(next, path, entry, hash, version) {
|
|
852
|
-
next.files[path] = {
|
|
853
|
-
...next.files[path] ?? {},
|
|
854
|
-
vendorVersion: version,
|
|
855
|
-
vendorHash: hash,
|
|
856
|
-
kind: entry.kind,
|
|
857
|
-
ownership: "verified",
|
|
858
|
-
...entry.ownedKey ? { ownedKey: entry.ownedKey } : {},
|
|
859
|
-
...entry.ownedRegion ? { ownedRegion: entry.ownedRegion } : {}
|
|
860
|
-
};
|
|
861
|
-
}
|
|
862
|
-
function actionBase(path, kind, reason, current, target, mode) {
|
|
863
|
-
const currentPresent = current !== void 0;
|
|
864
|
-
const targetPresent = target !== void 0;
|
|
865
|
-
const result = {
|
|
866
|
-
path,
|
|
867
|
-
kind,
|
|
868
|
-
selected: false,
|
|
869
|
-
reason,
|
|
870
|
-
currentPresent,
|
|
871
|
-
targetPresent,
|
|
872
|
-
...current !== void 0 ? { preservedContent: bytes(current) } : {},
|
|
873
|
-
...target !== void 0 ? { rawTargetHash: rawFileHash(target) } : {},
|
|
874
|
-
...mode === void 0 ? {} : { mode }
|
|
875
|
-
};
|
|
876
|
-
if (current !== void 0) result.rawPrecondition = rawFileHash(current);
|
|
877
|
-
return result;
|
|
878
|
-
}
|
|
879
|
-
function createUpdatePlan(input) {
|
|
880
|
-
const options = input.options ?? {};
|
|
881
|
-
const snapshotFiles = input.snapshot.files;
|
|
882
|
-
const current = /* @__PURE__ */ new Map();
|
|
883
|
-
for (const [path, value] of Object.entries(snapshotFiles)) current.set(path, contentOf(value));
|
|
884
|
-
const nextManifest = cloneManifest(input.manifest);
|
|
885
|
-
if (options.targetVersion !== void 0) nextManifest.targetVersion = options.targetVersion;
|
|
886
|
-
if (options.bundleIntegrity !== void 0) nextManifest.bundleIntegrity = options.bundleIntegrity;
|
|
887
|
-
const diagnostics = [];
|
|
888
|
-
const actions = [];
|
|
889
|
-
const groups = /* @__PURE__ */ new Map();
|
|
890
|
-
const knownPaths = /* @__PURE__ */ new Set();
|
|
891
|
-
for (const entry of input.inventory) {
|
|
892
|
-
knownPaths.add(entry.path);
|
|
893
|
-
if (entry.kind === "create-once" && entry.content === void 0 || !entry.active || !entry.installable || entry.kind === "vendor" && entry.content === void 0) continue;
|
|
894
|
-
let group = groups.get(entry.path);
|
|
895
|
-
if (!group) {
|
|
896
|
-
group = { path: entry.path, entries: [], invalidDefinition: false };
|
|
897
|
-
groups.set(entry.path, group);
|
|
898
|
-
}
|
|
899
|
-
if (group.entries.some((prior) => prior.kind !== entry.kind || prior.harness !== entry.harness)) group.invalidDefinition = true;
|
|
900
|
-
group.entries.push(entry);
|
|
901
|
-
}
|
|
902
|
-
const add = (action) => {
|
|
903
|
-
actions.push(action);
|
|
904
|
-
if (action.kind === "conflict" || action.kind === "orphan") {
|
|
905
|
-
if (action.preservedContent !== void 0) diagnostics.push(`${action.path}: ${action.reason}`);
|
|
906
|
-
}
|
|
907
|
-
};
|
|
908
|
-
for (const group of groups.values()) {
|
|
909
|
-
const manifestEntry = input.manifest.files[group.path];
|
|
910
|
-
const currentContent = current.get(group.path);
|
|
911
|
-
if (group.invalidDefinition) {
|
|
912
|
-
const action2 = actionBase(group.path, "conflict", "Conflicting inventory definitions for one path.", currentContent, void 0, void 0);
|
|
913
|
-
action2.selected = false;
|
|
914
|
-
add(action2);
|
|
915
|
-
continue;
|
|
916
|
-
}
|
|
917
|
-
const first = group.entries[0];
|
|
918
|
-
let target;
|
|
919
|
-
let targetFragment;
|
|
920
|
-
let fragmentHash = false;
|
|
921
|
-
if (first.kind === "config-patch") {
|
|
922
|
-
const patchDefinitions = group.entries.map((entry) => `${entry.ownedKey ?? ""}\0${entry.ownedRegion ?? ""}`);
|
|
923
|
-
for (let i = 0; i < group.entries.length; i += 1) {
|
|
924
|
-
for (let j = i + 1; j < group.entries.length; j += 1) {
|
|
925
|
-
if (patchDefinitions[i] === patchDefinitions[j]) {
|
|
926
|
-
const left = targetPayload(group.entries[i]);
|
|
927
|
-
const right = targetPayload(group.entries[j]);
|
|
928
|
-
if (left === void 0 !== (right === void 0) || left !== void 0 && right !== void 0 && normalized(left) !== normalized(right)) {
|
|
929
|
-
group.invalidDefinition = true;
|
|
930
|
-
}
|
|
931
|
-
}
|
|
932
|
-
}
|
|
933
|
-
}
|
|
934
|
-
if (new Set(patchDefinitions).size > 1) {
|
|
935
|
-
const action2 = actionBase(group.path, "conflict", "Multiple owned patch selectors share one path; refusing ambiguous composition.", currentContent, void 0, first.mode);
|
|
936
|
-
add(action2);
|
|
937
|
-
continue;
|
|
938
|
-
}
|
|
939
|
-
if (group.invalidDefinition) {
|
|
940
|
-
const action2 = actionBase(group.path, "conflict", "Conflicting inventory definitions for one path.", currentContent, void 0, void 0);
|
|
941
|
-
add(action2);
|
|
942
|
-
continue;
|
|
943
|
-
}
|
|
944
|
-
if (currentContent === void 0) continue;
|
|
945
|
-
const result = patchOutput(currentContent, group.entries);
|
|
946
|
-
if (!result.content) {
|
|
947
|
-
const action2 = actionBase(group.path, "conflict", result.reason ?? "Unable to calculate config patch.", currentContent, void 0, first.mode);
|
|
948
|
-
action2.selected = false;
|
|
949
|
-
add(action2);
|
|
950
|
-
continue;
|
|
951
|
-
}
|
|
952
|
-
target = result.content;
|
|
953
|
-
targetFragment = result.fragment;
|
|
954
|
-
fragmentHash = true;
|
|
955
|
-
} else {
|
|
956
|
-
const payloads = group.entries.map((entry) => targetPayload(entry)).filter((value) => value !== void 0);
|
|
957
|
-
if (!payloads.length) continue;
|
|
958
|
-
if (payloads.some((value) => normalized(value) !== normalized(payloads[0]))) {
|
|
959
|
-
const action2 = actionBase(group.path, "conflict", "Duplicate inventory entries have conflicting payloads.", currentContent, void 0, first.mode);
|
|
960
|
-
add(action2);
|
|
961
|
-
continue;
|
|
962
|
-
}
|
|
963
|
-
target = preserveNewlines(payloads[0], currentContent, first.executable);
|
|
964
|
-
}
|
|
965
|
-
const old = manifestEntry;
|
|
966
|
-
const verified = old?.ownership === "verified" && !!old.vendorHash;
|
|
967
|
-
const currentHash = currentContent === void 0 ? void 0 : fragmentHash && targetFragment !== void 0 ? (() => {
|
|
968
|
-
const selector = { ...first.ownedKey ? { ownedKey: first.ownedKey } : {}, ...first.ownedRegion ? { ownedRegion: first.ownedRegion } : {} };
|
|
969
|
-
const fragment = readOwnedContent(text(currentContent), selector);
|
|
970
|
-
return fragment.status === "present" ? normalized(fragment.content) : void 0;
|
|
971
|
-
})() : normalized(currentContent);
|
|
972
|
-
const targetHash = fragmentHash && targetFragment !== void 0 ? normalized(targetFragment) : normalized(target);
|
|
973
|
-
const baselineHash = verified ? old.vendorHash : trustedHash(group.path, options);
|
|
974
|
-
const currentEqualsTarget = currentHash !== void 0 && currentHash === targetHash;
|
|
975
|
-
const currentEqualsBase = currentHash !== void 0 && baselineHash !== void 0 && currentHash === baselineHash;
|
|
976
|
-
const targetEqualsBase = baselineHash !== void 0 && targetHash === baselineHash;
|
|
977
|
-
let kind;
|
|
978
|
-
let reason;
|
|
979
|
-
if (currentContent === void 0) {
|
|
980
|
-
if (verified) {
|
|
981
|
-
kind = "preserve";
|
|
982
|
-
reason = "Local deletion is preserved; repair requires explicit selection.";
|
|
983
|
-
} else if (old) {
|
|
984
|
-
kind = "preserve";
|
|
985
|
-
reason = "Prior ownership is unverified; preserve the local deletion.";
|
|
986
|
-
} else {
|
|
987
|
-
kind = first.kind === "vendor" || first.kind === "create-once" && first.content !== void 0 ? "create" : "preserve";
|
|
988
|
-
reason = kind === "create" ? "New selected file." : "Config patch has no current file.";
|
|
989
|
-
}
|
|
990
|
-
} else if (old?.kind === "create-once" && !explicitReplacement(options, group.path)) {
|
|
991
|
-
kind = "preserve";
|
|
992
|
-
reason = "Create-once document is user-owned after its first creation; preserve local content.";
|
|
993
|
-
} else if (currentEqualsTarget) {
|
|
994
|
-
kind = old && verified ? "reconcile" : "adopt";
|
|
995
|
-
reason = kind === "reconcile" ? "Current bytes already equal target; reconcile manifest metadata." : "Exact trusted target match establishes vendor ownership.";
|
|
996
|
-
} else if (currentEqualsBase) {
|
|
997
|
-
kind = "replace";
|
|
998
|
-
reason = "Current bytes equal the verified vendor base; safe replacement.";
|
|
999
|
-
} else if ((options.forceCustomized ?? []).includes(group.path)) {
|
|
1000
|
-
kind = "replace";
|
|
1001
|
-
reason = "Scoped init force selected this known customized path.";
|
|
1002
|
-
} else if (targetEqualsBase) {
|
|
1003
|
-
kind = "preserve";
|
|
1004
|
-
reason = "Vendor target is unchanged; preserve the local-only edit.";
|
|
1005
|
-
} else if (verified) {
|
|
1006
|
-
kind = "conflict";
|
|
1007
|
-
reason = "Current customization and target vendor content both differ from the verified base.";
|
|
1008
|
-
} else {
|
|
1009
|
-
kind = "conflict";
|
|
1010
|
-
reason = "Ownership is unverified; preserve current content until trusted evidence or explicit review.";
|
|
1011
|
-
}
|
|
1012
|
-
if (kind === "preserve" && explicitReplacement(options, group.path) && currentContent !== void 0 && target !== void 0) {
|
|
1013
|
-
kind = "replace";
|
|
1014
|
-
reason = "Explicit replacement selected for this customized path.";
|
|
1015
|
-
}
|
|
1016
|
-
const action = actionBase(group.path, kind, reason, currentContent, target, first.mode);
|
|
1017
|
-
if (target !== void 0 && ["replace", "create", "adopt", "conflict"].includes(kind)) action.content = bytes(target);
|
|
1018
|
-
action.selected = selected(options, group.path, kind);
|
|
1019
|
-
if (kind === "preserve" && currentContent === void 0 && verified && options.repair?.includes(group.path)) {
|
|
1020
|
-
action.kind = "repair";
|
|
1021
|
-
action.resolution = "repair";
|
|
1022
|
-
action.selected = true;
|
|
1023
|
-
if (target !== void 0) action.content = bytes(target);
|
|
1024
|
-
} else if (kind === "conflict" && explicitReplacement(options, group.path)) {
|
|
1025
|
-
action.resolution = "replace";
|
|
1026
|
-
action.selected = true;
|
|
1027
|
-
}
|
|
1028
|
-
if (kind === "conflict" && currentContent !== void 0 && target !== void 0) action.diff = diff(group.path, currentContent, target);
|
|
1029
|
-
if (first.kind === "config-patch") action.patch = { ...first.ownedKey ? { ownedKey: first.ownedKey } : {}, ...first.ownedRegion ? { ownedRegion: first.ownedRegion } : {} };
|
|
1030
|
-
add(action);
|
|
1031
|
-
if (action.selected && ["replace", "create", "adopt", "repair", "reconcile"].includes(action.kind)) addFile(nextManifest, group.path, first, targetHash, options.targetVersion ?? input.manifest.targetVersion);
|
|
1032
|
-
if (action.selected && action.kind === "conflict" && action.resolution === "replace") addFile(nextManifest, group.path, first, targetHash, options.targetVersion ?? input.manifest.targetVersion);
|
|
1033
|
-
}
|
|
1034
|
-
for (const [path, old] of Object.entries(input.manifest.files)) {
|
|
1035
|
-
if (knownPaths.has(path)) continue;
|
|
1036
|
-
const currentContent = current.get(path);
|
|
1037
|
-
if (currentContent === void 0) {
|
|
1038
|
-
const action = actionBase(path, "preserve", "Previously managed file is absent; preserve local deletion.", void 0, void 0, void 0);
|
|
1039
|
-
add(action);
|
|
1040
|
-
continue;
|
|
1041
|
-
}
|
|
1042
|
-
if (old.kind !== "vendor") {
|
|
1043
|
-
const unchangedCreateOnce = old.kind === "create-once" && old.vendorHash !== "" && normalized(currentContent) === old.vendorHash;
|
|
1044
|
-
const action = actionBase(
|
|
1045
|
-
path,
|
|
1046
|
-
"preserve",
|
|
1047
|
-
unchangedCreateOnce ? "Create-once document is unchanged; leave the existing file in place." : "Target no longer declares a patch/document; preserve the whole user file.",
|
|
1048
|
-
currentContent,
|
|
1049
|
-
void 0,
|
|
1050
|
-
void 0
|
|
1051
|
-
);
|
|
1052
|
-
if (unchangedCreateOnce) action.nonActionable = true;
|
|
1053
|
-
action.selected = false;
|
|
1054
|
-
add(action);
|
|
1055
|
-
continue;
|
|
1056
|
-
}
|
|
1057
|
-
if (old.ownership !== "verified" || !old.vendorHash) {
|
|
1058
|
-
const action = actionBase(path, "orphan", "Target no longer declares this file and ownership is unverified; preserve it.", currentContent, void 0, void 0);
|
|
1059
|
-
action.selected = false;
|
|
1060
|
-
add(action);
|
|
1061
|
-
delete nextManifest.files[path];
|
|
1062
|
-
continue;
|
|
1063
|
-
}
|
|
1064
|
-
const currentHash = normalized(currentContent);
|
|
1065
|
-
if (currentHash === old.vendorHash) {
|
|
1066
|
-
const action = actionBase(path, "delete", "Target no longer includes an owned file; delete only the verified file.", currentContent, void 0, void 0);
|
|
1067
|
-
action.selected = true;
|
|
1068
|
-
add(action);
|
|
1069
|
-
delete nextManifest.files[path];
|
|
1070
|
-
} else {
|
|
1071
|
-
const action = actionBase(path, "orphan", "Target no longer includes customized content; preserve it as an orphaned customization.", currentContent, void 0, void 0);
|
|
1072
|
-
action.selected = false;
|
|
1073
|
-
add(action);
|
|
1074
|
-
delete nextManifest.files[path];
|
|
1075
|
-
}
|
|
1076
|
-
}
|
|
1077
|
-
const preserved = actions.filter((action) => action.preservedContent !== void 0 && ["preserve", "conflict", "orphan"].includes(action.kind)).map((action) => ({ path: action.path, content: bytes(action.preservedContent), reason: action.reason }));
|
|
1078
|
-
const conflicts = actions.filter((action) => action.kind === "conflict");
|
|
1079
|
-
return {
|
|
1080
|
-
actions,
|
|
1081
|
-
preserved,
|
|
1082
|
-
conflicts,
|
|
1083
|
-
diagnostics,
|
|
1084
|
-
nextManifest,
|
|
1085
|
-
baseManifestDigest: options.baseManifestDigest !== void 0 ? options.baseManifestDigest : manifestDigest(input.manifest)
|
|
1086
|
-
};
|
|
1087
|
-
}
|
|
1088
|
-
|
|
1089
|
-
// src/update-transaction.ts
|
|
1090
|
-
import {
|
|
1091
|
-
chmodSync,
|
|
1092
|
-
closeSync,
|
|
1093
|
-
existsSync as existsSync3,
|
|
1094
|
-
fsyncSync,
|
|
1095
|
-
lstatSync,
|
|
1096
|
-
mkdirSync as mkdirSync2,
|
|
1097
|
-
openSync,
|
|
1098
|
-
readdirSync as readdirSync2,
|
|
1099
|
-
readFileSync as readFileSync3,
|
|
1100
|
-
rmdirSync,
|
|
1101
|
-
statSync,
|
|
1102
|
-
unlinkSync,
|
|
1103
|
-
writeFileSync as writeFileSync2
|
|
1104
|
-
} from "fs";
|
|
1105
|
-
import * as fs from "fs";
|
|
1106
|
-
import { dirname } from "path";
|
|
1107
|
-
import { randomUUID } from "crypto";
|
|
1108
|
-
var LOCAL_DIR = "docs/.joycraft/local";
|
|
1109
|
-
var LOCK_RELATIVE = `${LOCAL_DIR}/update.lock`;
|
|
1110
|
-
var JOURNAL_RELATIVE = `${LOCAL_DIR}/update-journal.json`;
|
|
1111
|
-
var BACKUPS_RELATIVE = `${LOCAL_DIR}/backups`;
|
|
1112
|
-
var LAST_SUCCESSFUL_RELATIVE = `${LOCAL_DIR}/last-successful.json`;
|
|
1113
|
-
var TransactionConflictError = class extends Error {
|
|
1114
|
-
conflictPath;
|
|
1115
|
-
constructor(message, conflictPath) {
|
|
1116
|
-
super(message);
|
|
1117
|
-
this.name = "TransactionConflictError";
|
|
1118
|
-
this.conflictPath = conflictPath;
|
|
1119
|
-
}
|
|
1120
|
-
};
|
|
1121
|
-
function encode(value) {
|
|
1122
|
-
if (Buffer.isBuffer(value)) return { __joycraftBuffer: value.toString("base64") };
|
|
1123
|
-
if (Array.isArray(value)) return value.map(encode);
|
|
1124
|
-
if (value && typeof value === "object") {
|
|
1125
|
-
return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, encode(item)]));
|
|
1126
|
-
}
|
|
1127
|
-
return value;
|
|
1128
|
-
}
|
|
1129
|
-
function decode(value) {
|
|
1130
|
-
if (Array.isArray(value)) return value.map(decode);
|
|
1131
|
-
if (value && typeof value === "object") {
|
|
1132
|
-
const object2 = value;
|
|
1133
|
-
if (typeof object2.__joycraftBuffer === "string" && Object.keys(object2).length === 1) {
|
|
1134
|
-
return Buffer.from(object2.__joycraftBuffer, "base64");
|
|
1135
|
-
}
|
|
1136
|
-
return Object.fromEntries(Object.entries(object2).map(([key, item]) => [key, decode(item)]));
|
|
1137
|
-
}
|
|
1138
|
-
return value;
|
|
1139
|
-
}
|
|
1140
|
-
function bytes2(value) {
|
|
1141
|
-
return Buffer.isBuffer(value) ? Buffer.from(value) : Buffer.from(value);
|
|
1142
|
-
}
|
|
1143
|
-
function imageBytes(image) {
|
|
1144
|
-
return image.present && image.bytes ? Buffer.from(image.bytes.data, "base64") : void 0;
|
|
1145
|
-
}
|
|
1146
|
-
function imageOf(content, mode) {
|
|
1147
|
-
if (!content) return { present: false };
|
|
1148
|
-
return { present: true, bytes: { encoding: "base64", data: content.toString("base64") }, hash: rawFileHash(content), ...mode === void 0 ? {} : { mode } };
|
|
1149
|
-
}
|
|
1150
|
-
function hitPhase(options, phase, info) {
|
|
1151
|
-
options.onPhase?.(phase, info);
|
|
1152
|
-
if (options.failureAt === phase) {
|
|
1153
|
-
throw new Error(`Injected transaction failure after ${phase}.`);
|
|
1154
|
-
}
|
|
1155
|
-
}
|
|
1156
|
-
function localPath(root, relativePath) {
|
|
1157
|
-
return resolveUpdatePath(root, relativePath);
|
|
1158
|
-
}
|
|
1159
|
-
function ensureDirectory(root, relativePath) {
|
|
1160
|
-
const path = localPath(root, relativePath);
|
|
1161
|
-
mkdirSync2(path, { recursive: true });
|
|
1162
|
-
return localPath(root, relativePath);
|
|
1163
|
-
}
|
|
1164
|
-
function durableWrite(path, data, mode) {
|
|
1165
|
-
mkdirSync2(dirname(path), { recursive: true });
|
|
1166
|
-
const fd = openSync(path, "w");
|
|
1167
|
-
try {
|
|
1168
|
-
writeFileSync2(fd, data);
|
|
1169
|
-
fsyncSync(fd);
|
|
1170
|
-
} finally {
|
|
1171
|
-
closeFd(fd);
|
|
1172
|
-
}
|
|
1173
|
-
if (mode !== void 0) chmodSync(path, mode);
|
|
1174
|
-
}
|
|
1175
|
-
function closeFd(fd) {
|
|
1176
|
-
closeSync(fd);
|
|
1177
|
-
}
|
|
1178
|
-
function readJournal(root) {
|
|
1179
|
-
const path = localPath(root, JOURNAL_RELATIVE);
|
|
1180
|
-
if (!existsSync3(path)) return null;
|
|
1181
|
-
const parsed = JSON.parse(readFileSync3(path, "utf8"));
|
|
1182
|
-
if (parsed.schemaVersion !== 1 || typeof parsed.operationId !== "string" || !/^[A-Za-z0-9_-]+$/.test(parsed.operationId) || !Array.isArray(parsed.operations) || typeof parsed.newManifestDigest !== "string" || !parsed.newManifest || typeof parsed.backupRelative !== "string") {
|
|
1183
|
-
throw new Error("Invalid Joycraft update journal; refusing recovery.");
|
|
1184
|
-
}
|
|
1185
|
-
return parsed;
|
|
1186
|
-
}
|
|
1187
|
-
function writeJournal(root, journal) {
|
|
1188
|
-
const path = localPath(root, JOURNAL_RELATIVE);
|
|
1189
|
-
const tempRelative = `${JOURNAL_RELATIVE}.tmp-${journal.operationId}`;
|
|
1190
|
-
const temp = localPath(root, tempRelative);
|
|
1191
|
-
durableWrite(temp, JSON.stringify(encode(journal), null, 2) + "\n");
|
|
1192
|
-
fs.renameSync(temp, path);
|
|
1193
|
-
return path;
|
|
1194
|
-
}
|
|
1195
|
-
function lock(root, operationId) {
|
|
1196
|
-
ensureDirectory(root, LOCAL_DIR);
|
|
1197
|
-
const path = localPath(root, LOCK_RELATIVE);
|
|
1198
|
-
try {
|
|
1199
|
-
mkdirSync2(path);
|
|
1200
|
-
} catch (error) {
|
|
1201
|
-
if (error.code === "EEXIST") return null;
|
|
1202
|
-
throw error;
|
|
1203
|
-
}
|
|
1204
|
-
const ownerPath = localPath(root, `${LOCK_RELATIVE}/owner.json`);
|
|
1205
|
-
try {
|
|
1206
|
-
durableWrite(ownerPath, JSON.stringify({ operationId, pid: process.pid, startedAt: (/* @__PURE__ */ new Date()).toISOString() }) + "\n");
|
|
1207
|
-
} catch (error) {
|
|
1208
|
-
try {
|
|
1209
|
-
if (lstatSync(path).isDirectory() && readdirSync2(path).length === 0) rmdirSync(path);
|
|
1210
|
-
} catch {
|
|
1211
|
-
}
|
|
1212
|
-
throw error;
|
|
1213
|
-
}
|
|
1214
|
-
return { path, ownerPath, operationId, acquired: true };
|
|
1215
|
-
}
|
|
1216
|
-
function recoveryLock(root, operationId) {
|
|
1217
|
-
const acquired = lock(root, operationId);
|
|
1218
|
-
if (acquired) return acquired;
|
|
1219
|
-
const ownerPath = localPath(root, `${LOCK_RELATIVE}/owner.json`);
|
|
1220
|
-
try {
|
|
1221
|
-
if (!lstatSync(ownerPath).isFile()) return null;
|
|
1222
|
-
const owner = JSON.parse(readFileSync3(ownerPath, "utf8"));
|
|
1223
|
-
if (owner.operationId !== operationId || typeof owner.pid !== "number" || !Number.isInteger(owner.pid) || owner.pid <= 0) return null;
|
|
1224
|
-
try {
|
|
1225
|
-
process.kill(owner.pid, 0);
|
|
1226
|
-
return null;
|
|
1227
|
-
} catch (error) {
|
|
1228
|
-
if (error.code !== "ESRCH") return null;
|
|
1229
|
-
}
|
|
1230
|
-
const check = JSON.parse(readFileSync3(ownerPath, "utf8"));
|
|
1231
|
-
if (check.operationId !== operationId || check.pid !== owner.pid) return null;
|
|
1232
|
-
unlinkSync(ownerPath);
|
|
1233
|
-
rmdirSync(localPath(root, LOCK_RELATIVE));
|
|
1234
|
-
return lock(root, operationId);
|
|
1235
|
-
} catch {
|
|
1236
|
-
return null;
|
|
1237
|
-
}
|
|
1238
|
-
}
|
|
1239
|
-
function unlock(handle) {
|
|
1240
|
-
if (!handle.acquired) return;
|
|
1241
|
-
try {
|
|
1242
|
-
if (!lstatSync(handle.path).isDirectory() || !lstatSync(handle.ownerPath).isFile()) return;
|
|
1243
|
-
const owner = JSON.parse(readFileSync3(handle.ownerPath, "utf8"));
|
|
1244
|
-
if (owner.operationId !== handle.operationId) return;
|
|
1245
|
-
unlinkSync(handle.ownerPath);
|
|
1246
|
-
rmdirSync(handle.path);
|
|
1247
|
-
} catch {
|
|
1248
|
-
}
|
|
1249
|
-
handle.acquired = false;
|
|
1250
|
-
}
|
|
1251
|
-
function profileFor(plan, options) {
|
|
1252
|
-
if (options.authorityTransition) {
|
|
1253
|
-
if (options.authorityTransition.newAuthority.profile !== plan.nextManifest.profile) {
|
|
1254
|
-
throw new Error(`Transaction profile '${options.authorityTransition.newAuthority.profile}' does not match manifest profile '${plan.nextManifest.profile}'.`);
|
|
1255
|
-
}
|
|
1256
|
-
return options.authorityTransition.newAuthority.profile;
|
|
1257
|
-
}
|
|
1258
|
-
if (options.profile && options.profile !== plan.nextManifest.profile) {
|
|
1259
|
-
throw new Error(`Transaction profile '${options.profile}' does not match manifest profile '${plan.nextManifest.profile}'.`);
|
|
1260
|
-
}
|
|
1261
|
-
return plan.nextManifest.profile;
|
|
1262
|
-
}
|
|
1263
|
-
function isControlPath(relativePath, profile) {
|
|
1264
|
-
const controls = [
|
|
1265
|
-
// Both authority locations are transaction control paths regardless of
|
|
1266
|
-
// the destination profile. A private transaction must not be able to
|
|
1267
|
-
// smuggle a write to the tracked shared authority through its plan.
|
|
1268
|
-
manifestPath("shared"),
|
|
1269
|
-
manifestPath("private"),
|
|
1270
|
-
LOCAL_DIR,
|
|
1271
|
-
LOCK_RELATIVE,
|
|
1272
|
-
JOURNAL_RELATIVE,
|
|
1273
|
-
`${LOCAL_DIR}/staging`,
|
|
1274
|
-
BACKUPS_RELATIVE,
|
|
1275
|
-
LAST_SUCCESSFUL_RELATIVE
|
|
1276
|
-
];
|
|
1277
|
-
return controls.some((control) => relativePath === control || relativePath.startsWith(`${control}/`));
|
|
1278
|
-
}
|
|
1279
|
-
var APPROVED_LOCAL_MIGRATION_PATHS = /* @__PURE__ */ new Set([
|
|
1280
|
-
STATE_PATH,
|
|
1281
|
-
LEGACY_VERSION_FILE,
|
|
1282
|
-
LEGACY_CLAUDE_STATE_PATH,
|
|
1283
|
-
`${LOCAL_DIR}/settings.json`,
|
|
1284
|
-
`${LOCAL_DIR}/preferences.json`,
|
|
1285
|
-
`${LOCAL_DIR}/legacy-state-backup.json`
|
|
1286
|
-
]);
|
|
1287
|
-
function validateLocalMigrationPath(root, relativePath) {
|
|
1288
|
-
localPath(root, relativePath);
|
|
1289
|
-
if (!APPROVED_LOCAL_MIGRATION_PATHS.has(relativePath)) {
|
|
1290
|
-
throw new Error(`Local migration action is not allowlisted: '${relativePath}'.`);
|
|
1291
|
-
}
|
|
1292
|
-
}
|
|
1293
|
-
function validateManagedPath(root, relativePath, profile) {
|
|
1294
|
-
localPath(root, relativePath);
|
|
1295
|
-
if (isControlPath(relativePath, profile)) {
|
|
1296
|
-
throw new Error(`Update action cannot target Joycraft transaction state: '${relativePath}'.`);
|
|
1297
|
-
}
|
|
1298
|
-
}
|
|
1299
|
-
function operationFromInput(input, root) {
|
|
1300
|
-
const path = localPath(root, input.path);
|
|
1301
|
-
let current;
|
|
1302
|
-
let mode;
|
|
1303
|
-
try {
|
|
1304
|
-
const stat = lstatSync(path);
|
|
1305
|
-
if (!stat.isFile()) throw new Error(`Planned update path is not a regular file: '${input.path}'.`);
|
|
1306
|
-
current = readFileSync3(path);
|
|
1307
|
-
mode = stat.mode & 4095;
|
|
1308
|
-
} catch (error) {
|
|
1309
|
-
if (error.code !== "ENOENT") throw error;
|
|
1310
|
-
}
|
|
1311
|
-
if (input.currentPresent !== (current !== void 0)) {
|
|
1312
|
-
throw new TransactionConflictError(`Raw precondition failed for '${input.path}'.`, input.path);
|
|
1313
|
-
}
|
|
1314
|
-
if (input.rawPrecondition !== void 0 && rawFileHash(current ?? Buffer.alloc(0)) !== input.rawPrecondition) {
|
|
1315
|
-
if (!(current === void 0 && input.rawPrecondition === "")) {
|
|
1316
|
-
throw new TransactionConflictError(`Raw precondition failed for '${input.path}'.`, input.path);
|
|
1317
|
-
}
|
|
1318
|
-
}
|
|
1319
|
-
if (input.kind === "delete") {
|
|
1320
|
-
return { path: input.path, kind: "delete", before: imageOf(current, mode), after: { present: false }, localMigration: true };
|
|
1321
|
-
}
|
|
1322
|
-
if (input.content === void 0) throw new Error(`Selected local migration has no content: '${input.path}'.`);
|
|
1323
|
-
const target = bytes2(input.content);
|
|
1324
|
-
return {
|
|
1325
|
-
path: input.path,
|
|
1326
|
-
kind: "write",
|
|
1327
|
-
before: imageOf(current, mode),
|
|
1328
|
-
after: imageOf(target, input.mode ?? mode ?? 420),
|
|
1329
|
-
localMigration: true
|
|
1330
|
-
};
|
|
1331
|
-
}
|
|
1332
|
-
function authorityPath(root, reference) {
|
|
1333
|
-
const expected = manifestPath(reference.profile);
|
|
1334
|
-
if (reference.path !== void 0 && reference.path !== expected) {
|
|
1335
|
-
throw new Error(`Authority path '${reference.path}' does not match profile '${reference.profile}'.`);
|
|
1336
|
-
}
|
|
1337
|
-
return localPath(root, expected);
|
|
1338
|
-
}
|
|
1339
|
-
function digestOfAuthorityInfo(info) {
|
|
1340
|
-
return info.manifest ? manifestDigest(info.manifest) : null;
|
|
1341
|
-
}
|
|
1342
|
-
function validateAuthorityReference(root, reference, info, label) {
|
|
1343
|
-
authorityPath(root, reference);
|
|
1344
|
-
if (info.status !== "valid" && info.status !== "missing") {
|
|
1345
|
-
throw new TransactionConflictError(`Cannot transition while the ${label} authority is ${info.status}.`, manifestPath(reference.profile));
|
|
1346
|
-
}
|
|
1347
|
-
const actual = digestOfAuthorityInfo(info);
|
|
1348
|
-
if (reference.digest !== void 0 && reference.digest !== actual) {
|
|
1349
|
-
throw new TransactionConflictError(`${label} manifest authority changed after planning.`, manifestPath(reference.profile));
|
|
1350
|
-
}
|
|
1351
|
-
if (reference.raw !== void 0) {
|
|
1352
|
-
const raw = info.raw;
|
|
1353
|
-
if (raw === void 0 || raw !== (Buffer.isBuffer(reference.raw) ? reference.raw.toString("utf8") : reference.raw)) {
|
|
1354
|
-
throw new TransactionConflictError(`${label} manifest authority bytes changed after planning.`, manifestPath(reference.profile));
|
|
1355
|
-
}
|
|
1356
|
-
}
|
|
1357
|
-
}
|
|
1358
|
-
function authorityReferenceForTransition(root, transition) {
|
|
1359
|
-
if (transition.oldAuthority.profile === transition.newAuthority.profile) {
|
|
1360
|
-
throw new Error("Authority transition requires distinct shared and private profiles.");
|
|
1361
|
-
}
|
|
1362
|
-
authorityPath(root, transition.oldAuthority);
|
|
1363
|
-
authorityPath(root, transition.newAuthority);
|
|
1364
|
-
const oldInfo = readInstallationManifestInfo(root, transition.oldAuthority.profile);
|
|
1365
|
-
const nextInfo = readInstallationManifestInfo(root, transition.newAuthority.profile);
|
|
1366
|
-
validateAuthorityReference(root, transition.oldAuthority, oldInfo, "old");
|
|
1367
|
-
if (nextInfo.status !== "missing") {
|
|
1368
|
-
throw new TransactionConflictError("The target manifest authority already exists; preserving it.", manifestPath(transition.newAuthority.profile));
|
|
1369
|
-
}
|
|
1370
|
-
if (transition.newAuthority.digest !== void 0 && transition.newAuthority.digest !== null) {
|
|
1371
|
-
throw new TransactionConflictError("The target manifest authority precondition must be missing.", manifestPath(transition.newAuthority.profile));
|
|
1372
|
-
}
|
|
1373
|
-
return { old: transition.oldAuthority, next: transition.newAuthority, oldInfo, nextInfo };
|
|
1374
|
-
}
|
|
1375
|
-
function authorityOperation(root, path, kind, content, before) {
|
|
1376
|
-
const current = currentImage(root, path);
|
|
1377
|
-
const expected = before ?? current;
|
|
1378
|
-
if (!sameImage(current, expected)) throw new TransactionConflictError(`Raw precondition failed for '${path}'.`, path);
|
|
1379
|
-
if (kind === "delete") return { path, kind, before: expected, after: { present: false }, authority: true };
|
|
1380
|
-
if (!content) throw new Error(`Authority write has no manifest bytes: '${path}'.`);
|
|
1381
|
-
return { path, kind, before: expected, after: imageOf(content, 420), authority: true };
|
|
1382
|
-
}
|
|
1383
|
-
function siblingStagePath(relativePath, operationId, index) {
|
|
1384
|
-
const slash = relativePath.lastIndexOf("/");
|
|
1385
|
-
const parent = slash < 0 ? "" : relativePath.slice(0, slash);
|
|
1386
|
-
const name = `.joycraft-${operationId}-${index}.stage`;
|
|
1387
|
-
return parent ? `${parent}/${name}` : name;
|
|
1388
|
-
}
|
|
1389
|
-
function operationFor(action, root) {
|
|
1390
|
-
if (!action.selected || action.kind === "reconcile" || action.kind === "adopt" || action.kind === "preserve" || action.kind === "orphan") return null;
|
|
1391
|
-
const path = localPath(root, action.path);
|
|
1392
|
-
let current;
|
|
1393
|
-
let mode;
|
|
1394
|
-
try {
|
|
1395
|
-
const stat = lstatSync(path);
|
|
1396
|
-
if (!stat.isFile()) throw new Error(`Planned update path is not a regular file: '${action.path}'.`);
|
|
1397
|
-
current = readFileSync3(path);
|
|
1398
|
-
mode = stat.mode & 4095;
|
|
1399
|
-
} catch (error) {
|
|
1400
|
-
if (error.code !== "ENOENT") throw error;
|
|
1401
|
-
}
|
|
1402
|
-
if (action.currentPresent !== (current !== void 0)) {
|
|
1403
|
-
throw new TransactionConflictError(`Raw precondition failed for '${action.path}'.`, action.path);
|
|
1404
|
-
}
|
|
1405
|
-
if (action.rawPrecondition !== void 0 && rawFileHash(current ?? Buffer.alloc(0)) !== action.rawPrecondition) {
|
|
1406
|
-
if (!(current === void 0 && action.rawPrecondition === "")) {
|
|
1407
|
-
throw new TransactionConflictError(`Raw precondition failed for '${action.path}'.`, action.path);
|
|
1408
|
-
}
|
|
1409
|
-
}
|
|
1410
|
-
if (action.kind === "delete") {
|
|
1411
|
-
return { path: action.path, kind: "delete", before: imageOf(current, mode), after: { present: false } };
|
|
1412
|
-
}
|
|
1413
|
-
if (action.content === void 0) throw new Error(`Selected update action has no content: '${action.path}'.`);
|
|
1414
|
-
const target = bytes2(action.content);
|
|
1415
|
-
const targetMode = action.mode ?? mode ?? 420;
|
|
1416
|
-
return {
|
|
1417
|
-
path: action.path,
|
|
1418
|
-
kind: "write",
|
|
1419
|
-
before: imageOf(current, mode),
|
|
1420
|
-
after: imageOf(target, targetMode)
|
|
1421
|
-
};
|
|
1422
|
-
}
|
|
1423
|
-
function validateMetadataPrecondition(action, root) {
|
|
1424
|
-
if (!action.selected || action.kind !== "reconcile" && action.kind !== "adopt") return;
|
|
1425
|
-
const current = currentImage(root, action.path);
|
|
1426
|
-
if (action.currentPresent !== current.present) throw new TransactionConflictError(`Raw precondition failed for '${action.path}'.`, action.path);
|
|
1427
|
-
if (action.rawPrecondition !== void 0) {
|
|
1428
|
-
const content = imageBytes(current);
|
|
1429
|
-
if (!content || rawFileHash(content) !== action.rawPrecondition) {
|
|
1430
|
-
throw new TransactionConflictError(`Raw precondition failed for '${action.path}'.`, action.path);
|
|
1431
|
-
}
|
|
1432
|
-
}
|
|
1433
|
-
}
|
|
1434
|
-
function currentImage(root, relativePath) {
|
|
1435
|
-
const path = localPath(root, relativePath);
|
|
1436
|
-
try {
|
|
1437
|
-
const stat = lstatSync(path);
|
|
1438
|
-
if (!stat.isFile()) throw new Error(`Transaction path is not a regular file: '${relativePath}'.`);
|
|
1439
|
-
const content = readFileSync3(path);
|
|
1440
|
-
return imageOf(content, stat.mode & 4095);
|
|
1441
|
-
} catch (error) {
|
|
1442
|
-
if (error.code === "ENOENT") return { present: false };
|
|
1443
|
-
throw error;
|
|
1444
|
-
}
|
|
1445
|
-
}
|
|
1446
|
-
function sameImage(left, right) {
|
|
1447
|
-
if (left.present !== right.present) return false;
|
|
1448
|
-
if (!left.present) return true;
|
|
1449
|
-
const leftBytes = imageBytes(left);
|
|
1450
|
-
const rightBytes = imageBytes(right);
|
|
1451
|
-
return !!leftBytes && !!rightBytes && rawFileHash(leftBytes) === rawFileHash(rightBytes) && (right.mode === void 0 || left.mode !== void 0 && // Windows chmod exposes writability, not Unix owner/group/execute bits.
|
|
1452
|
-
(process.platform === "win32" ? (left.mode & 128) === (right.mode & 128) : left.mode === right.mode));
|
|
1453
|
-
}
|
|
1454
|
-
function writeImage(root, relativePath, image) {
|
|
1455
|
-
const path = localPath(root, relativePath);
|
|
1456
|
-
if (!image.present) {
|
|
1457
|
-
try {
|
|
1458
|
-
unlinkSync(path);
|
|
1459
|
-
} catch (error) {
|
|
1460
|
-
if (error.code !== "ENOENT") throw error;
|
|
1461
|
-
}
|
|
1462
|
-
return;
|
|
1463
|
-
}
|
|
1464
|
-
const content = imageBytes(image);
|
|
1465
|
-
if (!content) throw new Error(`Missing preimage bytes for '${relativePath}'.`);
|
|
1466
|
-
mkdirSync2(dirname(path), { recursive: true });
|
|
1467
|
-
localPath(root, relativePath);
|
|
1468
|
-
const slash = relativePath.lastIndexOf("/");
|
|
1469
|
-
const parent = slash < 0 ? "" : relativePath.slice(0, slash);
|
|
1470
|
-
const tempRelative = `${parent ? `${parent}/` : ""}.joycraft-rollback-${randomUUID()}.stage`;
|
|
1471
|
-
const temp = localPath(root, tempRelative);
|
|
1472
|
-
durableWrite(temp, content, image.mode);
|
|
1473
|
-
fs.renameSync(temp, path);
|
|
1474
|
-
}
|
|
1475
|
-
function manifestBytes(manifest) {
|
|
1476
|
-
return Buffer.from(JSON.stringify(manifest, null, 2) + "\n");
|
|
1477
|
-
}
|
|
1478
|
-
function withTransactionMarker(manifest, operationId) {
|
|
1479
|
-
return { ...manifest, __joycraftTransactionId: operationId };
|
|
1480
|
-
}
|
|
1481
|
-
function withoutTransactionMarker(manifest) {
|
|
1482
|
-
const copy = { ...manifest };
|
|
1483
|
-
delete copy.__joycraftTransactionId;
|
|
1484
|
-
return copy;
|
|
1485
|
-
}
|
|
1486
|
-
function cleanupKnown(root, journal) {
|
|
1487
|
-
for (const operation of journal.operations) {
|
|
1488
|
-
if (!operation.stageRelative) continue;
|
|
1489
|
-
const staged = localPath(root, operation.stageRelative);
|
|
1490
|
-
if (existsSync3(staged)) unlinkSync(staged);
|
|
1491
|
-
}
|
|
1492
|
-
const journalPath = localPath(root, JOURNAL_RELATIVE);
|
|
1493
|
-
if (existsSync3(journalPath)) unlinkSync(journalPath);
|
|
1494
|
-
const tempPath = localPath(root, `${JOURNAL_RELATIVE}.tmp-${journal.operationId}`);
|
|
1495
|
-
if (existsSync3(tempPath)) unlinkSync(tempPath);
|
|
1496
|
-
const manifestTemp = localPath(root, `${manifestPath(journal.profile)}.tmp-${journal.operationId}`);
|
|
1497
|
-
if (existsSync3(manifestTemp)) unlinkSync(manifestTemp);
|
|
1498
|
-
}
|
|
1499
|
-
function successfulFromJournal(journal) {
|
|
1500
|
-
return {
|
|
1501
|
-
schemaVersion: 1,
|
|
1502
|
-
operationId: journal.operationId,
|
|
1503
|
-
profile: journal.profile,
|
|
1504
|
-
oldManifestDigest: journal.oldManifestDigest,
|
|
1505
|
-
newManifestDigest: journal.newManifestDigest,
|
|
1506
|
-
...journal.oldManifest ? { oldManifest: journal.oldManifest } : {},
|
|
1507
|
-
newManifest: journal.newManifest,
|
|
1508
|
-
operations: journal.operations,
|
|
1509
|
-
backupRelative: journal.backupRelative,
|
|
1510
|
-
...journal.oldAuthority ? { oldAuthority: journal.oldAuthority } : {},
|
|
1511
|
-
...journal.newAuthority ? { newAuthority: journal.newAuthority } : {}
|
|
1512
|
-
};
|
|
1513
|
-
}
|
|
1514
|
-
function retainSuccessfulBackup(root, journal) {
|
|
1515
|
-
const target = localPath(root, LAST_SUCCESSFUL_RELATIVE);
|
|
1516
|
-
const temp = localPath(root, `${LAST_SUCCESSFUL_RELATIVE}.tmp-${journal.operationId}`);
|
|
1517
|
-
durableWrite(temp, JSON.stringify(encode(successfulFromJournal(journal)), null, 2) + "\n");
|
|
1518
|
-
fs.renameSync(temp, target);
|
|
1519
|
-
}
|
|
1520
|
-
function attention(message, operationId, journalPath) {
|
|
1521
|
-
return { status: "attention", ...operationId ? { operationId } : {}, ...journalPath ? { journalPath } : {}, diagnostics: [message], conflicts: [] };
|
|
1522
|
-
}
|
|
1523
|
-
function applyUpdatePlan(root, plan, options = {}) {
|
|
1524
|
-
const operationId = options.operationId ?? randomUUID();
|
|
1525
|
-
const profile = profileFor(plan, options);
|
|
1526
|
-
let transitionAuthorities = null;
|
|
1527
|
-
localPath(root, manifestPath(profile));
|
|
1528
|
-
localPath(root, LOCAL_DIR);
|
|
1529
|
-
localPath(root, LOCK_RELATIVE);
|
|
1530
|
-
localPath(root, JOURNAL_RELATIVE);
|
|
1531
|
-
const journalPath = localPath(root, JOURNAL_RELATIVE);
|
|
1532
|
-
const info = { operationId, journalPath };
|
|
1533
|
-
if (existsSync3(journalPath)) {
|
|
1534
|
-
return attention("An interrupted update is awaiting recovery; recover it before applying a new plan.", operationId, journalPath);
|
|
1535
|
-
}
|
|
1536
|
-
if (options.authorityTransition) {
|
|
1537
|
-
try {
|
|
1538
|
-
transitionAuthorities = authorityReferenceForTransition(root, options.authorityTransition);
|
|
1539
|
-
} catch (error) {
|
|
1540
|
-
if (error instanceof TransactionConflictError) {
|
|
1541
|
-
return { status: "conflict", operationId, journalPath, diagnostics: [error.message], conflicts: error.conflictPath ? [error.conflictPath] : [] };
|
|
1542
|
-
}
|
|
1543
|
-
throw error;
|
|
1544
|
-
}
|
|
1545
|
-
localPath(root, manifestPath(transitionAuthorities.old.profile));
|
|
1546
|
-
}
|
|
1547
|
-
for (const action of plan.actions) if (action.selected) validateManagedPath(root, action.path, profile);
|
|
1548
|
-
for (const operation of options.localOperations ?? []) validateLocalMigrationPath(root, operation.path);
|
|
1549
|
-
const manifestProfile = transitionAuthorities?.old.profile ?? profile;
|
|
1550
|
-
const manifestInfo = readInstallationManifestInfo(root, manifestProfile);
|
|
1551
|
-
if (manifestInfo.status !== "valid" && manifestInfo.status !== "missing") {
|
|
1552
|
-
return attention(`Cannot apply update while the ${manifestInfo.status} installation manifest needs attention.`);
|
|
1553
|
-
}
|
|
1554
|
-
const currentManifest = manifestInfo.manifest;
|
|
1555
|
-
const currentDigest = currentManifest ? manifestDigest(currentManifest) : null;
|
|
1556
|
-
const expectedBaseDigest = transitionAuthorities?.old.digest ?? plan.baseManifestDigest;
|
|
1557
|
-
if (expectedBaseDigest !== void 0 && expectedBaseDigest !== currentDigest) {
|
|
1558
|
-
return { status: "conflict", operationId, journalPath, diagnostics: ["The installation manifest changed after this plan was created; re-plan before applying."], conflicts: [manifestPath(manifestProfile)] };
|
|
1559
|
-
}
|
|
1560
|
-
const markedNext = withTransactionMarker(plan.nextManifest, operationId);
|
|
1561
|
-
if (!validateManifest(markedNext)) throw new Error("Refusing to publish an invalid transaction manifest.");
|
|
1562
|
-
if (!transitionAuthorities && !options.localOperations?.length && currentManifest && manifestDigest(withoutTransactionMarker(markedNext)) === manifestDigest(withoutTransactionMarker(currentManifest)) && plan.actions.every((action) => !action.selected || action.kind === "reconcile" || action.kind === "adopt")) {
|
|
1563
|
-
try {
|
|
1564
|
-
for (const action of plan.actions) validateMetadataPrecondition(action, root);
|
|
1565
|
-
} catch (error) {
|
|
1566
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
1567
|
-
const match = message.match(/'([^']+)'/);
|
|
1568
|
-
return { status: "conflict", operationId, journalPath, diagnostics: [message], conflicts: match ? [match[1]] : [] };
|
|
1569
|
-
}
|
|
1570
|
-
return { status: "noop", diagnostics: [], conflicts: [] };
|
|
1571
|
-
}
|
|
1572
|
-
const handle = lock(root, operationId);
|
|
1573
|
-
if (!handle) return attention("Another Joycraft updater holds the project lock.", operationId, journalPath);
|
|
1574
|
-
try {
|
|
1575
|
-
hitPhase(options, "lock-acquired", info);
|
|
1576
|
-
if (existsSync3(journalPath)) return attention("An interrupted update appeared while acquiring the project lock; recover it before applying a new plan.", operationId, journalPath);
|
|
1577
|
-
const lockedInfo = readInstallationManifestInfo(root, manifestProfile);
|
|
1578
|
-
if (lockedInfo.status !== "valid" && lockedInfo.status !== "missing") return attention(`Cannot apply update while the ${lockedInfo.status} installation manifest needs attention.`, operationId, journalPath);
|
|
1579
|
-
const lockedDigest = lockedInfo.manifest ? manifestDigest(lockedInfo.manifest) : null;
|
|
1580
|
-
if (expectedBaseDigest !== void 0 && expectedBaseDigest !== lockedDigest) return { status: "conflict", operationId, journalPath, diagnostics: ["The installation manifest changed while the update lock was acquired; re-plan before applying."], conflicts: [manifestPath(manifestProfile)] };
|
|
1581
|
-
if (transitionAuthorities) {
|
|
1582
|
-
try {
|
|
1583
|
-
const lockedAuthorities = authorityReferenceForTransition(root, options.authorityTransition);
|
|
1584
|
-
transitionAuthorities = lockedAuthorities;
|
|
1585
|
-
} catch (error) {
|
|
1586
|
-
if (error instanceof TransactionConflictError) return { status: "conflict", operationId, journalPath, diagnostics: [error.message], conflicts: error.conflictPath ? [error.conflictPath] : [] };
|
|
1587
|
-
return attention(String(error), operationId, journalPath);
|
|
1588
|
-
}
|
|
1589
|
-
}
|
|
1590
|
-
try {
|
|
1591
|
-
for (const action of plan.actions) validateMetadataPrecondition(action, root);
|
|
1592
|
-
} catch (error) {
|
|
1593
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
1594
|
-
const match = message.match(/'([^']+)'/);
|
|
1595
|
-
return { status: "conflict", operationId, journalPath, diagnostics: [message], conflicts: match ? [match[1]] : [] };
|
|
1596
|
-
}
|
|
1597
|
-
let operations;
|
|
1598
|
-
try {
|
|
1599
|
-
operations = plan.actions.map((action) => operationFor(action, root)).filter((item) => item !== null);
|
|
1600
|
-
for (const migration of options.localOperations ?? []) operations.push(operationFromInput(migration, root));
|
|
1601
|
-
if (transitionAuthorities) {
|
|
1602
|
-
const oldPath = manifestPath(transitionAuthorities.old.profile);
|
|
1603
|
-
const nextPath = manifestPath(transitionAuthorities.next.profile);
|
|
1604
|
-
const oldImage = currentImage(root, oldPath);
|
|
1605
|
-
const nextImage = currentImage(root, nextPath);
|
|
1606
|
-
operations.push(authorityOperation(root, oldPath, "delete", void 0, oldImage));
|
|
1607
|
-
operations.push(authorityOperation(root, nextPath, "write", manifestBytes(markedNext), nextImage));
|
|
1608
|
-
}
|
|
1609
|
-
} catch (error) {
|
|
1610
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
1611
|
-
const match = message.match(/'([^']+)'/);
|
|
1612
|
-
return { status: "conflict", operationId, journalPath, diagnostics: [message], conflicts: match ? [match[1]] : [] };
|
|
1613
|
-
}
|
|
1614
|
-
const backupRelative = `${BACKUPS_RELATIVE}/${operationId}`;
|
|
1615
|
-
for (let index = 0; index < operations.length; index += 1) {
|
|
1616
|
-
const operation = operations[index];
|
|
1617
|
-
operation.backupRelative = `${backupRelative}/${index}.bin`;
|
|
1618
|
-
if (operation.kind === "write") {
|
|
1619
|
-
operation.stageRelative = siblingStagePath(operation.path, operationId, index);
|
|
1620
|
-
if (existsSync3(localPath(root, operation.stageRelative))) {
|
|
1621
|
-
throw new Error(`Transaction staging path already exists: '${operation.stageRelative}'.`);
|
|
1622
|
-
}
|
|
1623
|
-
}
|
|
1624
|
-
}
|
|
1625
|
-
const journal = {
|
|
1626
|
-
schemaVersion: 1,
|
|
1627
|
-
operationId,
|
|
1628
|
-
profile,
|
|
1629
|
-
phase: "lock-acquired",
|
|
1630
|
-
oldManifestDigest: lockedInfo.manifest ? manifestDigest(lockedInfo.manifest) : null,
|
|
1631
|
-
newManifestDigest: manifestDigest(markedNext),
|
|
1632
|
-
...!transitionAuthorities && lockedInfo.raw ? { oldManifest: { encoding: "base64", data: Buffer.from(lockedInfo.raw).toString("base64") } } : {},
|
|
1633
|
-
newManifest: { encoding: "base64", data: manifestBytes(markedNext).toString("base64") },
|
|
1634
|
-
plan: encode(plan),
|
|
1635
|
-
operations,
|
|
1636
|
-
backupRelative,
|
|
1637
|
-
...transitionAuthorities ? {
|
|
1638
|
-
oldAuthority: {
|
|
1639
|
-
profile: transitionAuthorities.old.profile,
|
|
1640
|
-
path: manifestPath(transitionAuthorities.old.profile),
|
|
1641
|
-
digest: lockedInfo.manifest ? manifestDigest(lockedInfo.manifest) : null,
|
|
1642
|
-
...lockedInfo.raw ? { bytes: { encoding: "base64", data: Buffer.from(lockedInfo.raw).toString("base64") } } : {}
|
|
1643
|
-
},
|
|
1644
|
-
newAuthority: {
|
|
1645
|
-
profile: transitionAuthorities.next.profile,
|
|
1646
|
-
path: manifestPath(transitionAuthorities.next.profile),
|
|
1647
|
-
digest: manifestDigest(markedNext),
|
|
1648
|
-
preconditionDigest: transitionAuthorities.nextInfo.manifest ? manifestDigest(transitionAuthorities.nextInfo.manifest) : null,
|
|
1649
|
-
bytes: { encoding: "base64", data: manifestBytes(markedNext).toString("base64") }
|
|
1650
|
-
}
|
|
1651
|
-
} : {}
|
|
1652
|
-
};
|
|
1653
|
-
journal.phase = "journal-written";
|
|
1654
|
-
writeJournal(root, journal);
|
|
1655
|
-
hitPhase(options, "journal-written", info);
|
|
1656
|
-
ensureDirectory(root, `${backupRelative}`);
|
|
1657
|
-
for (let index = 0; index < operations.length; index += 1) {
|
|
1658
|
-
const operation = operations[index];
|
|
1659
|
-
const before = imageBytes(operation.before);
|
|
1660
|
-
if (before) durableWrite(localPath(root, operation.backupRelative), before, operation.before.mode);
|
|
1661
|
-
}
|
|
1662
|
-
journal.phase = "backups-written";
|
|
1663
|
-
writeJournal(root, journal);
|
|
1664
|
-
hitPhase(options, "backups-written", info);
|
|
1665
|
-
for (let index = 0; index < operations.length; index += 1) {
|
|
1666
|
-
const operation = operations[index];
|
|
1667
|
-
if (operation.kind !== "write") continue;
|
|
1668
|
-
const targetPath = localPath(root, operation.path);
|
|
1669
|
-
mkdirSync2(dirname(targetPath), { recursive: true });
|
|
1670
|
-
localPath(root, operation.path);
|
|
1671
|
-
const stagePath = localPath(root, operation.stageRelative);
|
|
1672
|
-
if (existsSync3(stagePath)) throw new Error(`Transaction staging path already exists: '${operation.stageRelative}'.`);
|
|
1673
|
-
const content = imageBytes(operation.after);
|
|
1674
|
-
durableWrite(stagePath, content, operation.after.mode);
|
|
1675
|
-
const staged = currentImage(root, operation.stageRelative);
|
|
1676
|
-
if (!sameImage(staged, operation.after)) throw new Error(`Staged bytes or mode failed validation for '${operation.path}'.`);
|
|
1677
|
-
}
|
|
1678
|
-
journal.phase = "staged";
|
|
1679
|
-
writeJournal(root, journal);
|
|
1680
|
-
hitPhase(options, "staged", info);
|
|
1681
|
-
for (const operation of operations) {
|
|
1682
|
-
const target = localPath(root, operation.path);
|
|
1683
|
-
mkdirSync2(dirname(target), { recursive: true });
|
|
1684
|
-
localPath(root, operation.path);
|
|
1685
|
-
const current = currentImage(root, operation.path);
|
|
1686
|
-
if (!sameImage(current, operation.before)) throw new Error(`Raw precondition failed immediately before writing '${operation.path}'.`);
|
|
1687
|
-
if (operation.kind === "delete") {
|
|
1688
|
-
if (current.present) unlinkSync(target);
|
|
1689
|
-
} else fs.renameSync(localPath(root, operation.stageRelative), target);
|
|
1690
|
-
}
|
|
1691
|
-
journal.phase = "files-applied";
|
|
1692
|
-
writeJournal(root, journal);
|
|
1693
|
-
hitPhase(options, "files-applied", info);
|
|
1694
|
-
for (const operation of operations) {
|
|
1695
|
-
if (!sameImage(currentImage(root, operation.path), operation.after)) throw new Error(`Published bytes or mode failed validation for '${operation.path}'.`);
|
|
1696
|
-
}
|
|
1697
|
-
journal.phase = "files-verified";
|
|
1698
|
-
writeJournal(root, journal);
|
|
1699
|
-
hitPhase(options, "files-verified", info);
|
|
1700
|
-
const beforeManifest = readInstallationManifestInfo(root, manifestProfile);
|
|
1701
|
-
if (!transitionAuthorities && beforeManifest.status !== "valid" && beforeManifest.status !== "missing") throw new TransactionConflictError("Installation manifest changed before publication.", manifestPath(manifestProfile));
|
|
1702
|
-
const beforeDigest = beforeManifest.manifest ? manifestDigest(beforeManifest.manifest) : null;
|
|
1703
|
-
if (!transitionAuthorities && beforeDigest !== journal.oldManifestDigest) throw new TransactionConflictError("Installation manifest changed before publication.", manifestPath(manifestProfile));
|
|
1704
|
-
if (transitionAuthorities) {
|
|
1705
|
-
const oldAfter = readInstallationManifestInfo(root, transitionAuthorities.old.profile);
|
|
1706
|
-
const nextAfter = readInstallationManifestInfo(root, transitionAuthorities.next.profile);
|
|
1707
|
-
if (oldAfter.status !== "missing" || nextAfter.status !== "valid" || !nextAfter.manifest || manifestDigest(nextAfter.manifest) !== journal.newManifestDigest) {
|
|
1708
|
-
throw new TransactionConflictError("Manifest authority changed before transition commit.", manifestPath(transitionAuthorities.next.profile));
|
|
1709
|
-
}
|
|
1710
|
-
}
|
|
1711
|
-
for (const action of plan.actions) validateMetadataPrecondition(action, root);
|
|
1712
|
-
for (const operation of operations) if (!sameImage(currentImage(root, operation.path), operation.after)) throw new TransactionConflictError(`Published bytes changed before manifest publication for '${operation.path}'.`, operation.path);
|
|
1713
|
-
if (!transitionAuthorities) {
|
|
1714
|
-
const manifestRel = manifestPath(profile);
|
|
1715
|
-
const manifestAbs = localPath(root, manifestRel);
|
|
1716
|
-
const manifestTemp = localPath(root, `${manifestRel}.tmp-${operationId}`);
|
|
1717
|
-
durableWrite(manifestTemp, manifestBytes(markedNext));
|
|
1718
|
-
parseInstallationManifest(readFileSync3(manifestTemp, "utf8"));
|
|
1719
|
-
fs.renameSync(manifestTemp, manifestAbs);
|
|
1720
|
-
}
|
|
1721
|
-
retainSuccessfulBackup(root, journal);
|
|
1722
|
-
journal.phase = "manifest-renamed";
|
|
1723
|
-
writeJournal(root, journal);
|
|
1724
|
-
hitPhase(options, "manifest-renamed", info);
|
|
1725
|
-
journal.phase = "journal-bookkept";
|
|
1726
|
-
writeJournal(root, journal);
|
|
1727
|
-
hitPhase(options, "journal-bookkept", info);
|
|
1728
|
-
journal.phase = "cleanup";
|
|
1729
|
-
hitPhase(options, "cleanup", info);
|
|
1730
|
-
cleanupKnown(root, journal);
|
|
1731
|
-
hitPhase(options, "complete", info);
|
|
1732
|
-
return { status: "applied", operationId, backupPath: localPath(root, backupRelative), diagnostics: [], conflicts: [] };
|
|
1733
|
-
} catch (error) {
|
|
1734
|
-
if (error instanceof TransactionConflictError) {
|
|
1735
|
-
return { status: "conflict", operationId, journalPath, diagnostics: [error.message], conflicts: error.conflictPath ? [error.conflictPath] : [] };
|
|
1736
|
-
}
|
|
1737
|
-
throw error;
|
|
1738
|
-
} finally {
|
|
1739
|
-
unlock(handle);
|
|
1740
|
-
}
|
|
1741
|
-
}
|
|
1742
|
-
function decodeJournal(value) {
|
|
1743
|
-
return decode(value);
|
|
1744
|
-
}
|
|
1745
|
-
function verifiedJournalBytes(value) {
|
|
1746
|
-
if (!value || value.encoding !== "base64" || typeof value.data !== "string") {
|
|
1747
|
-
throw new Error("Invalid journal byte encoding.");
|
|
1748
|
-
}
|
|
1749
|
-
const decoded = Buffer.from(value.data, "base64");
|
|
1750
|
-
if (decoded.toString("base64") !== value.data) throw new Error("Invalid journal base64 payload.");
|
|
1751
|
-
return decoded;
|
|
1752
|
-
}
|
|
1753
|
-
function validateJournalImage(image) {
|
|
1754
|
-
if (!image || typeof image.present !== "boolean") throw new Error("Invalid journal file image.");
|
|
1755
|
-
if (!image.present) {
|
|
1756
|
-
if (image.bytes !== void 0 || image.hash !== void 0) throw new Error("Absent journal file has content.");
|
|
1757
|
-
return;
|
|
1758
|
-
}
|
|
1759
|
-
if (!image.bytes || rawFileHash(verifiedJournalBytes(image.bytes)) !== image.hash) {
|
|
1760
|
-
throw new Error("Journal preimage or target bytes do not match their recorded digest.");
|
|
1761
|
-
}
|
|
1762
|
-
if (image.mode !== void 0 && (!Number.isInteger(image.mode) || image.mode < 0 || image.mode > 4095)) {
|
|
1763
|
-
throw new Error("Invalid journal file mode.");
|
|
1764
|
-
}
|
|
1765
|
-
}
|
|
1766
|
-
function validateJournalAuthority(root, authority, label) {
|
|
1767
|
-
if (!authority || authority.profile !== "shared" && authority.profile !== "private" || authority.path !== manifestPath(authority.profile) || authority.digest !== null && !/^[0-9a-f]{64}$/i.test(authority.digest)) {
|
|
1768
|
-
throw new Error(`Invalid ${label} manifest authority descriptor.`);
|
|
1769
|
-
}
|
|
1770
|
-
authorityPath(root, authority);
|
|
1771
|
-
if (authority.bytes) {
|
|
1772
|
-
const parsed = parseInstallationManifest(verifiedJournalBytes(authority.bytes).toString("utf8"));
|
|
1773
|
-
if (manifestDigest(parsed) !== authority.digest || parsed.profile !== authority.profile) {
|
|
1774
|
-
throw new Error(`Invalid ${label} manifest authority digest.`);
|
|
1775
|
-
}
|
|
1776
|
-
} else if (authority.digest !== null) {
|
|
1777
|
-
throw new Error(`Missing ${label} manifest authority preimage.`);
|
|
1778
|
-
}
|
|
1779
|
-
if (authority.preconditionDigest !== void 0 && authority.preconditionDigest !== null && !/^[0-9a-f]{64}$/i.test(authority.preconditionDigest)) {
|
|
1780
|
-
throw new Error(`Invalid ${label} authority precondition digest.`);
|
|
1781
|
-
}
|
|
1782
|
-
}
|
|
1783
|
-
function authorityImageMatches(image, authority) {
|
|
1784
|
-
if (authority.digest === null) return !image.present;
|
|
1785
|
-
if (!image.present || !image.bytes || !authority.bytes) return false;
|
|
1786
|
-
return rawFileHash(imageBytes(image)) === rawFileHash(verifiedJournalBytes(authority.bytes));
|
|
1787
|
-
}
|
|
1788
|
-
function validateJournal(root, journal) {
|
|
1789
|
-
if (journal.schemaVersion !== 1 || !/^[A-Za-z0-9_-]+$/.test(journal.operationId) || !Array.isArray(journal.operations)) {
|
|
1790
|
-
throw new Error("Invalid update journal identity.");
|
|
1791
|
-
}
|
|
1792
|
-
if (journal.profile !== "shared" && journal.profile !== "private") throw new Error("Invalid update journal profile.");
|
|
1793
|
-
const next = parseInstallationManifest(verifiedJournalBytes(journal.newManifest).toString("utf8"));
|
|
1794
|
-
if (manifestDigest(next) !== journal.newManifestDigest || next.profile !== journal.profile || next.__joycraftTransactionId !== journal.operationId) {
|
|
1795
|
-
throw new Error("Journal commit marker does not match its recorded manifest.");
|
|
1796
|
-
}
|
|
1797
|
-
if (journal.oldManifest) {
|
|
1798
|
-
const previous = parseInstallationManifest(verifiedJournalBytes(journal.oldManifest).toString("utf8"));
|
|
1799
|
-
if (manifestDigest(previous) !== journal.oldManifestDigest || previous.profile !== journal.profile) throw new Error("Journal manifest preimage digest is invalid.");
|
|
1800
|
-
} else if (journal.oldManifestDigest !== null && !journal.oldAuthority) throw new Error("Journal is missing its manifest preimage.");
|
|
1801
|
-
if (journal.backupRelative !== `${BACKUPS_RELATIVE}/${journal.operationId}`) throw new Error("Update journal backup path is not transaction-owned.");
|
|
1802
|
-
localPath(root, journal.backupRelative);
|
|
1803
|
-
if (journal.oldAuthority === void 0 !== (journal.newAuthority === void 0)) {
|
|
1804
|
-
throw new Error("Update journal must contain both authority descriptors.");
|
|
1805
|
-
}
|
|
1806
|
-
if (journal.oldAuthority && journal.newAuthority) {
|
|
1807
|
-
validateJournalAuthority(root, journal.oldAuthority, "old");
|
|
1808
|
-
validateJournalAuthority(root, journal.newAuthority, "new");
|
|
1809
|
-
if (journal.oldAuthority.profile === journal.newAuthority.profile || journal.oldAuthority.path === journal.newAuthority.path) {
|
|
1810
|
-
throw new Error("Update journal authority descriptors must be distinct.");
|
|
1811
|
-
}
|
|
1812
|
-
if (journal.newAuthority.digest !== journal.newManifestDigest) throw new Error("New authority digest does not match the transaction manifest.");
|
|
1813
|
-
const authorityOperations = journal.operations.filter((operation) => operation.authority);
|
|
1814
|
-
const oldDeletes = authorityOperations.filter((operation) => operation.path === journal.oldAuthority.path && operation.kind === "delete");
|
|
1815
|
-
const newWrites = authorityOperations.filter((operation) => operation.path === journal.newAuthority.path && operation.kind === "write");
|
|
1816
|
-
if (authorityOperations.length !== 2 || oldDeletes.length !== 1 || newWrites.length !== 1 || !authorityImageMatches(oldDeletes[0].before, journal.oldAuthority) || oldDeletes[0].after.present || newWrites[0].before.present || !authorityImageMatches(newWrites[0].after, journal.newAuthority)) {
|
|
1817
|
-
throw new Error("Update journal authority operations do not match their recorded transition.");
|
|
1818
|
-
}
|
|
1819
|
-
} else if (journal.operations.some((operation) => operation.authority)) {
|
|
1820
|
-
throw new Error("Update journal contains authority operations without an authority transition.");
|
|
1821
|
-
}
|
|
1822
|
-
for (let index = 0; index < journal.operations.length; index += 1) {
|
|
1823
|
-
const operation = journal.operations[index];
|
|
1824
|
-
if (operation.kind !== "write" && operation.kind !== "delete") throw new Error("Invalid journal operation kind.");
|
|
1825
|
-
validateJournalImage(operation.before);
|
|
1826
|
-
validateJournalImage(operation.after);
|
|
1827
|
-
if (operation.authority) {
|
|
1828
|
-
if (!journal.oldAuthority || !journal.newAuthority || operation.path !== journal.oldAuthority.path && operation.path !== journal.newAuthority.path) {
|
|
1829
|
-
throw new Error("Update journal authority operation is not transaction-owned.");
|
|
1830
|
-
}
|
|
1831
|
-
} else if (operation.localMigration) {
|
|
1832
|
-
validateLocalMigrationPath(root, operation.path);
|
|
1833
|
-
} else {
|
|
1834
|
-
validateManagedPath(root, operation.path, journal.profile);
|
|
1835
|
-
}
|
|
1836
|
-
const expectedStage = operation.kind === "write" ? siblingStagePath(operation.path, journal.operationId, index) : void 0;
|
|
1837
|
-
const stageRequired = ["staged", "files-applied", "files-verified", "manifest-renamed", "journal-bookkept", "cleanup", "complete"].includes(journal.phase);
|
|
1838
|
-
if (stageRequired && operation.stageRelative !== expectedStage || operation.stageRelative !== void 0 && operation.stageRelative !== expectedStage) throw new Error("Update journal staging path is not transaction-owned.");
|
|
1839
|
-
if (operation.backupRelative && !operation.backupRelative.startsWith(`${journal.backupRelative}/`)) throw new Error("Update journal backup file is not transaction-owned.");
|
|
1840
|
-
}
|
|
1841
|
-
}
|
|
1842
|
-
function recoveryResult(status, journal, conflicts = [], diagnostics = []) {
|
|
1843
|
-
return { status, operationId: journal.operationId, journalPath: JOURNAL_RELATIVE, diagnostics, conflicts };
|
|
1844
|
-
}
|
|
1845
|
-
function transitionAuthorityState(root, journal) {
|
|
1846
|
-
if (!journal.oldAuthority || !journal.newAuthority) return { oldState: false, newState: false };
|
|
1847
|
-
const oldInfo = readInstallationManifestInfo(root, journal.oldAuthority.profile);
|
|
1848
|
-
const newInfo = readInstallationManifestInfo(root, journal.newAuthority.profile);
|
|
1849
|
-
if (oldInfo.status !== "valid" && oldInfo.status !== "missing") {
|
|
1850
|
-
return recoveryResult("attention", journal, [], [`Cannot recover while the old manifest authority is ${oldInfo.status}.`]);
|
|
1851
|
-
}
|
|
1852
|
-
if (newInfo.status !== "valid" && newInfo.status !== "missing") {
|
|
1853
|
-
return recoveryResult("attention", journal, [], [`Cannot recover while the new manifest authority is ${newInfo.status}.`]);
|
|
1854
|
-
}
|
|
1855
|
-
const oldDigest = digestOfAuthorityInfo(oldInfo);
|
|
1856
|
-
const newDigest = digestOfAuthorityInfo(newInfo);
|
|
1857
|
-
const oldMatches = oldDigest === journal.oldAuthority.digest;
|
|
1858
|
-
const newMatches = newDigest === journal.newAuthority.digest;
|
|
1859
|
-
if (oldMatches && newMatches) return recoveryResult("attention", journal, [journal.oldAuthority.path, journal.newAuthority.path], ["Both manifest authorities are present; transition state is ambiguous."]);
|
|
1860
|
-
if (newMatches && !oldInfo.manifest) return { oldState: false, newState: true };
|
|
1861
|
-
if (oldMatches && !newInfo.manifest) return { oldState: true, newState: false };
|
|
1862
|
-
if (!oldInfo.manifest && !newInfo.manifest) return { oldState: true, newState: false };
|
|
1863
|
-
return recoveryResult("attention", journal, [journal.oldAuthority.path, journal.newAuthority.path], ["Manifest authority matches neither the interrupted preimage nor its commit marker."]);
|
|
1864
|
-
}
|
|
1865
|
-
function recoverInterruptedUpdate(root, options = {}) {
|
|
1866
|
-
let journal;
|
|
1867
|
-
try {
|
|
1868
|
-
journal = decodeJournal(readJournal(root));
|
|
1869
|
-
} catch (error) {
|
|
1870
|
-
return attention(`Unable to read the interrupted update journal: ${String(error)}`);
|
|
1871
|
-
}
|
|
1872
|
-
if (!journal) return { status: "none", diagnostics: [], conflicts: [] };
|
|
1873
|
-
try {
|
|
1874
|
-
validateJournal(root, journal);
|
|
1875
|
-
} catch (error) {
|
|
1876
|
-
return attention(`Unable to recover the interrupted update safely: ${String(error)}`, journal.operationId, localPath(root, JOURNAL_RELATIVE));
|
|
1877
|
-
}
|
|
1878
|
-
const handle = recoveryLock(root, journal.operationId);
|
|
1879
|
-
if (!handle) return recoveryResult("attention", journal, [], ["Another Joycraft updater holds the project lock."]);
|
|
1880
|
-
try {
|
|
1881
|
-
const lockedJournalRaw = readJournal(root);
|
|
1882
|
-
if (!lockedJournalRaw || lockedJournalRaw.operationId !== journal.operationId || lockedJournalRaw.newManifestDigest !== journal.newManifestDigest) {
|
|
1883
|
-
return recoveryResult("attention", journal, [], ["The interrupted journal changed while recovery was acquiring the lock."]);
|
|
1884
|
-
}
|
|
1885
|
-
journal = decodeJournal(lockedJournalRaw);
|
|
1886
|
-
validateJournal(root, journal);
|
|
1887
|
-
const authorityState = transitionAuthorityState(root, journal);
|
|
1888
|
-
if ("status" in authorityState) return authorityState;
|
|
1889
|
-
let oldState;
|
|
1890
|
-
let newState;
|
|
1891
|
-
if (journal.oldAuthority && journal.newAuthority) {
|
|
1892
|
-
oldState = authorityState.oldState;
|
|
1893
|
-
newState = authorityState.newState;
|
|
1894
|
-
} else {
|
|
1895
|
-
const info = readInstallationManifestInfo(root, journal.profile);
|
|
1896
|
-
if (info.status !== "valid" && info.status !== "missing") return recoveryResult("attention", journal, [], [`Cannot recover while the ${info.status} installation manifest needs attention.`]);
|
|
1897
|
-
const digest = info.manifest ? manifestDigest(info.manifest) : null;
|
|
1898
|
-
oldState = digest === journal.oldManifestDigest;
|
|
1899
|
-
newState = digest === journal.newManifestDigest;
|
|
1900
|
-
if (!oldState && !newState) return recoveryResult("attention", journal, [], ["Current manifest matches neither the interrupted update preimage nor its commit marker."]);
|
|
1901
|
-
}
|
|
1902
|
-
const conflicts = [];
|
|
1903
|
-
for (const operation of journal.operations) {
|
|
1904
|
-
const current = currentImage(root, operation.path);
|
|
1905
|
-
if (newState ? !sameImage(current, operation.after) : !sameImage(current, operation.before) && !sameImage(current, operation.after)) conflicts.push(operation.path);
|
|
1906
|
-
}
|
|
1907
|
-
if (conflicts.length) return recoveryResult("conflict", journal, conflicts, ["Recovery found intervening user edits; backup material was retained."]);
|
|
1908
|
-
if (newState) {
|
|
1909
|
-
retainSuccessfulBackup(root, journal);
|
|
1910
|
-
cleanupKnown(root, journal);
|
|
1911
|
-
hitPhase(options, "complete", { operationId: journal.operationId, journalPath: localPath(root, JOURNAL_RELATIVE) });
|
|
1912
|
-
return recoveryResult("committed", journal);
|
|
1913
|
-
}
|
|
1914
|
-
for (const operation of [...journal.operations].reverse()) {
|
|
1915
|
-
const current = currentImage(root, operation.path);
|
|
1916
|
-
if (sameImage(current, operation.before)) continue;
|
|
1917
|
-
writeImage(root, operation.path, operation.before);
|
|
1918
|
-
}
|
|
1919
|
-
if (journal.oldAuthority && journal.newAuthority) {
|
|
1920
|
-
} else if (journal.oldManifest) {
|
|
1921
|
-
const oldManifest = Buffer.from(journal.oldManifest.data, "base64");
|
|
1922
|
-
const manifestRel = manifestPath(journal.profile);
|
|
1923
|
-
const temp = localPath(root, `${manifestRel}.recovery-${journal.operationId}`);
|
|
1924
|
-
durableWrite(temp, oldManifest);
|
|
1925
|
-
parseInstallationManifest(readFileSync3(temp, "utf8"));
|
|
1926
|
-
fs.renameSync(temp, localPath(root, manifestRel));
|
|
1927
|
-
} else {
|
|
1928
|
-
const manifest = localPath(root, manifestPath(journal.profile));
|
|
1929
|
-
if (existsSync3(manifest)) unlinkSync(manifest);
|
|
1930
|
-
}
|
|
1931
|
-
cleanupKnown(root, journal);
|
|
1932
|
-
hitPhase(options, "complete", { operationId: journal.operationId, journalPath: localPath(root, JOURNAL_RELATIVE) });
|
|
1933
|
-
return recoveryResult("rolled-back", journal);
|
|
1934
|
-
} finally {
|
|
1935
|
-
unlock(handle);
|
|
1936
|
-
}
|
|
1937
|
-
}
|
|
1938
|
-
function rollbackLastSuccessfulUpdate(root, options = {}) {
|
|
1939
|
-
const descriptorPath = localPath(root, LAST_SUCCESSFUL_RELATIVE);
|
|
1940
|
-
if (!existsSync3(descriptorPath)) return { status: "none", diagnostics: [], conflicts: [] };
|
|
1941
|
-
let backup;
|
|
1942
|
-
try {
|
|
1943
|
-
backup = decode(JSON.parse(readFileSync3(descriptorPath, "utf8")));
|
|
1944
|
-
} catch (error) {
|
|
1945
|
-
return attention(`Unable to read the retained successful backup: ${String(error)}`);
|
|
1946
|
-
}
|
|
1947
|
-
try {
|
|
1948
|
-
validateJournal(root, backup);
|
|
1949
|
-
} catch (error) {
|
|
1950
|
-
return attention(`Unable to use the retained successful backup safely: ${String(error)}`);
|
|
1951
|
-
}
|
|
1952
|
-
const handle = lock(root, backup.operationId);
|
|
1953
|
-
if (!handle) return attention("Another Joycraft updater holds the project lock.");
|
|
1954
|
-
try {
|
|
1955
|
-
let lockedBackup;
|
|
1956
|
-
try {
|
|
1957
|
-
lockedBackup = decode(JSON.parse(readFileSync3(descriptorPath, "utf8")));
|
|
1958
|
-
} catch (error) {
|
|
1959
|
-
return attention(`Unable to re-read the retained successful backup safely: ${String(error)}`);
|
|
1960
|
-
}
|
|
1961
|
-
if (lockedBackup.operationId !== backup.operationId || lockedBackup.newManifestDigest !== backup.newManifestDigest) {
|
|
1962
|
-
return attention("The retained successful backup changed while acquiring the project lock.");
|
|
1963
|
-
}
|
|
1964
|
-
backup = lockedBackup;
|
|
1965
|
-
validateJournal(root, backup);
|
|
1966
|
-
if (backup.oldAuthority && backup.newAuthority) {
|
|
1967
|
-
const oldInfo = readInstallationManifestInfo(root, backup.oldAuthority.profile);
|
|
1968
|
-
const newInfo = readInstallationManifestInfo(root, backup.newAuthority.profile);
|
|
1969
|
-
if (oldInfo.status !== "missing" || newInfo.status !== "valid" || !newInfo.manifest || manifestDigest(newInfo.manifest) !== backup.newManifestDigest) {
|
|
1970
|
-
return { status: "conflict", operationId: backup.operationId, diagnostics: ["Current manifest authority no longer matches the successful update; rollback is guarded."], conflicts: [manifestPath(backup.newAuthority.profile)] };
|
|
1971
|
-
}
|
|
1972
|
-
} else {
|
|
1973
|
-
const info = readInstallationManifestInfo(root, backup.profile);
|
|
1974
|
-
if (info.status !== "valid" || !info.manifest || manifestDigest(info.manifest) !== backup.newManifestDigest) {
|
|
1975
|
-
return { status: "conflict", operationId: backup.operationId, diagnostics: ["Current manifest no longer matches the successful update; rollback is guarded."], conflicts: [manifestPath(backup.profile)] };
|
|
1976
|
-
}
|
|
1977
|
-
}
|
|
1978
|
-
const conflicts = [];
|
|
1979
|
-
for (const operation of backup.operations) if (!sameImage(currentImage(root, operation.path), operation.after)) conflicts.push(operation.path);
|
|
1980
|
-
if (conflicts.length) return { status: "conflict", operationId: backup.operationId, diagnostics: ["Current files changed after the successful update; rollback left them untouched."], conflicts };
|
|
1981
|
-
for (const operation of [...backup.operations].reverse()) writeImage(root, operation.path, operation.before);
|
|
1982
|
-
if (backup.oldAuthority && backup.newAuthority) {
|
|
1983
|
-
} else if (backup.oldManifest) {
|
|
1984
|
-
const manifestRel = manifestPath(backup.profile);
|
|
1985
|
-
const temp = localPath(root, `${manifestRel}.rollback-${backup.operationId}`);
|
|
1986
|
-
durableWrite(temp, Buffer.from(backup.oldManifest.data, "base64"));
|
|
1987
|
-
parseInstallationManifest(readFileSync3(temp, "utf8"));
|
|
1988
|
-
fs.renameSync(temp, localPath(root, manifestRel));
|
|
1989
|
-
} else {
|
|
1990
|
-
const manifestRel = manifestPath(backup.profile);
|
|
1991
|
-
if (existsSync3(localPath(root, manifestRel))) unlinkSync(localPath(root, manifestRel));
|
|
1992
|
-
}
|
|
1993
|
-
hitPhase(options, "complete", { operationId: backup.operationId, journalPath: descriptorPath });
|
|
1994
|
-
return { status: "rolled-back", operationId: backup.operationId, backupPath: localPath(root, backup.backupRelative), diagnostics: [], conflicts: [] };
|
|
1995
|
-
} finally {
|
|
1996
|
-
unlock(handle);
|
|
1997
|
-
}
|
|
1998
|
-
}
|
|
1999
|
-
|
|
2000
|
-
// src/package-version.ts
|
|
2001
|
-
import { readFileSync as readFileSync4 } from "fs";
|
|
2002
|
-
import { fileURLToPath } from "url";
|
|
2003
|
-
import { dirname as dirname2, join as join4 } from "path";
|
|
2004
|
-
var __dirname = dirname2(fileURLToPath(import.meta.url));
|
|
2005
|
-
function getPackageVersion() {
|
|
2006
|
-
const pkgPath = join4(__dirname, "..", "package.json");
|
|
2007
|
-
const raw = readFileSync4(pkgPath, "utf-8");
|
|
2008
|
-
const pkg = JSON.parse(raw);
|
|
2009
|
-
if (typeof pkg.version !== "string" || pkg.version.length === 0) {
|
|
2010
|
-
throw new Error(`Joycraft package.json at ${pkgPath} is missing a version field`);
|
|
2011
|
-
}
|
|
2012
|
-
return pkg.version;
|
|
2013
|
-
}
|
|
2014
|
-
|
|
2015
|
-
// src/gitattributes.ts
|
|
2016
|
-
import { existsSync as existsSync4, readFileSync as readFileSync5, writeFileSync as writeFileSync3 } from "fs";
|
|
2017
|
-
import { join as join5 } from "path";
|
|
2018
|
-
var GITATTRIBUTES_COMMENT = "# Joycraft: collapse generated workflow docs in PR review (expand with one click)";
|
|
2019
|
-
var GITATTRIBUTES_ENTRIES = [
|
|
2020
|
-
"docs/features/** linguist-generated=true",
|
|
2021
|
-
"docs/bugfixes/** linguist-generated=true",
|
|
2022
|
-
"docs/discoveries/** linguist-generated=true",
|
|
2023
|
-
"docs/templates/** linguist-generated=true"
|
|
2024
|
-
];
|
|
2025
|
-
function planGitattributes(current) {
|
|
2026
|
-
const present = new Set(current.split("\n").map((line) => line.trim()));
|
|
2027
|
-
const missing = GITATTRIBUTES_ENTRIES.filter((entry) => !present.has(entry.trim()));
|
|
2028
|
-
if (missing.length === 0) return { content: current, added: [] };
|
|
2029
|
-
const lines = present.has(GITATTRIBUTES_COMMENT) ? missing : [GITATTRIBUTES_COMMENT, ...missing];
|
|
2030
|
-
const separator = current.length > 0 && !current.endsWith("\n") ? "\n" : "";
|
|
2031
|
-
return { content: current + separator + lines.join("\n") + "\n", added: missing };
|
|
2032
|
-
}
|
|
2033
|
-
|
|
2034
|
-
// src/auto-memory.ts
|
|
2035
|
-
import { createInterface } from "readline";
|
|
2036
|
-
var AUTO_MEMORY_KEY = "autoMemoryEnabled";
|
|
2037
|
-
function parseAutoMemoryAnswer(answer) {
|
|
2038
|
-
const normalized2 = answer.trim().toLowerCase();
|
|
2039
|
-
if (normalized2 === "") return false;
|
|
2040
|
-
if (normalized2 === "y" || normalized2 === "yes") return true;
|
|
2041
|
-
if (normalized2 === "n" || normalized2 === "no") return false;
|
|
2042
|
-
return null;
|
|
2043
|
-
}
|
|
2044
|
-
function promptAutoMemory() {
|
|
2045
|
-
console.log("\nJoycraft keeps project facts in one home: your repo.");
|
|
2046
|
-
console.log(
|
|
2047
|
-
" Claude Code auto-memory is a second, per-machine home for the same facts."
|
|
2048
|
-
);
|
|
2049
|
-
console.log(
|
|
2050
|
-
` Disabling it for this project writes "${AUTO_MEMORY_KEY}": false to .claude/settings.json.`
|
|
2051
|
-
);
|
|
2052
|
-
console.log(" Your other projects are unaffected.");
|
|
2053
|
-
const input = process.stdin;
|
|
2054
|
-
if (input.readableEnded === true || input.destroyed === true) {
|
|
2055
|
-
return Promise.resolve(false);
|
|
2056
|
-
}
|
|
2057
|
-
return new Promise((resolve2) => {
|
|
2058
|
-
const rl = createInterface({ input, output: process.stdout });
|
|
2059
|
-
let settled = false;
|
|
2060
|
-
const done = (value) => {
|
|
2061
|
-
if (settled) return;
|
|
2062
|
-
settled = true;
|
|
2063
|
-
rl.close();
|
|
2064
|
-
resolve2(value);
|
|
2065
|
-
};
|
|
2066
|
-
rl.once("close", () => done(false));
|
|
2067
|
-
const ask2 = (attempt) => {
|
|
2068
|
-
rl.question("Disable auto-memory for this project? [y/N]: ", (answer) => {
|
|
2069
|
-
const parsed = parseAutoMemoryAnswer(answer);
|
|
2070
|
-
if (parsed !== null) {
|
|
2071
|
-
done(parsed);
|
|
2072
|
-
return;
|
|
2073
|
-
}
|
|
2074
|
-
if (attempt >= 4) {
|
|
2075
|
-
done(false);
|
|
2076
|
-
return;
|
|
2077
|
-
}
|
|
2078
|
-
console.log(`Unrecognized answer '${answer.trim()}' \u2014 type 'y' or 'n', or press Enter for no change.`);
|
|
2079
|
-
ask2(attempt + 1);
|
|
2080
|
-
});
|
|
2081
|
-
};
|
|
2082
|
-
ask2(0);
|
|
2083
|
-
});
|
|
2084
|
-
}
|
|
2085
|
-
async function resolveAutoMemoryOffer(interactive2) {
|
|
2086
|
-
if (!interactive2) return false;
|
|
2087
|
-
return promptAutoMemory();
|
|
2088
|
-
}
|
|
2089
|
-
|
|
2090
|
-
// src/execution-profile.ts
|
|
2091
|
-
import { createInterface as createInterface2 } from "readline";
|
|
2092
|
-
var EXECUTION_PROFILE_OPEN = "<!-- joycraft:execution-profile -->";
|
|
2093
|
-
var EXECUTION_PROFILE_CLOSE = "<!-- /joycraft:execution-profile -->";
|
|
2094
|
-
var EXECUTION_PROFILE_HEADING = "## Execution Profile";
|
|
2095
|
-
var SESSION_DEFAULT = "session default";
|
|
2096
|
-
function defaultExecutionProfile(harnesses) {
|
|
2097
|
-
return {
|
|
2098
|
-
entries: harnesses.map((harness) => ({
|
|
2099
|
-
harness,
|
|
2100
|
-
swarmDecompose: false,
|
|
2101
|
-
swarmImplement: false,
|
|
2102
|
-
model: SESSION_DEFAULT,
|
|
2103
|
-
effort: SESSION_DEFAULT
|
|
2104
|
-
}))
|
|
2105
|
-
};
|
|
2106
|
-
}
|
|
2107
|
-
function yn(value) {
|
|
2108
|
-
return value ? "yes" : "no";
|
|
2109
|
-
}
|
|
2110
|
-
function renderExecutionProfileSection(profile) {
|
|
2111
|
-
const lines = [EXECUTION_PROFILE_HEADING, "", EXECUTION_PROFILE_OPEN];
|
|
2112
|
-
for (const e of profile.entries) {
|
|
2113
|
-
lines.push(
|
|
2114
|
-
`- ${e.harness}: Swarms: decompose ${yn(e.swarmDecompose)} \xB7 implement ${yn(e.swarmImplement)} \xB7 model ${e.model} \xB7 effort ${e.effort}`
|
|
2115
|
-
);
|
|
2116
|
-
}
|
|
2117
|
-
lines.push(EXECUTION_PROFILE_CLOSE);
|
|
2118
|
-
return lines.join("\n");
|
|
2119
|
-
}
|
|
2120
|
-
function ask(question) {
|
|
2121
|
-
return new Promise((resolve2) => {
|
|
2122
|
-
const input = process.stdin;
|
|
2123
|
-
if (input.readableEnded === true || input.destroyed === true) {
|
|
2124
|
-
resolve2("");
|
|
2125
|
-
return;
|
|
2126
|
-
}
|
|
2127
|
-
const rl = createInterface2({ input, output: process.stdout });
|
|
2128
|
-
let settled = false;
|
|
2129
|
-
const done = (value) => {
|
|
2130
|
-
if (settled) return;
|
|
2131
|
-
settled = true;
|
|
2132
|
-
rl.close();
|
|
2133
|
-
resolve2(value);
|
|
2134
|
-
};
|
|
2135
|
-
rl.once("close", () => done(""));
|
|
2136
|
-
try {
|
|
2137
|
-
rl.question(question, (answer) => done(answer.trim()));
|
|
2138
|
-
} catch {
|
|
2139
|
-
done("");
|
|
2140
|
-
}
|
|
2141
|
-
});
|
|
2142
|
-
}
|
|
2143
|
-
async function askYesNo(question) {
|
|
2144
|
-
for (let attempt = 0; attempt < 5; attempt++) {
|
|
2145
|
-
const answer = (await ask(`${question} [y/N]: `)).toLowerCase();
|
|
2146
|
-
if (answer === "" || answer === "n" || answer === "no") return false;
|
|
2147
|
-
if (answer === "y" || answer === "yes") return true;
|
|
2148
|
-
console.log("Please answer 'y' or 'n'.");
|
|
2149
|
-
}
|
|
2150
|
-
return false;
|
|
2151
|
-
}
|
|
2152
|
-
async function promptExecutionProfileInteractive(harnesses) {
|
|
2153
|
-
console.log("\nExecution profile \u2014 how should agents run on this project?");
|
|
2154
|
-
console.log(" (Recorded in AGENTS.md as data. Press Enter to accept the default.)");
|
|
2155
|
-
const entries = [];
|
|
2156
|
-
for (const harness of harnesses) {
|
|
2157
|
-
console.log(`
|
|
2158
|
-
${harness}:`);
|
|
2159
|
-
const swarmDecompose = await askYesNo(" Use swarms for decompose?");
|
|
2160
|
-
const swarmImplement = await askYesNo(" Use swarms for implement?");
|
|
2161
|
-
const model = await ask(` Model (${SESSION_DEFAULT}): `) || SESSION_DEFAULT;
|
|
2162
|
-
const effort = await ask(` Effort (${SESSION_DEFAULT}): `) || SESSION_DEFAULT;
|
|
2163
|
-
entries.push({ harness, swarmDecompose, swarmImplement, model, effort });
|
|
2164
|
-
}
|
|
2165
|
-
return { entries };
|
|
2166
|
-
}
|
|
2167
|
-
async function resolveExecutionProfile(harnesses, interactive2) {
|
|
2168
|
-
if (harnesses.length === 0) return { entries: [] };
|
|
2169
|
-
if (interactive2) return promptExecutionProfileInteractive(harnesses);
|
|
2170
|
-
return defaultExecutionProfile(harnesses);
|
|
2171
|
-
}
|
|
2172
|
-
|
|
2173
|
-
// src/update-inventory.ts
|
|
2174
|
-
import {
|
|
2175
|
-
lstatSync as lstatSync2,
|
|
2176
|
-
readFileSync as readFileSync7,
|
|
2177
|
-
readdirSync as readdirSync4,
|
|
2178
|
-
statSync as statSync2
|
|
2179
|
-
} from "fs";
|
|
2180
|
-
import { basename, join as join9 } from "path";
|
|
2181
|
-
|
|
2182
|
-
// src/folder-map.ts
|
|
2183
|
-
import { readdirSync as readdirSync3 } from "fs";
|
|
2184
|
-
import { join as join6 } from "path";
|
|
2185
|
-
var FOLDER_MAP_OPEN = "<!-- joycraft:folder-map -->";
|
|
2186
|
-
var FOLDER_MAP_CLOSE = "<!-- /joycraft:folder-map -->";
|
|
2187
|
-
var FOLDER_MAP_PLACEHOLDER = "_TODO: one line on what lives here_";
|
|
2188
|
-
var MAX_ROWS = 30;
|
|
2189
|
-
var SKIPPED_DIRS = /* @__PURE__ */ new Set([
|
|
2190
|
-
"node_modules",
|
|
2191
|
-
"dist",
|
|
2192
|
-
"build",
|
|
2193
|
-
"out",
|
|
2194
|
-
"coverage",
|
|
2195
|
-
"target",
|
|
2196
|
-
"vendor",
|
|
2197
|
-
"__pycache__",
|
|
2198
|
-
"venv",
|
|
2199
|
-
".venv",
|
|
2200
|
-
"tmp",
|
|
2201
|
-
"temp"
|
|
2202
|
-
]);
|
|
2203
|
-
var KEY_PARENTS = /* @__PURE__ */ new Set(["src", "docs"]);
|
|
2204
|
-
var KNOWN_DESCRIPTIONS = {
|
|
2205
|
-
"src/": "Source code",
|
|
2206
|
-
"docs/": "Documentation",
|
|
2207
|
-
"tests/": "Test suite",
|
|
2208
|
-
"test/": "Test suite",
|
|
2209
|
-
"scripts/": "Maintenance and build scripts",
|
|
2210
|
-
"templates/": "Templates",
|
|
2211
|
-
"public/": "Static assets served as-is",
|
|
2212
|
-
"assets/": "Static assets",
|
|
2213
|
-
"examples/": "Usage examples",
|
|
2214
|
-
"packages/": "Monorepo packages",
|
|
2215
|
-
"apps/": "Monorepo applications",
|
|
2216
|
-
"config/": "Configuration",
|
|
2217
|
-
"docs/context/": "Knowledge layer \u2014 operational fact-docs and reference",
|
|
2218
|
-
"docs/features/": "Per-feature briefs, designs, and atomic specs",
|
|
2219
|
-
"docs/discoveries/": "Session surprises worth remembering",
|
|
2220
|
-
"docs/templates/": "Bundled output and reference templates",
|
|
2221
|
-
"docs/backlog/": "Deferred work, one file per item",
|
|
2222
|
-
"docs/intent/": "Intent inbox \u2014 incoming work before a feature slug exists",
|
|
2223
|
-
"docs/research/": "Research notes and findings"
|
|
2224
|
-
};
|
|
2225
|
-
function listDirs(dir) {
|
|
2226
|
-
try {
|
|
2227
|
-
return readdirSync3(dir, { withFileTypes: true }).filter((e) => e.isDirectory() && !e.name.startsWith(".") && !SKIPPED_DIRS.has(e.name)).map((e) => e.name).sort();
|
|
2228
|
-
} catch {
|
|
2229
|
-
return [];
|
|
2230
|
-
}
|
|
2231
|
-
}
|
|
2232
|
-
function walkFolders(dir) {
|
|
2233
|
-
const tops = listDirs(dir);
|
|
2234
|
-
const folders = tops.map((top) => `${top}/`);
|
|
2235
|
-
for (const top of tops) {
|
|
2236
|
-
if (KEY_PARENTS.has(top)) {
|
|
2237
|
-
for (const sub of listDirs(join6(dir, top))) {
|
|
2238
|
-
folders.push(`${top}/${sub}/`);
|
|
2239
|
-
}
|
|
2240
|
-
}
|
|
2241
|
-
}
|
|
2242
|
-
const capped = folders.length > MAX_ROWS;
|
|
2243
|
-
return { folders: capped ? folders.slice(0, MAX_ROWS) : folders, capped };
|
|
2244
|
-
}
|
|
2245
|
-
function parseRows(block) {
|
|
2246
|
-
const rows = /* @__PURE__ */ new Map();
|
|
2247
|
-
for (const line of block.split("\n")) {
|
|
2248
|
-
const match = line.match(/^\| `([^`]+)` \| (.*) \|$/);
|
|
2249
|
-
if (match) rows.set(match[1], match[2]);
|
|
2250
|
-
}
|
|
2251
|
-
return rows;
|
|
2252
|
-
}
|
|
2253
|
-
function renderFolderMap(dir, existingBlock) {
|
|
2254
|
-
const { folders, capped } = walkFolders(dir);
|
|
2255
|
-
const previous = existingBlock ? parseRows(existingBlock) : /* @__PURE__ */ new Map();
|
|
2256
|
-
const lines = [FOLDER_MAP_OPEN, "| Folder | What lives here |", "|--------|-----------------|"];
|
|
2257
|
-
for (const folder of folders) {
|
|
2258
|
-
const description = previous.get(folder) ?? KNOWN_DESCRIPTIONS[folder] ?? FOLDER_MAP_PLACEHOLDER;
|
|
2259
|
-
lines.push(`| \`${folder}\` | ${description} |`);
|
|
2260
|
-
}
|
|
2261
|
-
if (capped) {
|
|
2262
|
-
lines.push("", `_Capped at ${MAX_ROWS} rows \u2014 this tree is past root-map scale; use the growth path below._`);
|
|
2263
|
-
}
|
|
2264
|
-
lines.push(
|
|
2265
|
-
"",
|
|
2266
|
-
"Past multi-team scale, replace this root map with nested per-directory instruction files (`joycraft-collaborative-setup`) \u2014 never a bigger tree.",
|
|
2267
|
-
FOLDER_MAP_CLOSE
|
|
2268
|
-
);
|
|
2269
|
-
return lines.join("\n");
|
|
2270
|
-
}
|
|
2271
|
-
var BLOCK_RE = new RegExp(`${FOLDER_MAP_OPEN}[\\s\\S]*?${FOLDER_MAP_CLOSE}`);
|
|
2272
|
-
|
|
2273
|
-
// src/improve-claude-md.ts
|
|
2274
|
-
import { existsSync as existsSync5 } from "fs";
|
|
2275
|
-
import { join as join7 } from "path";
|
|
2276
|
-
function nonEmptyLines(items) {
|
|
2277
|
-
return (items ?? []).map((s) => s.trim()).filter((s) => s.length > 0);
|
|
2278
|
-
}
|
|
2279
|
-
function glossaryEntries(glossary) {
|
|
2280
|
-
return Object.entries(glossary ?? []).map(([term, def]) => [term.trim(), def.trim()]).filter(([term, def]) => term.length > 0 && def.length > 0);
|
|
2281
|
-
}
|
|
2282
|
-
function generateProductIdentitySection(identity) {
|
|
2283
|
-
if (!identity) return null;
|
|
2284
|
-
const values = nonEmptyLines(identity.values);
|
|
2285
|
-
const taste = nonEmptyLines(identity.taste);
|
|
2286
|
-
const glossary = glossaryEntries(identity.glossary);
|
|
2287
|
-
if (values.length === 0 && taste.length === 0 && glossary.length === 0) return null;
|
|
2288
|
-
const today = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
|
|
2289
|
-
const parts = ["## Product Identity", "", `_Added ${today} \u2014 review at next optimize run_`];
|
|
2290
|
-
if (values.length > 0) {
|
|
2291
|
-
parts.push("", "### Values", "", ...values.map((v) => `- ${v}`));
|
|
2292
|
-
}
|
|
2293
|
-
if (glossary.length > 0) {
|
|
2294
|
-
parts.push("", "### Glossary", "", ...glossary.map(([term, def]) => `- **${term}** \u2014 ${def}`));
|
|
2295
|
-
}
|
|
2296
|
-
if (taste.length > 0) {
|
|
2297
|
-
parts.push("", "### Taste", "", ...taste.map((t) => `- ${t}`));
|
|
2298
|
-
}
|
|
2299
|
-
return parts.join("\n");
|
|
2300
|
-
}
|
|
2301
|
-
var PRIVATE_SETUP_NOTE_MARKER = "After cloning, run";
|
|
2302
|
-
function generatePrivateSetupNote() {
|
|
2303
|
-
return `> **Private setup:** The harness dirs (\`.claude/\`, \`.agents/\`, \`.pi/\`) are gitignored in this repo, so they aren't committed. ${PRIVATE_SETUP_NOTE_MARKER} \`npx joycraft init\` to regenerate the skill files locally \u2014 it only creates missing files and leaves your committed \`CLAUDE.md\`, \`AGENTS.md\`, and \`docs/\` untouched (use \`--force\` only if you deliberately want to regenerate them).`;
|
|
2304
|
-
}
|
|
2305
|
-
function generateCommandsBlock(stack) {
|
|
2306
|
-
const lines = ["```bash"];
|
|
2307
|
-
if (stack.commands.build) lines.push(`# Build
|
|
2308
|
-
${stack.commands.build}`);
|
|
2309
|
-
if (stack.commands.test) lines.push(`# Test
|
|
2310
|
-
${stack.commands.test}`);
|
|
2311
|
-
if (stack.commands.lint) lines.push(`# Lint
|
|
2312
|
-
${stack.commands.lint}`);
|
|
2313
|
-
if (stack.commands.typecheck) lines.push(`# Type check
|
|
2314
|
-
${stack.commands.typecheck}`);
|
|
2315
|
-
if (stack.commands.deploy) lines.push(`# Deploy
|
|
2316
|
-
${stack.commands.deploy}`);
|
|
2317
|
-
lines.push("```");
|
|
2318
|
-
return lines.join("\n");
|
|
2319
|
-
}
|
|
2320
|
-
function generateExternalApiSafetySection() {
|
|
2321
|
-
return "### External API Safety\n- Read official docs and type definitions before writing code against a third-party SDK\n- Add third-party SDKs as devDependencies so typecheck runs against real types, not stubs\n- Critical integration paths should have a smoke test that validates against the real runtime";
|
|
2322
|
-
}
|
|
2323
|
-
function generateClaudeMdPointer() {
|
|
2324
|
-
return `@AGENTS.md
|
|
2325
|
-
|
|
2326
|
-
## Claude Code
|
|
2327
|
-
|
|
2328
|
-
_Shared project instructions \u2014 boundaries, workflow, architecture \u2014 live in \`AGENTS.md\`, imported above so every AI tool reads the same source. Add Claude Code\u2013specific instructions in this section only._
|
|
2329
|
-
`;
|
|
2330
|
-
}
|
|
2331
|
-
function generateBoundariesSection() {
|
|
2332
|
-
return `## Behavioral Boundaries
|
|
2333
|
-
|
|
2334
|
-
### ALWAYS
|
|
2335
|
-
- Run tests and type-check before committing
|
|
2336
|
-
- Run tests before implementing new features -- confirm they fail first, then implement until they pass
|
|
2337
|
-
- Use \`verb: concise message\` format for commits
|
|
2338
|
-
- Commit after completing each discrete task (atomic commits)
|
|
2339
|
-
- Stage specific files by name (not \`git add -A\` or \`git add .\`)
|
|
2340
|
-
- Read \`docs/context/\` before making infrastructure or config changes
|
|
2341
|
-
- Follow existing code patterns and style
|
|
2342
|
-
|
|
2343
|
-
### ASK FIRST
|
|
2344
|
-
- Pushing to remote
|
|
2345
|
-
- Creating or merging pull requests
|
|
2346
|
-
- Adding new dependencies
|
|
2347
|
-
- Modifying database schema or data models
|
|
2348
|
-
- Changing authentication or authorization flows
|
|
2349
|
-
- Any destructive git operation (force-push, reset --hard, branch deletion)
|
|
2350
|
-
|
|
2351
|
-
### NEVER
|
|
2352
|
-
- Push directly to main/master without approval
|
|
2353
|
-
- Commit .env files, secrets, or credentials
|
|
2354
|
-
- Use --no-verify to skip hooks
|
|
2355
|
-
- Amend commits that have been pushed
|
|
2356
|
-
- Skip type-checking or linting
|
|
2357
|
-
- Commit code that doesn't build`;
|
|
2358
|
-
}
|
|
2359
|
-
function generateWorkflowSection(stack) {
|
|
2360
|
-
return `## Development Workflow
|
|
2361
|
-
|
|
2362
|
-
${generateCommandsBlock(stack)}
|
|
2363
|
-
|
|
2364
|
-
**Default execution mode:** batch
|
|
2365
|
-
|
|
2366
|
-
_How \`/joycraft-implement\` wraps up after each spec. \`joycraft-decompose\` reads this line (absent \u21D2 \`batch\`) and recommends a per-spec mode you approve. Modes: \`batch\` (implement a cluster, wrap once at the end), \`checkpoint\` (commit + status bump after each spec), \`isolated\` (fresh context per spec \u2014 on Pi, the \`joycraft-implement-loop\` driver). Change the value above to set your project default._
|
|
2367
|
-
|
|
2368
|
-
**Deferred work \u2192 \`docs/backlog/\`.** Ideas and follow-ups you surface mid-sprint but can't take on now go to \`docs/backlog/\` (one file per item) so the current spec stays focused without losing the thread. Promote an entry to a Feature Brief under \`docs/features/<slug>/\` when you're ready to build it.`;
|
|
2369
|
-
}
|
|
2370
|
-
function generateArchitectureSection(projectDir) {
|
|
2371
|
-
if (projectDir) {
|
|
2372
|
-
return `## Architecture
|
|
2373
|
-
|
|
2374
|
-
${renderFolderMap(projectDir)}`;
|
|
2375
|
-
}
|
|
2376
|
-
return `## Architecture
|
|
2377
|
-
|
|
2378
|
-
_TODO: Add a brief description of your project's architecture and key directories._`;
|
|
2379
|
-
}
|
|
2380
|
-
function generateKeyFilesSection() {
|
|
2381
|
-
return `## Key Files
|
|
2382
|
-
|
|
2383
|
-
| File | Purpose |
|
|
2384
|
-
|------|---------|
|
|
2385
|
-
| _TODO_ | _Add key files and their purposes_ |`;
|
|
2386
|
-
}
|
|
2387
|
-
function generateGotchasSection() {
|
|
2388
|
-
return `## Common Gotchas
|
|
2389
|
-
|
|
2390
|
-
_TODO: Add any gotchas, quirks, or non-obvious behaviors that developers should know about._`;
|
|
2391
|
-
}
|
|
2392
|
-
function generateGettingStartedSection(multiTool = false) {
|
|
2393
|
-
const invocationNote = multiTool ? "\n\nSkill names are shared across tools; only the invocation prefix differs: `/joycraft-*` (Claude Code), `$joycraft-*` (Codex), `/skill:joycraft-*` (Pi)." : "";
|
|
2394
|
-
return `## Getting Started with Joycraft
|
|
2395
|
-
|
|
2396
|
-
This project uses [Joycraft](https://github.com/maksutovic/joycraft) for AI development workflow. Available skills:
|
|
2397
|
-
|
|
2398
|
-
| Skill | Purpose |
|
|
2399
|
-
|-------|---------|
|
|
2400
|
-
| \`/joycraft-setup\` | Start here \u2014 the first-run door; sets up and assesses your project |
|
|
2401
|
-
| \`/joycraft-tune\` | Assess your harness, apply upgrades, see your maturity roadmap |
|
|
2402
|
-
| \`/joycraft-new-feature\` | Interview -> Feature Brief -> Atomic Specs |
|
|
2403
|
-
| \`/joycraft-interview\` | Lightweight brainstorm \u2014 yap about ideas, get a structured summary |
|
|
2404
|
-
| \`/joycraft-decompose\` | Break a brief into small, testable specs |
|
|
2405
|
-
| \`/joycraft-session-end\` | Capture discoveries, verify, commit |
|
|
2406
|
-
| \`/joycraft-implement-level5\` | Experimental \u2014 Level 5 autofix loop, holdout scenarios, scenario evolution |
|
|
2407
|
-
|
|
2408
|
-
Run \`/joycraft-tune\` to see where your project stands and what to improve next.${invocationNote}`;
|
|
2409
|
-
}
|
|
2410
|
-
var CONTEXT_MAP_TABLE_HEADER = "| Document | Read it when\u2026 |\n|----------|---------------|";
|
|
2411
|
-
function generateContextMapSection(modelProfilePointer = false) {
|
|
2412
|
-
const row = modelProfilePointer ? `
|
|
2413
|
-
${MODEL_PROFILE_CONTEXT_MAP_ROW}` : "";
|
|
2414
|
-
return `## Context Map
|
|
2415
|
-
|
|
2416
|
-
Keep this file lean \u2014 link out, don't inline. Long-form reference docs live in \`docs/context/reference/\`; this table points to what to read on demand.
|
|
2417
|
-
|
|
2418
|
-
${CONTEXT_MAP_TABLE_HEADER}${row}`;
|
|
2419
|
-
}
|
|
2420
|
-
function sourceLines(content) {
|
|
2421
|
-
const lines = [];
|
|
2422
|
-
let offset = 0;
|
|
2423
|
-
while (offset < content.length) {
|
|
2424
|
-
const newline = content.indexOf("\n", offset);
|
|
2425
|
-
const end = newline === -1 ? content.length : newline + 1;
|
|
2426
|
-
const raw = content.slice(offset, newline === -1 ? content.length : newline);
|
|
2427
|
-
lines.push({ text: raw.replace(/\r$/, ""), start: offset, end });
|
|
2428
|
-
offset = end;
|
|
2429
|
-
}
|
|
2430
|
-
return lines;
|
|
2431
|
-
}
|
|
2432
|
-
function insertAfterLine(content, line, block, newline) {
|
|
2433
|
-
if (content[line.end - 1] === "\n") {
|
|
2434
|
-
return content.slice(0, line.end) + block + newline + content.slice(line.end);
|
|
2435
|
-
}
|
|
2436
|
-
return content + newline + block;
|
|
2437
|
-
}
|
|
2438
|
-
function insertModelProfilePointer(content) {
|
|
2439
|
-
if (content.includes(MODEL_PROFILE_PATH)) return content;
|
|
2440
|
-
const newline = content.includes("\r\n") ? "\r\n" : "\n";
|
|
2441
|
-
const lines = sourceLines(content);
|
|
2442
|
-
const header = lines.findIndex((line) => line.text.startsWith("## ") && /context\s*map/i.test(line.text));
|
|
2443
|
-
if (header === -1) {
|
|
2444
|
-
const section = generateContextMapSection(true).replace(/\n/g, newline);
|
|
2445
|
-
if (content === "") return section + newline;
|
|
2446
|
-
const base = content.endsWith("\n") ? content : content + newline;
|
|
2447
|
-
return base + newline + section + newline;
|
|
2448
|
-
}
|
|
2449
|
-
let sectionEnd = lines.length;
|
|
2450
|
-
for (let index = header + 1; index < lines.length; index++) {
|
|
2451
|
-
if (lines[index].text.startsWith("## ")) {
|
|
2452
|
-
sectionEnd = index;
|
|
2453
|
-
break;
|
|
2454
|
-
}
|
|
2455
|
-
}
|
|
2456
|
-
const isTableLine = (index) => lines[index].text.trim().startsWith("|");
|
|
2457
|
-
let tableStart = -1;
|
|
2458
|
-
for (let index = header + 1; index < sectionEnd; index++) {
|
|
2459
|
-
if (isTableLine(index)) {
|
|
2460
|
-
tableStart = index;
|
|
2461
|
-
break;
|
|
2462
|
-
}
|
|
2463
|
-
}
|
|
2464
|
-
if (tableStart !== -1) {
|
|
2465
|
-
let last = tableStart;
|
|
2466
|
-
while (last + 1 < sectionEnd && isTableLine(last + 1)) last++;
|
|
2467
|
-
return insertAfterLine(content, lines[last], MODEL_PROFILE_CONTEXT_MAP_ROW, newline);
|
|
2468
|
-
}
|
|
2469
|
-
let lastContent = header;
|
|
2470
|
-
for (let index = header + 1; index < sectionEnd; index++) {
|
|
2471
|
-
if (lines[index].text.trim() !== "") lastContent = index;
|
|
2472
|
-
}
|
|
2473
|
-
const table = ["", ...CONTEXT_MAP_TABLE_HEADER.split("\n"), MODEL_PROFILE_CONTEXT_MAP_ROW].join(newline);
|
|
2474
|
-
return insertAfterLine(content, lines[lastContent], table, newline);
|
|
2475
|
-
}
|
|
2476
|
-
function generateAreasSection() {
|
|
2477
|
-
return `## Areas
|
|
2478
|
-
|
|
2479
|
-
This project organizes some work by area. When working on a specific area, read its README first; check for area-specific boundaries.
|
|
2480
|
-
|
|
2481
|
-
- For each area: see \`docs/areas/<area-name>/README.md\`
|
|
2482
|
-
- Area-level boundaries (when present): \`docs/areas/<area-name>/boundaries.md\``;
|
|
2483
|
-
}
|
|
2484
|
-
function projectHasAreas(opts) {
|
|
2485
|
-
if (!opts?.projectDir) return false;
|
|
2486
|
-
return existsSync5(join7(opts.projectDir, "docs", "areas"));
|
|
2487
|
-
}
|
|
2488
|
-
function generateProjectToolsSection(existingSkills) {
|
|
2489
|
-
const MAX_LISTED = 10;
|
|
2490
|
-
let skillList;
|
|
2491
|
-
if (existingSkills.length <= MAX_LISTED) {
|
|
2492
|
-
skillList = existingSkills.join(", ");
|
|
2493
|
-
} else {
|
|
2494
|
-
skillList = existingSkills.slice(0, MAX_LISTED).join(", ") + `, and ${existingSkills.length - MAX_LISTED} more \u2014 see .claude/skills/`;
|
|
2495
|
-
}
|
|
2496
|
-
return `## Project Tools
|
|
2497
|
-
|
|
2498
|
-
This project has additional tools beyond Joycraft. Always check \`.claude/skills/\` for available skills: ${skillList}`;
|
|
2499
|
-
}
|
|
2500
|
-
function generateCLAUDEMd(projectName2, stack, existingSkills = [], opts) {
|
|
2501
|
-
const frameworkNote = stack.framework ? ` (${stack.framework})` : "";
|
|
2502
|
-
const langLabel = stack.language === "unknown" ? "" : ` | **Stack:** ${stack.language}${frameworkNote}`;
|
|
2503
|
-
const lines = [
|
|
2504
|
-
`# ${projectName2}`,
|
|
2505
|
-
"",
|
|
2506
|
-
`**Component:** _TODO: describe what this project is_${langLabel}`,
|
|
2507
|
-
"",
|
|
2508
|
-
"---",
|
|
2509
|
-
"",
|
|
2510
|
-
generateBoundariesSection(),
|
|
2511
|
-
""
|
|
2512
|
-
];
|
|
2513
|
-
if (opts?.multiTool) {
|
|
2514
|
-
lines.push(generateExternalApiSafetySection(), "");
|
|
2515
|
-
}
|
|
2516
|
-
lines.push(
|
|
2517
|
-
generateWorkflowSection(stack),
|
|
2518
|
-
"",
|
|
2519
|
-
generateArchitectureSection(opts?.projectDir),
|
|
2520
|
-
"",
|
|
2521
|
-
generateKeyFilesSection(),
|
|
2522
|
-
"",
|
|
2523
|
-
generateGotchasSection(),
|
|
2524
|
-
"",
|
|
2525
|
-
generateContextMapSection(opts?.modelProfilePointer === true),
|
|
2526
|
-
"",
|
|
2527
|
-
generateGettingStartedSection(opts?.multiTool ?? false),
|
|
2528
|
-
""
|
|
2529
|
-
);
|
|
2530
|
-
const identitySection = generateProductIdentitySection(opts?.identity);
|
|
2531
|
-
if (identitySection) {
|
|
2532
|
-
lines.push(identitySection, "");
|
|
2533
|
-
}
|
|
2534
|
-
if (opts?.executionProfile) {
|
|
2535
|
-
lines.push(renderExecutionProfileSection(opts.executionProfile), "");
|
|
2536
|
-
}
|
|
2537
|
-
if (opts?.privateProfile) {
|
|
2538
|
-
lines.push(generatePrivateSetupNote(), "");
|
|
2539
|
-
}
|
|
2540
|
-
if (existingSkills.length > 0) {
|
|
2541
|
-
lines.push(generateProjectToolsSection(existingSkills), "");
|
|
2542
|
-
}
|
|
2543
|
-
if (projectHasAreas(opts)) {
|
|
2544
|
-
lines.push(generateAreasSection(), "");
|
|
2545
|
-
}
|
|
2546
|
-
return lines.join("\n");
|
|
2547
|
-
}
|
|
2548
|
-
|
|
2549
|
-
// src/agents-md.ts
|
|
2550
|
-
function generateCommandsBlock2(stack) {
|
|
2551
|
-
const lines = ["```bash"];
|
|
2552
|
-
if (stack.commands.build) lines.push(stack.commands.build);
|
|
2553
|
-
if (stack.commands.test) lines.push(stack.commands.test);
|
|
2554
|
-
if (stack.commands.lint) lines.push(stack.commands.lint);
|
|
2555
|
-
if (stack.commands.typecheck) lines.push(stack.commands.typecheck);
|
|
2556
|
-
if (stack.commands.deploy) lines.push(stack.commands.deploy);
|
|
2557
|
-
lines.push("```");
|
|
2558
|
-
return lines.join("\n");
|
|
2559
|
-
}
|
|
2560
|
-
function generateDevelopmentSection(stack) {
|
|
2561
|
-
return `## Development
|
|
2562
|
-
|
|
2563
|
-
${generateCommandsBlock2(stack)}
|
|
2564
|
-
|
|
2565
|
-
**Deferred work \u2192 \`docs/backlog/\`.** Ideas and follow-ups surfaced mid-sprint that can't be taken on now go to \`docs/backlog/\` (one file per item) so the current spec stays focused. Promote an entry to a Feature Brief under \`docs/features/<slug>/\` when ready to build it.`;
|
|
2566
|
-
}
|
|
2567
|
-
function generateArchitectureSection2(projectDir) {
|
|
2568
|
-
if (projectDir) {
|
|
2569
|
-
return `## Architecture
|
|
2570
|
-
|
|
2571
|
-
${renderFolderMap(projectDir)}`;
|
|
2572
|
-
}
|
|
2573
|
-
return `## Architecture
|
|
2574
|
-
|
|
2575
|
-
_TODO: Add a compact directory tree and one-paragraph summary._`;
|
|
2576
|
-
}
|
|
2577
|
-
function generateKeyFilesSection2() {
|
|
2578
|
-
return `## Key Files
|
|
2579
|
-
|
|
2580
|
-
| File | Purpose |
|
|
2581
|
-
|------|---------|
|
|
2582
|
-
| _TODO_ | _Add key files_ |`;
|
|
2583
|
-
}
|
|
2584
|
-
function generateAgentsMd(projectName2, stack, privateProfile = false, executionProfile, identity, projectDir, modelProfilePointer = false) {
|
|
2585
|
-
const frameworkNote = stack.framework ? ` (${stack.framework})` : "";
|
|
2586
|
-
const langLabel = stack.language === "unknown" ? "" : ` | **Stack:** ${stack.language}${frameworkNote}`;
|
|
2587
|
-
const lines = [
|
|
2588
|
-
`# ${projectName2}`,
|
|
2589
|
-
"",
|
|
2590
|
-
`**Component:** _TODO: describe what this project is_${langLabel}`,
|
|
2591
|
-
"",
|
|
2592
|
-
"> Auto-generated by Joycraft.",
|
|
2593
|
-
"",
|
|
2594
|
-
"---",
|
|
2595
|
-
"",
|
|
2596
|
-
generateBoundariesSection(),
|
|
2597
|
-
generateExternalApiSafetySection(),
|
|
2598
|
-
"",
|
|
2599
|
-
generateArchitectureSection2(projectDir),
|
|
2600
|
-
"",
|
|
2601
|
-
generateKeyFilesSection2(),
|
|
2602
|
-
"",
|
|
2603
|
-
generateDevelopmentSection(stack),
|
|
2604
|
-
""
|
|
2605
|
-
];
|
|
2606
|
-
if (modelProfilePointer) {
|
|
2607
|
-
lines.push(generateContextMapSection(true), "");
|
|
2608
|
-
}
|
|
2609
|
-
const identitySection = generateProductIdentitySection(identity);
|
|
2610
|
-
if (identitySection) {
|
|
2611
|
-
lines.push(identitySection, "");
|
|
2612
|
-
}
|
|
2613
|
-
if (executionProfile) {
|
|
2614
|
-
lines.push(renderExecutionProfileSection(executionProfile), "");
|
|
2615
|
-
}
|
|
2616
|
-
if (privateProfile) {
|
|
2617
|
-
lines.push(generatePrivateSetupNote(), "");
|
|
2618
|
-
}
|
|
2619
|
-
return lines.join("\n");
|
|
2620
|
-
}
|
|
2621
|
-
|
|
2622
|
-
// src/permissions.ts
|
|
2623
|
-
function generatePermissions(stack) {
|
|
2624
|
-
const deny = [
|
|
2625
|
-
"Bash(rm -rf *)",
|
|
2626
|
-
"Bash(git push --force *)",
|
|
2627
|
-
"Bash(git push -f *)",
|
|
2628
|
-
"Bash(git reset --hard *)",
|
|
2629
|
-
"Edit(//.env*)",
|
|
2630
|
-
"Edit(//*.pem)",
|
|
2631
|
-
"Edit(//*.key)",
|
|
2632
|
-
"Edit(//.git/**)"
|
|
2633
|
-
];
|
|
2634
|
-
const allow = [
|
|
2635
|
-
"Bash(git status)",
|
|
2636
|
-
"Bash(git diff *)",
|
|
2637
|
-
"Bash(git log *)",
|
|
2638
|
-
"Bash(git add *)",
|
|
2639
|
-
"Bash(git commit *)",
|
|
2640
|
-
"Bash(git checkout *)",
|
|
2641
|
-
"Bash(git branch *)"
|
|
2642
|
-
];
|
|
2643
|
-
if (stack.language === "node") {
|
|
2644
|
-
allow.push(`Bash(${stack.packageManager} *)`);
|
|
2645
|
-
if (stack.packageManager !== "npm") deny.push("Bash(npm install *)");
|
|
2646
|
-
if (stack.packageManager !== "yarn") deny.push("Bash(yarn add *)");
|
|
2647
|
-
if (stack.packageManager !== "pnpm") deny.push("Bash(pnpm add *)");
|
|
2648
|
-
if (stack.packageManager !== "bun") deny.push("Bash(bun add *)");
|
|
2649
|
-
if (stack.commands.test) allow.push(`Bash(${stack.commands.test})`);
|
|
2650
|
-
if (stack.commands.build) allow.push(`Bash(${stack.commands.build})`);
|
|
2651
|
-
if (stack.commands.lint) allow.push(`Bash(${stack.commands.lint})`);
|
|
2652
|
-
if (stack.commands.typecheck) allow.push(`Bash(${stack.commands.typecheck})`);
|
|
2653
|
-
}
|
|
2654
|
-
if (stack.language === "python") {
|
|
2655
|
-
allow.push(`Bash(${stack.packageManager} *)`);
|
|
2656
|
-
if (stack.commands.test) allow.push(`Bash(${stack.commands.test})`);
|
|
2657
|
-
if (stack.commands.lint) allow.push(`Bash(${stack.commands.lint})`);
|
|
2658
|
-
if (stack.commands.build) allow.push(`Bash(${stack.commands.build})`);
|
|
2659
|
-
}
|
|
2660
|
-
if (stack.language === "rust") {
|
|
2661
|
-
allow.push("Bash(cargo *)");
|
|
2662
|
-
}
|
|
2663
|
-
if (stack.language === "go") {
|
|
2664
|
-
allow.push("Bash(go *)");
|
|
2665
|
-
}
|
|
2666
|
-
if (stack.language === "swift") {
|
|
2667
|
-
allow.push("Bash(swift *)");
|
|
2668
|
-
allow.push("Bash(xcodebuild *)");
|
|
2669
|
-
}
|
|
2670
|
-
return { allow, deny };
|
|
2671
|
-
}
|
|
2672
|
-
|
|
2673
|
-
// src/tsconfig.ts
|
|
2674
|
-
import { existsSync as existsSync6, readFileSync as readFileSync6, writeFileSync as writeFileSync4 } from "fs";
|
|
2675
|
-
import { join as join8 } from "path";
|
|
2676
|
-
var PI_EXCLUDE = ".pi";
|
|
2677
|
-
function stripJsonComments(text2) {
|
|
2678
|
-
return text2.replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[^:])\/\/.*$/gm, "$1");
|
|
2679
|
-
}
|
|
2680
|
-
function alreadyExcludesPi(rawText) {
|
|
2681
|
-
try {
|
|
2682
|
-
const parsed = JSON.parse(stripJsonComments(rawText));
|
|
2683
|
-
if (!Array.isArray(parsed.exclude)) return false;
|
|
2684
|
-
return parsed.exclude.some(
|
|
2685
|
-
(e) => typeof e === "string" && (e === PI_EXCLUDE || e === "./.pi" || e === ".pi/**")
|
|
2686
|
-
);
|
|
2687
|
-
} catch {
|
|
2688
|
-
return false;
|
|
2689
|
-
}
|
|
2690
|
-
}
|
|
2691
|
-
function insertPiExclude(rawText) {
|
|
2692
|
-
const excludeArrayRe = /("exclude"\s*:\s*\[)(\s*)/;
|
|
2693
|
-
if (excludeArrayRe.test(rawText)) {
|
|
2694
|
-
return rawText.replace(excludeArrayRe, (_m, open, ws) => {
|
|
2695
|
-
const sep = ws.includes("\n") ? ws : " ";
|
|
2696
|
-
return `${open}${sep}"${PI_EXCLUDE}",${ws.includes("\n") ? "" : " "}`;
|
|
2697
|
-
});
|
|
2698
|
-
}
|
|
2699
|
-
const includeArrayRe = /("include"\s*:\s*\[[^\]]*\])/;
|
|
2700
|
-
if (includeArrayRe.test(rawText)) {
|
|
2701
|
-
return rawText.replace(includeArrayRe, (m) => `${m},
|
|
2702
|
-
"exclude": ["${PI_EXCLUDE}"]`);
|
|
2703
|
-
}
|
|
2704
|
-
const lastBrace = rawText.lastIndexOf("}");
|
|
2705
|
-
if (lastBrace > 0 && rawText.slice(0, lastBrace).includes(":")) {
|
|
2706
|
-
const before = rawText.slice(0, lastBrace).replace(/\s*$/, "");
|
|
2707
|
-
const after = rawText.slice(lastBrace);
|
|
2708
|
-
const needsComma = !before.endsWith(",") && !before.endsWith("{");
|
|
2709
|
-
return `${before}${needsComma ? "," : ""}
|
|
2710
|
-
"exclude": ["${PI_EXCLUDE}"]
|
|
2711
|
-
${after}`;
|
|
2712
|
-
}
|
|
2713
|
-
return null;
|
|
2714
|
-
}
|
|
2715
|
-
function planPiExcludedFromTsconfig(rawText) {
|
|
2716
|
-
if (alreadyExcludesPi(rawText)) return { status: "already-present" };
|
|
2717
|
-
const updated = insertPiExclude(rawText);
|
|
2718
|
-
if (updated === null || updated === rawText) {
|
|
2719
|
-
return {
|
|
2720
|
-
status: "skipped",
|
|
2721
|
-
reason: 'could not safely edit tsconfig.json \u2014 add ".pi" to its "exclude" array manually so the Pi extension stays out of your TypeScript build'
|
|
2722
|
-
};
|
|
2723
|
-
}
|
|
2724
|
-
if (!alreadyExcludesPi(updated)) {
|
|
2725
|
-
return {
|
|
2726
|
-
status: "skipped",
|
|
2727
|
-
reason: 'tsconfig.json edit could not be verified \u2014 add ".pi" to its "exclude" array manually'
|
|
2728
|
-
};
|
|
2729
|
-
}
|
|
2730
|
-
return { status: "added", content: updated };
|
|
2731
|
-
}
|
|
2732
|
-
|
|
2733
|
-
// src/update-inventory.ts
|
|
2734
|
-
var BACKLOG_README = `# Backlog
|
|
2735
|
-
|
|
2736
|
-
Deferred work lives here \u2014 ideas and follow-ups you surface mid-sprint but
|
|
2737
|
-
can't take on in the current feature. Capturing them keeps the current spec
|
|
2738
|
-
focused without losing the thread.
|
|
2739
|
-
|
|
2740
|
-
- One file per item: \`docs/backlog/YYYY-MM-DD-<short-name>.md\`.
|
|
2741
|
-
- Joycraft skills (\`/joycraft-interview\`, \`/joycraft-new-feature\`,
|
|
2742
|
-
\`/joycraft-design\`) offer to write entries here \u2014 always with your
|
|
2743
|
-
confirmation, never automatically.
|
|
2744
|
-
- Promote an item by turning it into a Feature Brief under
|
|
2745
|
-
\`docs/features/<slug>/\` when you're ready to build it.
|
|
2746
|
-
`;
|
|
2747
|
-
var INTENT_README = `# Intent inbox
|
|
2748
|
-
|
|
2749
|
-
An intent is a short note that describes a need before anyone commits to
|
|
2750
|
-
building it: a customer bug, a product idea, a ticket from another system, or
|
|
2751
|
-
an alert. Put intents here, one file per intent. Nothing needs to decide on a
|
|
2752
|
-
feature name first.
|
|
2753
|
-
|
|
2754
|
-
- One file per intent: \`docs/intent/YYYY-MM-DD-<short-name>.md\`.
|
|
2755
|
-
- Use the shape in \`docs/templates/INTENT_TEMPLATE.md\`: Author, Status,
|
|
2756
|
-
\`source\`, Problem, Proposed outcome, Affected users and systems,
|
|
2757
|
-
Constraints, Open questions.
|
|
2758
|
-
- A new intent starts with \`Status: untriaged\`. Joycraft skills update that
|
|
2759
|
-
line when they triage or consume the intent. The file stays here afterwards.
|
|
2760
|
-
- \`source:\` records where the intent came from, for example \`human\`,
|
|
2761
|
-
\`interview\`, \`linear:<id>\`, or \`alert:<name>\`. It is free text.
|
|
2762
|
-
|
|
2763
|
-
## How intents map to Joycraft artifacts
|
|
2764
|
-
|
|
2765
|
-
Anthropic's AI-native development playbook names a chain of artifacts. Joycraft
|
|
2766
|
-
already has most of them under its own names. Nothing is renamed. Use the
|
|
2767
|
-
Joycraft names below.
|
|
2768
|
-
|
|
2769
|
-
| Playbook term | Joycraft artifact | Where it lives |
|
|
2770
|
-
|---------------|-------------------|----------------|
|
|
2771
|
-
| intent | intent | \`docs/intent/<name>.md\` |
|
|
2772
|
-
| spec | brief | \`docs/features/<slug>/brief.md\` |
|
|
2773
|
-
| plan | design + atomic specs | \`docs/features/<slug>/design.md\` and \`docs/features/<slug>/specs/\` |
|
|
2774
|
-
|
|
2775
|
-
An intent becomes a brief through \`/joycraft-new-feature\`, or a bugfix spec
|
|
2776
|
-
through \`/joycraft-bugfix\`. The brief, design, and specs keep their current
|
|
2777
|
-
names and folders.
|
|
2778
|
-
`;
|
|
2779
|
-
var CLAUDE_SETTINGS = ".claude/settings.json";
|
|
2780
|
-
var TS_CONFIG = "tsconfig.json";
|
|
2781
|
-
var KNOWN_GENERATED_DOCUMENTS = /* @__PURE__ */ new Set(["CLAUDE.md", "AGENTS.md"]);
|
|
2782
|
-
var SAFE_GUARD_HOOK = ".claude/hooks/joycraft/block-dangerous.sh";
|
|
2783
|
-
var UPDATE_CHECK_HOOK = "node .claude/hooks/joycraft-version-check.mjs";
|
|
2784
|
-
function regularFile(root, relative) {
|
|
2785
|
-
try {
|
|
2786
|
-
return lstatSync2(join9(root, ...relative.split("/"))).isFile();
|
|
2787
|
-
} catch {
|
|
2788
|
-
return false;
|
|
2789
|
-
}
|
|
2790
|
-
}
|
|
2791
|
-
function isDirectory(root, relative) {
|
|
2792
|
-
try {
|
|
2793
|
-
return lstatSync2(join9(root, ...relative.split("/"))).isDirectory();
|
|
2794
|
-
} catch {
|
|
2795
|
-
return false;
|
|
2796
|
-
}
|
|
2797
|
-
}
|
|
2798
|
-
function existingPath(root, relative) {
|
|
2799
|
-
try {
|
|
2800
|
-
lstatSync2(join9(root, ...relative.split("/")));
|
|
2801
|
-
return true;
|
|
2802
|
-
} catch {
|
|
2803
|
-
return false;
|
|
2804
|
-
}
|
|
2805
|
-
}
|
|
2806
|
-
function projectName(root) {
|
|
2807
|
-
return (root.split(/[\\/]/).filter(Boolean).pop() ?? basename(root)) || "project";
|
|
2808
|
-
}
|
|
2809
|
-
function existingClaudeSkills(root, selected2) {
|
|
2810
|
-
if (!selected2.includes("claude")) return [];
|
|
2811
|
-
const directory = join9(root, ".claude", "skills");
|
|
2812
|
-
try {
|
|
2813
|
-
return readdirSync4(directory, { withFileTypes: true }).filter((entry) => !entry.name.startsWith("joycraft-") && !entry.name.startsWith(".")).filter((entry) => {
|
|
2814
|
-
try {
|
|
2815
|
-
return statSync2(join9(directory, entry.name)).isDirectory();
|
|
2816
|
-
} catch {
|
|
2817
|
-
return false;
|
|
2818
|
-
}
|
|
2819
|
-
}).map((entry) => entry.name);
|
|
2820
|
-
} catch {
|
|
2821
|
-
return [];
|
|
2822
|
-
}
|
|
2823
|
-
}
|
|
2824
|
-
function sharesAgentsMd(harnesses) {
|
|
2825
|
-
return harnesses.some((harness) => harness !== "claude");
|
|
2826
|
-
}
|
|
2827
|
-
function memoryFilePath(harnesses) {
|
|
2828
|
-
return sharesAgentsMd(harnesses) ? "AGENTS.md" : "CLAUDE.md";
|
|
2829
|
-
}
|
|
2830
|
-
function generatorContent(root, path, harnesses, profile, stack, existingSkills, executionProfile) {
|
|
2831
|
-
const multiTool = sharesAgentsMd(harnesses);
|
|
2832
|
-
const modelProfilePointer = selectsModelProfile(harnesses);
|
|
2833
|
-
if (path === "CLAUDE.md") {
|
|
2834
|
-
return multiTool ? generateClaudeMdPointer() : generateCLAUDEMd(projectName(root), stack, existingSkills, {
|
|
2835
|
-
privateProfile: profile === "private",
|
|
2836
|
-
projectDir: root,
|
|
2837
|
-
modelProfilePointer
|
|
2838
|
-
});
|
|
2839
|
-
}
|
|
2840
|
-
if (path === "AGENTS.md") {
|
|
2841
|
-
return multiTool ? generateCLAUDEMd(projectName(root), stack, existingSkills, {
|
|
2842
|
-
privateProfile: profile === "private",
|
|
2843
|
-
multiTool: true,
|
|
2844
|
-
executionProfile,
|
|
2845
|
-
projectDir: root,
|
|
2846
|
-
modelProfilePointer
|
|
2847
|
-
}) : generateAgentsMd(projectName(root), stack, profile === "private", executionProfile, void 0, root);
|
|
2848
|
-
}
|
|
2849
|
-
return void 0;
|
|
2850
|
-
}
|
|
2851
|
-
function materializeDocuments(input, existingSkills) {
|
|
2852
|
-
return input.entries.flatMap((entry) => {
|
|
2853
|
-
if (entry.path === CLAUDE_SETTINGS && entry.kind === "config-patch") return [];
|
|
2854
|
-
if (entry.kind !== "create-once") return [entry];
|
|
2855
|
-
const exists = regularFile(input.root, entry.path);
|
|
2856
|
-
const recorded = input.manifest.files[entry.path] !== void 0;
|
|
2857
|
-
const forceKnown = input.force === true && KNOWN_GENERATED_DOCUMENTS.has(entry.path);
|
|
2858
|
-
if (entry.content !== void 0) {
|
|
2859
|
-
if (!exists || forceKnown) return [entry];
|
|
2860
|
-
return [];
|
|
2861
|
-
}
|
|
2862
|
-
const content = generatorContent(
|
|
2863
|
-
input.root,
|
|
2864
|
-
entry.path,
|
|
2865
|
-
input.harnesses,
|
|
2866
|
-
input.profile,
|
|
2867
|
-
input.stack,
|
|
2868
|
-
existingSkills,
|
|
2869
|
-
input.executionProfile
|
|
2870
|
-
);
|
|
2871
|
-
if (content === void 0) return [];
|
|
2872
|
-
if (!exists && !recorded || forceKnown) {
|
|
2873
|
-
return [{ ...entry, installable: true, content }];
|
|
2874
|
-
}
|
|
2875
|
-
return [];
|
|
2876
|
-
});
|
|
2877
|
-
}
|
|
2878
|
-
function freshSettingsEntry(input) {
|
|
2879
|
-
if (!input.freshInstall || !input.harnesses.includes("claude") || existingPath(input.root, CLAUDE_SETTINGS)) return void 0;
|
|
2880
|
-
const permissions = generatePermissions(input.stack);
|
|
2881
|
-
const settings = {
|
|
2882
|
-
env: { CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS: "1" },
|
|
2883
|
-
hooks: {
|
|
2884
|
-
SessionStart: [{
|
|
2885
|
-
matcher: "",
|
|
2886
|
-
hooks: [{ type: "command", command: UPDATE_CHECK_HOOK }]
|
|
2887
|
-
}],
|
|
2888
|
-
PreToolUse: [{
|
|
2889
|
-
matcher: "Bash",
|
|
2890
|
-
hooks: [{ type: "command", command: SAFE_GUARD_HOOK }]
|
|
2891
|
-
}]
|
|
2892
|
-
},
|
|
2893
|
-
permissions
|
|
2894
|
-
};
|
|
2895
|
-
if (input.disableAutoMemory === true) settings.autoMemoryEnabled = false;
|
|
2896
|
-
return {
|
|
2897
|
-
path: CLAUDE_SETTINGS,
|
|
2898
|
-
harness: "claude",
|
|
2899
|
-
kind: "create-once",
|
|
2900
|
-
ownership: "managed",
|
|
2901
|
-
active: true,
|
|
2902
|
-
installable: true,
|
|
2903
|
-
content: JSON.stringify(settings, null, 2) + "\n"
|
|
2904
|
-
};
|
|
2905
|
-
}
|
|
2906
|
-
function freshBacklogEntry(input) {
|
|
2907
|
-
if (!input.freshInstall || regularFile(input.root, "docs/backlog/README.md")) return void 0;
|
|
2908
|
-
if (existingPath(input.root, "docs/backlog/README.md")) return void 0;
|
|
2909
|
-
return {
|
|
2910
|
-
path: "docs/backlog/README.md",
|
|
2911
|
-
harness: "shared",
|
|
2912
|
-
kind: "create-once",
|
|
2913
|
-
ownership: "managed",
|
|
2914
|
-
active: true,
|
|
2915
|
-
installable: true,
|
|
2916
|
-
content: BACKLOG_README
|
|
2917
|
-
};
|
|
2918
|
-
}
|
|
2919
|
-
function freshIntentEntry(input) {
|
|
2920
|
-
if (!input.freshInstall) return void 0;
|
|
2921
|
-
if (existingPath(input.root, "docs/intent") && !isDirectory(input.root, "docs/intent")) return void 0;
|
|
2922
|
-
if (existingPath(input.root, "docs/intent/README.md")) return void 0;
|
|
2923
|
-
return {
|
|
2924
|
-
path: "docs/intent/README.md",
|
|
2925
|
-
harness: "shared",
|
|
2926
|
-
kind: "create-once",
|
|
2927
|
-
ownership: "managed",
|
|
2928
|
-
active: true,
|
|
2929
|
-
installable: true,
|
|
2930
|
-
content: INTENT_README
|
|
2931
|
-
};
|
|
2932
|
-
}
|
|
2933
|
-
function parseSettings(raw) {
|
|
2934
|
-
try {
|
|
2935
|
-
const parsed = JSON.parse(raw);
|
|
2936
|
-
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0;
|
|
2937
|
-
} catch {
|
|
2938
|
-
return void 0;
|
|
2939
|
-
}
|
|
2940
|
-
}
|
|
2941
|
-
function arraySetting(value) {
|
|
2942
|
-
if (value === void 0) return [];
|
|
2943
|
-
if (!Array.isArray(value) || value.some((entry) => typeof entry !== "string")) return void 0;
|
|
2944
|
-
return [...value];
|
|
2945
|
-
}
|
|
2946
|
-
function addIfMissing(target, values) {
|
|
2947
|
-
let changed = false;
|
|
2948
|
-
for (const value of values) {
|
|
2949
|
-
if (!target.includes(value)) {
|
|
2950
|
-
target.push(value);
|
|
2951
|
-
changed = true;
|
|
2952
|
-
}
|
|
2953
|
-
}
|
|
2954
|
-
return changed;
|
|
2955
|
-
}
|
|
2956
|
-
function safeguardHookPresent(value) {
|
|
2957
|
-
if (!Array.isArray(value)) return false;
|
|
2958
|
-
return value.some((record) => {
|
|
2959
|
-
if (!record || typeof record !== "object" || Array.isArray(record)) return false;
|
|
2960
|
-
const hooks = record.hooks;
|
|
2961
|
-
return Array.isArray(hooks) && hooks.some(
|
|
2962
|
-
(hook) => hook && typeof hook === "object" && !Array.isArray(hook) && hook.command === SAFE_GUARD_HOOK
|
|
2963
|
-
);
|
|
2964
|
-
});
|
|
2965
|
-
}
|
|
2966
|
-
function updateCheckHookPresent(value) {
|
|
2967
|
-
if (!Array.isArray(value)) return false;
|
|
2968
|
-
return value.some((record) => {
|
|
2969
|
-
if (!record || typeof record !== "object" || Array.isArray(record)) return false;
|
|
2970
|
-
const hooks = record.hooks;
|
|
2971
|
-
return Array.isArray(hooks) && hooks.some(
|
|
2972
|
-
(hook) => hook && typeof hook === "object" && !Array.isArray(hook) && hook.command === UPDATE_CHECK_HOOK
|
|
2973
|
-
);
|
|
2974
|
-
});
|
|
2975
|
-
}
|
|
2976
|
-
function mergeOwnedSettings(raw, input, allowGenerated, diagnostics) {
|
|
2977
|
-
const settings = parseSettings(raw);
|
|
2978
|
-
if (!settings) {
|
|
2979
|
-
diagnostics.push("settings.json is malformed or not an object; preserving it without generated setup changes.");
|
|
2980
|
-
return void 0;
|
|
2981
|
-
}
|
|
2982
|
-
let changed = false;
|
|
2983
|
-
if (allowGenerated) {
|
|
2984
|
-
const env = settings.env === void 0 ? (settings.env = {}, settings.env) : settings.env && typeof settings.env === "object" && !Array.isArray(settings.env) ? settings.env : void 0;
|
|
2985
|
-
if (!env) {
|
|
2986
|
-
diagnostics.push("settings.json has a non-object env value; preserving it without generated setup changes.");
|
|
2987
|
-
return void 0;
|
|
2988
|
-
}
|
|
2989
|
-
if (!Object.prototype.hasOwnProperty.call(env, "CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS")) {
|
|
2990
|
-
env.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS = "1";
|
|
2991
|
-
changed = true;
|
|
2992
|
-
}
|
|
2993
|
-
const permissions = settings.permissions === void 0 ? (settings.permissions = {}, settings.permissions) : settings.permissions && typeof settings.permissions === "object" && !Array.isArray(settings.permissions) ? settings.permissions : void 0;
|
|
2994
|
-
if (!permissions) {
|
|
2995
|
-
diagnostics.push("settings.json has a non-object permissions value; preserving it without generated setup changes.");
|
|
2996
|
-
return void 0;
|
|
2997
|
-
}
|
|
2998
|
-
const allow = arraySetting(permissions.allow);
|
|
2999
|
-
const deny = arraySetting(permissions.deny);
|
|
3000
|
-
if (!allow || !deny) {
|
|
3001
|
-
diagnostics.push("settings.json has a non-array permissions list; preserving it without generated setup changes.");
|
|
3002
|
-
return void 0;
|
|
3003
|
-
}
|
|
3004
|
-
changed = addIfMissing(allow, generatePermissions(input.stack).allow) || changed;
|
|
3005
|
-
changed = addIfMissing(deny, generatePermissions(input.stack).deny) || changed;
|
|
3006
|
-
permissions.allow = allow;
|
|
3007
|
-
permissions.deny = deny;
|
|
3008
|
-
const hooks = settings.hooks === void 0 ? (settings.hooks = {}, settings.hooks) : settings.hooks && typeof settings.hooks === "object" && !Array.isArray(settings.hooks) ? settings.hooks : void 0;
|
|
3009
|
-
if (!hooks) {
|
|
3010
|
-
diagnostics.push("settings.json has a non-object hooks value; preserving it without generated setup changes.");
|
|
3011
|
-
return void 0;
|
|
3012
|
-
}
|
|
3013
|
-
const preToolUse = hooks.PreToolUse === void 0 ? (hooks.PreToolUse = [], hooks.PreToolUse) : hooks.PreToolUse;
|
|
3014
|
-
if (!Array.isArray(preToolUse)) {
|
|
3015
|
-
diagnostics.push("settings.json has a non-array hooks.PreToolUse value; preserving it without generated setup changes.");
|
|
3016
|
-
return void 0;
|
|
3017
|
-
}
|
|
3018
|
-
if (!safeguardHookPresent(preToolUse)) {
|
|
3019
|
-
preToolUse.push({ matcher: "Bash", hooks: [{ type: "command", command: SAFE_GUARD_HOOK }] });
|
|
3020
|
-
changed = true;
|
|
3021
|
-
}
|
|
3022
|
-
const sessionStart = hooks.SessionStart === void 0 ? (hooks.SessionStart = [], hooks.SessionStart) : hooks.SessionStart;
|
|
3023
|
-
if (!Array.isArray(sessionStart)) {
|
|
3024
|
-
diagnostics.push("settings.json has a non-array hooks.SessionStart value; preserving it without generated setup changes.");
|
|
3025
|
-
return void 0;
|
|
3026
|
-
}
|
|
3027
|
-
if (!updateCheckHookPresent(sessionStart)) {
|
|
3028
|
-
sessionStart.push({ matcher: "", hooks: [{ type: "command", command: UPDATE_CHECK_HOOK }] });
|
|
3029
|
-
changed = true;
|
|
3030
|
-
}
|
|
3031
|
-
}
|
|
3032
|
-
if (input.disableAutoMemory === true && !Object.prototype.hasOwnProperty.call(settings, "autoMemoryEnabled")) {
|
|
3033
|
-
settings.autoMemoryEnabled = false;
|
|
3034
|
-
changed = true;
|
|
3035
|
-
}
|
|
3036
|
-
if (!changed) return void 0;
|
|
3037
|
-
const newline = raw.includes("\r\n") ? "\r\n" : "\n";
|
|
3038
|
-
const serialized = JSON.stringify(settings, null, 2).replace(/\r?\n/g, newline);
|
|
3039
|
-
return raw.endsWith("\n") || raw.endsWith("\r") ? serialized + newline : serialized;
|
|
3040
|
-
}
|
|
3041
|
-
function retireLegacyChecker(raw, diagnostics) {
|
|
3042
|
-
const settings = parseSettings(raw);
|
|
3043
|
-
if (!settings) {
|
|
3044
|
-
diagnostics.push("settings.json is malformed or not an object; preserving it without legacy checker retirement.");
|
|
3045
|
-
return void 0;
|
|
3046
|
-
}
|
|
3047
|
-
const hooks = settings.hooks;
|
|
3048
|
-
if (!hooks || typeof hooks !== "object" || Array.isArray(hooks)) return void 0;
|
|
3049
|
-
const sessionStart = hooks.SessionStart;
|
|
3050
|
-
if (!Array.isArray(sessionStart)) return void 0;
|
|
3051
|
-
const checker = "node .claude/hooks/joycraft-version-check.mjs";
|
|
3052
|
-
let found = false;
|
|
3053
|
-
const nextSessionStart = sessionStart.flatMap((entry) => {
|
|
3054
|
-
if (!entry || typeof entry !== "object" || Array.isArray(entry)) return [entry];
|
|
3055
|
-
const record = entry;
|
|
3056
|
-
if (!Array.isArray(record.hooks)) return [entry];
|
|
3057
|
-
const nextHooks = record.hooks.filter((hook) => {
|
|
3058
|
-
const command = hook && typeof hook === "object" && !Array.isArray(hook) ? hook.command : void 0;
|
|
3059
|
-
if (command === checker) {
|
|
3060
|
-
found = true;
|
|
3061
|
-
return false;
|
|
3062
|
-
}
|
|
3063
|
-
return true;
|
|
3064
|
-
});
|
|
3065
|
-
return nextHooks.length ? [{ ...record, hooks: nextHooks }] : [];
|
|
3066
|
-
});
|
|
3067
|
-
if (!found) return void 0;
|
|
3068
|
-
const nextSettings = { ...settings, hooks: { ...hooks, SessionStart: nextSessionStart } };
|
|
3069
|
-
const newline = raw.includes("\r\n") ? "\r\n" : "\n";
|
|
3070
|
-
const serialized = JSON.stringify(nextSettings, null, 2).replace(/\r?\n/g, newline);
|
|
3071
|
-
return raw.endsWith("\n") || raw.endsWith("\r") ? serialized + newline : serialized;
|
|
3072
|
-
}
|
|
3073
|
-
function settingsPatch(input, diagnostics) {
|
|
3074
|
-
if (!input.harnesses.includes("claude") || !regularFile(input.root, CLAUDE_SETTINGS)) return void 0;
|
|
3075
|
-
const path = join9(input.root, ...CLAUDE_SETTINGS.split("/"));
|
|
3076
|
-
let raw;
|
|
3077
|
-
try {
|
|
3078
|
-
raw = readFileSync7(path, "utf8");
|
|
3079
|
-
} catch {
|
|
3080
|
-
diagnostics.push("settings.json could not be read; preserving it without generated setup changes.");
|
|
3081
|
-
return void 0;
|
|
3082
|
-
}
|
|
3083
|
-
const allowGenerated = input.freshInstall === true || input.configureClaude === true;
|
|
3084
|
-
let next = mergeOwnedSettings(raw, input, allowGenerated, diagnostics);
|
|
3085
|
-
if (next === void 0) next = raw;
|
|
3086
|
-
if (input.retireLegacyChecker === true) {
|
|
3087
|
-
const retired = retireLegacyChecker(next, diagnostics);
|
|
3088
|
-
if (retired !== void 0) next = retired;
|
|
3089
|
-
}
|
|
3090
|
-
if (next === raw) return void 0;
|
|
3091
|
-
return {
|
|
3092
|
-
path: CLAUDE_SETTINGS,
|
|
3093
|
-
kind: "write",
|
|
3094
|
-
content: next,
|
|
3095
|
-
currentPresent: true,
|
|
3096
|
-
rawPrecondition: rawFileHash(raw),
|
|
3097
|
-
reason: allowGenerated ? "Apply the selected initial Claude setup while preserving unrelated settings." : "Apply the explicitly selected auto-memory preference while preserving unrelated Claude settings."
|
|
3098
|
-
};
|
|
3099
|
-
}
|
|
3100
|
-
function tsconfigPatch(input, diagnostics) {
|
|
3101
|
-
if (!input.freshInstall || !input.harnesses.includes("pi") || !regularFile(input.root, TS_CONFIG)) return void 0;
|
|
3102
|
-
const path = join9(input.root, TS_CONFIG);
|
|
3103
|
-
let raw;
|
|
3104
|
-
try {
|
|
3105
|
-
raw = readFileSync7(path, "utf8");
|
|
3106
|
-
} catch {
|
|
3107
|
-
diagnostics.push('tsconfig.json could not be read; add ".pi" to its exclude array manually.');
|
|
3108
|
-
return void 0;
|
|
3109
|
-
}
|
|
3110
|
-
const planned = planPiExcludedFromTsconfig(raw);
|
|
3111
|
-
if (planned.status === "already-present") return void 0;
|
|
3112
|
-
if (planned.status === "skipped") {
|
|
3113
|
-
diagnostics.push(planned.reason);
|
|
3114
|
-
return void 0;
|
|
3115
|
-
}
|
|
3116
|
-
return {
|
|
3117
|
-
path: TS_CONFIG,
|
|
3118
|
-
kind: "write",
|
|
3119
|
-
content: planned.content,
|
|
3120
|
-
currentPresent: true,
|
|
3121
|
-
rawPrecondition: rawFileHash(raw),
|
|
3122
|
-
reason: "Exclude the installed Pi runtime from the project TypeScript program while preserving the existing tsconfig bytes."
|
|
3123
|
-
};
|
|
3124
|
-
}
|
|
3125
|
-
function contextMapPointerPatch(input, entries, diagnostics) {
|
|
3126
|
-
if (!selectsModelProfile(input.harnesses)) return void 0;
|
|
3127
|
-
const memory = memoryFilePath(input.harnesses);
|
|
3128
|
-
if (!regularFile(input.root, memory)) return void 0;
|
|
3129
|
-
if (entries.some((entry) => entry.path === memory && entry.content !== void 0)) return void 0;
|
|
3130
|
-
let raw;
|
|
3131
|
-
try {
|
|
3132
|
-
raw = readFileSync7(join9(input.root, memory), "utf8");
|
|
3133
|
-
} catch {
|
|
3134
|
-
diagnostics.push(`${memory} could not be read; add the model profile row to its Context Map manually.`);
|
|
3135
|
-
return void 0;
|
|
3136
|
-
}
|
|
3137
|
-
const next = insertModelProfilePointer(raw);
|
|
3138
|
-
if (next === raw) return void 0;
|
|
3139
|
-
return {
|
|
3140
|
-
path: memory,
|
|
3141
|
-
kind: "write",
|
|
3142
|
-
content: next,
|
|
3143
|
-
currentPresent: true,
|
|
3144
|
-
rawPrecondition: rawFileHash(raw),
|
|
3145
|
-
reason: "Add one Context Map row pointing at the Claude Fable 5.1 model profile; every other byte is preserved."
|
|
3146
|
-
};
|
|
3147
|
-
}
|
|
3148
|
-
function materializeFreshInstallInventory(input) {
|
|
3149
|
-
const diagnostics = [];
|
|
3150
|
-
const existingSkills = existingClaudeSkills(input.root, input.harnesses);
|
|
3151
|
-
const entries = materializeDocuments(input, existingSkills);
|
|
3152
|
-
const known = new Set(entries.map((entry) => entry.path));
|
|
3153
|
-
const backlog = freshBacklogEntry(input);
|
|
3154
|
-
if (backlog && !known.has(backlog.path)) entries.push(backlog);
|
|
3155
|
-
const intent = freshIntentEntry(input);
|
|
3156
|
-
if (intent && !known.has(intent.path)) entries.push(intent);
|
|
3157
|
-
const settings = freshSettingsEntry(input);
|
|
3158
|
-
if (settings && !known.has(settings.path)) entries.push(settings);
|
|
3159
|
-
const directories = [];
|
|
3160
|
-
if (input.freshInstall) {
|
|
3161
|
-
for (const relative of ["docs/context", "docs/backlog", "docs/intent"]) {
|
|
3162
|
-
if (!existingPath(input.root, relative)) directories.push(relative);
|
|
3163
|
-
else {
|
|
3164
|
-
try {
|
|
3165
|
-
if (!lstatSync2(join9(input.root, ...relative.split("/"))).isDirectory()) {
|
|
3166
|
-
diagnostics.push(`${relative} exists but is not a directory; preserving it.`);
|
|
3167
|
-
}
|
|
3168
|
-
} catch {
|
|
3169
|
-
diagnostics.push(`${relative} could not be inspected; preserving it.`);
|
|
3170
|
-
}
|
|
3171
|
-
}
|
|
3172
|
-
}
|
|
3173
|
-
}
|
|
3174
|
-
const patchOperations = [
|
|
3175
|
-
settingsPatch(input, diagnostics),
|
|
3176
|
-
tsconfigPatch(input, diagnostics),
|
|
3177
|
-
contextMapPointerPatch(input, entries, diagnostics)
|
|
3178
|
-
].filter((operation) => operation !== void 0);
|
|
3179
|
-
return {
|
|
3180
|
-
entries,
|
|
3181
|
-
setup: { directories, existingSkills, patchOperations },
|
|
3182
|
-
diagnostics
|
|
3183
|
-
};
|
|
3184
|
-
}
|
|
3185
|
-
|
|
3186
|
-
// src/auto-safe-update.ts
|
|
3187
|
-
function object(value) {
|
|
3188
|
-
return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
|
|
3189
|
-
}
|
|
3190
|
-
function descriptorEqual(left, right) {
|
|
3191
|
-
const a = object(left);
|
|
3192
|
-
const b = object(right);
|
|
3193
|
-
if (!a || !b) return false;
|
|
3194
|
-
return a.schemaVersion === b.schemaVersion && a.releaseVersion === b.releaseVersion && a.autoSafeEligible === b.autoSafeEligible && Array.isArray(a.manifestSchemas) && Array.isArray(b.manifestSchemas) && JSON.stringify(a.manifestSchemas) === JSON.stringify(b.manifestSchemas);
|
|
3195
|
-
}
|
|
3196
|
-
function evaluateAutoSafeEligibility(input) {
|
|
3197
|
-
const diagnostics = [];
|
|
3198
|
-
const reject = (message) => {
|
|
3199
|
-
diagnostics.push(message);
|
|
3200
|
-
};
|
|
3201
|
-
if (input.policy !== "auto-safe") reject("Automatic updates require the local auto-safe policy.");
|
|
3202
|
-
const candidate = input.candidate;
|
|
3203
|
-
if (!candidate || !isVerifiedReleaseArtifact(candidate)) {
|
|
3204
|
-
reject("Automatic updates require a verifier-issued exact release artifact.");
|
|
3205
|
-
}
|
|
3206
|
-
const release = candidate?.release;
|
|
3207
|
-
const descriptor = candidate?.descriptor;
|
|
3208
|
-
const descriptorObject = object(descriptor);
|
|
3209
|
-
if (candidate && release && release.packageName !== "joycraft") reject("The verified artifact package is not Joycraft.");
|
|
3210
|
-
if (candidate && release && release.version !== input.executingVersion) {
|
|
3211
|
-
reject("The verified artifact version does not match the executing bundle.");
|
|
3212
|
-
}
|
|
3213
|
-
if (candidate && input.executingIntegrity !== void 0 && release && release.integrity !== input.executingIntegrity) {
|
|
3214
|
-
reject("The verified artifact integrity does not match the executing bundle.");
|
|
3215
|
-
}
|
|
3216
|
-
if (input.executingDescriptor === void 0) reject("The executing bundle has no verified compatibility descriptor.");
|
|
3217
|
-
else if (candidate && !descriptorEqual(descriptor, input.executingDescriptor)) {
|
|
3218
|
-
reject("The verified compatibility descriptor does not match the executing bundle.");
|
|
3219
|
-
}
|
|
3220
|
-
if (!descriptorObject || descriptorObject.schemaVersion !== 1 || descriptorObject.releaseVersion !== release?.version) {
|
|
3221
|
-
reject("The verified artifact has no supported compatibility descriptor.");
|
|
3222
|
-
}
|
|
3223
|
-
if (descriptorObject?.autoSafeEligible !== true) reject("The release is not declared eligible for auto-safe updates.");
|
|
3224
|
-
const supportedSchemas = descriptorObject?.manifestSchemas;
|
|
3225
|
-
const schema = input.manifestSchema ?? input.plan.nextManifest.schemaVersion;
|
|
3226
|
-
if (!Array.isArray(supportedSchemas) || !supportedSchemas.includes(schema)) reject("The release does not support this manifest protocol.");
|
|
3227
|
-
if (!/^(\d+)\.(\d+)\.(\d+)$/.test(input.executingVersion) || !release?.version || !/^(\d+)\.(\d+)\.(\d+)$/.test(release.version)) {
|
|
3228
|
-
reject("Prerelease and malformed releases require an explicit update.");
|
|
3229
|
-
} else if (compareStableVersions(release.version, input.executingVersion) !== 0) {
|
|
3230
|
-
reject("Downgrades and version changes require an explicit update.");
|
|
3231
|
-
}
|
|
3232
|
-
if (!input.existingManifest) reject("Automatic updates require an existing installation manifest.");
|
|
3233
|
-
else if (compareStableVersions(release?.version ?? "", input.existingManifest.targetVersion) !== 1) {
|
|
3234
|
-
reject("The candidate is not newer than the installed release; use an explicit update.");
|
|
3235
|
-
}
|
|
3236
|
-
if (input.plan.conflicts.length > 0) reject("The update plan contains unresolved conflicts.");
|
|
3237
|
-
if (input.plan.actions.some((action) => action.kind === "conflict" || action.kind === "repair")) {
|
|
3238
|
-
reject("The update plan contains a conflict or repair action.");
|
|
3239
|
-
}
|
|
3240
|
-
if (input.plan.actions.some((action) => action.selected && (action.patch !== void 0 || action.path === ".claude/settings.json") && !(action.currentPresent && action.targetPresent && typeof action.rawPrecondition === "string" && action.rawPrecondition === action.rawTargetHash))) {
|
|
3241
|
-
reject("The update plan changes user configuration.");
|
|
3242
|
-
}
|
|
3243
|
-
if ((input.replaceCustomized?.length ?? 0) > 0) reject("Customized replacements require an explicit update.");
|
|
3244
|
-
if ((input.repair?.length ?? 0) > 0) reject("Repairs require an explicit update.");
|
|
3245
|
-
if (input.migration) reject("Migrations require an explicit update.");
|
|
3246
|
-
if (input.legacyBridge) reject("Legacy bridge adoption requires an explicit update.");
|
|
3247
|
-
if (input.setupChanges) reject("Setup and user-configuration changes require an explicit update.");
|
|
3248
|
-
if (input.profileChanges) reject("Profile changes require an explicit update.");
|
|
3249
|
-
if (input.localOperations) reject("Local state migrations require an explicit update.");
|
|
3250
|
-
if (input.authorityTransition) reject("Manifest authority transitions require an explicit update.");
|
|
3251
|
-
return { eligible: diagnostics.length === 0, diagnostics };
|
|
3252
|
-
}
|
|
3253
|
-
|
|
3254
|
-
// src/update.ts
|
|
3255
|
-
function updateStatusExitCode(status) {
|
|
3256
|
-
switch (status) {
|
|
3257
|
-
case "applied":
|
|
3258
|
-
case "noop":
|
|
3259
|
-
case "preserved":
|
|
3260
|
-
return 0;
|
|
3261
|
-
case "conflict":
|
|
3262
|
-
return 2;
|
|
3263
|
-
case "attention":
|
|
3264
|
-
return 3;
|
|
3265
|
-
case "invalid":
|
|
3266
|
-
case "failed":
|
|
3267
|
-
return 1;
|
|
3268
|
-
default: {
|
|
3269
|
-
const exhaustive = status;
|
|
3270
|
-
throw new Error(`Unknown update status: ${String(exhaustive)}`);
|
|
3271
|
-
}
|
|
3272
|
-
}
|
|
3273
|
-
}
|
|
3274
|
-
function outcome(status, fields = {}) {
|
|
3275
|
-
return {
|
|
3276
|
-
status,
|
|
3277
|
-
exitCode: updateStatusExitCode(status),
|
|
3278
|
-
applied: [],
|
|
3279
|
-
preserved: [],
|
|
3280
|
-
conflicts: [],
|
|
3281
|
-
diagnostics: [],
|
|
3282
|
-
registry: "not-requested",
|
|
3283
|
-
...fields
|
|
3284
|
-
};
|
|
3285
|
-
}
|
|
3286
|
-
function parseSelection(value) {
|
|
3287
|
-
if (typeof value === "string") return parseHarnessSelection(value);
|
|
3288
|
-
if (value === void 0) return null;
|
|
3289
|
-
if (value.some((entry) => typeof entry !== "string" || !HARNESSES.includes(entry.trim().toLowerCase()))) return null;
|
|
3290
|
-
return sanitizeHarnesses(value);
|
|
3291
|
-
}
|
|
3292
|
-
function interactive(options) {
|
|
3293
|
-
return options.nonInteractive !== true && options.yes !== true && process.stdin.isTTY === true;
|
|
3294
|
-
}
|
|
3295
|
-
function profileFromAuthorities(root, requested) {
|
|
3296
|
-
const explicit = requested === void 0 ? void 0 : parseGitignoreProfile(requested);
|
|
3297
|
-
if (requested !== void 0 && explicit === null) {
|
|
3298
|
-
return {
|
|
3299
|
-
profile: DEFAULT_GITIGNORE_PROFILE,
|
|
3300
|
-
manifestInfo: readInstallationManifestInfo(root, DEFAULT_GITIGNORE_PROFILE),
|
|
3301
|
-
diagnostic: `Invalid gitignore profile '${requested}'. Choose shared or private.`
|
|
3302
|
-
};
|
|
3303
|
-
}
|
|
3304
|
-
if (explicit) {
|
|
3305
|
-
const selected2 = readInstallationManifestInfo(root, explicit);
|
|
3306
|
-
const otherProfile = explicit === "shared" ? "private" : "shared";
|
|
3307
|
-
const other = readInstallationManifestInfo(root, otherProfile);
|
|
3308
|
-
if (selected2.status !== "missing" && selected2.status !== "valid" || other.status !== "missing" && other.status !== "valid") {
|
|
3309
|
-
const bad = selected2.status !== "missing" && selected2.status !== "valid" ? selected2 : other;
|
|
3310
|
-
return { profile: explicit, manifestInfo: selected2, diagnostic: `The ${bad.status} installation manifest needs attention.` };
|
|
3311
|
-
}
|
|
3312
|
-
if (selected2.status === "valid" && other.status === "valid") {
|
|
3313
|
-
return { profile: explicit, manifestInfo: selected2, diagnostic: "Both shared and private installation manifests are valid; choose one authority before updating." };
|
|
3314
|
-
}
|
|
3315
|
-
if (selected2.status === "missing" && other.status === "valid") {
|
|
3316
|
-
return { profile: explicit, manifestInfo: selected2, sourceProfile: otherProfile, sourceManifestInfo: other };
|
|
3317
|
-
}
|
|
3318
|
-
return { profile: explicit, manifestInfo: selected2 };
|
|
3319
|
-
}
|
|
3320
|
-
const shared = readInstallationManifestInfo(root, "shared");
|
|
3321
|
-
const privateManifest = readInstallationManifestInfo(root, "private");
|
|
3322
|
-
if (shared.status !== "missing" && shared.status !== "valid" || privateManifest.status !== "missing" && privateManifest.status !== "valid") {
|
|
3323
|
-
const bad = shared.status !== "missing" && shared.status !== "valid" ? shared : privateManifest;
|
|
3324
|
-
return { profile: "shared", manifestInfo: shared, diagnostic: `The ${bad.status} installation manifest needs attention.` };
|
|
3325
|
-
}
|
|
3326
|
-
if (shared.status === "valid" && privateManifest.status === "valid") {
|
|
3327
|
-
return { profile: "shared", manifestInfo: shared, diagnostic: "Both shared and private installation manifests are valid; choose one authority before updating." };
|
|
3328
|
-
}
|
|
3329
|
-
if (shared.status === "valid") return { profile: "shared", manifestInfo: shared };
|
|
3330
|
-
if (privateManifest.status === "valid") return { profile: "private", manifestInfo: privateManifest };
|
|
3331
|
-
const legacy = readVersion(root);
|
|
3332
|
-
return {
|
|
3333
|
-
profile: legacy?.gitignoreProfile ?? DEFAULT_GITIGNORE_PROFILE,
|
|
3334
|
-
manifestInfo: readInstallationManifestInfo(root, legacy?.gitignoreProfile ?? DEFAULT_GITIGNORE_PROFILE)
|
|
3335
|
-
};
|
|
3336
|
-
}
|
|
3337
|
-
function regularFile2(root, relative) {
|
|
3338
|
-
try {
|
|
3339
|
-
return lstatSync3(join10(root, ...relative.split("/"))).isFile();
|
|
3340
|
-
} catch {
|
|
3341
|
-
return false;
|
|
3342
|
-
}
|
|
3343
|
-
}
|
|
3344
|
-
function snapshotFor(root, paths) {
|
|
3345
|
-
const files = {};
|
|
3346
|
-
for (const relative of paths) {
|
|
3347
|
-
if (!regularFile2(root, relative)) continue;
|
|
3348
|
-
const absolute = join10(root, ...relative.split("/"));
|
|
3349
|
-
const stat = lstatSync3(absolute);
|
|
3350
|
-
files[relative] = { content: readFileSync8(absolute), mode: stat.mode & 4095 };
|
|
3351
|
-
}
|
|
3352
|
-
return { files };
|
|
3353
|
-
}
|
|
3354
|
-
function executingBundle(options) {
|
|
3355
|
-
const supplied = options.bundle;
|
|
3356
|
-
if (supplied) return { ...supplied, integrity: supplied.integrity ?? "" };
|
|
3357
|
-
let descriptor;
|
|
3358
|
-
try {
|
|
3359
|
-
descriptor = JSON.parse(readFileSync8(join10(dirname3(fileURLToPath2(import.meta.url)), "joycraft-release.json"), "utf8"));
|
|
3360
|
-
} catch {
|
|
3361
|
-
descriptor = void 0;
|
|
3362
|
-
}
|
|
3363
|
-
return { version: getPackageVersion(), integrity: "", descriptor };
|
|
3364
|
-
}
|
|
3365
|
-
function legacyStateExists(root) {
|
|
3366
|
-
return existsSync8(join10(root, STATE_PATH)) || existsSync8(join10(root, LEGACY_VERSION_FILE)) || existsSync8(join10(root, LEGACY_CLAUDE_STATE_PATH));
|
|
3367
|
-
}
|
|
3368
|
-
function legacyHarnesses(root) {
|
|
3369
|
-
for (const relative of [STATE_PATH, LEGACY_CLAUDE_STATE_PATH, LEGACY_VERSION_FILE]) {
|
|
3370
|
-
if (!regularFile2(root, relative)) continue;
|
|
3371
|
-
try {
|
|
3372
|
-
const parsed = JSON.parse(readFileSync8(join10(root, ...relative.split("/")), "utf8"));
|
|
3373
|
-
if (Array.isArray(parsed.harnesses)) return sanitizeHarnesses(parsed.harnesses) ?? void 0;
|
|
3374
|
-
} catch {
|
|
3375
|
-
}
|
|
3376
|
-
}
|
|
3377
|
-
return void 0;
|
|
3378
|
-
}
|
|
3379
|
-
function harnessTreeEntry(entry, harness) {
|
|
3380
|
-
return entry.harness === harness && entry.content !== void 0 && !entry.path.startsWith("docs/templates/");
|
|
3381
|
-
}
|
|
3382
|
-
function recognizedHarnesses(root) {
|
|
3383
|
-
const inventory = getBundleInventory(HARNESSES);
|
|
3384
|
-
return HARNESSES.filter((harness) => inventory.some((entry) => harnessTreeEntry(entry, harness) && regularFile2(root, entry.path)));
|
|
3385
|
-
}
|
|
3386
|
-
function legacyMigrationOperations(root, localSettings) {
|
|
3387
|
-
const sources = [STATE_PATH, LEGACY_CLAUDE_STATE_PATH, LEGACY_VERSION_FILE];
|
|
3388
|
-
const found = [];
|
|
3389
|
-
for (const relative of sources) {
|
|
3390
|
-
if (!regularFile2(root, relative)) continue;
|
|
3391
|
-
found.push({ path: relative, content: readFileSync8(join10(root, ...relative.split("/"))) });
|
|
3392
|
-
}
|
|
3393
|
-
const operations = [];
|
|
3394
|
-
const settingsPath = "docs/.joycraft/local/settings.json";
|
|
3395
|
-
if (localSettings && Object.keys(localSettings).length > 0) {
|
|
3396
|
-
let settings = localSettings;
|
|
3397
|
-
const existingSettings = regularFile2(root, settingsPath) ? readFileSync8(join10(root, ...settingsPath.split("/"))) : void 0;
|
|
3398
|
-
if (existingSettings) {
|
|
3399
|
-
try {
|
|
3400
|
-
const parsed = JSON.parse(existingSettings.toString("utf8"));
|
|
3401
|
-
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
|
|
3402
|
-
settings = { ...localSettings, ...parsed };
|
|
3403
|
-
} else {
|
|
3404
|
-
settings = void 0;
|
|
3405
|
-
}
|
|
3406
|
-
} catch {
|
|
3407
|
-
settings = void 0;
|
|
3408
|
-
}
|
|
3409
|
-
}
|
|
3410
|
-
if (settings) {
|
|
3411
|
-
operations.push({
|
|
3412
|
-
path: settingsPath,
|
|
3413
|
-
kind: "write",
|
|
3414
|
-
content: Buffer.from(JSON.stringify(settings, null, 2) + "\n"),
|
|
3415
|
-
currentPresent: existingSettings !== void 0,
|
|
3416
|
-
...existingSettings ? { rawPrecondition: rawFileHash(existingSettings) } : {}
|
|
3417
|
-
});
|
|
3418
|
-
}
|
|
3419
|
-
}
|
|
3420
|
-
if (!found.length || regularFile2(root, "docs/.joycraft/local/legacy-state-backup.json")) return operations;
|
|
3421
|
-
const backup = Buffer.from(JSON.stringify(Object.fromEntries(found.map((entry) => [entry.path, entry.content.toString("base64")]))));
|
|
3422
|
-
operations.push({
|
|
3423
|
-
path: "docs/.joycraft/local/legacy-state-backup.json",
|
|
3424
|
-
kind: "write",
|
|
3425
|
-
content: backup,
|
|
3426
|
-
currentPresent: false
|
|
3427
|
-
});
|
|
3428
|
-
for (const entry of found) {
|
|
3429
|
-
operations.push({
|
|
3430
|
-
path: entry.path,
|
|
3431
|
-
kind: "delete",
|
|
3432
|
-
currentPresent: true,
|
|
3433
|
-
rawPrecondition: rawFileHash(entry.content)
|
|
3434
|
-
});
|
|
3435
|
-
}
|
|
3436
|
-
return operations;
|
|
3437
|
-
}
|
|
3438
|
-
function hasRecognizedHarness(root) {
|
|
3439
|
-
return recognizedHarnesses(root).length > 0;
|
|
3440
|
-
}
|
|
3441
|
-
var RECORDED_SELECTION_PATHS = [STATE_PATH, LEGACY_CLAUDE_STATE_PATH, LEGACY_VERSION_FILE];
|
|
3442
|
-
function readRecordedSelection(root) {
|
|
3443
|
-
const recorded = { present: false };
|
|
3444
|
-
for (const profile of ["shared", "private"]) {
|
|
3445
|
-
const info = readInstallationManifestInfo(root, profile);
|
|
3446
|
-
if (info.status !== "missing") recorded.present = true;
|
|
3447
|
-
if (info.manifest) {
|
|
3448
|
-
recorded.harnesses ??= [...info.manifest.harnesses];
|
|
3449
|
-
recorded.profile ??= info.manifest.profile;
|
|
3450
|
-
}
|
|
3451
|
-
}
|
|
3452
|
-
for (const relative of RECORDED_SELECTION_PATHS) {
|
|
3453
|
-
const path = join10(root, ...relative.split("/"));
|
|
3454
|
-
if (!existsSync8(path)) continue;
|
|
3455
|
-
recorded.present = true;
|
|
3456
|
-
try {
|
|
3457
|
-
const parsed = JSON.parse(readFileSync8(path, "utf8"));
|
|
3458
|
-
if (!recorded.harnesses && Array.isArray(parsed.harnesses)) {
|
|
3459
|
-
recorded.harnesses = sanitizeHarnesses(parsed.harnesses) ?? void 0;
|
|
3460
|
-
}
|
|
3461
|
-
recorded.profile ??= parseGitignoreProfile(parsed.gitignoreProfile) ?? void 0;
|
|
3462
|
-
} catch {
|
|
3463
|
-
}
|
|
3464
|
-
}
|
|
3465
|
-
if (!recorded.present) recorded.present = hasRecognizedHarness(root);
|
|
3466
|
-
return recorded;
|
|
3467
|
-
}
|
|
3468
|
-
function emptyHarnessSelection(value) {
|
|
3469
|
-
if (Array.isArray(value)) return value.length === 0;
|
|
3470
|
-
return typeof value === "string" && parseHarnessSelection(value)?.length === 0;
|
|
3471
|
-
}
|
|
3472
|
-
function invalidExplicitHarnessSelection(value) {
|
|
3473
|
-
if (typeof value === "string") return parseHarnessSelection(value) === null;
|
|
3474
|
-
if (value === void 0) return false;
|
|
3475
|
-
return value.some((entry) => typeof entry !== "string" || !HARNESSES.includes(entry.trim().toLowerCase()));
|
|
3476
|
-
}
|
|
3477
|
-
async function resolveInteractiveInitOptions(root, input) {
|
|
3478
|
-
const recorded = readRecordedSelection(root);
|
|
3479
|
-
const prompting = process.stdin.isTTY === true && input.yes !== true && input.nonInteractive !== true && input.json !== true && input.recovery === void 0 && input.automatic !== true && !recorded.present;
|
|
3480
|
-
let options = { ...input };
|
|
3481
|
-
if (prompting && options.harnesses === void 0) {
|
|
3482
|
-
options.harnesses = await resolveHarnesses(true);
|
|
3483
|
-
} else if (!prompting && options.harnesses === void 0 && recorded.harnesses !== void 0) {
|
|
3484
|
-
options.harnesses = [...recorded.harnesses];
|
|
3485
|
-
}
|
|
3486
|
-
if (emptyHarnessSelection(options.harnesses)) {
|
|
3487
|
-
return { options, emptySelection: true };
|
|
3488
|
-
}
|
|
3489
|
-
if (invalidExplicitHarnessSelection(options.harnesses)) {
|
|
3490
|
-
return { options, emptySelection: false };
|
|
3491
|
-
}
|
|
3492
|
-
const selected2 = typeof options.harnesses === "string" ? parseHarnessSelection(options.harnesses) : options.harnesses === void 0 ? recorded.harnesses : sanitizeHarnesses(options.harnesses);
|
|
3493
|
-
const profileHarnesses = selected2 ?? [...HARNESSES];
|
|
3494
|
-
if (prompting && options.executionProfile === void 0) {
|
|
3495
|
-
options.executionProfile = await resolveExecutionProfile(profileHarnesses, true);
|
|
3496
|
-
}
|
|
3497
|
-
if (prompting && options.gitignore === void 0) {
|
|
3498
|
-
options.gitignore = (await resolveGitignoreProfile({
|
|
3499
|
-
persisted: recorded.profile,
|
|
3500
|
-
interactive: true,
|
|
3501
|
-
promptIntro: "\nHow should Joycraft files be tracked in git?"
|
|
3502
|
-
})).profile;
|
|
3503
|
-
} else if (options.gitignore === void 0 && recorded.profile !== void 0) {
|
|
3504
|
-
options.gitignore = recorded.profile;
|
|
3505
|
-
}
|
|
3506
|
-
if (prompting && options.disableAutoMemory === void 0 && profileHarnesses.includes("claude")) {
|
|
3507
|
-
options.disableAutoMemory = await resolveAutoMemoryOffer(true);
|
|
3508
|
-
}
|
|
3509
|
-
return { options, emptySelection: false };
|
|
3510
|
-
}
|
|
3511
|
-
function chosenHarnesses(root, options, manifest) {
|
|
3512
|
-
const explicit = parseSelection(options.harnesses);
|
|
3513
|
-
if (explicit !== null) return explicit;
|
|
3514
|
-
if (manifest?.harnesses?.length) return [...manifest.harnesses];
|
|
3515
|
-
const legacy = legacyHarnesses(root);
|
|
3516
|
-
if (legacy !== void 0 && legacy.length > 0) return legacy;
|
|
3517
|
-
const recognized = recognizedHarnesses(root);
|
|
3518
|
-
if (recognized.length > 0) return recognized;
|
|
3519
|
-
if (legacyStateExists(root)) return [...HARNESSES];
|
|
3520
|
-
if (options.legacyInit) return [...HARNESSES];
|
|
3521
|
-
if (!interactive(options)) return null;
|
|
3522
|
-
return null;
|
|
3523
|
-
}
|
|
3524
|
-
function localSettingsFromAdoption(root, entries, bundle, profile) {
|
|
3525
|
-
const adopted = adoptLegacyInstallation(root, {
|
|
3526
|
-
inventory: entries,
|
|
3527
|
-
candidateContent: Object.fromEntries(entries.filter((entry) => entry.content !== void 0).map((entry) => [entry.path, { content: entry.content, vendorVersion: bundle.version }])),
|
|
3528
|
-
targetVersion: bundle.version,
|
|
3529
|
-
bundleIntegrity: bundle.integrity ?? "",
|
|
3530
|
-
profile
|
|
3531
|
-
});
|
|
3532
|
-
return { manifest: adopted.manifest, localSettings: adopted.localSettings, conflicts: adopted.conflicts };
|
|
3533
|
-
}
|
|
3534
|
-
function pathsForOutcome(plan) {
|
|
3535
|
-
const applied = plan.actions.filter((action) => action.selected && ["replace", "create", "repair", "delete", "conflict"].includes(action.kind)).map((action) => action.path);
|
|
3536
|
-
const resolved = new Set(plan.actions.filter((action) => action.kind === "conflict" && action.selected && action.resolution === "replace").map((action) => action.path));
|
|
3537
|
-
const preserved = plan.preserved.filter((entry) => !resolved.has(entry.path)).filter((entry) => !plan.actions.some((action) => action.path === entry.path && action.nonActionable === true)).map((entry) => entry.path);
|
|
3538
|
-
const conflicts = plan.conflicts.filter((action) => !resolved.has(action.path)).map((action) => action.path);
|
|
3539
|
-
return { applied: [...new Set(applied)], preserved: [...new Set(preserved)], conflicts: [...new Set(conflicts)] };
|
|
3540
|
-
}
|
|
3541
|
-
function setupPatchAction(operation) {
|
|
3542
|
-
return {
|
|
3543
|
-
path: operation.path,
|
|
3544
|
-
kind: "replace",
|
|
3545
|
-
selected: true,
|
|
3546
|
-
reason: operation.reason,
|
|
3547
|
-
content: operation.content,
|
|
3548
|
-
rawPrecondition: operation.rawPrecondition,
|
|
3549
|
-
rawTargetHash: rawFileHash(operation.content),
|
|
3550
|
-
currentPresent: operation.currentPresent,
|
|
3551
|
-
targetPresent: true
|
|
3552
|
-
};
|
|
3553
|
-
}
|
|
3554
|
-
function profileBookkeepingActions(root, profile) {
|
|
3555
|
-
const paths = [".gitignore", ".gitattributes"];
|
|
3556
|
-
const resolved = paths.map((path) => ({ path, absolute: resolveUpdatePath(root, path) }));
|
|
3557
|
-
const actions = [];
|
|
3558
|
-
for (const target of resolved) {
|
|
3559
|
-
const current = regularFile2(root, target.path) ? readFileSync8(target.absolute) : void 0;
|
|
3560
|
-
const currentText = current?.toString("utf8") ?? "";
|
|
3561
|
-
const planned = target.path === ".gitignore" ? planGitignoreProfile(currentText, profile) : planGitattributes(currentText);
|
|
3562
|
-
if (planned.added.length === 0) continue;
|
|
3563
|
-
const stat = current ? lstatSync3(target.absolute) : void 0;
|
|
3564
|
-
actions.push({
|
|
3565
|
-
path: target.path,
|
|
3566
|
-
kind: "replace",
|
|
3567
|
-
selected: true,
|
|
3568
|
-
reason: `Append Joycraft ${target.path} entries while preserving existing project lines.`,
|
|
3569
|
-
content: planned.content,
|
|
3570
|
-
rawTargetHash: rawFileHash(planned.content),
|
|
3571
|
-
currentPresent: current !== void 0,
|
|
3572
|
-
targetPresent: true,
|
|
3573
|
-
...current ? { rawPrecondition: rawFileHash(current) } : {},
|
|
3574
|
-
...stat ? { mode: stat.mode & 4095 } : {}
|
|
3575
|
-
});
|
|
3576
|
-
}
|
|
3577
|
-
return actions;
|
|
3578
|
-
}
|
|
3579
|
-
function selectedHarnessIgnoreWarning(root, harnesses) {
|
|
3580
|
-
const warnings = [];
|
|
3581
|
-
for (const harness of harnesses) {
|
|
3582
|
-
const candidate = getBundleInventory([harness]).find((entry) => harnessTreeEntry(entry, harness))?.path;
|
|
3583
|
-
if (!candidate) continue;
|
|
3584
|
-
const top = candidate.split("/")[0];
|
|
3585
|
-
let localBroadIgnore = false;
|
|
3586
|
-
let localUnignore = false;
|
|
3587
|
-
try {
|
|
3588
|
-
const localRules = readFileSync8(join10(root, ".gitignore"), "utf8").split(/\r?\n/).map((line) => line.trim()).filter((line) => line.length > 0 && !line.startsWith("#"));
|
|
3589
|
-
localBroadIgnore = localRules.some((line) => line === top || line === `${top}/` || line === `${top}/*` || line === `${top}/**`);
|
|
3590
|
-
localUnignore = localRules.some((line) => line === `!${top}/skills/` || line === `!${top}/skills/**` || line === `!${candidate}`);
|
|
3591
|
-
} catch {
|
|
3592
|
-
}
|
|
3593
|
-
if (localBroadIgnore && !localUnignore) {
|
|
3594
|
-
const hint = harness === "claude" ? " Add !.claude/skills/ (and its parent directory exceptions) if teammates should receive those skills." : "";
|
|
3595
|
-
warnings.push(`Selected ${harness} harness path ${candidate} is hidden by .gitignore.${hint}`);
|
|
3596
|
-
continue;
|
|
3597
|
-
}
|
|
3598
|
-
try {
|
|
3599
|
-
execFileSync("git", ["check-ignore", "--no-index", "-q", "--", candidate], {
|
|
3600
|
-
cwd: root,
|
|
3601
|
-
stdio: ["ignore", "ignore", "ignore"]
|
|
3602
|
-
});
|
|
3603
|
-
const hint = harness === "claude" ? " Add !.claude/skills/ (and its parent directory exceptions) if teammates should receive those skills." : "";
|
|
3604
|
-
warnings.push(`Selected ${harness} harness path ${candidate} is hidden by the effective Git ignore rules.${hint}`);
|
|
3605
|
-
} catch {
|
|
3606
|
-
}
|
|
3607
|
-
}
|
|
3608
|
-
return warnings;
|
|
3609
|
-
}
|
|
3610
|
-
function transactionStatus(plan, result, authorityTransition = false, localOperations = false) {
|
|
3611
|
-
if (result.status === "attention") return "attention";
|
|
3612
|
-
if (result.status === "failed") return "failed";
|
|
3613
|
-
const unresolvedConflicts = pathsForOutcome(plan).conflicts;
|
|
3614
|
-
if (result.status === "conflict" || unresolvedConflicts.length > 0) return "conflict";
|
|
3615
|
-
if (pathsForOutcome(plan).preserved.length > 0 && pathsForOutcome(plan).applied.length === 0 && !authorityTransition && !localOperations) return "preserved";
|
|
3616
|
-
if (result.status === "noop" || result.status === "applied" && pathsForOutcome(plan).applied.length === 0 && !authorityTransition && !localOperations) return "noop";
|
|
3617
|
-
return "applied";
|
|
3618
|
-
}
|
|
3619
|
-
function recoveryOutcomeStatus(status) {
|
|
3620
|
-
if (status === "conflict") return "conflict";
|
|
3621
|
-
if (status === "attention") return "attention";
|
|
3622
|
-
if (status === "none") return "invalid";
|
|
3623
|
-
if (status === "failed") return "failed";
|
|
3624
|
-
return "applied";
|
|
3625
|
-
}
|
|
3626
|
-
async function update(dir, options = {}) {
|
|
3627
|
-
const root = resolve(dir);
|
|
3628
|
-
const bundle = executingBundle(options);
|
|
3629
|
-
if (!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(bundle.version)) {
|
|
3630
|
-
return outcome("invalid", { diagnostics: [`Invalid executing bundle version '${bundle.version}'.`] });
|
|
3631
|
-
}
|
|
3632
|
-
if (options.automatic && (options.recovery !== void 0 || options.legacyInit === true || options.force === true || (options.replaceCustomized?.length ?? 0) > 0 || (options.repair?.length ?? 0) > 0 || options.executionProfile !== void 0 || options.disableAutoMemory !== void 0 || options.gitignore !== void 0 || options.harnesses !== void 0)) {
|
|
3633
|
-
return outcome("invalid", { diagnostics: ["Automatic updates cannot include recovery, setup, repair, replacement, migration, or profile options."] });
|
|
3634
|
-
}
|
|
3635
|
-
if (options.preview && options.recovery !== void 0) {
|
|
3636
|
-
return outcome("invalid", { diagnostics: ["A preview cannot run a recovery or rollback operation."] });
|
|
3637
|
-
}
|
|
3638
|
-
if (options.force && !options.legacyInit) {
|
|
3639
|
-
return outcome("invalid", { diagnostics: ["--force is supported only by the init alias."] });
|
|
3640
|
-
}
|
|
3641
|
-
for (const requestedPath of [...options.replaceCustomized ?? [], ...options.repair ?? []]) {
|
|
3642
|
-
try {
|
|
3643
|
-
normalizeManifestPath(requestedPath);
|
|
3644
|
-
} catch (error) {
|
|
3645
|
-
return outcome("invalid", { diagnostics: [error instanceof Error ? error.message : String(error)] });
|
|
3646
|
-
}
|
|
3647
|
-
}
|
|
3648
|
-
const interactiveSelection = await resolveInteractiveInitOptions(root, options);
|
|
3649
|
-
options = interactiveSelection.options;
|
|
3650
|
-
if (interactiveSelection.emptySelection) {
|
|
3651
|
-
return outcome("noop", {
|
|
3652
|
-
targetVersion: bundle.version,
|
|
3653
|
-
harnesses: [],
|
|
3654
|
-
diagnostics: [
|
|
3655
|
-
"No harness selected \u2014 Joycraft will not install any skills.",
|
|
3656
|
-
`Please run init again and select at least one harness (${HARNESSES.join(", ")}).`
|
|
3657
|
-
],
|
|
3658
|
-
registry: "unknown"
|
|
3659
|
-
});
|
|
3660
|
-
}
|
|
3661
|
-
const requestedProfile = options.gitignore;
|
|
3662
|
-
const authority = profileFromAuthorities(root, requestedProfile);
|
|
3663
|
-
if (authority.diagnostic) {
|
|
3664
|
-
const invalidProfile = options.gitignore !== void 0 && parseGitignoreProfile(options.gitignore) === null;
|
|
3665
|
-
return outcome(invalidProfile ? "invalid" : "attention", { diagnostics: [authority.diagnostic], profile: authority.profile });
|
|
3666
|
-
}
|
|
3667
|
-
if (options.harnesses !== void 0 && parseSelection(options.harnesses) === null) {
|
|
3668
|
-
return outcome("invalid", { profile: authority.profile, diagnostics: ["Invalid harness selection. Choose from claude, codex, pi, copilot, or omp."] });
|
|
3669
|
-
}
|
|
3670
|
-
if (options.recovery === "recover") {
|
|
3671
|
-
const transaction2 = recoverInterruptedUpdate(root, { profile: authority.profile });
|
|
3672
|
-
const status2 = recoveryOutcomeStatus(transaction2.status);
|
|
3673
|
-
return outcome(status2, { profile: authority.profile, transaction: transaction2, diagnostics: transaction2.diagnostics, conflicts: transaction2.conflicts });
|
|
3674
|
-
}
|
|
3675
|
-
if (options.recovery === "rollback") {
|
|
3676
|
-
const transaction2 = rollbackLastSuccessfulUpdate(root, { profile: authority.profile });
|
|
3677
|
-
const status2 = recoveryOutcomeStatus(transaction2.status);
|
|
3678
|
-
return outcome(status2, { profile: authority.profile, transaction: transaction2, diagnostics: transaction2.diagnostics, conflicts: transaction2.conflicts });
|
|
3679
|
-
}
|
|
3680
|
-
const existingManifest = authority.manifestInfo.manifest ?? authority.sourceManifestInfo?.manifest;
|
|
3681
|
-
const legacyProject = legacyStateExists(root) || hasRecognizedHarness(root);
|
|
3682
|
-
let harnesses = chosenHarnesses(root, options, existingManifest);
|
|
3683
|
-
if (harnesses === null) {
|
|
3684
|
-
if (options.legacyInit && !interactive(options)) {
|
|
3685
|
-
harnesses = [...HARNESSES];
|
|
3686
|
-
} else {
|
|
3687
|
-
return outcome("invalid", {
|
|
3688
|
-
profile: authority.profile,
|
|
3689
|
-
diagnostics: ["Fresh unattended update requires explicit harness selection via --harnesses."]
|
|
3690
|
-
});
|
|
3691
|
-
}
|
|
3692
|
-
}
|
|
3693
|
-
if (harnesses.length === 0) return outcome("invalid", { profile: authority.profile, diagnostics: ["Select at least one harness."] });
|
|
3694
|
-
if (options.legacyInit && options.nonInteractive === true && options.harnesses === void 0) {
|
|
3695
|
-
}
|
|
3696
|
-
const baseEntries = bundle.inventory ? [...bundle.inventory] : getBundleInventory(harnesses);
|
|
3697
|
-
let manifest;
|
|
3698
|
-
let localSettings;
|
|
3699
|
-
if (existingManifest) {
|
|
3700
|
-
manifest = { ...existingManifest, harnesses: [...harnesses], profile: authority.profile };
|
|
3701
|
-
} else if (legacyProject) {
|
|
3702
|
-
const adopted = localSettingsFromAdoption(root, baseEntries, bundle, authority.profile);
|
|
3703
|
-
manifest = { ...adopted.manifest, harnesses: [...harnesses], profile: authority.profile };
|
|
3704
|
-
localSettings = adopted.localSettings;
|
|
3705
|
-
} else {
|
|
3706
|
-
manifest = {
|
|
3707
|
-
schemaVersion: 1,
|
|
3708
|
-
targetVersion: bundle.version,
|
|
3709
|
-
bundleIntegrity: bundle.integrity ?? "",
|
|
3710
|
-
harnesses: [...harnesses],
|
|
3711
|
-
profile: authority.profile,
|
|
3712
|
-
files: {}
|
|
3713
|
-
};
|
|
3714
|
-
}
|
|
3715
|
-
const stack = await detectStack(root);
|
|
3716
|
-
const canonicalInventory = !bundle.inventory || baseEntries.some((entry) => entry.path === "CLAUDE.md" && entry.kind === "create-once") && baseEntries.some((entry) => entry.path.startsWith("docs/templates/"));
|
|
3717
|
-
const materialized = materializeFreshInstallInventory({
|
|
3718
|
-
root,
|
|
3719
|
-
entries: baseEntries,
|
|
3720
|
-
manifest,
|
|
3721
|
-
harnesses,
|
|
3722
|
-
profile: authority.profile,
|
|
3723
|
-
stack,
|
|
3724
|
-
executionProfile: options.executionProfile ?? defaultExecutionProfile(harnesses),
|
|
3725
|
-
disableAutoMemory: options.disableAutoMemory,
|
|
3726
|
-
freshInstall: !existingManifest && !legacyProject && canonicalInventory,
|
|
3727
|
-
// The init alias is the explicit setup boundary. It may merge the
|
|
3728
|
-
// allowlisted Claude settings fragments on an established installation;
|
|
3729
|
-
// ordinary update/upgrade must leave that user configuration alone.
|
|
3730
|
-
configureClaude: options.legacyInit === true,
|
|
3731
|
-
force: options.legacyInit === true && options.force === true
|
|
3732
|
-
});
|
|
3733
|
-
const entries = materialized.entries;
|
|
3734
|
-
const setupPatches = materialized.setup.patchOperations;
|
|
3735
|
-
let profileActions;
|
|
3736
|
-
try {
|
|
3737
|
-
for (const directory of materialized.setup.directories) resolveUpdatePath(root, directory);
|
|
3738
|
-
profileActions = profileBookkeepingActions(root, authority.profile);
|
|
3739
|
-
} catch (error) {
|
|
3740
|
-
return outcome("attention", {
|
|
3741
|
-
targetVersion: bundle.version,
|
|
3742
|
-
profile: authority.profile,
|
|
3743
|
-
harnesses,
|
|
3744
|
-
diagnostics: [`Profile bookkeeping path needs attention: ${error instanceof Error ? error.message : String(error)}`],
|
|
3745
|
-
registry: "unknown"
|
|
3746
|
-
});
|
|
3747
|
-
}
|
|
3748
|
-
const paths = /* @__PURE__ */ new Set([
|
|
3749
|
-
...entries.map((entry) => entry.path),
|
|
3750
|
-
...Object.keys(manifest.files)
|
|
3751
|
-
]);
|
|
3752
|
-
const snapshot = snapshotFor(root, paths);
|
|
3753
|
-
const replaceCustomized = [...options.replaceCustomized ?? []];
|
|
3754
|
-
const forceCustomized = [];
|
|
3755
|
-
if (options.legacyInit && options.force) {
|
|
3756
|
-
for (const entry of entries) {
|
|
3757
|
-
if (entry.content !== void 0 && (entry.kind === "vendor" || entry.kind === "create-once")) {
|
|
3758
|
-
replaceCustomized.push(entry.path);
|
|
3759
|
-
forceCustomized.push(entry.path);
|
|
3760
|
-
}
|
|
3761
|
-
}
|
|
3762
|
-
}
|
|
3763
|
-
const plan = createUpdatePlan({
|
|
3764
|
-
snapshot,
|
|
3765
|
-
manifest,
|
|
3766
|
-
inventory: entries,
|
|
3767
|
-
options: {
|
|
3768
|
-
targetVersion: bundle.version,
|
|
3769
|
-
bundleIntegrity: bundle.integrity ?? "",
|
|
3770
|
-
safeUnattended: options.yes === true || options.nonInteractive === true || process.stdin.isTTY !== true,
|
|
3771
|
-
replaceCustomized: [...new Set(replaceCustomized)],
|
|
3772
|
-
forceCustomized: [...new Set(forceCustomized)],
|
|
3773
|
-
repair: options.repair,
|
|
3774
|
-
baseManifestDigest: existingManifest ? void 0 : null
|
|
3775
|
-
}
|
|
3776
|
-
});
|
|
3777
|
-
plan.diagnostics.push(...materialized.diagnostics.map((diagnostic) => /settings\.json is malformed/i.test(diagnostic) && !/fix the json/i.test(diagnostic) ? `${diagnostic} Fix the JSON before retrying.` : diagnostic));
|
|
3778
|
-
for (const operation of setupPatches) plan.actions.push(setupPatchAction(operation));
|
|
3779
|
-
plan.actions.push(...profileActions);
|
|
3780
|
-
plan.baseManifestDigest = existingManifest ? manifestDigest(existingManifest) : null;
|
|
3781
|
-
const selected2 = pathsForOutcome(plan);
|
|
3782
|
-
plan.nextManifest.pendingConflicts = selected2.conflicts;
|
|
3783
|
-
const authorityTransition = authority.sourceProfile && existingManifest ? {
|
|
3784
|
-
oldAuthority: {
|
|
3785
|
-
profile: authority.sourceProfile,
|
|
3786
|
-
digest: manifestDigest(existingManifest),
|
|
3787
|
-
...authority.sourceManifestInfo?.raw !== void 0 ? { raw: authority.sourceManifestInfo.raw } : {}
|
|
3788
|
-
},
|
|
3789
|
-
newAuthority: { profile: authority.profile, digest: null }
|
|
3790
|
-
} : void 0;
|
|
3791
|
-
const localOperations = legacyMigrationOperations(root, localSettings);
|
|
3792
|
-
if (options.automatic) {
|
|
3793
|
-
const eligibility = evaluateAutoSafeEligibility({
|
|
3794
|
-
policy: readUpdatePolicy(root),
|
|
3795
|
-
candidate: options.verifiedArtifact,
|
|
3796
|
-
executingVersion: bundle.version,
|
|
3797
|
-
executingIntegrity: bundle.integrity || void 0,
|
|
3798
|
-
executingDescriptor: bundle.descriptor,
|
|
3799
|
-
manifestSchema: manifest.schemaVersion,
|
|
3800
|
-
plan,
|
|
3801
|
-
existingManifest,
|
|
3802
|
-
replaceCustomized,
|
|
3803
|
-
repair: options.repair,
|
|
3804
|
-
migration: localOperations.length > 0,
|
|
3805
|
-
legacyBridge: !existingManifest && legacyProject,
|
|
3806
|
-
setupChanges: setupPatches.length > 0,
|
|
3807
|
-
// Profile bookkeeping is project configuration. An idempotent profile
|
|
3808
|
-
// has no action; any append belongs to an explicit reviewed update.
|
|
3809
|
-
profileChanges: profileActions.some((action) => action.selected),
|
|
3810
|
-
localOperations: localOperations.length > 0,
|
|
3811
|
-
authorityTransition: authorityTransition !== void 0
|
|
3812
|
-
});
|
|
3813
|
-
if (!eligibility.eligible) {
|
|
3814
|
-
return outcome(selected2.conflicts.length > 0 ? "conflict" : "invalid", {
|
|
3815
|
-
targetVersion: bundle.version,
|
|
3816
|
-
profile: authority.profile,
|
|
3817
|
-
harnesses,
|
|
3818
|
-
preserved: selected2.preserved,
|
|
3819
|
-
conflicts: selected2.conflicts,
|
|
3820
|
-
diagnostics: [...plan.diagnostics, ...eligibility.diagnostics],
|
|
3821
|
-
plan,
|
|
3822
|
-
localSettings,
|
|
3823
|
-
registry: "unknown"
|
|
3824
|
-
});
|
|
3825
|
-
}
|
|
3826
|
-
plan.nextManifest.bundleIntegrity = options.verifiedArtifact.release.integrity;
|
|
3827
|
-
}
|
|
3828
|
-
if (options.preview) {
|
|
3829
|
-
const previewStatus = selected2.conflicts.length > 0 ? "conflict" : selected2.preserved.length > 0 && selected2.applied.length === 0 ? "preserved" : selected2.applied.length > 0 ? "applied" : "noop";
|
|
3830
|
-
return outcome(previewStatus, {
|
|
3831
|
-
targetVersion: bundle.version,
|
|
3832
|
-
profile: authority.profile,
|
|
3833
|
-
harnesses,
|
|
3834
|
-
applied: [],
|
|
3835
|
-
preserved: selected2.preserved,
|
|
3836
|
-
conflicts: selected2.conflicts,
|
|
3837
|
-
diagnostics: plan.diagnostics,
|
|
3838
|
-
plan,
|
|
3839
|
-
localSettings,
|
|
3840
|
-
registry: "unknown"
|
|
3841
|
-
});
|
|
3842
|
-
}
|
|
3843
|
-
let transaction;
|
|
3844
|
-
try {
|
|
3845
|
-
transaction = applyUpdatePlan(root, plan, {
|
|
3846
|
-
profile: authority.profile,
|
|
3847
|
-
...authorityTransition ? { authorityTransition } : {},
|
|
3848
|
-
...localOperations.length ? { localOperations } : {}
|
|
3849
|
-
});
|
|
3850
|
-
} catch (error) {
|
|
3851
|
-
return outcome("failed", {
|
|
3852
|
-
targetVersion: bundle.version,
|
|
3853
|
-
profile: authority.profile,
|
|
3854
|
-
harnesses,
|
|
3855
|
-
applied: [],
|
|
3856
|
-
preserved: selected2.preserved,
|
|
3857
|
-
conflicts: selected2.conflicts,
|
|
3858
|
-
diagnostics: [error instanceof Error ? error.message : String(error)],
|
|
3859
|
-
plan,
|
|
3860
|
-
localSettings,
|
|
3861
|
-
registry: "unknown"
|
|
3862
|
-
});
|
|
3863
|
-
}
|
|
3864
|
-
const status = transactionStatus(plan, transaction, authorityTransition !== void 0, localOperations.length > 0);
|
|
3865
|
-
const actualApplied = transaction.status === "applied" ? selected2.applied : [];
|
|
3866
|
-
if (transaction.status === "applied" || transaction.status === "noop") {
|
|
3867
|
-
try {
|
|
3868
|
-
for (const directory of materialized.setup.directories) {
|
|
3869
|
-
resolveUpdatePath(root, directory);
|
|
3870
|
-
mkdirSync3(join10(root, ...directory.split("/")), { recursive: true });
|
|
3871
|
-
}
|
|
3872
|
-
} catch (error) {
|
|
3873
|
-
return outcome("attention", {
|
|
3874
|
-
targetVersion: bundle.version,
|
|
3875
|
-
profile: authority.profile,
|
|
3876
|
-
harnesses,
|
|
3877
|
-
applied: actualApplied,
|
|
3878
|
-
preserved: selected2.preserved,
|
|
3879
|
-
conflicts: selected2.conflicts,
|
|
3880
|
-
diagnostics: [`Update applied but profile bookkeeping needs attention: ${String(error)}`],
|
|
3881
|
-
transaction,
|
|
3882
|
-
plan,
|
|
3883
|
-
localSettings,
|
|
3884
|
-
registry: "unknown"
|
|
3885
|
-
});
|
|
3886
|
-
}
|
|
3887
|
-
}
|
|
3888
|
-
const diagnostics = [...plan.diagnostics, ...transaction.diagnostics];
|
|
3889
|
-
if (transaction.status === "applied" && authority.profile === "shared") {
|
|
3890
|
-
const manifestWarning = sharedManifestIgnoreWarning(root);
|
|
3891
|
-
if (manifestWarning) diagnostics.push(manifestWarning);
|
|
3892
|
-
diagnostics.push(...selectedHarnessIgnoreWarning(root, harnesses));
|
|
3893
|
-
}
|
|
3894
|
-
return outcome(status, {
|
|
3895
|
-
targetVersion: bundle.version,
|
|
3896
|
-
installedVersion: transaction.status === "applied" || transaction.status === "noop" ? plan.nextManifest.targetVersion : existingManifest?.targetVersion,
|
|
3897
|
-
profile: authority.profile,
|
|
3898
|
-
harnesses,
|
|
3899
|
-
applied: actualApplied,
|
|
3900
|
-
preserved: selected2.preserved,
|
|
3901
|
-
conflicts: [.../* @__PURE__ */ new Set([...selected2.conflicts, ...transaction.conflicts])],
|
|
3902
|
-
diagnostics,
|
|
3903
|
-
transaction,
|
|
3904
|
-
plan,
|
|
3905
|
-
localSettings,
|
|
3906
|
-
existingSkills: materialized.setup.existingSkills,
|
|
3907
|
-
registry: "unknown"
|
|
3908
|
-
});
|
|
3909
|
-
}
|
|
3910
|
-
function formatUpdateOutcome(result, json = false) {
|
|
3911
|
-
if (json) {
|
|
3912
|
-
return JSON.stringify({
|
|
3913
|
-
status: result.status,
|
|
3914
|
-
exitCode: result.exitCode,
|
|
3915
|
-
targetVersion: result.targetVersion,
|
|
3916
|
-
installedVersion: result.installedVersion,
|
|
3917
|
-
profile: result.profile,
|
|
3918
|
-
harnesses: result.harnesses,
|
|
3919
|
-
applied: result.applied,
|
|
3920
|
-
preserved: result.preserved,
|
|
3921
|
-
conflicts: result.conflicts,
|
|
3922
|
-
diagnostics: result.diagnostics,
|
|
3923
|
-
registry: result.registry,
|
|
3924
|
-
existingSkills: result.existingSkills,
|
|
3925
|
-
transaction: result.transaction
|
|
3926
|
-
});
|
|
3927
|
-
}
|
|
3928
|
-
const lines = [`Joycraft update: ${result.status}.`];
|
|
3929
|
-
if (result.targetVersion) lines.push(` Target: ${result.targetVersion}`);
|
|
3930
|
-
if (result.applied.length) lines.push(` Applied: ${result.applied.length}`);
|
|
3931
|
-
if (result.preserved.length) lines.push(` Preserved customizations: ${result.preserved.join(", ")}`);
|
|
3932
|
-
if (result.conflicts.length) lines.push(` Pending conflicts: ${result.conflicts.join(", ")}`);
|
|
3933
|
-
for (const diagnostic of result.diagnostics) lines.push(` \u26A0 ${diagnostic}`);
|
|
3934
|
-
return lines.join("\n");
|
|
3935
|
-
}
|
|
3936
|
-
|
|
3937
|
-
export {
|
|
3938
|
-
updateStatusExitCode,
|
|
3939
|
-
update,
|
|
3940
|
-
formatUpdateOutcome
|
|
3941
|
-
};
|
|
3942
|
-
//# sourceMappingURL=chunk-GTP7Z52K.js.map
|