draht-codex 2026.7.30 → 2026.10.4-2
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/.codex-plugin/plugin.json +1 -1
- package/CHANGELOG.md +81 -0
- package/README.md +57 -6
- package/agents/debugger.md +12 -1
- package/agents/git-committer.md +1 -0
- package/agents/implementer.md +11 -2
- package/agents/investigator.md +75 -0
- package/agents/reviewer.md +7 -0
- package/agents/speaker.md +44 -0
- package/agents/verifier.md +4 -3
- package/bin/draht-tools.cjs +472 -41
- package/bin/judge +613 -0
- package/cli.mjs +769 -46
- package/commands/atomic-commit.md +1 -12
- package/commands/create-verification-skill.md +105 -0
- package/commands/discuss-phase.md +3 -14
- package/commands/execute-phase.md +7 -14
- package/commands/fix.md +38 -17
- package/commands/grill.md +66 -0
- package/commands/init-project.md +5 -15
- package/commands/map-codebase.md +1 -13
- package/commands/new-project.md +5 -15
- package/commands/next-milestone.md +2 -13
- package/commands/orchestrate.md +1 -1
- package/commands/pause-work.md +1 -8
- package/commands/plan-phase.md +3 -11
- package/commands/progress.md +0 -8
- package/commands/quick.md +3 -11
- package/commands/resolve-conflicts.md +72 -0
- package/commands/resume-work.md +0 -8
- package/commands/review.md +6 -13
- package/commands/speak.md +45 -0
- package/commands/triage.md +161 -0
- package/commands/verify-work.md +6 -13
- package/commands/why.md +141 -0
- package/graph-archive.mjs +125 -0
- package/graph-manifest.mjs +97 -0
- package/hooks/hooks.json +39 -0
- package/package.json +5 -3
- package/scripts/gsd-quality-gate.cjs +3 -3
- package/scripts/judge-hook.cjs +42 -0
- package/scripts/judge-hook.py +391 -0
- package/scripts/judgegates.py +673 -0
- package/scripts/judgelib.py +382 -0
- package/scripts/speak.cjs +202 -0
- package/skills/atomic-commit/SKILL.md +1 -1
- package/skills/atomic-commit/command.md +62 -0
- package/skills/blast-radius/SKILL.md +56 -0
- package/skills/brainstorming/SKILL.md +11 -4
- package/skills/cinematic-continuation/SKILL.md +111 -0
- package/skills/cinematic-continuation/references/continuity-schema.md +75 -0
- package/skills/cinematic-continuation/references/seedance-adapter.md +44 -0
- package/skills/cinematic-continuation/references/style-bible.md +223 -0
- package/skills/cinematic-continuation/scripts/compile-continuation.mjs +173 -0
- package/skills/cinematic-continuation/templates/continuation-spec.json +50 -0
- package/skills/create-verification-skill/SKILL.md +14 -0
- package/skills/create-verification-skill/command.md +105 -0
- package/skills/debugging-workflow/SKILL.md +38 -10
- package/skills/discuss-phase/SKILL.md +1 -1
- package/skills/discuss-phase/command.md +44 -0
- package/skills/draht/SKILL.md +119 -0
- package/skills/epistemics/SKILL.md +99 -0
- package/skills/execute-phase/SKILL.md +1 -1
- package/skills/execute-phase/command.md +170 -0
- package/skills/explainers/SKILL.md +65 -0
- package/skills/fix/SKILL.md +1 -1
- package/skills/fix/command.md +154 -0
- package/skills/grill/SKILL.md +14 -0
- package/skills/grill/command.md +66 -0
- package/skills/gsd-workflow/SKILL.md +2 -0
- package/skills/init-project/SKILL.md +1 -1
- package/skills/init-project/command.md +57 -0
- package/skills/judge/SKILL.md +57 -0
- package/skills/map-codebase/SKILL.md +1 -1
- package/skills/map-codebase/command.md +61 -0
- package/skills/new-project/SKILL.md +1 -1
- package/skills/new-project/command.md +64 -0
- package/skills/next-milestone/SKILL.md +1 -1
- package/skills/next-milestone/command.md +42 -0
- package/skills/orchestrate/SKILL.md +1 -1
- package/skills/orchestrate/command.md +106 -0
- package/skills/orchestrate-loop/SKILL.md +1 -1
- package/skills/orchestrate-loop/command.md +100 -0
- package/skills/pause-work/SKILL.md +1 -1
- package/skills/pause-work/command.md +32 -0
- package/skills/plan-phase/SKILL.md +1 -1
- package/skills/plan-phase/command.md +140 -0
- package/skills/progress/SKILL.md +1 -1
- package/skills/progress/command.md +22 -0
- package/skills/quick/SKILL.md +1 -1
- package/skills/quick/command.md +91 -0
- package/skills/resolve-conflicts/SKILL.md +14 -0
- package/skills/resolve-conflicts/command.md +72 -0
- package/skills/resume-work/SKILL.md +1 -1
- package/skills/resume-work/command.md +27 -0
- package/skills/review/SKILL.md +1 -1
- package/skills/review/command.md +83 -0
- package/skills/saga-spawner/SKILL.md +131 -0
- package/skills/speak/SKILL.md +14 -0
- package/skills/speak/command.md +45 -0
- package/skills/tdd-workflow/SKILL.md +2 -0
- package/skills/triage/SKILL.md +14 -0
- package/skills/triage/command.md +161 -0
- package/skills/typescript-discipline/SKILL.md +50 -0
- package/skills/typescript-discipline/references/patterns.md +294 -0
- package/skills/unslop/SKILL.md +119 -0
- package/skills/verify-work/SKILL.md +1 -1
- package/skills/verify-work/command.md +117 -0
- package/skills/why/SKILL.md +14 -0
- package/skills/why/command.md +141 -0
package/cli.mjs
CHANGED
|
@@ -18,10 +18,14 @@
|
|
|
18
18
|
*/
|
|
19
19
|
|
|
20
20
|
import { execSync, spawnSync } from "node:child_process";
|
|
21
|
+
import * as crypto from "node:crypto";
|
|
21
22
|
import * as fs from "node:fs";
|
|
22
23
|
import * as os from "node:os";
|
|
23
24
|
import * as path from "node:path";
|
|
24
25
|
import { fileURLToPath } from "node:url";
|
|
26
|
+
import * as zlib from "node:zlib";
|
|
27
|
+
import { extractGraphZip } from "./graph-archive.mjs";
|
|
28
|
+
import { GRAPH_IO_LIMITS, validateGraphAttestation, validateGraphChecksums, validateGraphManifest } from "./graph-manifest.mjs";
|
|
25
29
|
|
|
26
30
|
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
27
31
|
const PACKAGE_ROOT = __dirname;
|
|
@@ -42,7 +46,10 @@ const IGNORE = new Set([
|
|
|
42
46
|
function parseArgs(argv) {
|
|
43
47
|
const args = argv.slice(2);
|
|
44
48
|
const command = args[0];
|
|
45
|
-
const flags = {
|
|
49
|
+
const flags = {
|
|
50
|
+
path: null, force: false, help: false, agent: null, model: null, list: false, reset: false,
|
|
51
|
+
noGraphEngine: false, graphEngine: false, graphEngineVersion: null, from: null, purgeGraphEngine: false,
|
|
52
|
+
};
|
|
46
53
|
const passthrough = [];
|
|
47
54
|
|
|
48
55
|
for (let i = 1; i < args.length; i++) {
|
|
@@ -63,6 +70,19 @@ function parseArgs(argv) {
|
|
|
63
70
|
flags.list = true;
|
|
64
71
|
} else if (a === "--reset" || a === "-r") {
|
|
65
72
|
flags.reset = true;
|
|
73
|
+
} else if (a === "--graph-engine") {
|
|
74
|
+
flags.graphEngine = true;
|
|
75
|
+
} else if (a === "--no-graph-engine") {
|
|
76
|
+
// Retained for compatibility and for scripted installs that want to be
|
|
77
|
+
// explicit; the fetch is opt-in, so this is a no-op unless combined
|
|
78
|
+
// with --graph-engine, where refusing wins.
|
|
79
|
+
flags.noGraphEngine = true;
|
|
80
|
+
} else if (a === "--graph-engine-version") {
|
|
81
|
+
flags.graphEngineVersion = args[++i];
|
|
82
|
+
} else if (a === "--from") {
|
|
83
|
+
flags.from = args[++i];
|
|
84
|
+
} else if (a === "--purge-graph-engine") {
|
|
85
|
+
flags.purgeGraphEngine = true;
|
|
66
86
|
}
|
|
67
87
|
}
|
|
68
88
|
|
|
@@ -78,6 +98,9 @@ Usage:
|
|
|
78
98
|
npx draht-codex install --force Reinstall even if already present
|
|
79
99
|
npx draht-codex install --path DIR Custom marketplace directory
|
|
80
100
|
npx draht-codex uninstall Remove the plugin and marketplace
|
|
101
|
+
--purge-graph-engine Also remove ~/.draht/bin/draht-graph — WARNING: shared with
|
|
102
|
+
draht-claude/coding-agent and baked into every repo's
|
|
103
|
+
post-commit hook; those stop refreshing MAP.json silently
|
|
81
104
|
npx draht-codex update Reinstall (same as install --force)
|
|
82
105
|
npx draht-codex status Show install state
|
|
83
106
|
npx draht-codex configure Configure bundled reference agent models
|
|
@@ -86,17 +109,29 @@ Usage:
|
|
|
86
109
|
--reset Reset all agent model metadata
|
|
87
110
|
--list List current agent model metadata
|
|
88
111
|
npx draht-codex draht-tools ... Run the bundled draht-tools CLI
|
|
112
|
+
npx draht-codex install-graph-engine Fetch the prebuilt draht-graph binary (alias: graph-engine)
|
|
113
|
+
--graph-engine-version <v> Pin a version instead of this package's own version
|
|
114
|
+
--from <path> Install a locally built binary instead of fetching
|
|
115
|
+
--force Re-install even if the same version is already present
|
|
89
116
|
|
|
90
117
|
Options:
|
|
91
118
|
-p, --path <dir> Custom local marketplace directory
|
|
92
119
|
-f, --force Overwrite existing install
|
|
93
120
|
-h, --help Show this help
|
|
121
|
+
--graph-engine Also fetch the prebuilt draht-graph binary during install/update
|
|
122
|
+
(opt-in; downloads an unsigned native binary from GitHub Releases)
|
|
94
123
|
|
|
95
124
|
What this installs:
|
|
96
125
|
- Local Codex marketplace named "${MARKETPLACE_NAME}" at ~/.draht/codex-marketplace/
|
|
97
126
|
- Plugin "${PLUGIN_NAME}" inside that marketplace
|
|
98
127
|
- Draht command prompt wrappers, reference prompt templates, specialist agent prompts, support skills, hooks, and scripts
|
|
99
|
-
- Self-contained draht-tools CLI
|
|
128
|
+
- Self-contained draht-tools CLI (JS graph engine built in — works out of the box)
|
|
129
|
+
|
|
130
|
+
Optional, not installed by default:
|
|
131
|
+
- The prebuilt draht-graph binary (~6x faster map-graph). It is an unsigned
|
|
132
|
+
native binary downloaded from GitHub Releases, so it is opt-in: pass
|
|
133
|
+
--graph-engine, or run 'npx draht-codex install-graph-engine' later.
|
|
134
|
+
Checksums are verified; any failure falls back to the built-in JS engine.
|
|
100
135
|
|
|
101
136
|
After install, restart Codex. Use $draht:<command> or /skills and select the command wrapper.
|
|
102
137
|
Prompt templates remain installed under commands/; Codex CLI currently does not expose plugin commands as slash commands.
|
|
@@ -141,10 +176,251 @@ function copyRecursive(src, dest) {
|
|
|
141
176
|
}
|
|
142
177
|
|
|
143
178
|
function removeRecursive(target) {
|
|
144
|
-
|
|
179
|
+
try {
|
|
180
|
+
fs.lstatSync(target);
|
|
181
|
+
} catch (error) {
|
|
182
|
+
if (error.code === "ENOENT") return;
|
|
183
|
+
throw error;
|
|
184
|
+
}
|
|
145
185
|
fs.rmSync(target, { recursive: true, force: true });
|
|
146
186
|
}
|
|
147
187
|
|
|
188
|
+
function lstatIfExists(target) {
|
|
189
|
+
try {
|
|
190
|
+
return fs.lstatSync(target);
|
|
191
|
+
} catch (error) {
|
|
192
|
+
if (error.code === "ENOENT") return null;
|
|
193
|
+
throw error;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
const MARKETPLACE_LOCK_MAX_AGE_MS = 6 * 60 * 60 * 1000;
|
|
198
|
+
function processIdentity(pid) {
|
|
199
|
+
try {
|
|
200
|
+
if (process.platform === "linux") {
|
|
201
|
+
const stat = fs.readFileSync(`/proc/${pid}/stat`, "utf8");
|
|
202
|
+
return stat.slice(stat.lastIndexOf(")") + 2).trim().split(/\s+/)[19] || null;
|
|
203
|
+
}
|
|
204
|
+
if (process.platform === "win32") {
|
|
205
|
+
const result = spawnSync("wmic", ["process", "where", `processid=${pid}`, "get", "CreationDate", "/value"], { encoding: "utf8" });
|
|
206
|
+
return result.status === 0 ? result.stdout.trim() || null : null;
|
|
207
|
+
}
|
|
208
|
+
const result = spawnSync("ps", ["-o", "lstart=", "-p", String(pid)], { encoding: "utf8" });
|
|
209
|
+
return result.status === 0 ? result.stdout.trim() || null : null;
|
|
210
|
+
} catch {
|
|
211
|
+
return null;
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
function readMarketplaceLock(lockPath) {
|
|
216
|
+
let descriptor;
|
|
217
|
+
try {
|
|
218
|
+
const before = fs.lstatSync(lockPath);
|
|
219
|
+
if (!before.isFile() || before.isSymbolicLink()) throw new Error("not a regular file");
|
|
220
|
+
const noFollow = fs.constants.O_NOFOLLOW || 0;
|
|
221
|
+
descriptor = fs.openSync(lockPath, fs.constants.O_RDONLY | noFollow);
|
|
222
|
+
const opened = fs.fstatSync(descriptor);
|
|
223
|
+
if (!opened.isFile() || opened.dev !== before.dev || opened.ino !== before.ino) throw new Error("changed while opening");
|
|
224
|
+
const owner = JSON.parse(fs.readFileSync(descriptor, "utf8"));
|
|
225
|
+
const after = fs.lstatSync(lockPath);
|
|
226
|
+
if (after.dev !== opened.dev || after.ino !== opened.ino) throw new Error("changed while reading");
|
|
227
|
+
return { owner, stat: opened };
|
|
228
|
+
} catch (error) {
|
|
229
|
+
const wrapped = new Error(`plugin update lock exists but is not safely readable: ${lockPath} (${error.message})`);
|
|
230
|
+
wrapped.lockChurn = error.code === "ENOENT" || error.message === "changed while opening" || error.message === "changed while reading";
|
|
231
|
+
throw wrapped;
|
|
232
|
+
} finally {
|
|
233
|
+
if (descriptor !== undefined) fs.closeSync(descriptor);
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
function sameFile(left, right) {
|
|
238
|
+
return left.dev === right.dev && left.ino === right.ino;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
function acquireMarketplaceLock(marketplaceDir) {
|
|
242
|
+
const lockPath = `${marketplaceDir}.draht-update-lock`;
|
|
243
|
+
let ownedQuarantine = null;
|
|
244
|
+
for (;;) {
|
|
245
|
+
const token = crypto.randomBytes(8).toString("hex");
|
|
246
|
+
const owner = {
|
|
247
|
+
owner: "draht-plugin-installer",
|
|
248
|
+
pid: process.pid,
|
|
249
|
+
identity: processIdentity(process.pid),
|
|
250
|
+
createdAt: Date.now(),
|
|
251
|
+
token,
|
|
252
|
+
};
|
|
253
|
+
const ownerPath = `${lockPath}.${process.pid}-${token}`;
|
|
254
|
+
fs.writeFileSync(ownerPath, JSON.stringify(owner), { flag: "wx", mode: 0o600 });
|
|
255
|
+
try {
|
|
256
|
+
fs.linkSync(ownerPath, lockPath);
|
|
257
|
+
if (ownedQuarantine) fs.unlinkSync(ownedQuarantine);
|
|
258
|
+
return { lockPath, token };
|
|
259
|
+
} catch (error) {
|
|
260
|
+
if (error.code !== "EEXIST") throw error;
|
|
261
|
+
} finally {
|
|
262
|
+
fs.rmSync(ownerPath, { force: true });
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
// Lock identity churn between the failed link and this read means another
|
|
266
|
+
// contender is mid-reclaim or mid-release — re-contend, it is not corruption.
|
|
267
|
+
let observed;
|
|
268
|
+
try {
|
|
269
|
+
observed = readMarketplaceLock(lockPath);
|
|
270
|
+
} catch (error) {
|
|
271
|
+
if (error.lockChurn) continue;
|
|
272
|
+
throw error;
|
|
273
|
+
}
|
|
274
|
+
const { owner: existing, stat: observedStat } = observed;
|
|
275
|
+
if (existing?.owner !== "draht-plugin-installer" || !Number.isSafeInteger(existing.pid) || typeof existing.token !== "string" ||
|
|
276
|
+
(existing.identity !== null && typeof existing.identity !== "string") || !Number.isSafeInteger(existing.createdAt)) {
|
|
277
|
+
throw new Error(`plugin update lock is not owned by draht: ${lockPath}`);
|
|
278
|
+
}
|
|
279
|
+
const identity = processIdentity(existing.pid);
|
|
280
|
+
let ownerAlive = identity !== null && existing.identity !== null && identity === existing.identity;
|
|
281
|
+
if (identity === null || existing.identity === null) {
|
|
282
|
+
try {
|
|
283
|
+
process.kill(existing.pid, 0);
|
|
284
|
+
ownerAlive = Date.now() - existing.createdAt < MARKETPLACE_LOCK_MAX_AGE_MS;
|
|
285
|
+
} catch (error) {
|
|
286
|
+
ownerAlive = error.code !== "ESRCH" && Date.now() - existing.createdAt < MARKETPLACE_LOCK_MAX_AGE_MS;
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
if (ownerAlive) {
|
|
290
|
+
if (ownedQuarantine) fs.rmSync(ownedQuarantine, { force: true });
|
|
291
|
+
throw new Error(`another plugin update is already in progress (pid ${existing.pid})`);
|
|
292
|
+
}
|
|
293
|
+
const quarantineId = crypto.createHash("sha256").update(existing.token).digest("hex").slice(0, 16);
|
|
294
|
+
const quarantinePath = `${lockPath}.reclaim-${quarantineId}`;
|
|
295
|
+
try {
|
|
296
|
+
fs.linkSync(lockPath, quarantinePath);
|
|
297
|
+
} catch (error) {
|
|
298
|
+
if (error.code === "EEXIST") throw new Error("another plugin update is already in progress reclaiming a stale lock");
|
|
299
|
+
if (error.code === "ENOENT") continue;
|
|
300
|
+
throw error;
|
|
301
|
+
}
|
|
302
|
+
try {
|
|
303
|
+
const quarantined = readMarketplaceLock(quarantinePath);
|
|
304
|
+
const current = fs.lstatSync(lockPath);
|
|
305
|
+
if (!sameFile(observedStat, quarantined.stat) || !sameFile(current, quarantined.stat) || quarantined.owner.token !== existing.token) continue;
|
|
306
|
+
fs.unlinkSync(lockPath);
|
|
307
|
+
ownedQuarantine = quarantinePath;
|
|
308
|
+
} finally {
|
|
309
|
+
if (ownedQuarantine !== quarantinePath) fs.rmSync(quarantinePath, { force: true });
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
function releaseMarketplaceLock(lock) {
|
|
315
|
+
const { owner, stat } = readMarketplaceLock(lock.lockPath);
|
|
316
|
+
if (owner.token !== lock.token) throw new Error(`plugin update lock ownership changed: ${lock.lockPath}`);
|
|
317
|
+
const releasePath = `${lock.lockPath}.release-${lock.token}`;
|
|
318
|
+
fs.linkSync(lock.lockPath, releasePath);
|
|
319
|
+
try {
|
|
320
|
+
const linked = fs.lstatSync(releasePath);
|
|
321
|
+
const current = fs.lstatSync(lock.lockPath);
|
|
322
|
+
if (!sameFile(stat, linked) || !sameFile(current, linked)) throw new Error(`plugin update lock ownership changed: ${lock.lockPath}`);
|
|
323
|
+
fs.unlinkSync(lock.lockPath);
|
|
324
|
+
} finally {
|
|
325
|
+
fs.rmSync(releasePath, { force: true });
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
function marketplaceTransactionPaths(marketplaceDir) {
|
|
330
|
+
const parent = path.dirname(marketplaceDir);
|
|
331
|
+
const name = path.basename(marketplaceDir);
|
|
332
|
+
if (!fs.existsSync(parent)) return { temps: [], backups: [] };
|
|
333
|
+
const entries = fs.readdirSync(parent);
|
|
334
|
+
const matching = (kind) => {
|
|
335
|
+
const prefix = `${name}.${kind}-`;
|
|
336
|
+
return entries
|
|
337
|
+
.filter((entry) => entry.startsWith(prefix) && /^\d+-[0-9a-f]{16}$/.test(entry.slice(prefix.length)))
|
|
338
|
+
.map((entry) => path.join(parent, entry));
|
|
339
|
+
};
|
|
340
|
+
return {
|
|
341
|
+
temps: matching("tmp"),
|
|
342
|
+
backups: matching("backup"),
|
|
343
|
+
};
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
function recoverMarketplaceTransaction(marketplaceDir) {
|
|
347
|
+
const { temps, backups } = marketplaceTransactionPaths(marketplaceDir);
|
|
348
|
+
for (const temp of temps) {
|
|
349
|
+
const stat = fs.lstatSync(temp);
|
|
350
|
+
if (stat.isSymbolicLink()) fs.unlinkSync(temp);
|
|
351
|
+
else removeRecursive(temp);
|
|
352
|
+
}
|
|
353
|
+
if (backups.length === 0) return;
|
|
354
|
+
const inspected = backups.map((backup) => ({ backup, stat: fs.lstatSync(backup) }));
|
|
355
|
+
const unsafe = inspected.filter(({ stat }) => stat.isSymbolicLink() || !stat.isDirectory());
|
|
356
|
+
if (unsafe.length > 0) {
|
|
357
|
+
for (const { backup } of unsafe) removeRecursive(backup);
|
|
358
|
+
throw new Error(`refusing unsafe stale marketplace backup (symbolic link or non-directory): ${unsafe[0].backup}`);
|
|
359
|
+
}
|
|
360
|
+
inspected.sort((a, b) => b.stat.mtimeMs - a.stat.mtimeMs);
|
|
361
|
+
const [{ backup }, ...staleBackups] = inspected;
|
|
362
|
+
removeRecursive(marketplaceDir);
|
|
363
|
+
fs.renameSync(backup, marketplaceDir);
|
|
364
|
+
for (const staleBackup of staleBackups) removeRecursive(staleBackup.backup);
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
function stageMarketplace(marketplaceDir, manifest) {
|
|
368
|
+
fs.mkdirSync(path.dirname(marketplaceDir), { recursive: true });
|
|
369
|
+
const lock = acquireMarketplaceLock(marketplaceDir);
|
|
370
|
+
const suffix = `${process.pid}-${lock.token}`;
|
|
371
|
+
const tempDir = `${marketplaceDir}.tmp-${suffix}`;
|
|
372
|
+
const backupDir = `${marketplaceDir}.backup-${suffix}`;
|
|
373
|
+
let hadPrevious = false;
|
|
374
|
+
let backedUp = false;
|
|
375
|
+
try {
|
|
376
|
+
if (lstatIfExists(marketplaceDir)?.isSymbolicLink()) {
|
|
377
|
+
throw new Error(`refusing to update symlink marketplace: ${marketplaceDir}`);
|
|
378
|
+
}
|
|
379
|
+
recoverMarketplaceTransaction(marketplaceDir);
|
|
380
|
+
const restoredRoot = lstatIfExists(marketplaceDir);
|
|
381
|
+
if (restoredRoot && (restoredRoot.isSymbolicLink() || !restoredRoot.isDirectory())) {
|
|
382
|
+
throw new Error(`refusing to stage through unsafe restored marketplace root: ${marketplaceDir}`);
|
|
383
|
+
}
|
|
384
|
+
hadPrevious = restoredRoot !== null;
|
|
385
|
+
if (hadPrevious) fs.cpSync(marketplaceDir, tempDir, { recursive: true, preserveTimestamps: true });
|
|
386
|
+
else fs.mkdirSync(tempDir, { recursive: true });
|
|
387
|
+
const stagedPluginDir = path.join(tempDir, "plugins", PLUGIN_NAME);
|
|
388
|
+
removeRecursive(stagedPluginDir);
|
|
389
|
+
fs.mkdirSync(stagedPluginDir, { recursive: true });
|
|
390
|
+
copyRecursive(PACKAGE_ROOT, stagedPluginDir);
|
|
391
|
+
writeMarketplaceManifest(tempDir, manifest);
|
|
392
|
+
if (hadPrevious) {
|
|
393
|
+
fs.renameSync(marketplaceDir, backupDir);
|
|
394
|
+
backedUp = true;
|
|
395
|
+
}
|
|
396
|
+
fs.renameSync(tempDir, marketplaceDir);
|
|
397
|
+
return { marketplaceDir, backupDir, hadPrevious, lock };
|
|
398
|
+
} catch (error) {
|
|
399
|
+
removeRecursive(tempDir);
|
|
400
|
+
if (backedUp && !fs.existsSync(marketplaceDir)) fs.renameSync(backupDir, marketplaceDir);
|
|
401
|
+
releaseMarketplaceLock(lock);
|
|
402
|
+
throw error;
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
function restoreMarketplaceContent(transaction) {
|
|
407
|
+
removeRecursive(transaction.marketplaceDir);
|
|
408
|
+
if (transaction.hadPrevious) fs.renameSync(transaction.backupDir, transaction.marketplaceDir);
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
function rollbackMarketplace(transaction) {
|
|
412
|
+
try {
|
|
413
|
+
restoreMarketplaceContent(transaction);
|
|
414
|
+
} finally {
|
|
415
|
+
releaseMarketplaceLock(transaction.lock);
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
function commitMarketplace(transaction) {
|
|
420
|
+
removeRecursive(transaction.backupDir);
|
|
421
|
+
releaseMarketplaceLock(transaction.lock);
|
|
422
|
+
}
|
|
423
|
+
|
|
148
424
|
function hasCodexCli() {
|
|
149
425
|
const which = spawnSync(process.platform === "win32" ? "where" : "which", ["codex"], { encoding: "utf-8" });
|
|
150
426
|
return which.status === 0 && which.stdout.trim().length > 0;
|
|
@@ -160,6 +436,96 @@ function runCodex(args, { allowFail = false } = {}) {
|
|
|
160
436
|
return res.status === 0;
|
|
161
437
|
}
|
|
162
438
|
|
|
439
|
+
function pluginListEntryMatches(entry, pluginSpec) {
|
|
440
|
+
if (entry === pluginSpec) return true;
|
|
441
|
+
if (!entry || typeof entry !== "object" || Array.isArray(entry)) return false;
|
|
442
|
+
for (const key of ["id", "pluginId", "plugin_id", "spec", "name"]) {
|
|
443
|
+
if (entry[key] === pluginSpec) return true;
|
|
444
|
+
}
|
|
445
|
+
const names = [entry.name, entry.plugin, entry.pluginName, entry.plugin_name];
|
|
446
|
+
const marketplaces = [entry.marketplace, entry.marketplaceName, entry.marketplace_name, entry.source];
|
|
447
|
+
return names.includes(PLUGIN_NAME) && marketplaces.includes(MARKETPLACE_NAME);
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
function isCodexPluginInstalled(pluginSpec) {
|
|
451
|
+
log("Checking whether the plugin is currently installed...");
|
|
452
|
+
log(" $ codex plugin list --json");
|
|
453
|
+
const result = spawnSync("codex", ["plugin", "list", "--json"], { encoding: "utf8" });
|
|
454
|
+
if (result.status !== 0) throw new Error(`codex plugin list failed with exit code ${result.status}`);
|
|
455
|
+
let output;
|
|
456
|
+
try {
|
|
457
|
+
output = JSON.parse(result.stdout);
|
|
458
|
+
} catch {
|
|
459
|
+
throw new Error("codex plugin list returned invalid JSON");
|
|
460
|
+
}
|
|
461
|
+
if (!output || !Array.isArray(output.installed)) throw new Error("codex plugin list returned an unexpected JSON shape");
|
|
462
|
+
return output.installed.some((entry) => pluginListEntryMatches(entry, pluginSpec));
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
function isCodexMarketplaceRegistered() {
|
|
466
|
+
log("Checking whether the marketplace is currently registered...");
|
|
467
|
+
log(" $ codex plugin marketplace list --json");
|
|
468
|
+
const result = spawnSync("codex", ["plugin", "marketplace", "list", "--json"], { encoding: "utf8" });
|
|
469
|
+
if (result.status !== 0) throw new Error(`codex plugin marketplace list failed with exit code ${result.status}`);
|
|
470
|
+
let output;
|
|
471
|
+
try {
|
|
472
|
+
output = JSON.parse(result.stdout);
|
|
473
|
+
} catch {
|
|
474
|
+
throw new Error("codex plugin marketplace list returned invalid JSON");
|
|
475
|
+
}
|
|
476
|
+
if (!output || !Array.isArray(output.marketplaces)) {
|
|
477
|
+
throw new Error("codex plugin marketplace list returned an unexpected JSON shape");
|
|
478
|
+
}
|
|
479
|
+
return output.marketplaces.some((entry) => entry && typeof entry === "object" && entry.name === MARKETPLACE_NAME);
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
function rollbackCodexPlugin(transaction, previousState, pluginSpec) {
|
|
483
|
+
const failures = [];
|
|
484
|
+
let marketplaceRestored = false;
|
|
485
|
+
try {
|
|
486
|
+
restoreMarketplaceContent(transaction);
|
|
487
|
+
marketplaceRestored = true;
|
|
488
|
+
} catch (error) {
|
|
489
|
+
failures.push(`marketplace restore failed: ${error.message}`);
|
|
490
|
+
}
|
|
491
|
+
try {
|
|
492
|
+
if (!marketplaceRestored) return failures;
|
|
493
|
+
const registrationCommand = previousState.registered
|
|
494
|
+
? ["plugin", "marketplace", "add", transaction.marketplaceDir]
|
|
495
|
+
: ["plugin", "marketplace", "remove", MARKETPLACE_NAME];
|
|
496
|
+
if (!runCodex(registrationCommand, { allowFail: true })) failures.push("could not restore the previous marketplace registration");
|
|
497
|
+
let current;
|
|
498
|
+
try {
|
|
499
|
+
current = isCodexPluginInstalled(pluginSpec);
|
|
500
|
+
} catch (error) {
|
|
501
|
+
failures.push(`could not inspect plugin state during rollback: ${error.message}`);
|
|
502
|
+
return failures;
|
|
503
|
+
}
|
|
504
|
+
if (current && !runCodex(["plugin", "remove", pluginSpec], { allowFail: true })) {
|
|
505
|
+
failures.push("could not remove the failed replacement plugin");
|
|
506
|
+
return failures;
|
|
507
|
+
}
|
|
508
|
+
if (previousState.installed && !runCodex(["plugin", "add", pluginSpec], { allowFail: true })) failures.push("could not reinstall the previously working plugin");
|
|
509
|
+
try {
|
|
510
|
+
if (isCodexPluginInstalled(pluginSpec) !== previousState.installed) failures.push("plugin state did not match the pre-update state after rollback");
|
|
511
|
+
} catch (error) {
|
|
512
|
+
failures.push(`could not verify plugin state after rollback: ${error.message}`);
|
|
513
|
+
}
|
|
514
|
+
try {
|
|
515
|
+
if (isCodexMarketplaceRegistered() !== previousState.registered) failures.push("marketplace registration did not match the pre-update state after rollback");
|
|
516
|
+
} catch (error) {
|
|
517
|
+
failures.push(`could not verify marketplace registration after rollback: ${error.message}`);
|
|
518
|
+
}
|
|
519
|
+
return failures;
|
|
520
|
+
} finally {
|
|
521
|
+
try {
|
|
522
|
+
releaseMarketplaceLock(transaction.lock);
|
|
523
|
+
} catch (error) {
|
|
524
|
+
failures.push(`could not release marketplace transaction lock: ${error.message}`);
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
|
|
163
529
|
function setModelInFrontmatter(content, model) {
|
|
164
530
|
const match = content.match(/^---\n([\s\S]*?)\n---\n?/);
|
|
165
531
|
if (!match) return content;
|
|
@@ -205,7 +571,307 @@ function writeMarketplaceManifest(marketplaceDir, pluginManifest) {
|
|
|
205
571
|
fs.writeFileSync(path.join(manifestDir, "marketplace.json"), `${JSON.stringify(manifest, null, 2)}\n`);
|
|
206
572
|
}
|
|
207
573
|
|
|
208
|
-
|
|
574
|
+
// ─── graph engine (Go binary fetch) ────────────────────────────────────────
|
|
575
|
+
// Installs the prebuilt `draht-graph` binary (go/, Phase 4) into ~/.draht/bin
|
|
576
|
+
// so draht-tools.cjs's dispatch shim can find it. This is the ONLY place in
|
|
577
|
+
// this CLI that reaches the network for this feature — the command path
|
|
578
|
+
// (map-graph, graph-*) must never fetch, since gsd-post-phase and the git
|
|
579
|
+
// post-commit hook run it unattended. See .planning/kg-integration/SPEC.md
|
|
580
|
+
// § "Go engine cutover".
|
|
581
|
+
|
|
582
|
+
const GRAPH_BIN_DIR = path.join(os.homedir(), ".draht", "bin");
|
|
583
|
+
const GRAPH_RELEASE_REPO = "draht-dev/draht";
|
|
584
|
+
// Must equal draht-tools.cjs's GRAPH_SCHEMA_VERSION — kept in sync by hand,
|
|
585
|
+
// these are separate npm packages with no shared import.
|
|
586
|
+
const GRAPH_SCHEMA_VERSION = 5;
|
|
587
|
+
// node-style platform ids matching scripts/build-graph-binaries.sh's
|
|
588
|
+
// PLATFORMS table — the only shapes a release ever ships.
|
|
589
|
+
const GRAPH_SHIPPED_PLATFORMS = new Set(["darwin-arm64", "darwin-x64", "linux-x64", "linux-arm64", "windows-x64"]);
|
|
590
|
+
|
|
591
|
+
function graphBinName() {
|
|
592
|
+
return process.platform === "win32" ? "draht-graph.exe" : "draht-graph";
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
function graphPlatform() {
|
|
596
|
+
const osName = { linux: "linux", darwin: "darwin", win32: "windows" }[process.platform];
|
|
597
|
+
const archName = { x64: "x64", arm64: "arm64" }[process.arch];
|
|
598
|
+
if (!osName || !archName) return null;
|
|
599
|
+
const p = `${osName}-${archName}`;
|
|
600
|
+
return GRAPH_SHIPPED_PLATFORMS.has(p) ? p : null;
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
function sha256(buf) {
|
|
604
|
+
return crypto.createHash("sha256").update(buf).digest("hex");
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
// entry.archive/entry.binary come from the fetched manifest.json (release
|
|
608
|
+
// metadata, not this package's own code) and flow unmodified into a
|
|
609
|
+
// path.join (path traversal), a download URL, and — in extractZip's
|
|
610
|
+
// PowerShell fallback — a single-quoted -Command string, where one
|
|
611
|
+
// apostrophe breaks out into arbitrary command execution. Reachable only by
|
|
612
|
+
// whoever controls the release manifest or an HTTPS MITM, but cheap to
|
|
613
|
+
// close: reject anything that isn't a plain filename.
|
|
614
|
+
const GRAPH_MANIFEST_NAME_RE = /^[A-Za-z0-9._-]+$/;
|
|
615
|
+
function graphManifestNameOk(name) {
|
|
616
|
+
return typeof name === "string" && name.length > 0 && GRAPH_MANIFEST_NAME_RE.test(name);
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
// Minimal POSIX ustar reader — Node ships no built-in tar support and this
|
|
620
|
+
// package may add no new dependency. Only handles what
|
|
621
|
+
// scripts/build-graph-binaries.sh actually produces (regular files +
|
|
622
|
+
// directories, short names, no pax/long-name extensions). Rejects
|
|
623
|
+
// path-traversal entries (zip-slip).
|
|
624
|
+
function extractTarGz(archivePath, destDir, maxDecompressedBytes) {
|
|
625
|
+
let tar;
|
|
626
|
+
try {
|
|
627
|
+
tar = zlib.gunzipSync(fs.readFileSync(archivePath), { maxOutputLength: maxDecompressedBytes });
|
|
628
|
+
} catch (error) {
|
|
629
|
+
if (error?.code === "ERR_BUFFER_TOO_LARGE") throw new Error(`graph archive decompressed data exceeds ${maxDecompressedBytes} bytes`);
|
|
630
|
+
throw error;
|
|
631
|
+
}
|
|
632
|
+
const readStr = (start, len) => {
|
|
633
|
+
const slice = tar.subarray(start, start + len);
|
|
634
|
+
const nul = slice.indexOf(0);
|
|
635
|
+
return Buffer.from(nul === -1 ? slice : slice.subarray(0, nul)).toString("utf-8");
|
|
636
|
+
};
|
|
637
|
+
let offset = 0;
|
|
638
|
+
while (offset + 512 <= tar.length) {
|
|
639
|
+
const header = tar.subarray(offset, offset + 512);
|
|
640
|
+
if (header.every((b) => b === 0)) break; // end-of-archive marker
|
|
641
|
+
const name = readStr(offset, 100);
|
|
642
|
+
const sizeOctal = readStr(offset + 124, 12).trim();
|
|
643
|
+
const typeflag = String.fromCharCode(header[156] || 0);
|
|
644
|
+
const size = sizeOctal ? Number.parseInt(sizeOctal, 8) || 0 : 0;
|
|
645
|
+
offset += 512;
|
|
646
|
+
const dataStart = offset;
|
|
647
|
+
const outPath = path.join(destDir, name);
|
|
648
|
+
if (!outPath.startsWith(destDir + path.sep) && outPath !== destDir) {
|
|
649
|
+
throw new Error(`unsafe tar entry path: ${name}`);
|
|
650
|
+
}
|
|
651
|
+
if (typeflag === "5") {
|
|
652
|
+
fs.mkdirSync(outPath, { recursive: true });
|
|
653
|
+
} else if (typeflag === "0" || typeflag === "\0" || typeflag === "") {
|
|
654
|
+
fs.mkdirSync(path.dirname(outPath), { recursive: true });
|
|
655
|
+
fs.writeFileSync(outPath, tar.subarray(dataStart, dataStart + size));
|
|
656
|
+
}
|
|
657
|
+
offset = dataStart + Math.ceil(size / 512) * 512;
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
function extractZip(archivePath, destDir, entry) {
|
|
662
|
+
extractGraphZip(archivePath, destDir, {
|
|
663
|
+
binary: entry.binary,
|
|
664
|
+
binaryBytes: entry.binaryBytes,
|
|
665
|
+
maxUncompressedBytes: Math.min(GRAPH_IO_LIMITS.decompressedBytes, entry.binaryBytes + 2 * 1024 * 1024),
|
|
666
|
+
maxCompressedBytes: entry.archiveBytes,
|
|
667
|
+
});
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
async function fetchBuffer(url, timeoutMs, { limit, label, aggregate }) {
|
|
671
|
+
const res = await fetch(url, { signal: AbortSignal.timeout(timeoutMs) });
|
|
672
|
+
if (!res.ok) throw new Error(`GET ${url}: ${res.status} ${res.statusText}`);
|
|
673
|
+
const contentLength = Number(res.headers?.get?.("content-length"));
|
|
674
|
+
if (Number.isFinite(contentLength) && contentLength > limit) throw new Error(`${label} Content-Length exceeds ${limit} byte limit`);
|
|
675
|
+
if (!res.body?.getReader) throw new Error(`${label} response body is not a readable stream`);
|
|
676
|
+
const reader = res.body.getReader();
|
|
677
|
+
const chunks = [];
|
|
678
|
+
let bytes = 0;
|
|
679
|
+
try {
|
|
680
|
+
while (true) {
|
|
681
|
+
const { done, value } = await reader.read();
|
|
682
|
+
if (done) break;
|
|
683
|
+
bytes += value.byteLength;
|
|
684
|
+
if (bytes > limit) throw new Error(`${label} exceeds ${limit} byte limit`);
|
|
685
|
+
if (aggregate.bytes + bytes > GRAPH_IO_LIMITS.aggregateDownloadBytes) throw new Error("graph release downloads exceed aggregate byte limit");
|
|
686
|
+
chunks.push(Buffer.from(value));
|
|
687
|
+
}
|
|
688
|
+
} catch (error) {
|
|
689
|
+
await reader.cancel(error).catch(() => {});
|
|
690
|
+
throw error;
|
|
691
|
+
}
|
|
692
|
+
aggregate.bytes += bytes;
|
|
693
|
+
return Buffer.concat(chunks, bytes);
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
async function fetchJson(url, timeoutMs, aggregate) {
|
|
697
|
+
const bytes = await fetchBuffer(url, timeoutMs, { limit: GRAPH_IO_LIMITS.manifestBytes, label: "graph manifest", aggregate });
|
|
698
|
+
try { return JSON.parse(bytes.toString("utf8")); }
|
|
699
|
+
catch (error) { throw new Error(`graph manifest is not valid JSON: ${error.message}`, { cause: error }); }
|
|
700
|
+
}
|
|
701
|
+
|
|
702
|
+
function runGh(args) {
|
|
703
|
+
const result = spawnSync("gh", args, { encoding: "utf8", windowsHide: true, maxBuffer: 8 * 1024 * 1024 });
|
|
704
|
+
if (result.error) throw new Error(`gh ${args[0]} unavailable: ${result.error.message}`);
|
|
705
|
+
if (result.status !== 0) throw new Error(`gh ${args[0]} failed: ${(result.stderr || "").trim()}`);
|
|
706
|
+
return result.stdout;
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
function resolveGraphReleaseCommit(tag) {
|
|
710
|
+
let object = JSON.parse(runGh(["api", `repos/${GRAPH_RELEASE_REPO}/git/ref/tags/${tag}`])).object;
|
|
711
|
+
for (let depth = 0; depth < 8 && object?.type === "tag"; depth++) {
|
|
712
|
+
object = JSON.parse(runGh(["api", `repos/${GRAPH_RELEASE_REPO}/git/tags/${object.sha}`])).object;
|
|
713
|
+
}
|
|
714
|
+
if (object?.type !== "commit" || !/^[a-f0-9]{40}$/.test(object.sha)) throw new Error(`release tag ${tag} does not resolve to an exact commit`);
|
|
715
|
+
return object.sha;
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
function verifyGraphAttestation(archivePath, entry, commit, tag) {
|
|
719
|
+
const output = runGh(["attestation", "verify", archivePath, "--repo", GRAPH_RELEASE_REPO, "--predicate-type", "https://slsa.dev/provenance/v1", "--deny-self-hosted-runners", "--format", "json"]);
|
|
720
|
+
validateGraphAttestation(output, { archive: entry.archive, digest: entry.archiveSha256, repo: GRAPH_RELEASE_REPO, commit, tag });
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
// Atomically installs `srcPath` (an already-verified local binary) as the
|
|
724
|
+
// stable ~/.draht/bin/draht-graph[.exe] entry point — a REAL COPY, not a
|
|
725
|
+
// symlink (graph-hook bakes os.Executable()'s fully-resolved path into
|
|
726
|
+
// .git/hooks/post-commit; a symlink target would break on the next
|
|
727
|
+
// upgrade+prune) — and writes the provenance stamp draht-tools.cjs's
|
|
728
|
+
// resolver checks. Used by both the network fetch path and `--from <path>`.
|
|
729
|
+
function installGraphBinary(srcPath, { version, binarySha256, binaryBytes }) {
|
|
730
|
+
fs.mkdirSync(GRAPH_BIN_DIR, { recursive: true });
|
|
731
|
+
const target = path.join(GRAPH_BIN_DIR, graphBinName());
|
|
732
|
+
const stampPath = path.join(GRAPH_BIN_DIR, ".draht-graph.json");
|
|
733
|
+
const nonce = `${process.pid}.${Date.now()}`;
|
|
734
|
+
const binaryTmp = `${target}.${nonce}.tmp`;
|
|
735
|
+
const stampTmp = `${stampPath}.${nonce}.tmp`;
|
|
736
|
+
const stamp = `${JSON.stringify(
|
|
737
|
+
{
|
|
738
|
+
name: "draht-graph",
|
|
739
|
+
version,
|
|
740
|
+
schemaVersion: GRAPH_SCHEMA_VERSION,
|
|
741
|
+
sha256: binarySha256,
|
|
742
|
+
size: binaryBytes,
|
|
743
|
+
installedAt: new Date().toISOString(),
|
|
744
|
+
},
|
|
745
|
+
null,
|
|
746
|
+
2,
|
|
747
|
+
)}\n`;
|
|
748
|
+
try {
|
|
749
|
+
fs.copyFileSync(srcPath, binaryTmp);
|
|
750
|
+
fs.chmodSync(binaryTmp, 0o755);
|
|
751
|
+
fs.writeFileSync(stampTmp, stamp, { mode: 0o600 });
|
|
752
|
+
// Each file replacement is atomic. Publishing the stamp first means a crash
|
|
753
|
+
// between renames leaves a digest mismatch, which all resolvers reject.
|
|
754
|
+
fs.renameSync(stampTmp, stampPath);
|
|
755
|
+
fs.renameSync(binaryTmp, target);
|
|
756
|
+
} finally {
|
|
757
|
+
fs.rmSync(binaryTmp, { force: true });
|
|
758
|
+
fs.rmSync(stampTmp, { force: true });
|
|
759
|
+
}
|
|
760
|
+
if (process.platform === "darwin") {
|
|
761
|
+
// Unsigned/unnotarized artifacts get Gatekeeper-quarantined on
|
|
762
|
+
// download; a quarantined binary silently fails to exec inside a hook.
|
|
763
|
+
spawnSync("xattr", ["-d", "com.apple.quarantine", target], { stdio: "ignore" });
|
|
764
|
+
}
|
|
765
|
+
return target;
|
|
766
|
+
}
|
|
767
|
+
|
|
768
|
+
function installedGraphBinaryMatches(target, stampPath, version) {
|
|
769
|
+
try {
|
|
770
|
+
const stamp = JSON.parse(fs.readFileSync(stampPath, "utf-8"));
|
|
771
|
+
if (!stamp || typeof stamp !== "object" || Array.isArray(stamp)) return false;
|
|
772
|
+
if (stamp.name !== "draht-graph" || stamp.version !== version || stamp.schemaVersion !== GRAPH_SCHEMA_VERSION) return false;
|
|
773
|
+
if (!Number.isSafeInteger(stamp.size) || stamp.size < 0 || !/^[0-9a-f]{64}$/.test(stamp.sha256)) return false;
|
|
774
|
+
const binary = fs.readFileSync(target);
|
|
775
|
+
return binary.length === stamp.size && sha256(binary) === stamp.sha256;
|
|
776
|
+
} catch {
|
|
777
|
+
return false;
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
// Never throws — every failure degrades to "draht will use the built-in JS
|
|
782
|
+
// engine", per SPEC.md's non-negotiable install policy. Called as the LAST
|
|
783
|
+
// step of cmdInstall (after the plugin itself is installed), so a
|
|
784
|
+
// graph-engine fetch failure can never fail `npx draht-codex install`.
|
|
785
|
+
async function ensureGraphEngine(flags) {
|
|
786
|
+
if (flags.noGraphEngine || process.env.DRAHT_SKIP_GRAPH_ENGINE) return;
|
|
787
|
+
try {
|
|
788
|
+
if (flags.from) {
|
|
789
|
+
const buf = fs.readFileSync(flags.from);
|
|
790
|
+
const target = installGraphBinary(flags.from, {
|
|
791
|
+
version: flags.graphEngineVersion || "local",
|
|
792
|
+
binarySha256: sha256(buf),
|
|
793
|
+
binaryBytes: buf.length,
|
|
794
|
+
});
|
|
795
|
+
log(`installed graph engine from ${flags.from} -> ${target}`);
|
|
796
|
+
return;
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
const target = path.join(GRAPH_BIN_DIR, graphBinName());
|
|
800
|
+
const stampPath = path.join(GRAPH_BIN_DIR, ".draht-graph.json");
|
|
801
|
+
let pkgVersion = "0.0.0";
|
|
802
|
+
try {
|
|
803
|
+
pkgVersion = JSON.parse(fs.readFileSync(path.join(PACKAGE_ROOT, "package.json"), "utf-8")).version;
|
|
804
|
+
} catch { /* fall back to 0.0.0 — forces a fetch attempt rather than a false "up to date" */ }
|
|
805
|
+
const version = flags.graphEngineVersion || process.env.DRAHT_GRAPH_ENGINE_VERSION || pkgVersion;
|
|
806
|
+
|
|
807
|
+
if (fs.existsSync(target) && !flags.force && installedGraphBinaryMatches(target, stampPath, version)) {
|
|
808
|
+
log(`graph engine v${version} already installed`);
|
|
809
|
+
return;
|
|
810
|
+
}
|
|
811
|
+
|
|
812
|
+
const platform = graphPlatform();
|
|
813
|
+
if (!platform) {
|
|
814
|
+
log(`no prebuilt graph engine binary for ${process.platform}/${process.arch} — draht will use the built-in JS engine.`);
|
|
815
|
+
return;
|
|
816
|
+
}
|
|
817
|
+
|
|
818
|
+
const tag = version.startsWith("v") ? version : `v${version}`;
|
|
819
|
+
const base = `https://github.com/${GRAPH_RELEASE_REPO}/releases/download/${tag}`;
|
|
820
|
+
const releaseCommit = resolveGraphReleaseCommit(tag);
|
|
821
|
+
const aggregate = { bytes: 0 };
|
|
822
|
+
const manifest = await fetchJson(`${base}/manifest.json`, 15_000, aggregate);
|
|
823
|
+
const entry = validateGraphManifest(manifest, { version, tag, platform, commit: releaseCommit });
|
|
824
|
+
if (!graphManifestNameOk(entry.archive) || !graphManifestNameOk(entry.binary)) {
|
|
825
|
+
log(`release ${tag}'s manifest.json has an invalid archive/binary name for ${platform} — refusing to use it. draht will use the built-in JS engine.`);
|
|
826
|
+
return;
|
|
827
|
+
}
|
|
828
|
+
const checksums = (await fetchBuffer(`${base}/SHA256SUMS`, 15_000, { limit: GRAPH_IO_LIMITS.checksumBytes, label: "graph checksum file", aggregate })).toString("utf8");
|
|
829
|
+
validateGraphChecksums(checksums, entry, platform);
|
|
830
|
+
|
|
831
|
+
const archiveBuf = await fetchBuffer(`${base}/${entry.archive}`, 120_000, { limit: entry.archiveBytes, label: "graph archive", aggregate });
|
|
832
|
+
if (sha256(archiveBuf) !== entry.archiveSha256 || archiveBuf.length !== entry.archiveBytes) {
|
|
833
|
+
log(`graph engine download failed (checksum mismatch on ${entry.archive}) — draht will use the built-in JS engine.`);
|
|
834
|
+
return;
|
|
835
|
+
}
|
|
836
|
+
|
|
837
|
+
const workDir = fs.mkdtempSync(path.join(os.tmpdir(), "draht-graph-"));
|
|
838
|
+
try {
|
|
839
|
+
const archivePath = path.join(workDir, entry.archive);
|
|
840
|
+
fs.writeFileSync(archivePath, archiveBuf);
|
|
841
|
+
verifyGraphAttestation(archivePath, entry, releaseCommit, tag);
|
|
842
|
+
const extractDir = path.join(workDir, "extracted");
|
|
843
|
+
if (entry.archive.endsWith(".zip")) extractZip(archivePath, extractDir, entry);
|
|
844
|
+
else extractTarGz(archivePath, extractDir, Math.min(GRAPH_IO_LIMITS.decompressedBytes, entry.binaryBytes + 2 * 1024 * 1024));
|
|
845
|
+
|
|
846
|
+
// Both archive formats wrap a draht-graph/ directory — see
|
|
847
|
+
// scripts/build-graph-binaries.sh.
|
|
848
|
+
const binPath = path.join(extractDir, "draht-graph", entry.binary);
|
|
849
|
+
const binarySize = fs.statSync(binPath).size;
|
|
850
|
+
if (binarySize > entry.binaryBytes || binarySize > GRAPH_IO_LIMITS.binaryBytes) throw new Error(`extracted graph binary exceeds ${entry.binaryBytes} byte limit`);
|
|
851
|
+
const binBuf = fs.readFileSync(binPath);
|
|
852
|
+
if (sha256(binBuf) !== entry.binarySha256 || binBuf.length !== entry.binaryBytes) {
|
|
853
|
+
log(`graph engine download failed (checksum mismatch on extracted ${entry.binary}) — draht will use the built-in JS engine.`);
|
|
854
|
+
return;
|
|
855
|
+
}
|
|
856
|
+
|
|
857
|
+
installGraphBinary(binPath, { version, binarySha256: entry.binarySha256, binaryBytes: entry.binaryBytes });
|
|
858
|
+
log(`graph engine v${version} -> ${target} (${(entry.binaryBytes / 1e6).toFixed(1)} MB) — map-graph is now much faster`);
|
|
859
|
+
} finally {
|
|
860
|
+
fs.rmSync(workDir, { recursive: true, force: true });
|
|
861
|
+
}
|
|
862
|
+
} catch (error) {
|
|
863
|
+
log(`graph engine download failed (${error.message}) — draht will use the built-in JS engine.`);
|
|
864
|
+
log(" Retry any time: npx draht-codex install-graph-engine");
|
|
865
|
+
}
|
|
866
|
+
}
|
|
867
|
+
|
|
868
|
+
function removeGraphEngine() {
|
|
869
|
+
if (!fs.existsSync(GRAPH_BIN_DIR)) return;
|
|
870
|
+
removeRecursive(path.join(GRAPH_BIN_DIR, graphBinName()));
|
|
871
|
+
removeRecursive(path.join(GRAPH_BIN_DIR, ".draht-graph.json"));
|
|
872
|
+
}
|
|
873
|
+
|
|
874
|
+
async function cmdInstall(flags) {
|
|
209
875
|
const marketplaceDir = flags.path || DEFAULT_MARKETPLACE_DIR;
|
|
210
876
|
const pluginDir = path.join(marketplaceDir, "plugins", PLUGIN_NAME);
|
|
211
877
|
const pluginSpec = `${PLUGIN_NAME}@${MARKETPLACE_NAME}`;
|
|
@@ -230,26 +896,63 @@ function cmdInstall(flags) {
|
|
|
230
896
|
process.exit(1);
|
|
231
897
|
}
|
|
232
898
|
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
899
|
+
// Build the complete marketplace beside the live tree, then switch it with
|
|
900
|
+
// rename operations. A surviving backup means an interrupted transaction and
|
|
901
|
+
// is restored before staging the next update.
|
|
902
|
+
log("Staging plugin files and marketplace.json...");
|
|
903
|
+
const marketplaceTransaction = stageMarketplace(marketplaceDir, manifest);
|
|
904
|
+
|
|
905
|
+
// Capture registration state while holding the marketplace transaction lock
|
|
906
|
+
// and before any destructive CLI command. JSON avoids display-format parsing.
|
|
907
|
+
let previousState;
|
|
908
|
+
try {
|
|
909
|
+
previousState = {
|
|
910
|
+
registered: isCodexMarketplaceRegistered(),
|
|
911
|
+
installed: isCodexPluginInstalled(pluginSpec),
|
|
912
|
+
};
|
|
913
|
+
} catch (error) {
|
|
914
|
+
try {
|
|
915
|
+
rollbackMarketplace(marketplaceTransaction);
|
|
916
|
+
} catch (rollbackError) {
|
|
917
|
+
err(`rollback failed: marketplace restore failed: ${rollbackError.message}`);
|
|
918
|
+
}
|
|
919
|
+
err(`could not determine existing plugin state: ${error.message}`);
|
|
920
|
+
process.exit(1);
|
|
236
921
|
}
|
|
237
|
-
fs.mkdirSync(pluginDir, { recursive: true });
|
|
238
|
-
copyRecursive(PACKAGE_ROOT, pluginDir);
|
|
239
922
|
|
|
240
|
-
|
|
241
|
-
|
|
923
|
+
try {
|
|
924
|
+
log("Registering marketplace with Codex...");
|
|
925
|
+
if (!runCodex(["plugin", "marketplace", "add", marketplaceDir], { allowFail: true })) throw new Error("marketplace registration failed");
|
|
242
926
|
|
|
243
|
-
|
|
244
|
-
|
|
927
|
+
if (previousState.installed) {
|
|
928
|
+
log("Removing previous installed plugin cache...");
|
|
929
|
+
if (!runCodex(["plugin", "remove", pluginSpec], { allowFail: true })) throw new Error("previous plugin removal failed");
|
|
930
|
+
}
|
|
245
931
|
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
932
|
+
log("Installing plugin...");
|
|
933
|
+
if (!runCodex(["plugin", "add", pluginSpec], { allowFail: true })) throw new Error("replacement install failed");
|
|
934
|
+
if (!isCodexPluginInstalled(pluginSpec)) throw new Error("post-install plugin state verification failed");
|
|
935
|
+
} catch (error) {
|
|
936
|
+
const rollbackFailures = rollbackCodexPlugin(marketplaceTransaction, previousState, pluginSpec);
|
|
937
|
+
err(error.message);
|
|
938
|
+
err(marketplaceTransaction.hadPrevious ? "rollback: restored the previous marketplace content" : "rollback: removed the failed marketplace content");
|
|
939
|
+
for (const failure of rollbackFailures) err(`rollback failed: ${failure}`);
|
|
940
|
+
process.exit(1);
|
|
249
941
|
}
|
|
942
|
+
commitMarketplace(marketplaceTransaction);
|
|
250
943
|
|
|
251
|
-
|
|
252
|
-
|
|
944
|
+
// The graph engine is a separate, OPT-IN download. It is deliberately not
|
|
945
|
+
// fetched by default: the artifact is an unsigned native binary pulled from
|
|
946
|
+
// a GitHub release, and silently downloading and exec'ing one as a side
|
|
947
|
+
// effect of installing a plugin is not a decision this installer should make
|
|
948
|
+
// for the user. `--graph-engine` (or `install-graph-engine` later) asks for
|
|
949
|
+
// it explicitly. Until binaries are actually published, a default fetch
|
|
950
|
+
// would also just be a doomed request on every install.
|
|
951
|
+
// Runs LAST so a download failure can never fail the plugin install
|
|
952
|
+
// (ensureGraphEngine never throws).
|
|
953
|
+
if (flags.graphEngine) {
|
|
954
|
+
await ensureGraphEngine(flags);
|
|
955
|
+
}
|
|
253
956
|
|
|
254
957
|
log("");
|
|
255
958
|
log(`installed ${pluginSpec} v${manifest.version}`);
|
|
@@ -266,6 +969,20 @@ function cmdUninstall(flags) {
|
|
|
266
969
|
const marketplaceDir = flags.path || DEFAULT_MARKETPLACE_DIR;
|
|
267
970
|
const pluginSpec = `${PLUGIN_NAME}@${MARKETPLACE_NAME}`;
|
|
268
971
|
|
|
972
|
+
// ~/.draht/bin is a sibling of the marketplace dir, shared across
|
|
973
|
+
// draht-claude/draht-codex/coding-agent, AND its resolved absolute path is
|
|
974
|
+
// baked into every repo's .git/hooks/post-commit (go/internal/hook). Removing
|
|
975
|
+
// it here would silently break graph-engine use in every OTHER package and
|
|
976
|
+
// silently no-op every repo's post-commit hook — so it is opt-in only.
|
|
977
|
+
if (flags.purgeGraphEngine) {
|
|
978
|
+
removeGraphEngine();
|
|
979
|
+
log("Removed ~/.draht/bin/draht-graph (--purge-graph-engine) — draht-claude/coding-agent");
|
|
980
|
+
log("and any repo's post-commit hook that used it will now fall back to the JS engine.");
|
|
981
|
+
} else if (fs.existsSync(GRAPH_BIN_DIR)) {
|
|
982
|
+
log("Leaving ~/.draht/bin/draht-graph in place (shared with draht-claude/coding-agent).");
|
|
983
|
+
log("Remove it too with: npx draht-codex uninstall --purge-graph-engine");
|
|
984
|
+
}
|
|
985
|
+
|
|
269
986
|
log("draht-codex uninstaller");
|
|
270
987
|
log(` marketplace: ${marketplaceDir}`);
|
|
271
988
|
log(` plugin: ${pluginSpec}`);
|
|
@@ -289,8 +1006,8 @@ function cmdUninstall(flags) {
|
|
|
289
1006
|
log("uninstalled");
|
|
290
1007
|
}
|
|
291
1008
|
|
|
292
|
-
function cmdUpdate(flags) {
|
|
293
|
-
cmdInstall({ ...flags, force: true });
|
|
1009
|
+
async function cmdUpdate(flags) {
|
|
1010
|
+
await cmdInstall({ ...flags, force: true });
|
|
294
1011
|
}
|
|
295
1012
|
|
|
296
1013
|
function cmdStatus(flags) {
|
|
@@ -424,29 +1141,35 @@ if (flags.help) {
|
|
|
424
1141
|
process.exit(0);
|
|
425
1142
|
}
|
|
426
1143
|
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
1144
|
+
(async () => {
|
|
1145
|
+
switch (command) {
|
|
1146
|
+
case "install":
|
|
1147
|
+
await cmdInstall(flags);
|
|
1148
|
+
break;
|
|
1149
|
+
case "uninstall":
|
|
1150
|
+
case "remove":
|
|
1151
|
+
cmdUninstall(flags);
|
|
1152
|
+
break;
|
|
1153
|
+
case "update":
|
|
1154
|
+
case "upgrade":
|
|
1155
|
+
await cmdUpdate(flags);
|
|
1156
|
+
break;
|
|
1157
|
+
case "status":
|
|
1158
|
+
cmdStatus(flags);
|
|
1159
|
+
break;
|
|
1160
|
+
case "configure":
|
|
1161
|
+
cmdConfigure(flags);
|
|
1162
|
+
break;
|
|
1163
|
+
case "draht-tools":
|
|
1164
|
+
cmdDrahtTools(passthrough);
|
|
1165
|
+
break;
|
|
1166
|
+
case "install-graph-engine":
|
|
1167
|
+
case "graph-engine":
|
|
1168
|
+
await ensureGraphEngine(flags);
|
|
1169
|
+
break;
|
|
1170
|
+
default:
|
|
1171
|
+
err(`unknown command: ${command}`);
|
|
1172
|
+
err("run 'draht-codex --help' for usage");
|
|
1173
|
+
process.exit(1);
|
|
1174
|
+
}
|
|
1175
|
+
})();
|