-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathinstall.test.ts
More file actions
1361 lines (1222 loc) · 56.8 KB
/
Copy pathinstall.test.ts
File metadata and controls
1361 lines (1222 loc) · 56.8 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
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { spawnSync } from 'node:child_process';
import {
mkdtempSync,
readdirSync,
readFileSync,
rmSync,
writeFileSync,
existsSync,
mkdirSync,
chmodSync,
statSync,
} from 'node:fs';
import { tmpdir } from 'node:os';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import { afterAll, afterEach, beforeEach, describe, expect, it } from 'vitest';
// Tests for the whole installer system: the repo-root `install.sh` shim AND
// the `apps/plugin/install.sh` orchestrator it forwards to. Co-located with the
// root shim (the canonical entry point). Drives the installer through its
// headless (non-interactive) surface — the arrow-key TUI needs a real /dev/tty
// and is verified by the operator (see the rembric-tui-installer-e2e skill).
// Everything runs with REMBRIC_SRC pointed at the repo so the script reads
// artifacts from disk (cp), never the network.
const REPO_ROOT = dirname(fileURLToPath(import.meta.url));
const INSTALL_SH = join(REPO_ROOT, 'apps', 'plugin', 'install.sh');
const ROOT_SHIM = join(REPO_ROOT, 'install.sh');
// The installer reports each agent's "available" plugin version from
// .release-please-manifest.json per component. Derive expectations from the
// same source so a release-please bump doesn't break these tests.
const MANIFEST = JSON.parse(
readFileSync(join(REPO_ROOT, '.release-please-manifest.json'), 'utf8'),
) as Record<string, string>;
const INSTALLER_SRC = readFileSync(INSTALL_SH, 'utf8');
// The regex requires the installer to keep its single-line `CLIENTS='…'` form.
const CLIENTS: string[] = (() => {
const m = /^CLIENTS='([^']+)'$/m.exec(INSTALLER_SRC);
if (!m) throw new Error('apps/plugin/install.sh has no single CLIENTS= definition');
return m[1].split(' ');
})();
// Parsed from the installer's own definition so the expectations cannot drift
// from what the parser accepts. Same single-line requirement as CLIENTS.
const ACTIONS: string[] = (() => {
const m = /^ACTIONS='([^']+)'$/m.exec(INSTALLER_SRC);
if (!m) throw new Error('apps/plugin/install.sh has no single ACTIONS= definition');
return m[1].split(' ');
})();
// The status table's ACTION column prints one of these when the state warrants
// no action at all. Everything else in that column must be an ACTIONS verb.
const NON_RECOMMENDATIONS = ['up to date', 'ahead', '-'];
// Core tools live in /usr/bin:/bin and no client binary does, so a case that
// needs a client to look absent points PATH here.
const CORE_PATH = '/usr/bin:/bin';
// A stub client binary first on PATH, so the real one never runs from the suite
// and installs into the developer's own configuration. The `RAN:` sentinel is
// what distinguishes "executed" from "merely printed".
function fakeClientBinDir(name: 'claude' | 'codex' | 'pi'): string {
const d = mkdtempSync(join(tmpdir(), 'rembric-fakeclient-'));
writeFileSync(join(d, name), `#!/bin/sh\necho "RAN:${name} $*"\n`);
chmodSync(join(d, name), 0o755);
return d;
}
const PI_STUB_DIR = fakeClientBinDir('pi');
afterAll(() => rmSync(PI_STUB_DIR, { recursive: true, force: true }));
const PLUGIN_VERSION: Record<string, string> = Object.fromEntries(
// All clients ship under the single unified `plugin` release-please component
// (`apps/plugin`) — one shared version (unify-plugin-release-track).
CLIENTS.map((c) => [c, MANIFEST['apps/plugin']]),
);
interface RunOpts {
cwd?: string;
home?: string;
env?: Record<string, string>;
path?: string;
script?: string;
}
function run(args: string[], opts: RunOpts = {}): { code: number; out: string } {
const env: Record<string, string> = {
REMBRIC_SRC: REPO_ROOT,
REMBRIC_NONINTERACTIVE: '1',
REMBRIC_UPDATE_CHECK: 'off', // no GitHub network in tests unless a case opts in
PATH: opts.path ?? process.env.PATH ?? '/usr/bin:/bin',
HOME: opts.home ?? process.env.HOME ?? '/tmp',
...opts.env,
};
const res = spawnSync('/bin/sh', [opts.script ?? INSTALL_SH, ...args], {
cwd: opts.cwd,
env,
encoding: 'utf8',
});
return { code: res.status ?? -1, out: `${res.stdout}${res.stderr}` };
}
let dir: string;
let home: string;
beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), 'rembric-cwd-'));
home = mkdtempSync(join(tmpdir(), 'rembric-home-'));
});
afterEach(() => {
rmSync(dir, { recursive: true, force: true });
rmSync(home, { recursive: true, force: true });
});
describe('argument handling', () => {
it('--help exits 0 and documents the full flag set', () => {
const { code, out } = run(['--help']);
expect(code).toBe(0);
expect(out).toContain('rembric installer');
for (const flag of [
'--server',
'--agent=',
'--action=',
'--status',
'--json',
'--token=',
'--port=',
'--up',
'--ref=',
]) {
expect(out).toContain(flag);
}
for (const c of CLIENTS) expect(out).toContain(c); // the --agent list derives from CLIENTS
});
it('no flags (headless) refuses and exits non-zero', () => {
const { code, out } = run([]);
expect(code).toBe(2);
expect(out).toContain('Interactive:');
});
it('--agent without --action errors', () => {
const { code, out } = run(['--agent=opencode']);
expect(code).toBe(2);
expect(out).toContain('--agent requires --action');
});
it('unknown agent errors', () => {
const { code, out } = run(['--agent=bogus', '--action=install']);
expect(code).toBe(2);
expect(out).toContain('unknown agent');
});
it('an unrecognised --action is refused at parse time, before anything runs', () => {
// --yes is on so the run WOULD execute the client CLI if it got that far.
const opts = { home, path: `${PI_STUB_DIR}:${CORE_PATH}` };
const { code, out } = run(['--agent=pi', '--action=bogus', '--yes'], opts);
expect(code).toBe(2);
expect(out).toContain('invalid --action=bogus');
for (const a of ACTIONS) expect(out).toContain(a); // the error names what is accepted
expect(out).not.toContain('RAN:pi');
expect(out).not.toContain('Next');
// Control: the same invocation with an accepted verb does all three.
const ok = run(['--agent=pi', '--action=install', '--yes'], opts);
expect(ok.code).toBe(0);
expect(ok.out).toContain('RAN:pi');
expect(ok.out).toContain('Next');
});
it('--server refuses an action it has no backend for', () => {
// do_server treats every non-`update` action as install, so accepting
// `uninstall` here would install under an "uninstall" heading.
const { code, out } = run(['--server', '--action=uninstall'], { cwd: dir });
expect(code).toBe(2);
expect(out).toContain('--server accepts --action=install|update');
expect(existsSync(join(dir, '.env'))).toBe(false);
});
});
describe('preflight', () => {
it('aborts listing missing core tools when PATH is empty (remote mode)', () => {
// Empty PATH + no REMBRIC_SRC → curl + core tools missing. command -v is a
// shell builtin so preflight still runs and reports.
const { code, out } = run(['--server'], { path: '/nonexistent', env: { REMBRIC_SRC: '' } });
expect(code).toBe(1);
expect(out).toContain('missing required tool');
});
});
describe('server install', () => {
it('fresh dir: generates a 64-hex token, prepares files, never starts docker', () => {
const { code, out } = run(['--server', '--action=install'], { cwd: dir });
expect(code).toBe(0);
expect(out).toContain('Generated admin token');
expect(existsSync(join(dir, 'docker-compose.yml'))).toBe(true);
const envText = readFileSync(join(dir, '.env'), 'utf8');
const token = /^REMBRIC_ADMIN_TOKEN=([0-9a-f]+)$/m.exec(envText)?.[1];
expect(token).toBeDefined();
expect(token).toHaveLength(64);
// Headless without --up must not bring the stack up.
expect(out).not.toContain('Up.');
});
it('interrupted run (empty token in existing .env) gets filled on re-run', () => {
writeFileSync(join(dir, '.env'), 'REMBRIC_ADMIN_TOKEN=\n# REMBRIC_VERSION=\n');
const { code, out } = run(['--server', '--action=install'], { cwd: dir });
expect(code).toBe(0);
expect(out).toContain('is empty');
const token = /^REMBRIC_ADMIN_TOKEN=([0-9a-f]{64})$/m.exec(
readFileSync(join(dir, '.env'), 'utf8'),
)?.[1];
expect(token).toBeDefined();
});
it('configured .env is left untouched and its token shown', () => {
writeFileSync(join(dir, '.env'), 'REMBRIC_ADMIN_TOKEN=existingtok123\n');
const { code, out } = run(['--server', '--action=install'], { cwd: dir });
expect(code).toBe(0);
expect(out).toContain('already configured');
expect(out).toContain('existingtok123');
expect(readFileSync(join(dir, '.env'), 'utf8')).toContain('REMBRIC_ADMIN_TOKEN=existingtok123');
});
});
describe('server update', () => {
it('with a configured .env: refetches and offers the gated bring-up', () => {
writeFileSync(join(dir, '.env'), 'REMBRIC_ADMIN_TOKEN=tok\n');
const { code, out } = run(['--server', '--action=update'], { cwd: dir });
expect(code).toBe(0);
expect(out).toContain('Refetched');
expect(out).toContain('docker compose pull && docker compose up -d');
});
it('without a .env: refuses to bring up and points to install', () => {
const { code, out } = run(['--server', '--action=update'], { cwd: dir });
expect(code).toBe(0);
expect(out).toContain('No ./.env');
expect(out).toContain('install first');
});
});
describe('agent routing', () => {
it('codex install prints marketplace commands, copies nothing', () => {
const { code, out } = run(['--agent=codex', '--action=install'], { home });
expect(code).toBe(0);
expect(out).toContain('codex plugin marketplace add');
expect(out).toContain('codex plugin add rembric@rembric');
});
it('claude uninstall prints the marketplace command and the conservative note', () => {
const { out } = run(['--agent=claude', '--action=uninstall'], { home });
expect(out).toContain('claude plugin uninstall rembric@rembric');
expect(out).toContain('Left in place');
});
it('claude/codex update use their real upgrade commands, not re-install', () => {
const claude = run(['--agent=claude', '--action=update'], { home });
expect(claude.code).toBe(0);
expect(claude.out).toContain('claude plugin update rembric@rembric');
expect(claude.out).not.toContain('claude plugin install'); // update ≠ re-install
expect(claude.out).not.toContain('marketplace add'); // marketplace already added
const codex = run(['--agent=codex', '--action=update'], { home });
expect(codex.code).toBe(0);
expect(codex.out).toContain('codex plugin marketplace upgrade rembric');
expect(codex.out).not.toContain('codex plugin install'); // no such subcommand in the Codex CLI
});
it('a comma-separated --agent list drives multiple agents in one run', () => {
const { code, out } = run(['--agent=codex,claude', '--action=install'], { home });
expect(code).toBe(0);
expect(out).toContain('codex plugin add rembric@rembric');
expect(out).toContain('claude plugin install rembric@rembric');
});
it('install surfaces the required post-install steps per agent', () => {
const codex = run(['--agent=codex', '--action=install'], { home });
expect(codex.out).not.toContain('plugin_hooks'); // flag removed upstream in codex-cli 0.142.3+
expect(codex.out).toContain('/hooks');
const hermes = run(['--agent=hermes', '--action=install'], { home });
expect(hermes.out).toContain('hermes plugins install rembric'); // triggers requires_env prompts
expect(hermes.out).toContain('hermes plugins enable rembric');
expect(hermes.out).toContain('hermes gateway restart');
});
it('hermes update explains the automatic legacy migration and exact fallback before restart', () => {
const { code, out } = run(['--agent=hermes', '--action=update'], { home });
expect(code).toBe(0);
expect(out).toContain(`args: ['-y', '@rembric/mcp-bridge@${PLUGIN_VERSION.hermes}']`);
expect(out).toContain('REMBRIC_SERVER_URL: ${REMBRIC_SERVER_URL}');
expect(out).toContain('enabled: true');
expect(out).toContain('repairs recognized Rembric MCP blocks');
expect(out).toContain('writes a backup before changing config');
expect(out).toContain('hermes gateway restart');
expect(out).not.toContain('hermes plugins install rembric');
});
it('hermes update migrates only the documented legacy MCP block and preserves a backup', () => {
const hermesHome = join(home, '.hermes');
mkdirSync(hermesHome, { recursive: true });
const config = join(hermesHome, 'config.yaml');
const legacy = `mcp_servers:\n rembric:\n command: npx\n args:\n [\n '-y',\n 'mcp-remote@latest',\n '\${REMBRIC_SERVER_URL}/mcp/\${REMBRIC_PROJECT_SLUG}',\n '--header',\n 'Authorization: Bearer \${REMBRIC_API_TOKEN}',\n '--allow-http',\n ]\n other:\n command: other-mcp\n`;
writeFileSync(config, legacy);
const { code, out } = run(['--agent=hermes', '--action=update'], { home });
expect(code).toBe(0);
expect(readFileSync(join(hermesHome, 'config.yaml.rembric-mcp-remote.bak'), 'utf8')).toBe(
legacy,
);
expect(out).toContain('migrated mcp_servers.rembric');
expect(readFileSync(config, 'utf8')).toBe(
`mcp_servers:\n rembric:\n command: npx\n args: ['-y', '@rembric/mcp-bridge@${PLUGIN_VERSION.hermes}']\n env:\n REMBRIC_SERVER_URL: \${REMBRIC_SERVER_URL}\n REMBRIC_API_TOKEN: \${REMBRIC_API_TOKEN}\n REMBRIC_PROJECT_SLUG: \${REMBRIC_PROJECT_SLUG}\n enabled: true\n other:\n command: other-mcp\n`,
);
});
it('hermes update repairs only the incomplete bridge block emitted by the prior updater', () => {
const hermesHome = join(home, '.hermes');
mkdirSync(hermesHome, { recursive: true });
const config = join(hermesHome, 'config.yaml');
const incomplete = `mcp_servers:\n rembric:\n command: npx\n args: ['-y', '@rembric/mcp-bridge@0.29.1']\n`;
writeFileSync(config, incomplete);
run(['--agent=hermes', '--action=update'], { home });
expect(readFileSync(join(hermesHome, 'config.yaml.rembric-mcp-env.bak'), 'utf8')).toBe(
incomplete,
);
expect(readFileSync(config, 'utf8')).toContain('REMBRIC_API_TOKEN: ${REMBRIC_API_TOKEN}');
expect(readFileSync(config, 'utf8')).toContain('enabled: true');
});
it('hermes update preserves canonical and custom bridge blocks', () => {
const hermesHome = join(home, '.hermes');
mkdirSync(hermesHome, { recursive: true });
const config = join(hermesHome, 'config.yaml');
const custom = `mcp_servers:\n rembric:\n command: wrapper\n args: ['rembric']\n`;
writeFileSync(config, custom);
run(['--agent=hermes', '--action=update'], { home });
expect(readFileSync(config, 'utf8')).toBe(custom);
expect(existsSync(join(hermesHome, 'config.yaml.rembric-mcp-env.bak'))).toBe(false);
});
it('opencode/claude update notes drop the install-only wiring (just restart)', () => {
const opencode = run(['--agent=opencode', '--action=update'], { home });
expect(opencode.code).toBe(0);
expect(opencode.out).toContain('restart opencode');
expect(opencode.out).not.toContain('paste the printed MCP block'); // install-only
const claude = run(['--agent=claude', '--action=update'], { home });
expect(claude.code).toBe(0);
expect(claude.out).toContain('restart Claude Code');
expect(claude.out).not.toContain('prompts for the server URL'); // install-only
});
it('uninstall does not print post-install "Next" steps', () => {
const { out } = run(['--agent=codex', '--action=uninstall'], { home });
expect(out).not.toContain('Next');
});
it('opencode install then uninstall round-trips against a throwaway HOME', () => {
const installed = join(home, '.config', 'opencode', 'plugins', 'rembric.ts');
const ins = run(['--agent=opencode', '--action=install'], { home });
expect(ins.code).toBe(0);
expect(existsSync(installed)).toBe(true);
// The version comment survives the install rewrite (used for detection).
expect(readFileSync(installed, 'utf8')).toMatch(/@rembric-plugin-version\s+\d+\.\d+\.\d+/);
const un = run(['--agent=opencode', '--action=uninstall'], { home });
expect(un.code).toBe(0);
expect(existsSync(installed)).toBe(false);
expect(un.out).toContain('Left in place');
});
});
describe('--action=update with no --agent (update-all)', () => {
// #262 / memory.about's `update_all` command: before this feature, a bare
// `--action=update` errored ("--agent requires --action" is backwards —
// actually it fell through to the usage error because ARG_AGENTS was
// empty). This section proves the fix: it updates only what has an update
// available and never errors.
function ageOpencodePlugin(version: string): void {
const dir = join(home, '.config', 'opencode', 'plugins');
mkdirSync(dir, { recursive: true });
writeFileSync(
join(dir, 'rembric.ts'),
`// @rembric-plugin-version ${version}\nimport { readRembricSlug } from './lib/rembric-dotenv.mjs';\nexport const RembricPlugin = () => ({});\n`,
);
}
it('updates only the installed-and-outdated agent, skips the rest, never errors', () => {
ageOpencodePlugin('0.0.1'); // older than PLUGIN_VERSION.opencode from the manifest
const { code, out } = run(['--action=update'], { home });
expect(code).toBe(0);
expect(out).toContain('Updating all plugins with an update available');
// opencode was outdated → updated (its update note, not the install-only one).
expect(out).toContain('restart opencode');
expect(out).not.toContain('paste the printed MCP block');
// claude/codex/hermes were never installed → skipped, not errored.
expect(out).toContain('claude: not installed — skipped');
expect(out).toContain('codex: not installed — skipped');
expect(out).toContain('hermes: not installed — skipped');
expect(out).toContain(`Done: 1 updated, ${CLIENTS.length - 1} skipped.`);
});
it('--agent=all --action=update is an explicit alias for the same behavior', () => {
ageOpencodePlugin('0.0.1');
const { code, out } = run(['--agent=all', '--action=update'], { home });
expect(code).toBe(0);
expect(out).toContain(`Done: 1 updated, ${CLIENTS.length - 1} skipped.`);
});
it('an up-to-date agent is skipped as "up to date", not re-updated', () => {
ageOpencodePlugin(PLUGIN_VERSION.opencode); // matches the manifest exactly
const { code, out } = run(['--action=update'], { home });
expect(code).toBe(0);
expect(out).toContain('opencode: up to date — skipped');
expect(out).toContain(`Done: 0 updated, ${CLIENTS.length} skipped.`);
});
});
describe('the client set has a single definition every surface agrees with', () => {
it('is exactly the five supported clients, in a stable order', () => {
// Non-vacuity control for every assertion below that derives from CLIENTS.
expect(CLIENTS).toEqual(['claude', 'codex', 'hermes', 'opencode', 'pi']);
});
it('no second line in the installer enumerates the client set', () => {
const enumerating = INSTALLER_SRC.split('\n').filter(
(line) => CLIENTS.filter((c) => new RegExp(`\\b${c}\\b`).test(line)).length >= 4,
);
expect(enumerating).toEqual([`CLIENTS='${CLIENTS.join(' ')}'`]);
});
it('the interactive agent menu and its index mapping both derive from it', () => {
// The arrow-key menu needs a real /dev/tty, so this is asserted at the source.
expect(INSTALLER_SRC).toContain('arrow_menu "Which agent?" "all — update outdated" $CLIENTS');
expect(INSTALLER_SRC).toContain('c=$(client_at "$MENU_INDEX")');
});
it('--status --json emits one entry per client, in the same order', () => {
const { code, out } = run(['--status', '--json'], { home });
expect(code).toBe(0);
expect(JSON.parse(out).agents.map((a: { agent: string }) => a.agent)).toEqual(CLIENTS);
});
it('update-all accounts for every client in the set', () => {
const { code, out } = run(['--action=update'], { home });
expect(code).toBe(0);
for (const c of CLIENTS) expect(out).toMatch(new RegExp(`^ ${c}: `, 'm'));
expect(out).toContain(`Done: 0 updated, ${CLIENTS.length} skipped.`);
});
it.each(CLIENTS)('--agent=%s is routed to a backend and has post-install steps', (client) => {
const { code, out } = run([`--agent=${client}`, '--action=install'], {
home,
path: `${PI_STUB_DIR}:${process.env.PATH ?? '/usr/bin:/bin'}`,
});
expect(code).toBe(0);
expect(out).not.toContain('unknown agent');
expect(out).toContain(`${client} (install)`);
// A client with no post_install_notes arm installs and says nothing about the
// wiring it still needs.
expect(out).toContain('Next');
});
it('every client has a presence adapter (an unmatched case would report present)', () => {
// Every row must read absent here, and a client missing from client_present's
// `case` falls through to an empty arm, which exits 0 — i.e. reports present.
const { out } = run(['--status', '--json'], { home, path: '/usr/bin:/bin' });
const agents = JSON.parse(out).agents as { agent: string; present: boolean }[];
expect(agents.map((a) => a.present)).toEqual(CLIENTS.map(() => false));
});
});
describe('the ACTION column recommends only actions --action accepts', () => {
// The three surfaces derived from client_state print different things: the
// table prints the recommended VERB, `--status --json` the detected STATE, and
// update-all the verb it would take.
function tableRows(out: string): { agent: string; action: string }[] {
return out
.split('\n')
.map((line) => line.split(/\s{2,}/).filter(Boolean))
.filter((cells) => cells.length === 5 && CLIENTS.includes(cells[0]))
.map((cells) => ({ agent: cells[0], action: cells[4] }));
}
function writeOpencodePlugin(version: string): void {
const d = join(home, '.config', 'opencode', 'plugins');
mkdirSync(d, { recursive: true });
writeFileSync(join(d, 'rembric.ts'), `// @rembric-plugin-version ${version}\n`);
}
it('no cell in any detectable state is outside the accepted verbs', () => {
const withPi = { home, path: `${PI_STUB_DIR}:${CORE_PATH}` };
// One scenario per state that reaches the column: not installed (install),
// installed-and-old (update), installed-and-current (up to date), ahead of
// the published version, and present-but-unreadable (the pi row).
const scenarios = [
() => undefined,
() => writeOpencodePlugin('0.0.1'),
() => writeOpencodePlugin(PLUGIN_VERSION.opencode),
() => writeOpencodePlugin('99.0.0'),
];
const seen = new Set<string>();
for (const setup of scenarios) {
setup();
const rows = tableRows(run(['--status'], withPi).out);
// Non-vacuity: an unparsed table would make every assertion below empty.
expect(rows.map((r) => r.agent)).toEqual(CLIENTS);
for (const row of rows) {
expect([...ACTIONS, ...NON_RECOMMENDATIONS]).toContain(row.action);
seen.add(row.action);
}
}
// …and the scenarios really did exercise more than one outcome.
expect(seen.size).toBeGreaterThan(2);
});
it('following the recommendation the table prints resolves to a real action', () => {
const withPi = { home, path: `${PI_STUB_DIR}:${CORE_PATH}` };
const pi = tableRows(run(['--status'], withPi).out).find((r) => r.agent === 'pi');
expect(pi).toBeDefined();
expect(ACTIONS).toContain(pi!.action);
const followed = run(['--agent=pi', `--action=${pi!.action}`, '--yes'], withPi);
expect(followed.code).toBe(0);
expect(followed.out).toContain('RAN:pi');
expect(followed.out).not.toMatch(/invalid --action|parameter not set|unsupported action/);
});
it.each(ACTIONS)(
'--yes with --action=%s reaches a real command, never an unset one',
(action) => {
const { code, out } = run(['--agent=pi', `--action=${action}`, '--yes'], {
home,
path: `${PI_STUB_DIR}:${CORE_PATH}`,
});
expect(code).toBe(0);
expect(out).not.toMatch(/parameter not set|unbound variable|unsupported action/);
expect(out).toContain('RAN:pi');
},
);
it("the CLI backend's action table has one arm per verb and fails closed", () => {
// Unreachable from the CLI while the parser refuses unknown verbs, so it is
// asserted at the source: an unmatched POSIX `case` exits 0, silently.
const block = /client_cli_cmds\(\)[\s\S]*?\n {2}case "\$action" in\n([\s\S]*?)\n {2}esac/.exec(
INSTALLER_SRC,
);
expect(block).not.toBeNull();
const arms = [...block![1].matchAll(/^[ \t]*([a-z]+|\*)\)/gm)].map((m) => m[1]);
expect(arms).toContain('*');
expect(arms.filter((a) => a !== '*').sort()).toEqual([...ACTIONS].sort());
});
it('update-all names a verb the parser accepts when it declines to act', () => {
const { code, out } = run(['--action=update', '--yes'], {
home,
path: `${PI_STUB_DIR}:${CORE_PATH}`,
});
expect(code).toBe(0);
const hint = /pi: version unknown — skipped \(use --agent=pi --action=(\S+) to force\)/.exec(
out,
);
expect(hint).not.toBeNull();
expect(ACTIONS).toContain(hint![1]);
});
});
describe('pi (registry-CLI backend)', () => {
const piAgent = (root: string): string => join(root, 'npm', 'node_modules', '@rembric', 'pi');
function installedFixture(agentDir: string, version: string): void {
const pkg = piAgent(agentDir);
mkdirSync(pkg, { recursive: true });
writeFileSync(
join(pkg, 'package.json'),
`${JSON.stringify({ name: '@rembric/pi', version }, null, 2)}\n`,
);
}
function piRow(out: string): string {
return out.split('\n').find((l) => /^ {2}pi\s/.test(l)) ?? '';
}
it('has no repo-side install or uninstall script', () => {
const piPlugin = join(REPO_ROOT, 'apps', 'plugin', '.pi-plugin');
expect(existsSync(join(piPlugin, 'install.sh'))).toBe(false);
expect(existsSync(join(piPlugin, 'uninstall.sh'))).toBe(false);
});
it('install and update print the SAME unpinned command, even under --ref', () => {
const spec = 'pi install npm:@rembric/pi';
const ins = run(['--agent=pi', '--action=install'], { home, path: CORE_PATH });
const upd = run(['--agent=pi', '--action=update'], { home, path: CORE_PATH });
const pinned = run(['--agent=pi', '--action=install', '--ref=v9.9.9'], {
home,
path: CORE_PATH,
});
expect(ins.code).toBe(0);
expect(upd.code).toBe(0);
expect(pinned.code).toBe(0);
for (const { out } of [ins, upd, pinned]) {
expect(out).toContain(spec);
// A version-pinned spec is skipped by `pi update`, freezing the operator
// while reporting success.
expect(out).not.toMatch(/@rembric\/pi@/);
}
// --ref names a git ref; this artifact comes from the registry.
expect(pinned.out).not.toContain('9.9.9');
});
it("uninstall routes to the client's own removal verb and keeps credentials", () => {
const { code, out } = run(['--agent=pi', '--action=uninstall'], { home, path: CORE_PATH });
expect(code).toBe(0);
expect(out).toContain('pi remove npm:@rembric/pi');
expect(out).toContain('Left in place');
expect(out).not.toContain('Next');
});
it('install prints the shell-environment step and offers no settings-file alternative', () => {
const { out } = run(['--agent=pi', '--action=install'], { home, path: CORE_PATH });
expect(out).toContain('REMBRIC_SERVER_URL');
expect(out).toContain('REMBRIC_API_TOKEN');
// Pi reads no environment from its settings file, so there is no
// settings-file alternative to offer.
expect(out).not.toMatch(/settings/i);
});
it('update prints only the restart, not the install-only credential step', () => {
const { out } = run(['--agent=pi', '--action=update'], { home, path: CORE_PATH });
expect(out).toContain('restart Pi');
expect(out).not.toContain('REMBRIC_API_TOKEN');
});
it('--yes runs the registry command when the binary is present, and nothing when absent', () => {
const present = run(['--agent=pi', '--action=install', '--yes'], {
home,
path: `${PI_STUB_DIR}:${CORE_PATH}`,
});
expect(present.code).toBe(0);
expect(present.out).toContain('RAN:pi install npm:@rembric/pi');
const noFlag = run(['--agent=pi', '--action=install'], {
home,
path: `${PI_STUB_DIR}:${CORE_PATH}`,
});
expect(noFlag.out).toContain('pi install npm:@rembric/pi'); // printed
expect(noFlag.out).not.toContain('RAN:pi'); // never executed
const absent = run(['--agent=pi', '--action=install', '--yes'], { home, path: CORE_PATH });
expect(absent.out).toContain('pi install npm:@rembric/pi');
expect(absent.out).not.toContain('RAN:pi');
});
describe('installed-version detection', () => {
// A user-scope `pi install npm:<pkg>` leaves the manifest under
// <agentDir>/npm/node_modules/; every other install vector leaves no version
// on disk at all.
it('reads the version from the deterministic location under PI_CODING_AGENT_DIR', () => {
const agentDir = join(home, 'piagent');
installedFixture(agentDir, '0.0.1');
const { out } = run(['--status'], {
home,
path: `${PI_STUB_DIR}:${CORE_PATH}`,
env: { PI_CODING_AGENT_DIR: agentDir },
});
expect(piRow(out)).toContain('0.0.1');
expect(piRow(out)).toContain('update');
installedFixture(agentDir, PLUGIN_VERSION.pi);
const current = run(['--status'], {
home,
path: `${PI_STUB_DIR}:${CORE_PATH}`,
env: { PI_CODING_AGENT_DIR: agentDir },
});
expect(piRow(current.out)).toContain('up to date');
});
it('defaults to ~/.pi/agent when PI_CODING_AGENT_DIR is unset', () => {
installedFixture(join(home, '.pi', 'agent'), '0.0.2');
const { out } = run(['--status'], { home, path: `${PI_STUB_DIR}:${CORE_PATH}` });
expect(piRow(out)).toContain('0.0.2');
});
it('reads a prerelease version whole, not truncated to its release core', () => {
// The digits-only extraction the other four adapters use returns empty or a
// truncated `9.9.9` here, so vercmp would compare a version nobody has.
const agentDir = join(home, 'piagent');
installedFixture(agentDir, '9.9.9-rc.1');
const { out } = run(['--status'], {
home,
path: `${PI_STUB_DIR}:${CORE_PATH}`,
env: { PI_CODING_AGENT_DIR: agentDir },
});
expect(piRow(out)).toContain('9.9.9-rc.1');
});
it('renders unknown + the idempotent install verb when no version is on disk', () => {
const { code, out } = run(['--status'], { home, path: `${PI_STUB_DIR}:${CORE_PATH}` });
expect(code).toBe(0);
expect(piRow(out)).toContain('unknown');
const action = piRow(out)
.trim()
.split(/\s{2,}/)
.at(-1);
expect(action).toBe('install');
expect(ACTIONS).toContain(action);
// An unreadable version is neither determinate state, so the table must
// claim neither.
expect(piRow(out)).not.toContain('up to date');
expect(piRow(out)).not.toContain('update');
});
it('--status --json carries a null version and an unknown action', () => {
const { out } = run(['--status', '--json'], { home, path: `${PI_STUB_DIR}:${CORE_PATH}` });
const pi = JSON.parse(out).agents.find((a: { agent: string }) => a.agent === 'pi');
expect(pi.present).toBe(true);
expect(pi.installed).toBeNull(); // a semver or null, never a marker string
expect(pi.action).toBe('unknown');
});
});
describe('update-all', () => {
it('skips an unknown row with unknown as the reason, exits 0, and runs nothing', () => {
const { code, out } = run(['--action=update', '--yes'], {
home,
path: `${PI_STUB_DIR}:${CORE_PATH}`,
});
expect(code).toBe(0);
expect(out).toContain('pi: version unknown — skipped');
// Unattended, so reinstalling on ignorance would act on every run.
expect(out).not.toContain('RAN:pi');
});
it('control — the same command DOES update it when the version is readable and old', () => {
const agentDir = join(home, 'piagent');
installedFixture(agentDir, '0.0.1');
const { code, out } = run(['--action=update', '--yes'], {
home,
path: `${PI_STUB_DIR}:${CORE_PATH}`,
env: { PI_CODING_AGENT_DIR: agentDir },
});
expect(code).toBe(0);
expect(out).toContain('RAN:pi install npm:@rembric/pi');
expect(out).not.toContain('pi: version unknown');
});
});
});
describe('opencode installer verifications', () => {
const OPENCODE_INSTALL = join(REPO_ROOT, 'apps', 'plugin', '.opencode-plugin', 'install.sh');
it('is idempotent: a second install produces byte-identical files', () => {
const files = [
join(home, '.config', 'opencode', 'plugins', 'rembric.ts'),
join(home, '.config', 'rembric', 'bin', 'rembric-dotenv.mjs'),
join(home, '.config', 'rembric', 'bin', 'rembric-plugin-core.mjs'),
];
const first = run(['--agent=opencode', '--action=install'], { home });
expect(first.code).toBe(0);
const snapshot = files.map((f) => readFileSync(f, 'utf8'));
expect(existsSync(join(home, '.config', 'opencode', 'opencode.json'))).toBe(false);
expect(first.out).toContain('adds the MCP entry in memory');
const second = run(['--agent=opencode', '--action=install'], { home });
expect(second.code).toBe(0);
expect(second.out).toContain('left untouched');
expect(files.map((f) => readFileSync(f, 'utf8'))).toEqual(snapshot);
});
it('leaves an existing opencode.json byte-identical', () => {
const cfgDir = join(home, '.config', 'opencode');
mkdirSync(cfgDir, { recursive: true });
const configPath = join(cfgDir, 'opencode.json');
const oldConfig = JSON.stringify(
{
mcp: {
rembric: {
type: 'local',
command: ['node', '/home/user/.config/rembric/bin/rembric-bridge.mjs'],
environment: { REMBRIC_SERVER_URL: 'old-url', REMBRIC_API_TOKEN: 'old-token' },
},
},
operatorSetting: 'leave-me-alone',
},
null,
2,
);
writeFileSync(configPath, oldConfig);
const result = run(['--agent=opencode', '--action=update'], { home });
expect(result.code).toBe(0);
expect(readFileSync(configPath, 'utf8')).toBe(oldConfig);
expect(result.out).toContain('left untouched');
expect(result.out).toContain('adds the MCP entry in memory');
});
it('forwards the local bridge source and keeps the public ref source wired', () => {
const noNetwork = mkdtempSync(join(tmpdir(), 'rembric-no-network-'));
writeFileSync(join(noNetwork, 'curl'), '#!/bin/sh\nexit 91\n');
chmodSync(join(noNetwork, 'curl'), 0o755);
const result = run(['--agent=opencode', '--action=install'], {
home,
path: `${noNetwork}:${CORE_PATH}`,
});
rmSync(noNetwork, { recursive: true, force: true });
expect(result.code).toBe(0);
expect(INSTALLER_SRC).toContain('MCP_BRIDGE_SRC="$REMBRIC_SRC/apps/plugin/mcp-bridge"');
expect(INSTALLER_SRC).toContain('MCP_BRIDGE_SRC="$base/mcp-bridge"');
});
it('an unrelated "rembric" string elsewhere in opencode.json is NOT treated as configured', () => {
const cfgDir = join(home, '.config', 'opencode');
mkdirSync(cfgDir, { recursive: true });
const cfg = JSON.stringify({ mcp: { 'rembric-foo': { type: 'local' } }, theme: 'rembric' });
writeFileSync(join(cfgDir, 'opencode.json'), cfg);
const { code, out } = run(['--agent=opencode', '--action=install'], { home });
expect(code).toBe(0);
expect(out).toContain('left untouched');
expect(readFileSync(join(cfgDir, 'opencode.json'), 'utf8')).toBe(cfg); // untouched
});
it('a real mcp.rembric entry is detected as already configured', () => {
const cfgDir = join(home, '.config', 'opencode');
mkdirSync(cfgDir, { recursive: true });
const cfg = JSON.stringify({ mcp: { rembric: { type: 'local', enabled: true } } });
writeFileSync(join(cfgDir, 'opencode.json'), cfg);
const { out } = run(['--agent=opencode', '--action=install'], { home });
expect(out).toContain('left untouched');
expect(readFileSync(join(cfgDir, 'opencode.json'), 'utf8')).toBe(cfg);
});
it('aborts loudly and removes the partial plugin when the import rewrite no-ops', () => {
const drift = mkdtempSync(join(tmpdir(), 'rembric-drift-'));
writeFileSync(
join(drift, 'plugin.ts'),
`// @rembric-plugin-version 0.0.0\nimport { readRembricSlug } from './lib/rembric-dotenv.mjs';\nexport const RembricPlugin = () => ({});\n`,
);
const { code, out } = run([], {
home,
script: OPENCODE_INSTALL,
env: {
PLUGIN_SRC: drift,
BIN_SRC: join(REPO_ROOT, 'apps', 'plugin', 'bin'),
MCP_BRIDGE_SRC: join(REPO_ROOT, 'apps', 'plugin', 'mcp-bridge'),
},
});
rmSync(drift, { recursive: true, force: true });
expect(code).toBe(1);
expect(out).toContain('rewrite failed');
expect(existsSync(join(home, '.config', 'opencode', 'plugins', 'rembric.ts'))).toBe(false);
});
it.each([
{ label: 'core', good: 'rembric-dotenv.mjs', drifted: 'rembric-plugin-core.mjs' },
{ label: 'dotenv', good: 'rembric-plugin-core.mjs', drifted: 'rembric-dotenv.mjs' },
])('a drifted $label import aborts even though the other rewrite succeeded', ({ drifted }) => {
const drift = mkdtempSync(join(tmpdir(), 'rembric-drift-'));
writeFileSync(
join(drift, 'plugin.ts'),
[
'// @rembric-plugin-version 0.0.0',
"import { readRembricSlug } from '../mcp-bridge/rembric-dotenv.mjs';",
"import { createSessionProtocol } from '../bin/rembric-plugin-core.mjs';",
'export const RembricPlugin = () => ({});',
'',
]
.join('\n')
// Drift ONE import out of the sed pattern's reach; the other still rewrites.
.replace(
`../${drifted === 'rembric-dotenv.mjs' ? 'mcp-bridge' : 'bin'}/${drifted}`,
`./lib/${drifted}`,
),
);
const { code, out } = run([], {
home,
script: OPENCODE_INSTALL,
env: {
PLUGIN_SRC: drift,
BIN_SRC: join(REPO_ROOT, 'apps', 'plugin', 'bin'),
MCP_BRIDGE_SRC: join(REPO_ROOT, 'apps', 'plugin', 'mcp-bridge'),
},
});
rmSync(drift, { recursive: true, force: true });
expect(code).toBe(1);
expect(out).toContain('rewrite failed');
expect(out).toContain(drifted);
expect(existsSync(join(home, '.config', 'opencode', 'plugins', 'rembric.ts'))).toBe(false);
});
it('the installed plugin loads, resolving both shared modules from disk', async () => {
const ins = run(['--agent=opencode', '--action=install'], { home });
expect(ins.code).toBe(0);
const installed = join(home, '.config', 'opencode', 'plugins', 'rembric.ts');
const mod = (await import(installed)) as Record<string, unknown>;
expect(typeof mod.RembricPlugin).toBe('function');
// opencode invokes EVERY named export with the plugin ctx, so a leaked helper
// crashes on load.
expect(Object.keys(mod)).toEqual(['RembricPlugin']);
});
it('every file the install copies is removed by the uninstall', () => {
const filesUnder = (root: string): string[] => {
const walk = (rel: string): string[] =>
readdirSync(join(root, rel), { withFileTypes: true }).flatMap((e) =>
e.isDirectory() ? walk(join(rel, e.name)) : [join(rel, e.name)],
);
return walk('.').sort();
};
expect(run(['--agent=opencode', '--action=install'], { home }).code).toBe(0);
const installedFiles = filesUnder(home);
expect(installedFiles).toContain('.config/rembric/bin/rembric-plugin-core.mjs');
expect(run(['--agent=opencode', '--action=uninstall'], { home }).code).toBe(0);
expect(filesUnder(home)).toEqual([]);
});
});
describe('--yes runs the marketplace command (stubbed client binary)', () => {
it('--yes executes the claude update command when the claude binary is present', () => {
const bin = fakeClientBinDir('claude');
const { code, out } = run(['--agent=claude', '--action=update', '--yes'], {
home,
path: `${bin}:${CORE_PATH}`,
});
rmSync(bin, { recursive: true, force: true });
expect(code).toBe(0);
expect(out).toContain('claude plugin update rembric@rembric'); // still printed
expect(out).toContain('RAN:claude plugin update rembric@rembric'); // and executed
});
it('-y is an alias for --yes', () => {
const bin = fakeClientBinDir('claude');
const { code, out } = run(['--agent=claude', '--action=update', '-y'], {
home,
path: `${bin}:${CORE_PATH}`,
});
rmSync(bin, { recursive: true, force: true });
expect(code).toBe(0);
expect(out).toContain('RAN:claude plugin update rembric@rembric');
});
it('--yes executes the codex upgrade command when the codex binary is present', () => {
const bin = fakeClientBinDir('codex');
const { code, out } = run(['--agent=codex', '--action=update', '--yes'], {
home,
path: `${bin}:${CORE_PATH}`,
});
rmSync(bin, { recursive: true, force: true });
expect(code).toBe(0);
expect(out).toContain('RAN:codex plugin marketplace upgrade rembric');
});
it('without --yes a headless run only prints, never executes', () => {
const bin = fakeClientBinDir('claude');
const { code, out } = run(['--agent=claude', '--action=update'], {
home,
path: `${bin}:${CORE_PATH}`,
});
rmSync(bin, { recursive: true, force: true });
expect(code).toBe(0);
expect(out).toContain('claude plugin update rembric@rembric'); // printed
expect(out).not.toContain('RAN:claude'); // not executed
});
it('--yes with an absent client binary prints but executes nothing', () => {
const { code, out } = run(['--agent=codex', '--action=update', '--yes'], {
home,
path: CORE_PATH, // no codex on PATH
});
expect(code).toBe(0);
expect(out).toContain('codex plugin marketplace upgrade rembric'); // printed
expect(out).not.toContain('RAN:codex'); // nothing ran
});
it('--help documents the --yes / -y flag', () => {
const { out } = run(['--help']);
expect(out).toContain('--yes');
expect(out).toContain('-y');
});
});
describe('root install.sh shim', () => {
it('--help is identical to the plugin installer (pure forwarder)', () => {
const root = run(['--help'], { script: ROOT_SHIM });