@litfamily/litcodex 1.0.39 → 1.0.41
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-Ko-KR.md +37 -15
- package/README.md +37 -15
- package/dist/cli.js +13 -0
- package/dist/install/auto-handoff-doctor.js +14 -8
- package/dist/install/extensions-notice.d.ts +13 -0
- package/dist/install/extensions-notice.js +26 -6
- package/dist/install/extensions.d.ts +74 -0
- package/dist/install/extensions.js +856 -0
- package/dist/install/generated-skill-payload-hashes.d.ts +8 -8
- package/dist/install/generated-skill-payload-hashes.js +8 -8
- package/dist/install/index.js +7 -1
- package/marketplace/plugins/litcodex/.codex-plugin/plugin.json +1 -1
- package/marketplace/plugins/litcodex/components/auto-update/dist/extensions-notice.js +13 -2
- package/marketplace/plugins/litcodex/components/auto-update/dist/shown-notices.d.ts +6 -0
- package/marketplace/plugins/litcodex/components/auto-update/dist/shown-notices.js +63 -0
- package/marketplace/plugins/litcodex/components/auto-update/package.json +1 -1
- package/marketplace/plugins/litcodex/components/comment-checker/package.json +1 -1
- package/marketplace/plugins/litcodex/components/git-bash/package.json +1 -1
- package/marketplace/plugins/litcodex/components/lit-loop/directives/lit-schematic.md +5 -3
- package/marketplace/plugins/litcodex/components/lit-loop/directives/lit-scientific-visualization.md +5 -3
- package/marketplace/plugins/litcodex/components/lit-loop/dist/auto-handoff-settings.d.ts +7 -4
- package/marketplace/plugins/litcodex/components/lit-loop/dist/auto-handoff-settings.js +38 -22
- package/marketplace/plugins/litcodex/components/lit-loop/dist/auto-handoff.js +7 -5
- package/marketplace/plugins/litcodex/components/lit-loop/dist/hook-cli.js +7 -0
- package/marketplace/plugins/litcodex/components/lit-loop/dist/route-heads.js +1 -2
- package/marketplace/plugins/litcodex/components/lit-loop/dist/run-end.d.ts +22 -0
- package/marketplace/plugins/litcodex/components/lit-loop/dist/run-end.js +93 -0
- package/marketplace/plugins/litcodex/components/lit-loop/dist/workflow-map.d.ts +2 -0
- package/marketplace/plugins/litcodex/components/lit-loop/dist/workflow-map.js +3 -1
- package/marketplace/plugins/litcodex/components/lit-loop/package.json +1 -1
- package/marketplace/plugins/litcodex/components/lsp/package.json +1 -1
- package/marketplace/plugins/litcodex/components/rules/package.json +1 -1
- package/marketplace/plugins/litcodex/components/start-work-continuation/package.json +1 -1
- package/marketplace/plugins/litcodex/components/telemetry/package.json +1 -1
- package/marketplace/plugins/litcodex/components/wikify-knowledge/package.json +1 -1
- package/marketplace/plugins/litcodex/skills/frontend-ui-ux/SKILL.md +6 -4
- package/marketplace/plugins/litcodex/skills/lit-diagram-drawer/SKILL.md +6 -4
- package/marketplace/plugins/litcodex/skills/lit-docx/SKILL.md +6 -4
- package/marketplace/plugins/litcodex/skills/lit-pptx/SKILL.md +6 -4
- package/marketplace/plugins/litcodex/skills/lit-schematic/SKILL.md +6 -4
- package/marketplace/plugins/litcodex/skills/lit-scientific-visualization/SKILL.md +6 -4
- package/marketplace/plugins/litcodex/skills/lit-typographic-motion/SKILL.md +6 -4
- package/marketplace/plugins/litcodex/skills/readme-studio/SKILL.md +6 -4
- package/marketplace/plugins/litcodex/skills/visual-qa/SKILL.md +6 -4
- package/node_modules/@litcodex/lit-loop/README.md +4 -4
- package/node_modules/@litcodex/lit-loop/directives/lit-schematic.md +5 -3
- package/node_modules/@litcodex/lit-loop/directives/lit-scientific-visualization.md +5 -3
- package/node_modules/@litcodex/lit-loop/dist/auto-handoff-settings.d.ts +7 -4
- package/node_modules/@litcodex/lit-loop/dist/auto-handoff-settings.js +38 -22
- package/node_modules/@litcodex/lit-loop/dist/auto-handoff.js +7 -5
- package/node_modules/@litcodex/lit-loop/dist/hook-cli.js +7 -0
- package/node_modules/@litcodex/lit-loop/dist/route-heads.js +1 -2
- package/node_modules/@litcodex/lit-loop/dist/run-end.d.ts +22 -0
- package/node_modules/@litcodex/lit-loop/dist/run-end.js +93 -0
- package/node_modules/@litcodex/lit-loop/dist/workflow-map.d.ts +2 -0
- package/node_modules/@litcodex/lit-loop/dist/workflow-map.js +3 -1
- package/node_modules/@litcodex/lit-loop/package.json +1 -1
- package/node_modules/@litcodex/lit-loop/skills/lit-schematic/SKILL.md +6 -4
- package/node_modules/@litcodex/lit-loop/skills/lit-scientific-visualization/SKILL.md +6 -4
- package/package.json +2 -2
- package/readme-assets/badge-version.svg +1 -1
|
@@ -0,0 +1,856 @@
|
|
|
1
|
+
// `litcodex extensions <verb>`: list, check, install, update, remove and prune the nine LitFamily extensions.
|
|
2
|
+
//
|
|
3
|
+
// This is the four manual stub lines (check, move aside, copy, receipt) done in code. It writes only to
|
|
4
|
+
// ${CODEX_HOME}/skills/<id>, ${CODEX_HOME}/extension-backups/ and its own source clone under
|
|
5
|
+
// ${XDG_CACHE_HOME:-~/.cache}/litcodex/extensions-src. The other folders Codex reads skills from (~/.agents/skills and
|
|
6
|
+
// the project's .agents/skills and .codex/skills) are only read: a same-name skill there stops an install. Every write
|
|
7
|
+
// verb is a dry run until --yes is given, and nothing is ever deleted except backups by `prune-backups --yes`.
|
|
8
|
+
import { spawnSync } from "node:child_process";
|
|
9
|
+
import { createHash } from "node:crypto";
|
|
10
|
+
import { cpSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync, } from "node:fs";
|
|
11
|
+
import { createRequire } from "node:module";
|
|
12
|
+
import { homedir } from "node:os";
|
|
13
|
+
import { dirname, join, relative, resolve, sep } from "node:path";
|
|
14
|
+
import { resolveCodexHome } from "./codex.js";
|
|
15
|
+
import { CLONE_PLACEHOLDER, EXTENSIONS_REPO_URL, extensionsNoticePath, leftoverRuntimePaths, } from "./extensions-notice.js";
|
|
16
|
+
export const EXTENSION_FAMILIES = {
|
|
17
|
+
decks: ["lit-pptx"],
|
|
18
|
+
documents: ["lit-docx"],
|
|
19
|
+
figures: ["lit-diagram-drawer", "lit-schematic", "lit-scientific-visualization"],
|
|
20
|
+
design: ["frontend-ui-ux", "visual-qa"],
|
|
21
|
+
"video-covers": ["lit-typographic-motion", "readme-studio"],
|
|
22
|
+
};
|
|
23
|
+
export const EXTENSION_IDS = Object.values(EXTENSION_FAMILIES).flat();
|
|
24
|
+
export const RECEIPT_NAME = ".litfamily-extension.json";
|
|
25
|
+
const VARIANT = "litcodex";
|
|
26
|
+
const USAGE_EXIT_CODE = 64;
|
|
27
|
+
const PACKAGE_VERSION = createRequire(import.meta.url)("../../package.json").version;
|
|
28
|
+
const familyOf = (id) => Object.entries(EXTENSION_FAMILIES).find(([, ids]) => ids.includes(id))?.[0] ?? "";
|
|
29
|
+
function pathsFor(env) {
|
|
30
|
+
const codexHome = resolveCodexHome(env);
|
|
31
|
+
const home = env["HOME"]?.trim() || homedir();
|
|
32
|
+
const cacheRoot = env["XDG_CACHE_HOME"]?.trim() || join(home, ".cache");
|
|
33
|
+
return {
|
|
34
|
+
codexHome,
|
|
35
|
+
skills: join(codexHome, "skills"),
|
|
36
|
+
backups: join(codexHome, "extension-backups"),
|
|
37
|
+
cache: join(cacheRoot, "litcodex", "extensions-src"),
|
|
38
|
+
home,
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
function lstat(path) {
|
|
42
|
+
try {
|
|
43
|
+
return lstatSync(path);
|
|
44
|
+
}
|
|
45
|
+
catch {
|
|
46
|
+
return undefined;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
function readReceipt(dir, id) {
|
|
50
|
+
try {
|
|
51
|
+
const parsed = JSON.parse(readFileSync(join(dir, RECEIPT_NAME), "utf8"));
|
|
52
|
+
if (parsed.id !== id || parsed.variant !== VARIANT)
|
|
53
|
+
return undefined;
|
|
54
|
+
if (typeof parsed.source !== "string" || typeof parsed.installed_at !== "string")
|
|
55
|
+
return undefined;
|
|
56
|
+
return parsed;
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
return undefined;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
function skillName(skillMd) {
|
|
63
|
+
try {
|
|
64
|
+
const text = readFileSync(skillMd, "utf8");
|
|
65
|
+
return /^---\r?\n(?:[^\n]*\n)*?name:\s*["']?([^"'\r\n]+?)["']?\s*\r?\n/u.exec(text)?.[1];
|
|
66
|
+
}
|
|
67
|
+
catch {
|
|
68
|
+
return undefined;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
/** The repo root Codex resolves project skills against: the nearest folder holding .git, or cwd. */
|
|
72
|
+
function projectFolders(cwd) {
|
|
73
|
+
const chain = [];
|
|
74
|
+
let dir = resolve(cwd);
|
|
75
|
+
for (;;) {
|
|
76
|
+
chain.push(dir);
|
|
77
|
+
if (existsSync(join(dir, ".git")))
|
|
78
|
+
return chain;
|
|
79
|
+
const parent = dirname(dir);
|
|
80
|
+
if (parent === dir)
|
|
81
|
+
return [resolve(cwd)];
|
|
82
|
+
dir = parent;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
/** Every other folder Codex 0.167 reads skills from, in the order it was probed. */
|
|
86
|
+
function otherRoots(ctx, paths) {
|
|
87
|
+
const chain = projectFolders(ctx.cwd);
|
|
88
|
+
const root = chain.at(-1);
|
|
89
|
+
return [
|
|
90
|
+
...chain.map((dir) => join(dir, ".agents", "skills")),
|
|
91
|
+
join(root, ".codex", "skills"),
|
|
92
|
+
join(paths.home, ".agents", "skills"),
|
|
93
|
+
].filter((dir, index, all) => all.indexOf(dir) === index && resolve(dir) !== resolve(paths.skills));
|
|
94
|
+
}
|
|
95
|
+
/** Folders in `dir` named `id`, or whose SKILL.md says `name: <id>`. */
|
|
96
|
+
function sameNameIn(dir, id) {
|
|
97
|
+
let names;
|
|
98
|
+
try {
|
|
99
|
+
names = readdirSync(dir).sort();
|
|
100
|
+
}
|
|
101
|
+
catch {
|
|
102
|
+
return [];
|
|
103
|
+
}
|
|
104
|
+
return names
|
|
105
|
+
.filter((name) => name === id || skillName(join(dir, name, "SKILL.md")) === id)
|
|
106
|
+
.map((name) => join(dir, name));
|
|
107
|
+
}
|
|
108
|
+
function entryFor(id, ctx, paths) {
|
|
109
|
+
const path = join(paths.skills, id);
|
|
110
|
+
const competing = otherRoots(ctx, paths).flatMap((dir) => sameNameIn(dir, id));
|
|
111
|
+
const stat = lstat(path);
|
|
112
|
+
const base = { id, family: familyOf(id), path, competing };
|
|
113
|
+
if (stat === undefined)
|
|
114
|
+
return { ...base, state: "not-installed" };
|
|
115
|
+
if (stat.isSymbolicLink() || !stat.isDirectory())
|
|
116
|
+
return { ...base, state: "not-a-folder" };
|
|
117
|
+
const receipt = readReceipt(path, id);
|
|
118
|
+
return receipt === undefined ? { ...base, state: "user-managed" } : { ...base, state: "installed", receipt };
|
|
119
|
+
}
|
|
120
|
+
function dirBytes(dir) {
|
|
121
|
+
let total = 0;
|
|
122
|
+
for (const name of readdirSync(dir)) {
|
|
123
|
+
const path = join(dir, name);
|
|
124
|
+
const stat = lstatSync(path);
|
|
125
|
+
total += stat.isDirectory() ? dirBytes(path) : stat.size;
|
|
126
|
+
}
|
|
127
|
+
return total;
|
|
128
|
+
}
|
|
129
|
+
const STAMP_RE = /^(\d{4})(\d{2})(\d{2})-(\d{2})(\d{2})(\d{2})(?:-\d+)?$/u;
|
|
130
|
+
function listBackups(paths) {
|
|
131
|
+
const stat = lstat(paths.backups);
|
|
132
|
+
if (stat === undefined || stat.isSymbolicLink() || !stat.isDirectory())
|
|
133
|
+
return [];
|
|
134
|
+
return readdirSync(paths.backups)
|
|
135
|
+
.sort()
|
|
136
|
+
.flatMap((name) => {
|
|
137
|
+
const match = STAMP_RE.exec(name);
|
|
138
|
+
const path = join(paths.backups, name);
|
|
139
|
+
const entry = lstat(path);
|
|
140
|
+
if (match === null || entry === undefined || entry.isSymbolicLink() || !entry.isDirectory())
|
|
141
|
+
return [];
|
|
142
|
+
const [y = 0, mo = 1, d = 1, h = 0, mi = 0, s = 0] = match.slice(1, 7).map(Number);
|
|
143
|
+
return [{ name, path, bytes: dirBytes(path), takenAt: new Date(y, mo - 1, d, h, mi, s) }];
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
/** Other folders in Codex's own skills folder whose SKILL.md names an extension id. */
|
|
147
|
+
function duplicatesIn(paths) {
|
|
148
|
+
if (lstat(paths.skills)?.isDirectory() !== true)
|
|
149
|
+
return [];
|
|
150
|
+
return readdirSync(paths.skills)
|
|
151
|
+
.sort()
|
|
152
|
+
.flatMap((name) => {
|
|
153
|
+
if (EXTENSION_IDS.includes(name))
|
|
154
|
+
return [];
|
|
155
|
+
const id = skillName(join(paths.skills, name, "SKILL.md"));
|
|
156
|
+
return id !== undefined && EXTENSION_IDS.includes(id) ? [{ id, name, path: join(paths.skills, name) }] : [];
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
/** A shell line that moves a folder into a dated backup set, the way the manual move-aside line does. */
|
|
160
|
+
function moveAsideLine(paths, path, name) {
|
|
161
|
+
return `b="${paths.backups}/$(date +%Y%m%d-%H%M%S)"; mkdir -p "$b" && [ ! -e "$b/${name}" ] && mv "${path}" "$b/${name}"`;
|
|
162
|
+
}
|
|
163
|
+
export function checkExtensions(ctx) {
|
|
164
|
+
const paths = pathsFor(ctx.env);
|
|
165
|
+
const entries = EXTENSION_IDS.map((id) => entryFor(id, ctx, paths));
|
|
166
|
+
const findings = [];
|
|
167
|
+
for (const entry of entries) {
|
|
168
|
+
for (const path of entry.competing) {
|
|
169
|
+
findings.push({
|
|
170
|
+
kind: "competing",
|
|
171
|
+
id: entry.id,
|
|
172
|
+
path,
|
|
173
|
+
message: `${entry.id}: Codex also lists ${path}, a same-name skill LitCodex never touches`,
|
|
174
|
+
fix: `move ${path} out of that folder yourself, or keep it on purpose and install with --allow-shadow`,
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
if (entry.state === "not-a-folder") {
|
|
178
|
+
findings.push({
|
|
179
|
+
kind: "not-a-folder",
|
|
180
|
+
id: entry.id,
|
|
181
|
+
path: entry.path,
|
|
182
|
+
message: `${entry.id}: ${entry.path} is a symbolic link or a file`,
|
|
183
|
+
fix: `move ${entry.path} away yourself, then run \`litcodex extensions install ${entry.id} --yes\``,
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
if (entry.state === "user-managed") {
|
|
187
|
+
findings.push({
|
|
188
|
+
kind: "no-receipt",
|
|
189
|
+
id: entry.id,
|
|
190
|
+
path: entry.path,
|
|
191
|
+
message: `${entry.id}: ${entry.path} has no receipt, so it is yours and update leaves it alone`,
|
|
192
|
+
fix: `litcodex extensions install ${entry.id} --yes (moves your folder to extension-backups and installs a tracked copy)`,
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
if (entry.state === "installed" || entry.state === "user-managed") {
|
|
196
|
+
if (existsSync(join(entry.path, entry.id, "SKILL.md"))) {
|
|
197
|
+
findings.push({
|
|
198
|
+
kind: "nested",
|
|
199
|
+
id: entry.id,
|
|
200
|
+
path: join(entry.path, entry.id),
|
|
201
|
+
message: `${entry.id}: a second copy sits inside the first at ${join(entry.path, entry.id)}`,
|
|
202
|
+
fix: `litcodex extensions install ${entry.id} --yes (moves the whole folder aside and copies once)`,
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
if (entry.receipt !== undefined && !existsSync(join(entry.receipt.source, "SKILL.md"))) {
|
|
207
|
+
findings.push({
|
|
208
|
+
kind: "source-missing",
|
|
209
|
+
id: entry.id,
|
|
210
|
+
path: entry.receipt.source,
|
|
211
|
+
message: `${entry.id}: its receipt points at ${entry.receipt.source}, which no longer exists`,
|
|
212
|
+
fix: `litcodex extensions update ${entry.id} --yes (or add --from <path to your wjgoarxiv-skills clone>)`,
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
for (const { id, name, path } of duplicatesIn(paths)) {
|
|
217
|
+
findings.push({
|
|
218
|
+
kind: "duplicate",
|
|
219
|
+
id,
|
|
220
|
+
path,
|
|
221
|
+
message: `${id}: ${path} is a second copy under another folder name, and Codex lists both`,
|
|
222
|
+
fix: moveAsideLine(paths, path, name),
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
const notice = extensionsNoticePath(ctx.env);
|
|
226
|
+
try {
|
|
227
|
+
const parsed = JSON.parse(readFileSync(notice, "utf8"));
|
|
228
|
+
if (parsed.version !== PACKAGE_VERSION) {
|
|
229
|
+
findings.push({
|
|
230
|
+
kind: "stale-notice",
|
|
231
|
+
path: notice,
|
|
232
|
+
message: `an unshown extensions notice from LitCodex ${String(parsed.version)} is still waiting`,
|
|
233
|
+
fix: `rm "${notice}"`,
|
|
234
|
+
});
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
catch {
|
|
238
|
+
// No notice waiting, or one the session hook will drop as malformed.
|
|
239
|
+
}
|
|
240
|
+
for (const path of leftoverRuntimePaths(ctx.env)) {
|
|
241
|
+
findings.push({
|
|
242
|
+
kind: "leftover-runtime",
|
|
243
|
+
path,
|
|
244
|
+
message: `LitCodex 1.0.38 and earlier left a runtime in ${path}; nothing uses it now`,
|
|
245
|
+
fix: `rm -r "${path}"`,
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
const sets = listBackups(paths);
|
|
249
|
+
return {
|
|
250
|
+
entries,
|
|
251
|
+
findings,
|
|
252
|
+
backups: { root: paths.backups, count: sets.length, bytes: sets.reduce((sum, set) => sum + set.bytes, 0) },
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
/** The one line `litcodex doctor` prints. */
|
|
256
|
+
export function extensionsDoctorLine(ctx) {
|
|
257
|
+
let report;
|
|
258
|
+
try {
|
|
259
|
+
report = checkExtensions(ctx);
|
|
260
|
+
}
|
|
261
|
+
catch (error) {
|
|
262
|
+
return `LitFamily extensions: could not be checked (${error.message}); run \`litcodex extensions check\``;
|
|
263
|
+
}
|
|
264
|
+
const installed = report.entries.filter((entry) => entry.state === "installed").length;
|
|
265
|
+
if (report.findings.length > 0) {
|
|
266
|
+
return `LitFamily extensions: ${installed} installed, ${report.findings.length} need action; run \`litcodex extensions check\` for the fix lines`;
|
|
267
|
+
}
|
|
268
|
+
if (installed === 0) {
|
|
269
|
+
return "LitFamily extensions: none installed; `litcodex extensions list` shows the nine and `litcodex extensions install <id>` adds one";
|
|
270
|
+
}
|
|
271
|
+
return `LitFamily extensions: ${installed} installed, nothing to fix`;
|
|
272
|
+
}
|
|
273
|
+
/** One notice line for existing users, or undefined when check is clean. */
|
|
274
|
+
export function extensionsNoticeLine(ctx) {
|
|
275
|
+
try {
|
|
276
|
+
// The install that prints this line also rewrites the notice, so a stale one is not counted.
|
|
277
|
+
const count = checkExtensions(ctx).findings.filter((finding) => finding.kind !== "stale-notice").length;
|
|
278
|
+
return count === 0
|
|
279
|
+
? undefined
|
|
280
|
+
: `${count} thing${count === 1 ? "" : "s"} about your extension folders need a look: run \`litcodex extensions check\`. Nothing was changed.`;
|
|
281
|
+
}
|
|
282
|
+
catch {
|
|
283
|
+
return undefined;
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
class StopError extends Error {
|
|
287
|
+
}
|
|
288
|
+
const realGit = (args) => {
|
|
289
|
+
const result = spawnSync("git", [...args], {
|
|
290
|
+
encoding: "utf8",
|
|
291
|
+
timeout: 180_000,
|
|
292
|
+
env: { ...process.env, GIT_TERMINAL_PROMPT: "0" },
|
|
293
|
+
});
|
|
294
|
+
return { status: result.status, stderr: result.stderr ?? "", ...(result.error ? { error: result.error } : {}) };
|
|
295
|
+
};
|
|
296
|
+
function gitOrStop(git, args, what) {
|
|
297
|
+
const result = git(args);
|
|
298
|
+
if (result.error !== undefined) {
|
|
299
|
+
throw new StopError(`git is not available (${result.error.message}), so the shelf cannot be ${what}. Nothing was installed. Clone ${EXTENSIONS_REPO_URL} yourself and pass --from ${CLONE_PLACEHOLDER}.`);
|
|
300
|
+
}
|
|
301
|
+
if (result.status !== 0) {
|
|
302
|
+
const reason = result.stderr.trim().split("\n").at(-1) ?? `exit ${String(result.status)}`;
|
|
303
|
+
throw new StopError(`the shelf could not be ${what} (${reason}). Nothing was installed. If you are offline, clone ${EXTENSIONS_REPO_URL} when you can and pass --from ${CLONE_PLACEHOLDER}.`);
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
function variantRoot(root) {
|
|
307
|
+
return join(root, "variants", VARIANT);
|
|
308
|
+
}
|
|
309
|
+
function resolveSource(from, paths, opts, deps) {
|
|
310
|
+
if (from !== undefined) {
|
|
311
|
+
const root = resolve(from);
|
|
312
|
+
if (lstat(variantRoot(root))?.isDirectory() !== true) {
|
|
313
|
+
throw new StopError(`${root} is not a wjgoarxiv-skills clone: ${variantRoot(root)} is missing.`);
|
|
314
|
+
}
|
|
315
|
+
return { root, kind: "from" };
|
|
316
|
+
}
|
|
317
|
+
const cached = lstat(variantRoot(paths.cache))?.isDirectory() === true;
|
|
318
|
+
if (!opts.apply) {
|
|
319
|
+
if (!cached)
|
|
320
|
+
return { kind: "cache", pending: "clone" };
|
|
321
|
+
return { root: paths.cache, kind: "cache", ...(opts.refresh ? { pending: "fetch" } : {}) };
|
|
322
|
+
}
|
|
323
|
+
const git = deps.git ?? realGit;
|
|
324
|
+
if (!cached) {
|
|
325
|
+
if (lstat(paths.cache) !== undefined) {
|
|
326
|
+
throw new StopError(`${paths.cache} exists but holds no variants/${VARIANT} folder. Move it away, or pass --from ${CLONE_PLACEHOLDER}.`);
|
|
327
|
+
}
|
|
328
|
+
const staging = `${paths.cache}.incoming-${process.pid}`;
|
|
329
|
+
mkdirSync(dirname(paths.cache), { recursive: true });
|
|
330
|
+
try {
|
|
331
|
+
gitOrStop(git, [
|
|
332
|
+
"clone",
|
|
333
|
+
"--quiet",
|
|
334
|
+
"--depth",
|
|
335
|
+
"1",
|
|
336
|
+
"--filter=blob:none",
|
|
337
|
+
"--sparse",
|
|
338
|
+
deps.repoUrl ?? `${EXTENSIONS_REPO_URL}.git`,
|
|
339
|
+
staging,
|
|
340
|
+
], "cloned");
|
|
341
|
+
gitOrStop(git, ["-C", staging, "sparse-checkout", "set", `variants/${VARIANT}`], "checked out");
|
|
342
|
+
if (lstat(variantRoot(staging))?.isDirectory() !== true) {
|
|
343
|
+
throw new StopError(`the clone has no variants/${VARIANT} folder. Nothing was installed.`);
|
|
344
|
+
}
|
|
345
|
+
renameSync(staging, paths.cache);
|
|
346
|
+
}
|
|
347
|
+
finally {
|
|
348
|
+
if (lstat(staging) !== undefined)
|
|
349
|
+
rmSync(staging, { recursive: true, force: true });
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
else if (opts.refresh) {
|
|
353
|
+
gitOrStop(git, ["-C", paths.cache, "fetch", "--quiet", "--depth", "1", "origin", "HEAD"], "fetched");
|
|
354
|
+
gitOrStop(git, ["-C", paths.cache, "checkout", "--quiet", "--force", "--detach", "FETCH_HEAD"], "checked out");
|
|
355
|
+
}
|
|
356
|
+
return { root: paths.cache, kind: "cache" };
|
|
357
|
+
}
|
|
358
|
+
// ---- folder helpers -------------------------------------------------------------------------------------------
|
|
359
|
+
function filesOf(dir, base = dir) {
|
|
360
|
+
return readdirSync(dir)
|
|
361
|
+
.sort()
|
|
362
|
+
.flatMap((name) => {
|
|
363
|
+
const path = join(dir, name);
|
|
364
|
+
const stat = lstatSync(path);
|
|
365
|
+
if (stat.isSymbolicLink())
|
|
366
|
+
throw new StopError(`${path} is a symbolic link; the source must be plain files.`);
|
|
367
|
+
if (stat.isDirectory())
|
|
368
|
+
return filesOf(path, base);
|
|
369
|
+
return [relative(base, path)];
|
|
370
|
+
});
|
|
371
|
+
}
|
|
372
|
+
/** sha256 over every file's relative path and bytes, leaving out the receipt. */
|
|
373
|
+
export function folderHash(dir) {
|
|
374
|
+
const hash = createHash("sha256");
|
|
375
|
+
for (const rel of filesOf(dir)) {
|
|
376
|
+
if (rel === RECEIPT_NAME)
|
|
377
|
+
continue;
|
|
378
|
+
hash.update(rel.split(sep).join("/"));
|
|
379
|
+
hash.update("\0");
|
|
380
|
+
hash.update(readFileSync(join(dir, rel)));
|
|
381
|
+
hash.update("\0");
|
|
382
|
+
}
|
|
383
|
+
return hash.digest("hex");
|
|
384
|
+
}
|
|
385
|
+
/** Local time, like the manual lines' `date +%Y%m%d-%H%M%S`. */
|
|
386
|
+
function stampOf(date) {
|
|
387
|
+
const pad = (n) => String(n).padStart(2, "0");
|
|
388
|
+
return `${date.getFullYear()}${pad(date.getMonth() + 1)}${pad(date.getDate())}-${pad(date.getHours())}${pad(date.getMinutes())}${pad(date.getSeconds())}`;
|
|
389
|
+
}
|
|
390
|
+
function backupTarget(paths, stamp, id) {
|
|
391
|
+
for (let n = 1;; n += 1) {
|
|
392
|
+
const target = join(paths.backups, n === 1 ? stamp : `${stamp}-${n}`, id);
|
|
393
|
+
if (lstat(target) === undefined)
|
|
394
|
+
return target;
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
function assertRealDir(path) {
|
|
398
|
+
const stat = lstat(path);
|
|
399
|
+
if (stat !== undefined && (stat.isSymbolicLink() || !stat.isDirectory())) {
|
|
400
|
+
throw new StopError(`refused: ${path} is not a plain folder. LitCodex writes only into a real folder there.`);
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
const VERB_OPTIONS = {
|
|
404
|
+
list: ["--json"],
|
|
405
|
+
check: ["--json"],
|
|
406
|
+
install: ["--family", "--all", "--from", "--yes", "--json", "--allow-shadow"],
|
|
407
|
+
update: ["--all", "--from", "--yes", "--json", "--allow-shadow"],
|
|
408
|
+
remove: ["--yes", "--json"],
|
|
409
|
+
"prune-backups": ["--older-than", "--yes", "--json"],
|
|
410
|
+
};
|
|
411
|
+
const VALUE_OPTIONS = new Set(["--family", "--from", "--older-than"]);
|
|
412
|
+
export const EXTENSIONS_HELP_TEXT = [
|
|
413
|
+
"litcodex extensions — manage the nine LitFamily extensions in Codex's own skills folder",
|
|
414
|
+
"",
|
|
415
|
+
" litcodex extensions list [--json] What is installed, yours, or competing",
|
|
416
|
+
" litcodex extensions check [--json] Read-only; exit 1 with a fix line for each problem",
|
|
417
|
+
" litcodex extensions install <id...>|--family <name>|--all [--from <clone>] [--allow-shadow] [--yes]",
|
|
418
|
+
" litcodex extensions update [<id...>|--all] [--from <clone>] [--yes] Reinstall what changed upstream",
|
|
419
|
+
" litcodex extensions remove <id...> [--yes] Move an installed copy to extension-backups",
|
|
420
|
+
" litcodex extensions prune-backups [--older-than <days>] [--yes]",
|
|
421
|
+
"",
|
|
422
|
+
"Every write is a dry run until you add --yes. Old copies move to ~/.codex/extension-backups/ (or under CODEX_HOME),",
|
|
423
|
+
"which Codex does not read; only prune-backups --yes deletes, and only there. Without --from, LitCodex keeps its own",
|
|
424
|
+
`sparse clone of ${EXTENSIONS_REPO_URL} under ~/.cache/litcodex/extensions-src.`,
|
|
425
|
+
`Families: ${Object.entries(EXTENSION_FAMILIES)
|
|
426
|
+
.map(([name, ids]) => `${name} (${ids.join(", ")})`)
|
|
427
|
+
.join("; ")}.`,
|
|
428
|
+
"",
|
|
429
|
+
].join("\n");
|
|
430
|
+
function parse(args) {
|
|
431
|
+
const help = args.includes("--help") || args.includes("-h");
|
|
432
|
+
const verb = args[0];
|
|
433
|
+
if (help)
|
|
434
|
+
return { verb: verb ?? "", ids: [], families: [], all: false, yes: false, json: false, allowShadow: false, help };
|
|
435
|
+
if (verb === undefined || !Object.hasOwn(VERB_OPTIONS, verb))
|
|
436
|
+
return `unknown verb "${verb ?? ""}"`;
|
|
437
|
+
const allowed = VERB_OPTIONS[verb];
|
|
438
|
+
const ids = [];
|
|
439
|
+
const families = [];
|
|
440
|
+
let from;
|
|
441
|
+
let olderThan;
|
|
442
|
+
const flags = new Set();
|
|
443
|
+
for (let i = 1; i < args.length; i += 1) {
|
|
444
|
+
const token = args[i];
|
|
445
|
+
if (!token.startsWith("-")) {
|
|
446
|
+
if (verb === "list" || verb === "check" || verb === "prune-backups")
|
|
447
|
+
return `unexpected argument "${token}"`;
|
|
448
|
+
if (!EXTENSION_IDS.includes(token))
|
|
449
|
+
return `unknown extension "${token}"; the nine are ${EXTENSION_IDS.join(", ")}`;
|
|
450
|
+
ids.push(token);
|
|
451
|
+
continue;
|
|
452
|
+
}
|
|
453
|
+
if (!allowed.includes(token))
|
|
454
|
+
return `unknown option "${token}" for ${verb}; accepted: ${allowed.join(", ")}`;
|
|
455
|
+
if (VALUE_OPTIONS.has(token)) {
|
|
456
|
+
const value = args[i + 1];
|
|
457
|
+
if (value === undefined || value.startsWith("-"))
|
|
458
|
+
return `${token} needs a value`;
|
|
459
|
+
i += 1;
|
|
460
|
+
if (token === "--family") {
|
|
461
|
+
if (!Object.hasOwn(EXTENSION_FAMILIES, value)) {
|
|
462
|
+
return `unknown family "${value}"; the five are ${Object.keys(EXTENSION_FAMILIES).join(", ")}`;
|
|
463
|
+
}
|
|
464
|
+
families.push(value);
|
|
465
|
+
}
|
|
466
|
+
else if (token === "--from")
|
|
467
|
+
from = value;
|
|
468
|
+
else {
|
|
469
|
+
if (!/^\d+$/u.test(value))
|
|
470
|
+
return "--older-than takes a whole number of days";
|
|
471
|
+
olderThan = Number(value);
|
|
472
|
+
}
|
|
473
|
+
continue;
|
|
474
|
+
}
|
|
475
|
+
flags.add(token);
|
|
476
|
+
}
|
|
477
|
+
return {
|
|
478
|
+
verb,
|
|
479
|
+
ids,
|
|
480
|
+
families,
|
|
481
|
+
all: flags.has("--all"),
|
|
482
|
+
...(from === undefined ? {} : { from }),
|
|
483
|
+
yes: flags.has("--yes"),
|
|
484
|
+
json: flags.has("--json"),
|
|
485
|
+
allowShadow: flags.has("--allow-shadow"),
|
|
486
|
+
...(olderThan === undefined ? {} : { olderThan }),
|
|
487
|
+
help: false,
|
|
488
|
+
};
|
|
489
|
+
}
|
|
490
|
+
function selected(parsed) {
|
|
491
|
+
if (parsed.all)
|
|
492
|
+
return [...EXTENSION_IDS];
|
|
493
|
+
const picked = new Set(parsed.ids);
|
|
494
|
+
for (const family of parsed.families)
|
|
495
|
+
for (const id of EXTENSION_FAMILIES[family])
|
|
496
|
+
picked.add(id);
|
|
497
|
+
return EXTENSION_IDS.filter((id) => picked.has(id));
|
|
498
|
+
}
|
|
499
|
+
function describeState(entry) {
|
|
500
|
+
if (entry.state === "installed" && entry.receipt !== undefined) {
|
|
501
|
+
return `installed (${entry.receipt.variant}, ${entry.receipt.installed_at}, ${entry.receipt.source})`;
|
|
502
|
+
}
|
|
503
|
+
if (entry.state === "user-managed")
|
|
504
|
+
return `user-managed (no receipt: ${entry.path})`;
|
|
505
|
+
if (entry.state === "not-a-folder")
|
|
506
|
+
return `not a folder (${entry.path})`;
|
|
507
|
+
return "not installed";
|
|
508
|
+
}
|
|
509
|
+
function renderList(report) {
|
|
510
|
+
const width = Math.max(...EXTENSION_IDS.map((id) => id.length));
|
|
511
|
+
const lines = [`LitFamily extensions in ${dirname(report.entries[0]?.path ?? "")}`];
|
|
512
|
+
for (const entry of report.entries) {
|
|
513
|
+
lines.push(` ${entry.id.padEnd(width)} ${describeState(entry)}`);
|
|
514
|
+
for (const path of entry.competing)
|
|
515
|
+
lines.push(` ${"".padEnd(width)} competing: ${path}`);
|
|
516
|
+
}
|
|
517
|
+
return `${lines.join("\n")}\n`;
|
|
518
|
+
}
|
|
519
|
+
function renderCheck(report) {
|
|
520
|
+
const lines = [];
|
|
521
|
+
if (report.findings.length === 0)
|
|
522
|
+
lines.push("LitFamily extensions: nothing needs action.");
|
|
523
|
+
else
|
|
524
|
+
lines.push(`LitFamily extensions: ${report.findings.length} need action.`);
|
|
525
|
+
for (const finding of report.findings) {
|
|
526
|
+
lines.push(`- ${finding.message}`);
|
|
527
|
+
lines.push(` fix: ${finding.fix}`);
|
|
528
|
+
}
|
|
529
|
+
if (report.backups.count > 0) {
|
|
530
|
+
lines.push(`${report.backups.count} backup set${report.backups.count === 1 ? "" : "s"} in ${report.backups.root} use ${formatBytes(report.backups.bytes)}; \`litcodex extensions prune-backups\` lists them.`);
|
|
531
|
+
}
|
|
532
|
+
return `${lines.join("\n")}\n`;
|
|
533
|
+
}
|
|
534
|
+
function formatBytes(bytes) {
|
|
535
|
+
if (bytes < 1024)
|
|
536
|
+
return `${bytes} B`;
|
|
537
|
+
if (bytes < 1024 * 1024)
|
|
538
|
+
return `${(bytes / 1024).toFixed(1)} KB`;
|
|
539
|
+
return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
|
|
540
|
+
}
|
|
541
|
+
function preflight(ids, ctx, paths, source, allowShadow, out) {
|
|
542
|
+
assertRealDir(paths.codexHome);
|
|
543
|
+
assertRealDir(paths.skills);
|
|
544
|
+
assertRealDir(paths.backups);
|
|
545
|
+
const items = [];
|
|
546
|
+
const problems = [];
|
|
547
|
+
const duplicates = duplicatesIn(paths);
|
|
548
|
+
for (const id of ids) {
|
|
549
|
+
const entry = entryFor(id, ctx, paths);
|
|
550
|
+
const src = join(source.root === undefined ? variantRoot(paths.cache) : variantRoot(source.root), id);
|
|
551
|
+
if (entry.state === "not-a-folder") {
|
|
552
|
+
problems.push(`refused: ${entry.path} is a symbolic link or a file. Move it away yourself; LitCodex does not follow it.`);
|
|
553
|
+
continue;
|
|
554
|
+
}
|
|
555
|
+
if (source.root !== undefined) {
|
|
556
|
+
const srcStat = lstat(src);
|
|
557
|
+
if (srcStat !== undefined && (srcStat.isSymbolicLink() || !srcStat.isDirectory())) {
|
|
558
|
+
problems.push(`${id}: ${src} is a symbolic link or a file; the source must be a plain folder.`);
|
|
559
|
+
continue;
|
|
560
|
+
}
|
|
561
|
+
if (lstat(join(src, "SKILL.md"))?.isFile() !== true) {
|
|
562
|
+
problems.push(`${id}: the source ${src} has no SKILL.md. Pull your clone, or check the --from path.`);
|
|
563
|
+
continue;
|
|
564
|
+
}
|
|
565
|
+
try {
|
|
566
|
+
filesOf(src);
|
|
567
|
+
}
|
|
568
|
+
catch (error) {
|
|
569
|
+
problems.push(`${id}: ${error.message}`);
|
|
570
|
+
continue;
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
for (const path of entry.competing) {
|
|
574
|
+
if (allowShadow)
|
|
575
|
+
out.warnings.push(`warning: Codex will also list ${path}, a same-name skill LitCodex leaves alone.`);
|
|
576
|
+
else {
|
|
577
|
+
problems.push(`stopped: ${path} is a same-name ${id} that Codex would list beside the extension. Move it out of that folder yourself, or pass --allow-shadow to install anyway.`);
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
for (const twin of duplicates.filter((duplicate) => duplicate.id === id)) {
|
|
581
|
+
if (allowShadow)
|
|
582
|
+
out.warnings.push(`warning: Codex will also list ${twin.path}, a second ${id} in its skills folder.`);
|
|
583
|
+
else {
|
|
584
|
+
problems.push(`stopped: ${twin.path} is a second ${id} in Codex's skills folder under another folder name. Move it aside with \`${moveAsideLine(paths, twin.path, twin.name)}\`, or pass --allow-shadow to install anyway.`);
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
items.push({ id, source: src, dest: entry.path, moveAside: entry.state !== "not-installed" });
|
|
588
|
+
}
|
|
589
|
+
if (problems.length > 0)
|
|
590
|
+
throw new StopError(`${problems.join("\n")}\nNothing was installed.`);
|
|
591
|
+
return items;
|
|
592
|
+
}
|
|
593
|
+
function installOne(item, paths, stamp, now, out) {
|
|
594
|
+
mkdirSync(paths.skills, { recursive: true });
|
|
595
|
+
mkdirSync(paths.backups, { recursive: true });
|
|
596
|
+
const staging = join(paths.backups, `.incoming-${process.pid}-${item.id}`);
|
|
597
|
+
const staged = join(staging, item.id);
|
|
598
|
+
if (lstat(staging) !== undefined)
|
|
599
|
+
rmSync(staging, { recursive: true, force: true });
|
|
600
|
+
mkdirSync(staging);
|
|
601
|
+
let movedTo;
|
|
602
|
+
try {
|
|
603
|
+
cpSync(item.source, staged, { recursive: true, errorOnExist: true, force: false, verbatimSymlinks: true });
|
|
604
|
+
const receipt = {
|
|
605
|
+
id: item.id,
|
|
606
|
+
source: item.source,
|
|
607
|
+
variant: VARIANT,
|
|
608
|
+
installed_at: now.toISOString(),
|
|
609
|
+
sha256: folderHash(staged),
|
|
610
|
+
};
|
|
611
|
+
writeFileSync(join(staged, RECEIPT_NAME), `${JSON.stringify(receipt)}\n`);
|
|
612
|
+
if (item.moveAside && lstat(item.dest) !== undefined) {
|
|
613
|
+
movedTo = backupTarget(paths, stamp, item.id);
|
|
614
|
+
mkdirSync(dirname(movedTo), { recursive: true });
|
|
615
|
+
renameSync(item.dest, movedTo);
|
|
616
|
+
out.lines.push(`${item.id}: moved aside: ${movedTo}`);
|
|
617
|
+
}
|
|
618
|
+
renameSync(staged, item.dest);
|
|
619
|
+
out.lines.push(`${item.id}: installed ${item.dest}`);
|
|
620
|
+
out.actions.push({ id: item.id, action: "installed", ...(movedTo ? { detail: movedTo } : {}) });
|
|
621
|
+
}
|
|
622
|
+
catch (error) {
|
|
623
|
+
if (movedTo !== undefined && lstat(item.dest) === undefined)
|
|
624
|
+
renameSync(movedTo, item.dest);
|
|
625
|
+
throw error;
|
|
626
|
+
}
|
|
627
|
+
finally {
|
|
628
|
+
if (lstat(staging) !== undefined)
|
|
629
|
+
rmSync(staging, { recursive: true, force: true });
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
function describeSource(source, paths) {
|
|
633
|
+
if (source.kind === "from")
|
|
634
|
+
return `source: ${source.root} (--from)`;
|
|
635
|
+
if (source.pending === "clone") {
|
|
636
|
+
return `source: would clone ${EXTENSIONS_REPO_URL} (only variants/${VARIANT}) into ${paths.cache}`;
|
|
637
|
+
}
|
|
638
|
+
if (source.pending === "fetch")
|
|
639
|
+
return `source: ${paths.cache}; would fetch the newest shelf first`;
|
|
640
|
+
return `source: ${paths.cache}`;
|
|
641
|
+
}
|
|
642
|
+
function runInstall(parsed, ctx, deps, out) {
|
|
643
|
+
const ids = selected(parsed);
|
|
644
|
+
if (ids.length === 0)
|
|
645
|
+
throw new UsageError("install needs <id...>, --family <name> or --all");
|
|
646
|
+
const paths = pathsFor(ctx.env);
|
|
647
|
+
const source = resolveSource(parsed.from, paths, { apply: parsed.yes, refresh: false }, deps);
|
|
648
|
+
const items = preflight(ids, ctx, paths, source, parsed.allowShadow, out);
|
|
649
|
+
return applyInstall(items, parsed, paths, source, deps, out);
|
|
650
|
+
}
|
|
651
|
+
function applyInstall(items, parsed, paths, source, deps, out) {
|
|
652
|
+
if (!parsed.yes) {
|
|
653
|
+
out.lines.push(`litcodex extensions ${parsed.verb} (dry run: nothing was changed)`, describeSource(source, paths));
|
|
654
|
+
for (const item of items) {
|
|
655
|
+
const steps = [
|
|
656
|
+
...(item.moveAside ? [`move ${item.dest} to ${join(paths.backups, "<date-time>", item.id)}`] : []),
|
|
657
|
+
`copy ${item.source} to ${item.dest}`,
|
|
658
|
+
`write ${join(item.dest, RECEIPT_NAME)}`,
|
|
659
|
+
];
|
|
660
|
+
out.lines.push(`${item.id}: ${steps.join("; ")}`);
|
|
661
|
+
out.actions.push({ id: item.id, action: "would-install" });
|
|
662
|
+
}
|
|
663
|
+
out.lines.push("Run it again with --yes to do this. Start a new Codex session afterwards.");
|
|
664
|
+
return 0;
|
|
665
|
+
}
|
|
666
|
+
const now = (deps.now ?? (() => new Date()))();
|
|
667
|
+
const stamp = stampOf(now);
|
|
668
|
+
for (const item of items)
|
|
669
|
+
installOne(item, paths, stamp, now, out);
|
|
670
|
+
if (items.length > 0)
|
|
671
|
+
out.lines.push("Start a new Codex session to see the change.");
|
|
672
|
+
return 0;
|
|
673
|
+
}
|
|
674
|
+
function runUpdate(parsed, ctx, deps, out) {
|
|
675
|
+
const paths = pathsFor(ctx.env);
|
|
676
|
+
const requested = parsed.ids.length > 0 ? parsed.ids : [...EXTENSION_IDS];
|
|
677
|
+
const entries = requested.map((id) => entryFor(id, ctx, paths));
|
|
678
|
+
const installed = entries.filter((entry) => entry.state === "installed");
|
|
679
|
+
for (const entry of entries) {
|
|
680
|
+
if (entry.state === "user-managed")
|
|
681
|
+
out.lines.push(`${entry.id}: yours (no receipt), left alone; install it to track it`);
|
|
682
|
+
else if (entry.state !== "installed" && parsed.ids.length > 0)
|
|
683
|
+
out.lines.push(`${entry.id}: not installed`);
|
|
684
|
+
}
|
|
685
|
+
if (installed.length === 0) {
|
|
686
|
+
out.lines.push("No installed extension to update. `litcodex extensions install <id>` adds one.");
|
|
687
|
+
return 0;
|
|
688
|
+
}
|
|
689
|
+
// A dry run never fetches: it compares with the cached copy, or with nothing when no cache exists yet.
|
|
690
|
+
const source = resolveSource(parsed.from, paths, { apply: parsed.yes, refresh: true }, deps);
|
|
691
|
+
if (source.root === undefined) {
|
|
692
|
+
out.lines.push(`litcodex extensions update (dry run: nothing was changed): no cached shelf yet, so --yes clones it into ${paths.cache} and compares ${installed.map((entry) => entry.id).join(", ")} after the fetch.`);
|
|
693
|
+
return 0;
|
|
694
|
+
}
|
|
695
|
+
if (!parsed.yes && source.kind === "cache") {
|
|
696
|
+
out.lines.push(`Compared with the cached copy in ${paths.cache}; --yes fetches first, so the result may differ.`);
|
|
697
|
+
}
|
|
698
|
+
const changed = [];
|
|
699
|
+
for (const entry of installed) {
|
|
700
|
+
const src = join(variantRoot(source.root), entry.id);
|
|
701
|
+
if (lstat(src)?.isSymbolicLink() === true) {
|
|
702
|
+
changed.push(entry.id);
|
|
703
|
+
continue;
|
|
704
|
+
}
|
|
705
|
+
if (lstat(join(src, "SKILL.md")) === undefined) {
|
|
706
|
+
out.warnings.push(`${entry.id}: the source ${src} is gone; kept the installed copy`);
|
|
707
|
+
continue;
|
|
708
|
+
}
|
|
709
|
+
const was = entry.receipt?.sha256 ?? folderHash(entry.path);
|
|
710
|
+
const sourceMoved = resolve(entry.receipt?.source ?? "") !== resolve(src);
|
|
711
|
+
if (folderHash(src) !== was) {
|
|
712
|
+
out.lines.push(`${entry.id}: source changed`);
|
|
713
|
+
changed.push(entry.id);
|
|
714
|
+
}
|
|
715
|
+
else if (!sourceMoved)
|
|
716
|
+
out.lines.push(`${entry.id}: current`);
|
|
717
|
+
else if (!parsed.yes)
|
|
718
|
+
out.lines.push(`${entry.id}: current; --yes points its receipt at ${src}`);
|
|
719
|
+
else {
|
|
720
|
+
rewriteReceiptSource(entry.path, entry.receipt, src);
|
|
721
|
+
out.lines.push(`${entry.id}: current; its receipt now points at ${src}`);
|
|
722
|
+
out.actions.push({ id: entry.id, action: "receipt-source", detail: src });
|
|
723
|
+
}
|
|
724
|
+
}
|
|
725
|
+
if (changed.length === 0)
|
|
726
|
+
return 0;
|
|
727
|
+
const items = preflight(changed, ctx, paths, source, parsed.allowShadow, out);
|
|
728
|
+
return applyInstall(items, parsed, paths, source, deps, out);
|
|
729
|
+
}
|
|
730
|
+
/** Same content, new source path: only the receipt's source changes, written to a temp file and renamed over it. */
|
|
731
|
+
function rewriteReceiptSource(dir, receipt, source) {
|
|
732
|
+
const path = join(dir, RECEIPT_NAME);
|
|
733
|
+
const temporary = `${path}.tmp-${process.pid}`;
|
|
734
|
+
writeFileSync(temporary, `${JSON.stringify({ ...receipt, source })}\n`, { flag: "wx" });
|
|
735
|
+
renameSync(temporary, path);
|
|
736
|
+
}
|
|
737
|
+
function runRemove(parsed, ctx, deps, out) {
|
|
738
|
+
if (parsed.ids.length === 0)
|
|
739
|
+
throw new UsageError("remove needs <id...>");
|
|
740
|
+
const paths = pathsFor(ctx.env);
|
|
741
|
+
const entries = parsed.ids.map((id) => entryFor(id, ctx, paths));
|
|
742
|
+
const refusals = entries.flatMap((entry) => {
|
|
743
|
+
if (entry.state === "installed")
|
|
744
|
+
return [];
|
|
745
|
+
if (entry.state === "not-installed")
|
|
746
|
+
return [`${entry.id}: not installed; nothing to remove`];
|
|
747
|
+
return [`refused: ${entry.path} has no LitCodex receipt, so it is yours; LitCodex does not move it`];
|
|
748
|
+
});
|
|
749
|
+
if (refusals.some((line) => line.startsWith("refused:")))
|
|
750
|
+
throw new StopError(`${refusals.join("\n")}\nNothing was moved.`);
|
|
751
|
+
out.lines.push(...refusals);
|
|
752
|
+
const targets = entries.filter((entry) => entry.state === "installed");
|
|
753
|
+
if (!parsed.yes) {
|
|
754
|
+
out.lines.push("litcodex extensions remove (dry run: nothing was changed)");
|
|
755
|
+
for (const entry of targets) {
|
|
756
|
+
out.lines.push(`${entry.id}: move ${entry.path} to ${join(paths.backups, "<date-time>", entry.id)}`);
|
|
757
|
+
}
|
|
758
|
+
out.lines.push("Run it again with --yes to do this. Nothing is deleted.");
|
|
759
|
+
return 0;
|
|
760
|
+
}
|
|
761
|
+
assertRealDir(paths.backups);
|
|
762
|
+
const stamp = stampOf((deps.now ?? (() => new Date()))());
|
|
763
|
+
for (const entry of targets) {
|
|
764
|
+
const target = backupTarget(paths, stamp, entry.id);
|
|
765
|
+
mkdirSync(dirname(target), { recursive: true });
|
|
766
|
+
renameSync(entry.path, target);
|
|
767
|
+
out.lines.push(`${entry.id}: moved aside: ${target}`);
|
|
768
|
+
out.actions.push({ id: entry.id, action: "removed", detail: target });
|
|
769
|
+
}
|
|
770
|
+
return 0;
|
|
771
|
+
}
|
|
772
|
+
function runPrune(parsed, ctx, deps, out) {
|
|
773
|
+
const paths = pathsFor(ctx.env);
|
|
774
|
+
assertRealDir(paths.backups);
|
|
775
|
+
const now = (deps.now ?? (() => new Date()))().getTime();
|
|
776
|
+
const sets = listBackups(paths);
|
|
777
|
+
const picked = sets.filter((set) => parsed.olderThan === undefined || now - set.takenAt.getTime() > parsed.olderThan * 86_400_000);
|
|
778
|
+
if (sets.length === 0) {
|
|
779
|
+
out.lines.push(`No backups in ${paths.backups}.`);
|
|
780
|
+
return 0;
|
|
781
|
+
}
|
|
782
|
+
out.lines.push(`Backups in ${paths.backups}:`);
|
|
783
|
+
for (const set of sets) {
|
|
784
|
+
const contents = readdirSync(set.path).sort().join(", ");
|
|
785
|
+
out.lines.push(` ${set.name} ${formatBytes(set.bytes).padStart(9)} ${contents}${picked.includes(set) ? "" : " (kept)"}`);
|
|
786
|
+
}
|
|
787
|
+
const total = picked.reduce((sum, set) => sum + set.bytes, 0);
|
|
788
|
+
if (!parsed.yes) {
|
|
789
|
+
out.lines.push(`Would delete ${picked.length} of ${sets.length} (${formatBytes(total)}). Run it again with --yes to delete them.`);
|
|
790
|
+
return 0;
|
|
791
|
+
}
|
|
792
|
+
const backupsReal = realpathSync(paths.backups);
|
|
793
|
+
for (const set of picked) {
|
|
794
|
+
const real = realpathSync(set.path);
|
|
795
|
+
if (dirname(real) !== backupsReal || lstat(set.path)?.isSymbolicLink() !== false) {
|
|
796
|
+
throw new StopError(`refused: ${set.path} is not a plain folder inside ${paths.backups}`);
|
|
797
|
+
}
|
|
798
|
+
rmSync(real, { recursive: true });
|
|
799
|
+
out.actions.push({ id: set.name, action: "deleted" });
|
|
800
|
+
}
|
|
801
|
+
out.lines.push(`Deleted ${picked.length} backup set${picked.length === 1 ? "" : "s"} (${formatBytes(total)}).`);
|
|
802
|
+
return 0;
|
|
803
|
+
}
|
|
804
|
+
class UsageError extends Error {
|
|
805
|
+
}
|
|
806
|
+
/** `litcodex extensions <verb> ...`; returns the exit code and never throws. */
|
|
807
|
+
export function runExtensionsCli(args, io, deps = {}) {
|
|
808
|
+
const parsed = parse(args);
|
|
809
|
+
if (typeof parsed === "string") {
|
|
810
|
+
io.stderr.write(`litcodex extensions: ${parsed}. Nothing was changed.\n\n${EXTENSIONS_HELP_TEXT}`);
|
|
811
|
+
return USAGE_EXIT_CODE;
|
|
812
|
+
}
|
|
813
|
+
if (parsed.help) {
|
|
814
|
+
io.stdout.write(EXTENSIONS_HELP_TEXT);
|
|
815
|
+
return 0;
|
|
816
|
+
}
|
|
817
|
+
const ctx = { env: io.env, cwd: io.cwd };
|
|
818
|
+
if (parsed.verb === "list" || parsed.verb === "check") {
|
|
819
|
+
const report = checkExtensions(ctx);
|
|
820
|
+
const code = parsed.verb === "check" && report.findings.length > 0 ? 1 : 0;
|
|
821
|
+
if (parsed.json) {
|
|
822
|
+
io.stdout.write(`${JSON.stringify(parsed.verb === "list" ? { extensions: report.entries } : { ok: code === 0, ...report })}\n`);
|
|
823
|
+
}
|
|
824
|
+
else
|
|
825
|
+
io.stdout.write(parsed.verb === "list" ? renderList(report) : renderCheck(report));
|
|
826
|
+
return code;
|
|
827
|
+
}
|
|
828
|
+
const out = { lines: [], warnings: [], errors: [], actions: [] };
|
|
829
|
+
let code;
|
|
830
|
+
try {
|
|
831
|
+
const verbs = {
|
|
832
|
+
install: runInstall,
|
|
833
|
+
update: runUpdate,
|
|
834
|
+
remove: runRemove,
|
|
835
|
+
"prune-backups": runPrune,
|
|
836
|
+
};
|
|
837
|
+
code = verbs[parsed.verb](parsed, ctx, deps, out);
|
|
838
|
+
}
|
|
839
|
+
catch (error) {
|
|
840
|
+
if (error instanceof UsageError) {
|
|
841
|
+
io.stderr.write(`litcodex extensions: ${error.message}. Nothing was changed.\n`);
|
|
842
|
+
return USAGE_EXIT_CODE;
|
|
843
|
+
}
|
|
844
|
+
out.errors.push(error instanceof StopError ? error.message : `failed: ${error.message}`);
|
|
845
|
+
code = 1;
|
|
846
|
+
}
|
|
847
|
+
if (parsed.json) {
|
|
848
|
+
io.stdout.write(`${JSON.stringify({ ok: code === 0, dryRun: !parsed.yes, actions: out.actions, lines: out.lines, warnings: out.warnings, errors: out.errors })}\n`);
|
|
849
|
+
return code;
|
|
850
|
+
}
|
|
851
|
+
if (out.lines.length > 0)
|
|
852
|
+
io.stdout.write(`${out.lines.join("\n")}\n`);
|
|
853
|
+
for (const line of [...out.warnings, ...out.errors])
|
|
854
|
+
io.stderr.write(`${line}\n`);
|
|
855
|
+
return code;
|
|
856
|
+
}
|