Repository navigation
Expand file tree
/
Copy pathlauncher.js
More file actions
858 lines (815 loc) · 44.2 KB
/
Copy pathlauncher.js
File metadata and controls
858 lines (815 loc) · 44.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
'use strict';
/**
* The PassionCode.ai launcher: installs the vendored payload as one release,
* gives Claude Code the plugins through a local marketplace, gives every other
* agent the same skills through the ~/.agents/skills hub, registers the MCP servers of
* the installed PassionCode.ai apps for every agent that is present, and removes what would
* shadow them — reversibly. Every step is recorded; nothing is deleted.
*
* One channel per agent: Claude Code reads plugins, so nothing is written to
* ~/.claude/skills (a plain copy there shadows the plugin and serves its frozen
* version forever); every other agent reads the hub through its own channel.
*/
const { spawnSync } = require('child_process');
const fs = require('fs');
const os = require('os');
const path = require('path');
const PACKAGE_ROOT = path.resolve(__dirname, '..');
const PAYLOAD = () => process.env.PASSIONCODE_PAYLOAD || path.join(PACKAGE_ROOT, 'payload');
const MARKETPLACE = 'passioncode';
/** Agent channels read from the hub, and the path each keeps its skills in. */
const CHANNELS = [
'.cursor/skills', '.codex/skills', '.gemini/skills', '.gemini/antigravity/skills', '.config/opencode/skills',
'.kiro/skills', '.openclaw/skills', '.codeium/windsurf/skills', '.config/goose/skills', '.hermes/skills',
'.kilocode/skills', '.openhands/skills',
];
function paths(home = os.homedir()) {
const state = process.env.PASSIONCODE_HOME || path.join(home, '.passioncode');
return {
home, state,
releases: path.join(state, 'releases'),
current: path.join(state, 'current'),
stateFile: path.join(state, 'state.json'),
quarantine: path.join(state, 'quarantine'),
hub: path.join(home, '.agents', 'skills'),
claudeSkills: path.join(home, '.claude', 'skills'),
claudePlugins: path.join(home, '.claude', 'plugins'),
claudeSettings: path.join(home, '.claude', 'settings.json'),
};
}
function readJson(file, fallback) { try { return JSON.parse(fs.readFileSync(file, 'utf8')); } catch (_) { return fallback; } }
function writeJson(file, value) {
fs.mkdirSync(path.dirname(file), { recursive: true });
const tmp = `${file}.${process.pid}.tmp`;
fs.writeFileSync(tmp, JSON.stringify(value, null, 2) + '\n');
fs.renameSync(tmp, file);
}
function writeText(file, text) {
fs.mkdirSync(path.dirname(file), { recursive: true });
const tmp = `${file}.${process.pid}.tmp`;
fs.writeFileSync(tmp, text);
fs.renameSync(tmp, file);
}
function lstat(p) { try { return fs.lstatSync(p); } catch (_) { return null; } }
function linkTarget(p) { try { return fs.readlinkSync(p); } catch (_) { return null; } }
function pointsTo(at, target) { const link = linkTarget(at); return link !== null && path.resolve(path.dirname(at), link) === target; }
function isDirectory(at) { try { return fs.statSync(at).isDirectory(); } catch (_) { return false; } }
function readState(file, { tolerant = false } = {}) {
try { return readSettings(file).doc; } catch (error) {
if (tolerant) return {};
throw new Error(`Cannot read state ${file}: ${error.message}. Preserve the file and repair it before retrying.`);
}
}
/** Replace a symlink atomically (create beside it, rename over it). */
function symlinkAtomic(target, at) {
fs.mkdirSync(path.dirname(at), { recursive: true });
const tmp = `${at}.${process.pid}.lnk`;
try { fs.unlinkSync(tmp); } catch (_) { /* none */ }
fs.symlinkSync(target, tmp);
fs.renameSync(tmp, at);
}
// --- one update at a time (lifecycle contract LC-03) ---------------------------------------
// update, restore and uninstall all write installed_plugins.json, the hub and state.json. A
// background update (started by the session hook) and a manual one used to interleave their
// `claude plugin` writes. They now take one lock; the second refuses and names the holder.
const O_EXLOCK = 0x20; // BSD/macOS open(2) flag: take flock(LOCK_EX); absent from fs.constants
class UpdateRunning extends Error {
constructor(pid, file) {
super(`Another PassionCode update is already running (${pid ? `process ${pid}` : 'another process'} holds ${file}); let it finish, then retry.`);
this.pid = pid;
}
}
function readPid(file) {
try { const text = fs.readFileSync(file, 'utf8').trim(); return /^\d{1,10}$/.test(text) ? Number(text) : null; } catch (_) { return null; }
}
function alive(pid) {
try { process.kill(pid, 0); return true; } catch (error) { return error.code === 'EPERM'; }
}
/**
* Take ~/.passioncode/update.lock. On macOS it is a kernel flock (released when the holder dies,
* so it is never stale); elsewhere an exclusively created pid file whose holder must be alive.
* Returns `{ release() }`; throws UpdateRunning when another process holds it.
*/
function acquireUpdateLock(p) {
fs.mkdirSync(p.state, { recursive: true });
const file = path.join(p.state, 'update.lock');
if (process.platform === 'darwin') {
let fd;
try {
fd = fs.openSync(file, fs.constants.O_RDWR | fs.constants.O_CREAT | O_EXLOCK | fs.constants.O_NONBLOCK, 0o600);
} catch (error) {
if (error.code === 'EAGAIN' || error.code === 'EWOULDBLOCK') throw new UpdateRunning(readPid(file), file);
throw error;
}
fs.ftruncateSync(fd, 0);
fs.writeSync(fd, String(process.pid));
return { release() { if (fd !== null) { fs.closeSync(fd); fd = null; } } };
}
for (let attempt = 0; attempt < 2; attempt += 1) {
try {
fs.writeFileSync(file, String(process.pid), { flag: 'wx', mode: 0o600 });
return { release() { if (readPid(file) === process.pid) fs.rmSync(file, { force: true }); } };
} catch (error) {
if (error.code !== 'EEXIST') throw error;
const pid = readPid(file);
if (pid && pid !== process.pid && alive(pid)) throw new UpdateRunning(pid, file);
// The holder is gone: move its file aside atomically, so two takers cannot both steal it.
try { fs.renameSync(file, `${file}.stale.${process.pid}`); fs.rmSync(`${file}.stale.${process.pid}`, { force: true }); } catch (_) { /* another taker moved it */ }
}
}
throw new UpdateRunning(readPid(file), file);
}
function withUpdateLock(home, fn) {
const lock = acquireUpdateLock(paths(home));
try { return fn(); } finally { lock.release(); }
}
// --- release retention (LC-11, LC-15) -----------------------------------------------------------
const semver = (v) => v.split('.').map(Number);
function newerVersion(a, b) {
const pa = semver(a), pb = semver(b);
for (let i = 0; i < 3; i += 1) if (pa[i] !== pb[i]) return pa[i] > pb[i];
return false;
}
/**
* The release directories an update may remove: every one except the release it installed and
* the one it replaced (the rollback; the newest other release when it replaced none), plus any
* `*.partial` copy a killed update left behind (safe: the caller holds the update lock).
* Files, symlinks and anything not named like a release are never touched.
*/
function staleReleases(p, version, previous) {
let entries;
try { entries = fs.readdirSync(p.releases, { withFileTypes: true }); } catch (_) { return []; }
const dirs = entries.filter((e) => e.isDirectory() && !e.isSymbolicLink()).map((e) => e.name);
const partial = dirs.filter((n) => /^\d+\.\d+\.\d+\.\d+\.partial$/.test(n));
const versions = dirs.filter((n) => /^\d+\.\d+\.\d+$/.test(n));
let keep = previous && versions.includes(previous) && previous !== version ? previous : null;
if (!keep) {
for (const v of versions) if (v !== version && (!keep || newerVersion(v, keep))) keep = v;
}
return [...versions.filter((v) => v !== version && v !== keep), ...partial].map((n) => path.join(p.releases, n));
}
/** Claude Code's plugin CLI, overridable for tests. */
function claudeRunner() {
const bin = process.env.PASSIONCODE_CLAUDE || 'claude';
let found;
const available = () => found ?? (found = spawnSync(bin, ['--version'], { encoding: 'utf8', timeout: 5000 }).status === 0);
const run = (args, { cwd } = {}) => {
const r = spawnSync(bin, args, { encoding: 'utf8', timeout: 180000, ...(cwd ? { cwd } : {}) });
return { code: r.status === null ? 1 : r.status, out: `${r.stdout || ''}${r.stderr || ''}`.trim() };
};
return { available, run };
}
/**
* Claude Code's user settings. A missing file is empty; a file that does not parse is
* an error — rewriting it would drop whatever the person keeps there.
*/
function readSettings(file) {
let text;
try { text = fs.readFileSync(file, 'utf8'); } catch (error) { if (error.code === 'ENOENT') return { exists: false, doc: {} }; throw error; }
const doc = JSON.parse(text);
if (!doc || typeof doc !== 'object' || Array.isArray(doc)) throw new Error(`${file} is not a JSON object`);
return { exists: true, doc };
}
/** The argument `claude plugin marketplace add` takes for a recorded marketplace source. */
function marketplaceAddArg(source) {
if (!source || typeof source !== 'object') return null;
if (source.source === 'github') return source.repo || null;
if (source.source === 'directory' || source.source === 'file') return source.path || null;
return source.url || source.repo || source.path || null;
}
const catalog = require('./catalog');
/**
* The stdio MCP servers inside the PassionCode.ai app bundles (lib/catalog.js): name, the
* product's label, the command, and the arguments each agent gets (null: no runner for it).
*/
function bundledMcpServers() {
return catalog.PRODUCTS.filter((pr) => pr.mcp && !pr.mcp.external && pr.mcp.bin).map((pr) => {
const agentOf = (id) => catalog.AGENTS.find((a) => a.id === id);
const first = catalog.mcpCommand(pr, agentOf('claude')) || catalog.mcpCommand(pr, agentOf('codex'));
return {
name: pr.mcp.name, label: pr.name, product: pr.id, claudePlugin: pr.mcp.claudePlugin || null, preview: !!pr.preview,
command: first ? first.command : catalog.appPath(pr),
argsFor: (id) => { const c = catalog.mcpCommand(pr, agentOf(id)); return c ? c.args : null; },
};
});
}
/**
* The agents besides Claude Code the apps' MCP servers are registered for, and
* the file each keeps its MCP configuration in. An agent is present when its directory
* is; a missing file under a present agent is created. Claude Code is registered through
* its own CLI instead: every running session rewrites ~/.claude.json, so a second writer
* there would lose one side's change.
*/
function mcpFileTargets(home) {
const kimiHome = process.env.KIMI_CODE_HOME || path.join(home, '.kimi-code');
return [
{ id: 'codex', agent: 'Codex CLI', dir: path.join(home, '.codex'), file: path.join(home, '.codex', 'config.toml'), kind: 'toml' },
{ id: 'gemini', agent: 'Gemini CLI', dir: path.join(home, '.gemini'), file: path.join(home, '.gemini', 'settings.json'), kind: 'json' },
{ id: 'kimi', agent: 'Kimi Code', dir: kimiHome, file: path.join(kimiHome, 'mcp.json'), kind: 'json' },
];
}
/** The line range of the `["mcp_servers"."<name>"]` table in a TOML text, or null. */
function tomlTableRange(text, name) {
const lines = text.split('\n');
const header = new RegExp(`^\\s*\\[\\s*["']?mcp_servers["']?\\s*\\.\\s*["']?${name}["']?\\s*\\]\\s*(?:#.*)?$`);
for (let i = 0; i < lines.length; i++) {
if (!header.test(lines[i])) continue;
let end = lines.length;
for (let j = i + 1; j < lines.length; j++) {
if (/^\s*\[/.test(lines[j])) { end = j; break; }
}
return { start: i, end, lines };
}
return null;
}
/**
* Any other way a TOML text can already define the server — a sub-table such as
* `[mcp_servers.<name>.env]` or an inline `<name> = { … }` under `[mcp_servers]`.
* Appending a table then would declare the key twice and Codex would refuse the file.
*/
function tomlMentions(text, name) {
return new RegExp(`^\\s*\\[\\s*["']?mcp_servers["']?\\s*\\.\\s*["']?${name}["']?\\s*\\.`, 'm').test(text)
|| new RegExp(`^\\s*["']?${name}["']?\\s*=`, 'm').test(text);
}
/** The `command` of a TOML table range: the string, null when absent, undefined when unreadable. */
function tomlTableCommand(range) {
for (let i = range.start + 1; i < range.end; i++) {
const m = /^\s*command\s*=\s*("(?:[^"\\]|\\.)*")\s*(?:#.*)?$/.exec(range.lines[i]);
if (m) { try { return JSON.parse(m[1]); } catch (_) { return undefined; } }
}
return null;
}
/** The `args` array of a TOML table range: an array, [] when absent, null when unreadable. */
function tomlTableArgs(range) {
for (let i = range.start + 1; i < range.end; i++) {
const m = /^\s*args\s*=\s*(\[.*\])\s*(?:#.*)?$/.exec(range.lines[i]);
if (m) { try { return JSON.parse(m[1]); } catch (_) { return null; } }
}
return [];
}
/**
* Settings of server `name` left elsewhere in a TOML text: a `[mcp_servers.<name>.…]` sub-table
* header anywhere, or a `<name>.…` / `<name> =` key inside the `[mcp_servers]` table itself. A key
* of the same name in any other table is not the server's.
*/
function tomlSubSettings(text, name) {
const lines = text.split('\n');
const sub = new RegExp(`^\\s*\\[\\s*["']?mcp_servers["']?\\s*\\.\\s*["']?${name}["']?\\s*\\.`);
const key = new RegExp(`^\\s*["']?${name}["']?\\s*(\\.|=)`);
let inServers = false;
for (const line of lines) {
if (sub.test(line)) return true;
if (/^\s*\[/.test(line)) { inServers = /^\s*\[\s*["']?mcp_servers["']?\s*\]\s*(?:#.*)?$/.test(line); continue; }
if (inServers && key.test(line)) return true;
}
return false;
}
function mcpTomlTable(name, command, args = []) {
return `["mcp_servers"."${name}"]\ncommand = ${JSON.stringify(command)}\nargs = ${JSON.stringify(args).replace(/,/g, ', ')}\n`;
}
/** Two MCP entries are the same when their JSON lines up at every depth, key order aside. */
function sameEntry(a, b) {
const canon = (v) => (v && typeof v === 'object' && !Array.isArray(v)
? Object.fromEntries(Object.keys(v).sort().map((k) => [k, canon(v[k])]))
: Array.isArray(v) ? v.map(canon) : v);
return JSON.stringify(canon(a)) === JSON.stringify(canon(b));
}
/**
* Remove an MCP entry the launcher added, only while it is still exactly that entry.
* Returns a note, or null when the entry is already gone. Never deletes the file.
*/
function removeMcpRegistration(record, claude) {
const kept = (why) => `${record.file}: ${record.name} for ${record.agent} ${why}; kept`;
const removed = `${record.name} for ${record.agent} removed from ${record.file}`;
if (record.file.endsWith('.toml')) {
let text;
try { text = fs.readFileSync(record.file, 'utf8'); } catch (_) { return null; }
const range = tomlTableRange(text, record.name);
if (!range) return null;
if (tomlTableCommand(range) !== record.entry.command) return kept('was changed');
if (JSON.stringify(tomlTableArgs(range)) !== JSON.stringify(record.entry.args || [])) return kept('was changed');
// A sub-table or dotted key added since (e.g. [mcp_servers.<name>.env]) would be left without
// its command, and Codex refuses such a file: the entry is the person's now.
const rest = range.lines.slice(0, range.start).concat(range.lines.slice(range.end)).join('\n');
if (tomlSubSettings(rest, record.name)) return kept('has settings added since');
writeText(record.file, rest);
return removed;
}
let cfg;
try { cfg = readSettings(record.file); } catch (error) { return kept(`could not be read (${error.message})`); }
const servers = cfg.doc.mcpServers;
if (!servers || !Object.prototype.hasOwnProperty.call(servers, record.name)) return null;
if (!sameEntry(servers[record.name], record.entry)) return kept('was changed');
if (record.via === 'claude') {
if (!claude.available()) return kept('is registered with Claude Code, whose CLI was not found');
const r = claude.run(['mcp', 'remove', '--scope', 'user', record.name]);
return r.code === 0 ? removed : kept(`could not be removed (${r.out || 'claude mcp remove failed'})`);
}
delete servers[record.name];
writeJson(record.file, cfg.doc);
return removed;
}
function payloadManifest(dir = PAYLOAD()) {
const m = readJson(path.join(dir, 'manifest.json'), null);
if (!m || !Array.isArray(m.members)) throw new Error(`No payload in ${dir}: the package is incomplete (run scripts/vendor.mjs).`);
const name = (value) => typeof value === 'string' && /^[a-z0-9][a-z0-9._-]*$/.test(value);
const version = (value) => typeof value === 'string' && /^\d+\.\d+\.\d+$/.test(value);
const names = new Set(), skills = new Set();
if (!version(m.version)) throw new Error(`Invalid payload version in ${dir}.`);
for (const member of m.members) {
if (!member || !name(member.name) || names.has(member.name) || !version(member.version) || !Array.isArray(member.skills)) {
throw new Error(`Invalid or duplicate payload member in ${dir}.`);
}
names.add(member.name);
for (const skill of member.skills) {
if (!name(skill) || skills.has(skill)) throw new Error(`Invalid or duplicate skill in ${dir}.`);
skills.add(skill);
}
}
return m;
}
function verifyPayload(dir, manifest) {
for (const m of manifest.members) {
const root = path.join(dir, 'plugins', m.name);
const plugin = readJson(path.join(root, '.claude-plugin/plugin.json'), null);
if (!plugin || plugin.name !== m.name || plugin.version !== m.version) throw new Error(`Payload plugin mismatch: ${m.name}.`);
for (const skill of m.skills) {
if (!fs.existsSync(path.join(root, 'skills', skill, 'SKILL.md'))) throw new Error(`Payload skill missing: ${m.name}/${skill}.`);
}
}
}
/** Plan and apply an update. Returns the steps with their outcomes. */
function update({ home, dryRun = false, includePreview = false, claude = claudeRunner(), log = () => {} } = {}) {
const p = paths(home);
const manifest = payloadManifest();
verifyPayload(PAYLOAD(), manifest);
const version = manifest.version;
const state = readState(p.stateFile);
const steps = [];
const step = (kind, detail, fn) => {
if (dryRun) { steps.push({ kind, detail, outcome: 'planned' }); return true; }
try {
const result = fn();
steps.push({ kind, detail, outcome: result === false ? 'skipped' : 'done' });
return result !== false;
} catch (error) {
steps.push({ kind, detail, outcome: 'failed', error: error.message });
return false;
}
};
const moved = [];
const quarantineDir = path.join(p.quarantine, `${new Date().toISOString().replace(/[:.]/g, '-')}-${process.pid}`);
const recordMove = (entry) => {
writeJson(path.join(quarantineDir, 'moved.json'), [...moved, entry]);
const fresh = readState(p.stateFile);
fresh.quarantines = [...new Set([...(fresh.quarantines || []), quarantineDir])];
writeJson(p.stateFile, fresh);
moved.push(entry);
};
const quarantine = (target, why, replacement = null) => {
const dest = path.join(quarantineDir, target.replace(/^\//, '').replace(/\//g, '__'));
fs.mkdirSync(path.dirname(dest), { recursive: true });
recordMove({ from: target, to: dest, why, replacement });
fs.renameSync(target, dest);
};
/** Move a legacy marketplace out of settings.json and the registry, recorded for restore. */
const retireMarketplace = (name, member, uninstalling) => {
const knownNow = readJson(path.join(p.claudePlugins, 'known_marketplaces.json'), {});
let settings;
try { settings = readSettings(p.claudeSettings); } catch (error) {
steps.push({ kind: 'legacy-marketplace', detail: `keep the ${name} marketplace: ${p.claudeSettings} could not be read`, outcome: 'failed', error: error.message });
return;
}
const declared = settings.doc.extraKnownMarketplaces && Object.prototype.hasOwnProperty.call(settings.doc.extraKnownMarketplaces, name)
? settings.doc.extraKnownMarketplaces[name] : undefined;
const registered = Object.prototype.hasOwnProperty.call(knownNow, name);
if (!registered && declared === undefined) return;
const serving = installedIds().filter((pid) => pid.endsWith(`@${name}`) && !uninstalling.has(pid));
if (serving.length) {
steps.push({ kind: 'legacy-marketplace', detail: `keep the ${name} marketplace: it still serves ${serving.join(', ')}`, outcome: 'skipped' });
return;
}
step('legacy-marketplace', `remove the ${name} marketplace; ${MARKETPLACE} serves ${member}`, () => {
const record = {
kind: 'marketplace', name,
source: (registered && knownNow[name].source) || (declared && declared.source) || null,
why: `legacy marketplace of ${member}, replaced by ${member}@${MARKETPLACE}`,
};
if (declared !== undefined) {
fs.mkdirSync(quarantineDir, { recursive: true });
record.settingsBackup = path.join(quarantineDir, `settings.json.before-${name}`);
fs.copyFileSync(p.claudeSettings, record.settingsBackup);
record.settingsEntry = declared;
}
recordMove(record); // durable before settings or the registry changes
if (declared !== undefined) {
const doc = settings.doc;
delete doc.extraKnownMarketplaces[name];
writeJson(p.claudeSettings, doc);
}
if (registered) {
// No --scope: with the user entry already moved it would refuse. From ~/.passioncode
// "every scope" is the user one — no project's .claude/settings.json is touched.
const r = claude.run(['plugin', 'marketplace', 'remove', name], { cwd: p.state });
if (r.code !== 0 && !/not found/i.test(r.out)) throw new Error(r.out || 'marketplace remove failed');
}
});
};
// 1. The release: an immutable copy of the payload, then `current` points at it.
const release = path.join(p.releases, version);
step('release', `install ${version} at ${release}`, () => {
if (lstat(path.join(release, 'manifest.json'))) {
const existing = payloadManifest(release);
verifyPayload(release, existing);
const identity = (m) => JSON.stringify([m.version, m.members.map(({ via, ...member }) => member)]);
if (identity(existing) !== identity(manifest)) throw new Error(`Release ${version} has a different manifest; use a new version instead of overwriting an immutable release.`);
return false;
}
const tmp = `${release}.${process.pid}.partial`;
fs.rmSync(tmp, { recursive: true, force: true });
fs.cpSync(PAYLOAD(), tmp, { recursive: true });
fs.renameSync(tmp, release);
return true;
});
if (steps.at(-1).outcome === 'failed') return { version, steps, moved };
step('current', `point ${p.current} at ${version}`, () => { symlinkAtomic(release, p.current); });
if (steps.at(-1).outcome === 'failed') return { version, steps, moved };
// 2. Claude Code: one local marketplace, one plugin per member.
const hasClaude = claude.available();
const installedIds = () => Object.keys(readJson(path.join(p.claudePlugins, 'installed_plugins.json'), { plugins: {} }).plugins || {});
const verified = new Set();
if (!hasClaude) {
steps.push({ kind: 'claude', detail: 'Claude Code CLI not found; its plugins were not installed', outcome: 'skipped' });
} else {
const known = readJson(path.join(p.claudePlugins, 'known_marketplaces.json'), {});
const marketplaceReady = step('marketplace', known[MARKETPLACE] ? `update the ${MARKETPLACE} marketplace` : `add ${p.current} as the ${MARKETPLACE} marketplace`, () => {
const r = known[MARKETPLACE] ? claude.run(['plugin', 'marketplace', 'update', MARKETPLACE]) : claude.run(['plugin', 'marketplace', 'add', p.current]);
if (r.code !== 0) throw new Error(r.out || 'marketplace command failed');
});
for (const m of marketplaceReady ? manifest.members : []) {
const id = `${m.name}@${MARKETPLACE}`;
const present = installedIds().includes(id);
const ok = step('plugin', `${present ? 'update' : 'install'} ${id} ${m.version}`, () => {
const r = claude.run(['plugin', present ? 'update' : 'install', id]);
if (r.code !== 0 && !/already (installed|at the latest)/i.test(r.out)) throw new Error(r.out || `plugin ${present ? 'update' : 'install'} failed`);
const entries = readJson(path.join(p.claudePlugins, 'installed_plugins.json'), { plugins: {} }).plugins?.[id];
if (!Array.isArray(entries) || !entries.some((entry) => entry.version === m.version)) {
throw new Error(`Claude Code did not register ${id} at version ${m.version}; legacy entries were kept.`);
}
});
if (ok && (dryRun || installedIds().includes(id))) verified.add(m.name);
// The same plugin from its old single-member marketplace is a second copy of every skill.
const uninstalling = new Set();
for (const legacy of m.legacyPluginIds || []) {
if (!installedIds().includes(legacy) || !verified.has(m.name)) continue;
const gone = step('legacy', `uninstall ${legacy}; ${id} replaces it`, () => {
const r = claude.run(['plugin', 'uninstall', legacy]);
if (r.code !== 0) throw new Error(r.out || 'uninstall failed');
(state.legacyRemoved = state.legacyRemoved || []).push({ id: legacy, at: new Date().toISOString() });
});
if (gone && dryRun) uninstalling.add(legacy);
}
// ...and its old marketplace, left registered, would install it again: Claude Code
// re-registers whatever settings.json declares, with autoUpdate if it was on.
for (const name of m.legacyMarketplaces || []) {
if (name === MARKETPLACE || !verified.has(m.name)) continue;
retireMarketplace(name, m.name, uninstalling);
}
}
}
// 3. Every other agent: hub link → the release, channel link → the hub.
const channels = CHANNELS.map((c) => path.join(p.home, c)).filter(isDirectory);
for (const m of manifest.members) {
for (const skill of m.skills) {
const source = path.join(p.current, 'plugins', m.name, 'skills', skill);
const hubLink = path.join(p.hub, skill);
const existing = lstat(hubLink);
if (!existing || linkTarget(hubLink) !== source) {
step('hub', `${hubLink} → ${source}`, () => {
if (lstat(hubLink)) quarantine(hubLink, existing.isSymbolicLink() ? `pointed at ${linkTarget(hubLink)}` : 'a plain copy', source);
symlinkAtomic(source, hubLink);
});
}
for (const channel of channels) {
const at = path.join(channel, skill);
const cur = lstat(at);
if (cur && cur.isSymbolicLink() && (linkTarget(at) === hubLink || path.resolve(channel, linkTarget(at) || '') === hubLink)) continue;
step('channel', `${at} → ${hubLink}`, () => {
if (lstat(at)) quarantine(at, cur.isSymbolicLink() ? `pointed at ${linkTarget(at)}` : 'a plain copy', hubLink);
symlinkAtomic(hubLink, at);
});
}
// 4. Claude Code reads the plugin; a plain ~/.claude/skills entry would shadow it.
const shadow = path.join(p.claudeSkills, skill);
if (lstat(shadow) && verified.has(m.name)) {
step('shadow', `move aside ${shadow}; the ${m.name} plugin serves it`, () => quarantine(shadow, 'shadowed the plugin'));
}
}
}
// 5. The MCP servers of the installed apps (ADR-0003, ADR-0004), for every agent that is
// present. Entries a person or another tool set are never rewritten: a matching entry is
// left, a different one is reported. What the launcher adds is journalled before it is
// written, so restore and uninstall can take it out again.
const registered = [];
const mcpBackup = (file, agent) => {
if (!lstat(file)) return null;
fs.mkdirSync(quarantineDir, { recursive: true });
const backup = path.join(quarantineDir, `${path.basename(file)}.before-mcp-${agent.toLowerCase().replace(/[^a-z0-9]+/g, '-')}`);
if (!lstat(backup)) fs.copyFileSync(file, backup);
return backup;
};
for (const server of bundledMcpServers()) {
const { name, label, command: mcpCommand } = server;
const register = (record, write, backupOf = null) => step('mcp', `register ${name} for ${record.agent} in ${record.file}`, () => {
record.backup = backupOf ? backupOf() : null; // only when it applies: a dry run copies nothing
recordMove(record);
write();
registered.push({ agent: record.agent, file: record.file, name: record.name, entry: record.entry, ...(record.via ? { via: record.via } : {}) });
});
// The same entry means the same command AND arguments; anything else is the person's and is kept.
const existingNote = (agent, existing, args, want) => existing === mcpCommand && JSON.stringify(args || []) === JSON.stringify(want || [])
? { kind: 'mcp', detail: `${agent} already runs ${name} from ${mcpCommand}`, outcome: 'skipped' }
: { kind: 'mcp', detail: `${agent} has its own ${name} entry (${existing || 'not a stdio server'}${existing === mcpCommand ? ` with arguments ${JSON.stringify(args || [])}` : ''}); it was kept`, outcome: 'skipped' };
if (!lstat(mcpCommand)) {
steps.push({ kind: 'mcp', detail: `no ${label} MCP at ${mcpCommand}; ${name} was not registered`, outcome: 'skipped' });
continue;
}
if (server.preview && !includePreview) {
steps.push({ kind: 'mcp', detail: `${label} is an early preview: ${name} is registered by \`passioncode setup\`, not by an update`, outcome: 'skipped' });
continue;
}
const claudeJson = path.join(p.home, '.claude.json');
const claudeArgs = server.argsFor('claude');
if (!hasClaude) {
steps.push({ kind: 'mcp', detail: `Claude Code CLI not found; ${name} was not registered for it`, outcome: 'skipped' });
} else if (server.claudePlugin && installedIds().some((pid) => pid.startsWith(server.claudePlugin))) {
steps.push({ kind: 'mcp', detail: `Claude Code gets ${name} from its ${server.claudePlugin.replace(/@$/, '')} plugin; no second entry was added`, outcome: 'skipped' });
} else if (claudeArgs) {
let servers = null;
try { servers = readSettings(claudeJson).doc.mcpServers || {}; } catch (error) {
steps.push({ kind: 'mcp', detail: `keep ${claudeJson}: it could not be read; ${name} was not registered`, outcome: 'failed', error: error.message });
}
const existing = servers && servers[name];
if (existing) steps.push(existingNote('Claude Code', typeof existing === 'object' ? existing.command || existing.url : null, typeof existing === 'object' ? existing.args : undefined, claudeArgs));
else if (servers) {
const entry = { type: 'stdio', command: mcpCommand, args: claudeArgs, env: {} };
register({ kind: 'mcp', via: 'claude', agent: 'Claude Code', file: claudeJson, name, entry, backup: null }, () => {
const r = claude.run(['mcp', 'add', '--scope', 'user', name, '--', mcpCommand, ...claudeArgs], { cwd: p.state });
if (r.code !== 0) throw new Error(r.out || 'claude mcp add failed');
const now = readSettings(claudeJson).doc.mcpServers || {};
if (!now[name] || now[name].command !== mcpCommand) throw new Error(`Claude Code did not register ${name} in ${claudeJson}`);
// What the CLI wrote is what restore and uninstall compare against.
entry.type = now[name].type; entry.args = now[name].args; entry.env = now[name].env;
});
}
}
for (const target of mcpFileTargets(p.home)) {
if (!isDirectory(target.dir)) {
steps.push({ kind: 'mcp', detail: `${target.agent} not found; ${name} was not registered for it`, outcome: 'skipped' });
continue;
}
const args = server.argsFor(target.id);
if (!args) {
steps.push({ kind: 'mcp', detail: `${label} has no ${target.agent} runner; ${name} was not registered for it`, outcome: 'skipped' });
continue;
}
if (target.kind === 'json') {
let cfg;
try { cfg = readSettings(target.file); } catch (error) {
steps.push({ kind: 'mcp', detail: `keep ${target.file}: it could not be read; ${name} was not registered`, outcome: 'failed', error: error.message });
continue;
}
const existing = (cfg.doc.mcpServers || {})[name];
if (existing) { steps.push(existingNote(target.agent, typeof existing === 'object' ? existing.command || existing.url : null, typeof existing === 'object' ? existing.args : undefined, args)); continue; }
const entry = { command: mcpCommand, args, env: {} };
register({ kind: 'mcp', agent: target.agent, file: target.file, name, entry }, () => {
const fresh = readSettings(target.file).doc; // an earlier server may have written it this run
fresh.mcpServers = { ...(fresh.mcpServers || {}), [name]: entry };
writeJson(target.file, fresh);
}, () => mcpBackup(target.file, target.agent));
} else {
let text = '';
try { text = fs.readFileSync(target.file, 'utf8'); } catch (error) {
if (error.code !== 'ENOENT') {
steps.push({ kind: 'mcp', detail: `keep ${target.file}: it could not be read; ${name} was not registered`, outcome: 'failed', error: error.message });
continue;
}
}
const range = tomlTableRange(text, name);
if (range) { const c = tomlTableCommand(range); steps.push(existingNote(target.agent, c == null ? null : c, tomlTableArgs(range), args)); continue; }
if (tomlMentions(text, name)) {
steps.push({ kind: 'mcp', detail: `${target.agent} declares ${name} in ${target.file} in a form the launcher does not edit; it was kept`, outcome: 'skipped' });
continue;
}
const entry = { command: mcpCommand, args };
register({ kind: 'mcp', agent: target.agent, file: target.file, name, entry }, () => {
let now = '';
try { now = fs.readFileSync(target.file, 'utf8'); } catch (_) { now = ''; }
writeText(target.file, now ? `${now.endsWith('\n') ? now : `${now}\n`}\n${mcpTomlTable(name, mcpCommand, args)}` : mcpTomlTable(name, mcpCommand, args));
}, () => mcpBackup(target.file, target.agent));
}
}
}
// 6. The launcher's own releases: keep this one and the one it replaced, remove the rest.
// They are its own output, reinstallable from npm — not the person's files, which are
// only ever moved to the quarantine.
const stale = staleReleases(p, version, state.installed || null);
if (stale.length) {
step('prune', `remove ${stale.map((d) => path.basename(d)).join(', ')} from ${p.releases}; keep ${version} and the release before it`, () => {
for (const dir of stale) fs.rmSync(dir, { recursive: true, force: true });
});
}
if (!dryRun) {
if (moved.length) writeJson(path.join(quarantineDir, 'moved.json'), moved);
// A probe or config command may have written while the plugin CLI ran.
const fresh = readState(p.stateFile);
fresh.installed = version;
fresh.installedAt = new Date().toISOString();
fresh.members = manifest.members.map((m) => ({ name: m.name, version: m.version, ref: m.ref, commit: m.commit }));
fresh.quarantines = [...new Set([...(fresh.quarantines || []), ...(moved.length ? [quarantineDir] : [])])];
if (state.legacyRemoved) fresh.legacyRemoved = state.legacyRemoved;
if (registered.length) {
fresh.mcpRegistrations = [...(fresh.mcpRegistrations || []).filter((r) => !registered.some((n) => n.file === r.file && n.name === r.name)), ...registered];
}
delete fresh.updatingSince;
writeJson(p.stateFile, fresh);
}
log(`${dryRun ? 'Plan' : 'Updated'}: PassionCode.ai ${version}`);
return { version, steps, moved };
}
/** Put back everything a run moved aside (newest run first unless one is named). */
function restore({ home, which, claude = claudeRunner() } = {}) {
const p = paths(home);
const state = readState(p.stateFile);
const dirs = which ? [which] : (state.quarantines || []).slice(-1);
const restored = [];
for (const dir of dirs) {
const journal = path.join(dir, 'moved.json');
const entries = JSON.parse(fs.readFileSync(journal, 'utf8'));
for (const entry of [...entries].reverse()) {
if (entry.restoredAt) continue;
if (entry.kind === 'marketplace') {
restored.push(restoreMarketplace(p, entry, claude));
} else if (entry.kind === 'mcp') {
const note = removeMcpRegistration(entry, claude);
if (note) restored.push(note);
const state = readState(p.stateFile);
if (state.mcpRegistrations) {
state.mcpRegistrations = state.mcpRegistrations.filter((r) => !(r.file === entry.file && r.name === entry.name));
if (!state.mcpRegistrations.length) delete state.mcpRegistrations;
writeJson(p.stateFile, state);
}
} else if (lstat(entry.to)) {
if (lstat(entry.from)) {
// Old journals did not record the replacement. Only recognise a link
// into this launcher's hub/current tree; never erase an arbitrary link.
const target = linkTarget(entry.from);
const resolved = target === null ? null : path.resolve(path.dirname(entry.from), target);
const owned = entry.replacement !== undefined ? resolved === entry.replacement && resolved !== null
: resolved && (resolved.startsWith(p.current + path.sep) || resolved.startsWith(p.hub + path.sep));
if (!owned) throw new Error(`Restore conflict at ${entry.from}; move the replacement aside and retry.`);
fs.unlinkSync(entry.from);
}
fs.mkdirSync(path.dirname(entry.from), { recursive: true });
fs.renameSync(entry.to, entry.from);
restored.push(entry.from);
} else if (!lstat(entry.from)) {
throw new Error(`Restore source missing: ${entry.to}; preserve the quarantine for recovery.`);
}
// Also recognise already-restored entries from releases with no checkpoint.
entry.restoredAt = new Date().toISOString();
writeJson(journal, entries);
}
}
return restored;
}
/** Re-register a retired marketplace and put its settings.json declaration back as it was. */
function restoreMarketplace(p, entry, claude) {
const notes = [];
const known = readJson(path.join(p.claudePlugins, 'known_marketplaces.json'), {});
const arg = marketplaceAddArg(entry.source);
if (!Object.prototype.hasOwnProperty.call(known, entry.name)) {
if (!arg) notes.push('no recorded source to re-add from');
else if (!claude.available()) notes.push('Claude Code CLI not found; it re-registers from settings.json at its next start');
else {
fs.mkdirSync(p.state, { recursive: true });
const r = claude.run(['plugin', 'marketplace', 'add', arg], { cwd: p.state });
if (r.code !== 0) notes.push(`re-add failed: ${r.out || 'marketplace add failed'}`);
}
}
if (entry.settingsEntry !== undefined) {
// After `marketplace add`, which declares a bare { source }: the recorded entry keeps autoUpdate.
try {
const { doc } = readSettings(p.claudeSettings);
doc.extraKnownMarketplaces = { ...(doc.extraKnownMarketplaces || {}), [entry.name]: entry.settingsEntry };
writeJson(p.claudeSettings, doc);
} catch (error) {
notes.push(`settings.json not restored (${error.message}); the original is at ${entry.settingsBackup}`);
}
}
if (notes.length) throw new Error(`Could not fully restore marketplace ${entry.name}: ${notes.join('; ')}. Retry restore after fixing it.`);
return `marketplace ${entry.name}`;
}
function status({ home, claude = claudeRunner() } = {}) {
const p = paths(home);
const state = readState(p.stateFile, { tolerant: true });
let payload = null;
try { payload = payloadManifest(); } catch (_) { /* reported as unknown */ }
// What is installed is the release `current` points at. The payload beside this CLI is
// only what an update would install — from a checkout it is whatever was last vendored
// there, so reading members from it described a set that is not on the machine.
let release = null;
try { release = payloadManifest(p.current); } catch (_) { /* nothing installed yet */ }
const described = release || payload;
const installed = Object.keys(readJson(path.join(p.claudePlugins, 'installed_plugins.json'), { plugins: {} }).plugins || {});
const known = readJson(path.join(p.claudePlugins, 'known_marketplaces.json'), {});
let declared = {};
try { declared = readSettings(p.claudeSettings).doc.extraKnownMarketplaces || {}; } catch (_) { /* reported by update */ }
const members = (described ? described.members : []).map((m) => ({
name: m.name, version: m.version,
claude: installed.includes(`${m.name}@${MARKETPLACE}`) ? 'plugin' : (claude.available() ? 'missing' : 'no Claude Code'),
legacy: (m.legacyPluginIds || []).filter((id) => installed.includes(id)),
legacyMarketplaces: (m.legacyMarketplaces || []).filter((n) => n !== MARKETPLACE && (known[n] || declared[n])),
hub: m.skills.map((s) => ({ skill: s, ok: linkTarget(path.join(p.hub, s)) === path.join(p.current, 'plugins', m.name, 'skills', s) })),
shadows: m.skills.filter((s) => lstat(path.join(p.claudeSkills, s))),
}));
return {
installed: release ? release.version : (state.installed || null), latest: state.latest || null, checkedAt: state.checkedAt || null,
package: payload ? payload.version : null, source: release ? 'installed' : (payload ? 'package' : null),
auto: (state.config || {}).auto !== false, members,
};
}
function setConfig({ home, key, value }) {
if (key !== 'update.auto' || !['on', 'off'].includes(value)) throw new Error('Only `config set update.auto on|off` is supported.');
const p = paths(home);
const state = readState(p.stateFile);
state.config = { ...(state.config || {}), auto: value === 'on' };
writeJson(p.stateFile, state);
return state.config;
}
function uninstall({ home, claude = claudeRunner() } = {}) {
const p = paths(home);
readState(p.stateFile); // refuse to overwrite a damaged recovery record
const manifest = lstat(p.current) ? payloadManifest(p.current) : { members: [] };
const removed = [];
const failures = [];
const hasClaude = claude.available();
const installedIds = () => Object.keys(readJson(path.join(p.claudePlugins, 'installed_plugins.json'), { plugins: {} }).plugins || {});
for (const m of manifest.members) {
for (const skill of m.skills) {
const hubLink = path.join(p.hub, skill);
if (pointsTo(hubLink, path.join(p.current, 'plugins', m.name, 'skills', skill))) { fs.unlinkSync(hubLink); removed.push(hubLink); }
for (const c of CHANNELS) {
const at = path.join(p.home, c, skill);
if (pointsTo(at, hubLink)) { fs.unlinkSync(at); removed.push(at); }
}
}
const id = `${m.name}@${MARKETPLACE}`;
if (installedIds().includes(id)) {
if (!hasClaude) { failures.push(`${id}: Claude Code CLI not found`); continue; }
const r = claude.run(['plugin', 'uninstall', id]);
if (r.code === 0 && !installedIds().includes(id)) removed.push(id);
else failures.push(`${id}: ${r.out || 'plugin remains registered after uninstall'}`);
}
}
const known = readJson(path.join(p.claudePlugins, 'known_marketplaces.json'), {});
if (!failures.length && known[MARKETPLACE] && !installedIds().some((id) => id.endsWith(`@${MARKETPLACE}`))) {
if (!hasClaude) failures.push('Claude Code CLI not found; marketplace remains registered');
else {
const r = claude.run(['plugin', 'marketplace', 'remove', MARKETPLACE]);
if (r.code !== 0) failures.push(r.out || 'marketplace remove failed');
}
}
if (failures.length) throw new Error(`Uninstall incomplete: ${failures.join('; ')}. Fix the error and retry uninstall.`);
if (lstat(p.current)) {
if (!lstat(p.current).isSymbolicLink()) throw new Error(`Refusing to remove non-symlink ${p.current}.`);
fs.unlinkSync(p.current);
}
const state = readState(p.stateFile);
// The MCP registrations this launcher added — only while they are still exactly what
// it wrote; an entry a person changed since stays.
for (const record of state.mcpRegistrations || []) {
const note = removeMcpRegistration(record, claude);
if (note) removed.push(note);
}
delete state.mcpRegistrations;
state.installed = null;
state.members = [];
state.config = { ...(state.config || {}), auto: false };
delete state.installedAt;
delete state.updatingSince;
writeJson(p.stateFile, state);
return removed;
}
module.exports = {
// An invalid payload is refused before the lock creates anything under ~/.passioncode.
update: (opts = {}) => {
if (opts.dryRun) return update(opts);
verifyPayload(PAYLOAD(), payloadManifest());
return withUpdateLock(opts.home, () => update(opts));
},
restore: (opts = {}) => withUpdateLock(opts.home, () => restore(opts)),
uninstall: (opts = {}) => withUpdateLock(opts.home, () => uninstall(opts)),
status, setConfig, paths, CHANNELS, MARKETPLACE, payloadManifest, marketplaceAddArg,
acquireUpdateLock, UpdateRunning, staleReleases, claudeRunner, bundledMcpServers, mcpFileTargets, readSettings, tomlTableRange, tomlTableCommand, tomlTableArgs, tomlMentions,
};