@memnexus-ai/mx-agent-cli 0.1.240 → 0.1.241

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.
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Isolation-banner probes (#4646) — FL-2 false-green remediation.
3
+ *
4
+ * The banner used to print three unconditional `✓` literals. Each line is now
5
+ * computed from a probe, so each probe needs all three of its states driven by
6
+ * INJECTED faults, not by observing that a healthy worktree looks healthy
7
+ * (FL-16: running the tool and seeing no complaint is not verification).
8
+ *
9
+ * Every test builds a real worktree fixture on disk — settings.json, deployed
10
+ * hooks, an agent-config source to hash against — and then breaks exactly one
11
+ * thing. The one-thing-at-a-time structure is what makes the mutation checks at
12
+ * the bottom meaningful: deleting a probe's check has to fail a named test.
13
+ */
14
+ export {};
15
+ //# sourceMappingURL=isolation-probe.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"isolation-probe.test.d.ts","sourceRoot":"","sources":["../../src/__tests__/isolation-probe.test.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG"}
@@ -0,0 +1,611 @@
1
+ /**
2
+ * Isolation-banner probes (#4646) — FL-2 false-green remediation.
3
+ *
4
+ * The banner used to print three unconditional `✓` literals. Each line is now
5
+ * computed from a probe, so each probe needs all three of its states driven by
6
+ * INJECTED faults, not by observing that a healthy worktree looks healthy
7
+ * (FL-16: running the tool and seeing no complaint is not verification).
8
+ *
9
+ * Every test builds a real worktree fixture on disk — settings.json, deployed
10
+ * hooks, an agent-config source to hash against — and then breaks exactly one
11
+ * thing. The one-thing-at-a-time structure is what makes the mutation checks at
12
+ * the bottom meaningful: deleting a probe's check has to fail a named test.
13
+ */
14
+ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
15
+ import { mkdtempSync, mkdirSync, writeFileSync, rmSync, existsSync, unlinkSync, symlinkSync } from 'fs';
16
+ import { join } from 'path';
17
+ import { tmpdir } from 'os';
18
+ import chalk from 'chalk';
19
+ import { probeContainment, probeBranchPin, probePushBlock, probeIsolation, renderProbeLine, bannerHeading, renderIsolationBanner, safeConfigSource, ISOLATION_CLAIMS, } from '../lib/isolation-probe.js';
20
+ const CONFIG_SOURCE = 'mx-agent-system/agent-config';
21
+ const GUARD_BODY = '#!/bin/bash\n# worktree-guard fixture\nexit 0\n';
22
+ const DENY_ALL = [
23
+ 'Bash(git checkout main)',
24
+ 'Bash(git checkout main *)',
25
+ 'Bash(git switch main)',
26
+ 'Bash(git switch main *)',
27
+ 'Bash(git push origin main)',
28
+ 'Bash(git push origin main *)',
29
+ 'Bash(git push -u origin main)',
30
+ 'Bash(git push -u origin main *)',
31
+ ];
32
+ let root;
33
+ let worktree;
34
+ /**
35
+ * An INDEPENDENT freshness anchor, outside both the worktree and the project
36
+ * root — the npm-installed CLI bundle's role in production. A healthy fixture
37
+ * needs one: without it the probes correctly report `unknown` rather than `pass`,
38
+ * because there is nothing to compare the deployed guard against that an attacker
39
+ * with write access to the worktree could not also have written.
40
+ */
41
+ let bundleDir;
42
+ let prevBundleEnv;
43
+ /** Build a fully healthy fixture: contained worktree, registered+fresh guard, full deny list. */
44
+ function makeFixture(opts = {}) {
45
+ root = mkdtempSync(join(tmpdir(), 'iso-probe-'));
46
+ worktree = join(root, '.worktrees', 'team-x');
47
+ mkdirSync(join(worktree, '.claude', 'hooks'), { recursive: true });
48
+ mkdirSync(join(worktree, CONFIG_SOURCE, 'hooks'), { recursive: true });
49
+ // agent-config SOURCE: settings.json (drives the expected-guard set) + guard.
50
+ const sourceSettings = {
51
+ hooks: {
52
+ PreToolUse: [
53
+ { matcher: 'Bash', hooks: [{ type: 'command', command: 'bash .claude/hooks/worktree-guard.sh' }] },
54
+ ],
55
+ },
56
+ };
57
+ writeFileSync(join(worktree, CONFIG_SOURCE, 'settings.json'), JSON.stringify(sourceSettings, null, 2));
58
+ writeFileSync(join(worktree, CONFIG_SOURCE, 'hooks', 'worktree-guard.sh'), opts.sourceGuardBody ?? GUARD_BODY);
59
+ // Deployed worktree config.
60
+ const liveSettings = {
61
+ permissions: { deny: opts.deny ?? DENY_ALL },
62
+ hooks: sourceSettings.hooks,
63
+ };
64
+ writeFileSync(join(worktree, '.claude', 'settings.json'), JSON.stringify(liveSettings, null, 2));
65
+ writeFileSync(join(worktree, '.claude', 'hooks', 'worktree-guard.sh'), opts.guardBody ?? GUARD_BODY);
66
+ // Independent anchor: same bytes as a healthy deployed guard.
67
+ bundleDir = mkdtempSync(join(tmpdir(), 'iso-bundle-'));
68
+ mkdirSync(join(bundleDir, 'hooks'), { recursive: true });
69
+ writeFileSync(join(bundleDir, 'settings.json'), '{}');
70
+ writeFileSync(join(bundleDir, 'hooks', 'worktree-guard.sh'), opts.bundledGuardBody ?? GUARD_BODY);
71
+ }
72
+ function input(over = {}) {
73
+ return {
74
+ projectRoot: root,
75
+ worktreePath: worktree,
76
+ baseBranch: 'main',
77
+ configSource: CONFIG_SOURCE,
78
+ cwd: worktree,
79
+ currentBranch: 'worktree/team-x-20260730',
80
+ // Test seam, not the env var: production ignores MX_BUNDLED_CONFIG_DIR.
81
+ resolveBundledDir: () => bundleDir,
82
+ ...over,
83
+ };
84
+ }
85
+ beforeEach(() => {
86
+ // The env override is cleared, not used: the probe ignores it by design, and a
87
+ // stray value in the ambient environment must not change these results.
88
+ prevBundleEnv = process.env.MX_BUNDLED_CONFIG_DIR;
89
+ delete process.env.MX_BUNDLED_CONFIG_DIR;
90
+ makeFixture();
91
+ });
92
+ afterEach(() => {
93
+ vi.restoreAllMocks();
94
+ if (prevBundleEnv === undefined)
95
+ delete process.env.MX_BUNDLED_CONFIG_DIR;
96
+ else
97
+ process.env.MX_BUNDLED_CONFIG_DIR = prevBundleEnv;
98
+ if (root && existsSync(root))
99
+ rmSync(root, { recursive: true, force: true });
100
+ if (bundleDir && existsSync(bundleDir))
101
+ rmSync(bundleDir, { recursive: true, force: true });
102
+ });
103
+ // ── Probe 1: containment ─────────────────────────────────────────────────────
104
+ describe('probeContainment', () => {
105
+ it('PASSES on a contained worktree with a registered, fresh guard', () => {
106
+ expect(probeContainment(input())).toEqual({ state: 'pass' });
107
+ });
108
+ it('FAILS when the worktree directory does not exist', () => {
109
+ const r = probeContainment(input({ worktreePath: join(root, '.worktrees', 'gone') }));
110
+ expect(r.state).toBe('fail');
111
+ expect(r.reason).toMatch(/not a directory/);
112
+ });
113
+ it('FAILS when the worktree is outside the project root', () => {
114
+ const outside = mkdtempSync(join(tmpdir(), 'iso-outside-'));
115
+ try {
116
+ mkdirSync(join(outside, '.claude', 'hooks'), { recursive: true });
117
+ const r = probeContainment(input({ worktreePath: outside, cwd: outside }));
118
+ expect(r.state).toBe('fail');
119
+ expect(r.reason).toMatch(/not under project root/);
120
+ }
121
+ finally {
122
+ rmSync(outside, { recursive: true, force: true });
123
+ }
124
+ });
125
+ it('FAILS when cwd is outside the worktree', () => {
126
+ const r = probeContainment(input({ cwd: root }));
127
+ expect(r.state).toBe('fail');
128
+ expect(r.reason).toMatch(/outside the worktree/);
129
+ });
130
+ it('FAILS when the guard is registered but absent on disk (hook fails open)', () => {
131
+ unlinkSync(join(worktree, '.claude', 'hooks', 'worktree-guard.sh'));
132
+ const r = probeContainment(input());
133
+ expect(r.state).toBe('fail');
134
+ expect(r.reason).toMatch(/MISSING on disk|absent from/);
135
+ });
136
+ it('FAILS when the deployed guard is STALE relative to its source', () => {
137
+ // Present and registered, so an existence check passes — but the deployed
138
+ // bytes are an older build (FL-9: presence is not verification).
139
+ writeFileSync(join(worktree, '.claude', 'hooks', 'worktree-guard.sh'), GUARD_BODY + '# drifted\n');
140
+ const r = probeContainment(input());
141
+ expect(r.state).toBe('fail');
142
+ expect(r.reason).toMatch(/STALE/);
143
+ });
144
+ it('FAILS when the guard is not registered at all', () => {
145
+ writeFileSync(join(worktree, '.claude', 'settings.json'), JSON.stringify({ permissions: { deny: DENY_ALL }, hooks: {} }));
146
+ const r = probeContainment(input());
147
+ expect(r.state).toBe('fail');
148
+ expect(r.reason).toMatch(/not registered/);
149
+ });
150
+ it('CANNOT PROBE (unknown) when settings.json is absent', () => {
151
+ unlinkSync(join(worktree, '.claude', 'settings.json'));
152
+ const r = probeContainment(input());
153
+ expect(r.state).toBe('unknown');
154
+ expect(r.reason).toMatch(/settings\.json/);
155
+ });
156
+ it('CANNOT PROBE (unknown) when settings.json is malformed', () => {
157
+ writeFileSync(join(worktree, '.claude', 'settings.json'), '{ not json');
158
+ const r = probeContainment(input());
159
+ expect(r.state).toBe('unknown');
160
+ });
161
+ it('PASSES with no in-repo source when the independent bundled anchor matches', () => {
162
+ // The anchor redesign makes the in-repo source optional: an independent
163
+ // anchor is a better answer, not a supplementary one.
164
+ rmSync(join(worktree, CONFIG_SOURCE), { recursive: true, force: true });
165
+ expect(probeContainment(input()).state).toBe('pass');
166
+ });
167
+ it('CANNOT PROBE (unknown) with neither an in-repo source nor a bundled anchor', () => {
168
+ rmSync(join(worktree, CONFIG_SOURCE), { recursive: true, force: true });
169
+ rmSync(bundleDir, { recursive: true, force: true });
170
+ const r = probeContainment(input({ resolveBundledDir: () => null }));
171
+ expect(r.state).toBe('unknown');
172
+ expect(r.reason).toMatch(/cannot compare|not found|no CLI bundle/);
173
+ });
174
+ it('CANNOT PROBE (unknown) when cwd cannot be resolved', () => {
175
+ const r = probeContainment(input({ cwd: join(root, 'no', 'such', 'dir') }));
176
+ expect(r.state).toBe('unknown');
177
+ expect(r.reason).toMatch(/could not be resolved/);
178
+ });
179
+ });
180
+ // ── Probe 2: branch pin ──────────────────────────────────────────────────────
181
+ describe('probeBranchPin', () => {
182
+ it('PASSES on a team branch with the switch-to-main deny rules present', () => {
183
+ expect(probeBranchPin(input())).toEqual({ state: 'pass' });
184
+ });
185
+ it('FAILS when the worktree is sitting ON the base branch', () => {
186
+ const r = probeBranchPin(input({ currentBranch: 'main' }));
187
+ expect(r.state).toBe('fail');
188
+ expect(r.reason).toMatch(/ON the base branch/);
189
+ });
190
+ it('FAILS on a detached HEAD (no branch is pinned)', () => {
191
+ const r = probeBranchPin(input({ currentBranch: 'HEAD' }));
192
+ expect(r.state).toBe('fail');
193
+ expect(r.reason).toMatch(/detached HEAD/);
194
+ });
195
+ it('FAILS when a switch-to-main deny rule has been removed', () => {
196
+ makeFixture({ deny: DENY_ALL.filter((d) => d !== 'Bash(git switch main)') });
197
+ const r = probeBranchPin(input());
198
+ expect(r.state).toBe('fail');
199
+ expect(r.reason).toMatch(/switch-to-main rules/);
200
+ });
201
+ it('FAILS when the deny list is emptied entirely', () => {
202
+ makeFixture({ deny: [] });
203
+ const r = probeBranchPin(input());
204
+ expect(r.state).toBe('fail');
205
+ expect(r.reason).toMatch(/missing 4 of 4/);
206
+ });
207
+ it('FAILS when the guard is stale even with every deny rule present', () => {
208
+ writeFileSync(join(worktree, '.claude', 'hooks', 'worktree-guard.sh'), GUARD_BODY + '# drifted\n');
209
+ const r = probeBranchPin(input());
210
+ expect(r.state).toBe('fail');
211
+ expect(r.reason).toMatch(/STALE/);
212
+ });
213
+ it('CANNOT PROBE (unknown) when the branch cannot be read', () => {
214
+ const r = probeBranchPin(input({ currentBranch: null }));
215
+ expect(r.state).toBe('unknown');
216
+ expect(r.reason).toMatch(/could not be read/);
217
+ });
218
+ it('CANNOT PROBE (unknown) when no base branch is configured', () => {
219
+ const r = probeBranchPin(input({ baseBranch: '' }));
220
+ expect(r.state).toBe('unknown');
221
+ expect(r.reason).toMatch(/no base branch/);
222
+ });
223
+ it('CANNOT PROBE (unknown) when permissions.deny is not an array', () => {
224
+ writeFileSync(join(worktree, '.claude', 'settings.json'), JSON.stringify({ permissions: { deny: 'nope' }, hooks: {} }));
225
+ const r = probeBranchPin(input());
226
+ expect(r.state).toBe('unknown');
227
+ expect(r.reason).toMatch(/permissions\.deny/);
228
+ });
229
+ it('falls back to the injected reader when currentBranch is omitted', () => {
230
+ const inp = input();
231
+ delete inp.currentBranch;
232
+ const r = probeBranchPin({ ...inp, readBranch: () => 'worktree/from-reader' });
233
+ expect(r.state).toBe('pass');
234
+ });
235
+ it('reports unknown when the injected reader fails', () => {
236
+ const inp = input();
237
+ delete inp.currentBranch;
238
+ const r = probeBranchPin({ ...inp, readBranch: () => null });
239
+ expect(r.state).toBe('unknown');
240
+ });
241
+ });
242
+ // ── Probe 3: push-to-main block ──────────────────────────────────────────────
243
+ describe('probePushBlock', () => {
244
+ it('PASSES with every push-to-main deny rule present and a fresh guard', () => {
245
+ expect(probePushBlock(input())).toEqual({ state: 'pass' });
246
+ });
247
+ it('FAILS when a push-to-main deny rule has been removed', () => {
248
+ makeFixture({ deny: DENY_ALL.filter((d) => d !== 'Bash(git push origin main)') });
249
+ const r = probePushBlock(input());
250
+ expect(r.state).toBe('fail');
251
+ expect(r.reason).toMatch(/push-to-main rules/);
252
+ });
253
+ it('FAILS when only the -u forms were removed (partial gap still a gap)', () => {
254
+ makeFixture({ deny: DENY_ALL.filter((d) => !d.includes('-u')) });
255
+ const r = probePushBlock(input());
256
+ expect(r.state).toBe('fail');
257
+ expect(r.reason).toMatch(/missing 2 of 4/);
258
+ });
259
+ it('FAILS when the guard is missing on disk', () => {
260
+ unlinkSync(join(worktree, '.claude', 'hooks', 'worktree-guard.sh'));
261
+ const r = probePushBlock(input());
262
+ expect(r.state).toBe('fail');
263
+ });
264
+ it('CANNOT PROBE (unknown) when settings.json is absent', () => {
265
+ unlinkSync(join(worktree, '.claude', 'settings.json'));
266
+ const r = probePushBlock(input());
267
+ expect(r.state).toBe('unknown');
268
+ });
269
+ });
270
+ // ── probeIsolation: aggregation never throws ──────────────────────────────────
271
+ describe('probeIsolation', () => {
272
+ it('returns all three probes on a healthy fixture', () => {
273
+ const rep = probeIsolation(input());
274
+ expect(rep.containment.state).toBe('pass');
275
+ expect(rep.branchPin.state).toBe('pass');
276
+ expect(rep.pushBlock.state).toBe('pass');
277
+ });
278
+ it('converts an unexpected throw into unknown, never a pass', () => {
279
+ const inp = input();
280
+ delete inp.currentBranch;
281
+ const rep = probeIsolation({
282
+ ...inp,
283
+ readBranch: () => { throw new Error('boom'); },
284
+ });
285
+ expect(rep.branchPin.state).toBe('unknown');
286
+ expect(rep.branchPin.reason).toMatch(/probe threw/);
287
+ });
288
+ it('reports each line independently — one failure does not mask the others', () => {
289
+ makeFixture({ deny: DENY_ALL.filter((d) => !d.includes('push')) });
290
+ const rep = probeIsolation(input());
291
+ expect(rep.containment.state).toBe('pass');
292
+ expect(rep.branchPin.state).toBe('pass');
293
+ expect(rep.pushBlock.state).toBe('fail');
294
+ });
295
+ it('completes well inside the 100ms budget', () => {
296
+ const start = Date.now();
297
+ probeIsolation(input());
298
+ expect(Date.now() - start).toBeLessThan(100);
299
+ });
300
+ });
301
+ // ── Render: three distinct glyphs, no ✓ without a pass ───────────────────────
302
+ describe('render', () => {
303
+ const origLevel = chalk.level;
304
+ beforeEach(() => { chalk.level = 0; });
305
+ afterEach(() => { chalk.level = origLevel; });
306
+ it('renders ✓ only for a pass, and with no reason appended', () => {
307
+ const line = renderProbeLine('claim', { state: 'pass' });
308
+ expect(line).toContain('✓');
309
+ expect(line).not.toContain('—');
310
+ });
311
+ it('renders ✗ plus the reason for a fail', () => {
312
+ const line = renderProbeLine('claim', { state: 'fail', reason: 'guard is STALE' });
313
+ expect(line).toContain('✗');
314
+ expect(line).not.toContain('✓');
315
+ expect(line).toContain('guard is STALE');
316
+ });
317
+ it('renders ? plus the reason for could-not-probe — never ✓', () => {
318
+ const line = renderProbeLine('claim', { state: 'unknown', reason: 'settings.json absent' });
319
+ expect(line).toContain('?');
320
+ expect(line).not.toContain('✓');
321
+ expect(line).toContain('settings.json absent');
322
+ });
323
+ it('never renders ✓ for any non-pass state', () => {
324
+ for (const state of ['fail', 'unknown']) {
325
+ expect(renderProbeLine('c', { state, reason: 'r' })).not.toContain('✓');
326
+ }
327
+ });
328
+ it('says "no reason given" rather than nothing when a reason is missing', () => {
329
+ expect(renderProbeLine('c', { state: 'fail' })).toContain('no reason given');
330
+ });
331
+ const rep = (c, b, p) => ({ containment: c, branchPin: b, pushBlock: p });
332
+ const P = { state: 'pass' };
333
+ it('heading claims verified only when all three pass', () => {
334
+ expect(bannerHeading(rep(P, P, P))).toContain('verified');
335
+ expect(bannerHeading(rep(P, P, P))).not.toContain('NOT');
336
+ });
337
+ it('heading goes red when any line fails', () => {
338
+ expect(bannerHeading(rep(P, { state: 'fail', reason: 'x' }, P))).toContain('NOT fully enabled');
339
+ });
340
+ it('heading warns when any line could not be probed', () => {
341
+ expect(bannerHeading(rep(P, { state: 'unknown', reason: 'x' }, P))).toContain('partially verified');
342
+ });
343
+ it('a fail is echoed to stderr as well as stdout, and does not throw', () => {
344
+ const out = [];
345
+ const err = [];
346
+ vi.spyOn(console, 'log').mockImplementation((m) => { out.push(String(m ?? '')); });
347
+ vi.spyOn(console, 'error').mockImplementation((m) => { err.push(String(m ?? '')); });
348
+ expect(() => renderIsolationBanner(rep(P, { state: 'fail', reason: 'guard is STALE' }, P))).not.toThrow();
349
+ expect(out.join('\n')).toContain(ISOLATION_CLAIMS.branchPin);
350
+ expect(err.join('\n')).toContain('NOT VERIFIED');
351
+ expect(err.join('\n')).toContain('guard is STALE');
352
+ expect(out.join('\n')).toContain('1 of 3 isolation claims are not verified');
353
+ });
354
+ it('an all-pass banner writes nothing to stderr', () => {
355
+ const err = [];
356
+ vi.spyOn(console, 'log').mockImplementation(() => { });
357
+ vi.spyOn(console, 'error').mockImplementation((m) => { err.push(String(m ?? '')); });
358
+ renderIsolationBanner(rep(P, P, P));
359
+ expect(err).toEqual([]);
360
+ });
361
+ it('an unknown line is NOT echoed to stderr but IS counted as unverified', () => {
362
+ const out = [];
363
+ const err = [];
364
+ vi.spyOn(console, 'log').mockImplementation((m) => { out.push(String(m ?? '')); });
365
+ vi.spyOn(console, 'error').mockImplementation((m) => { err.push(String(m ?? '')); });
366
+ renderIsolationBanner(rep(P, P, { state: 'unknown', reason: 'x' }));
367
+ expect(err).toEqual([]);
368
+ expect(out.join('\n')).toContain('1 of 3 isolation claims are not verified');
369
+ });
370
+ });
371
+ // ── Hostile input (security review round 1) ──────────────────────────────────
372
+ describe('hostile input', () => {
373
+ const ESC = String.fromCharCode(27);
374
+ const origLevel = chalk.level;
375
+ beforeEach(() => { chalk.level = 0; });
376
+ afterEach(() => { chalk.level = origLevel; });
377
+ it('MF1 (CWE-150): ANSI/control content in a hook command cannot forge the banner', () => {
378
+ // An unresolvable hook command becomes part of a reason string. This one
379
+ // carries erase-line + cursor-up + green-fg, the shape that overwrites an
380
+ // already-printed ✗ with a fake ✓.
381
+ const payload = `bash $HOOKDIR/.claude/hooks/${ESC}[2K${ESC}[A${ESC}[32m✓ git push origin main blocked${ESC}[0m`;
382
+ writeFileSync(join(worktree, '.claude', 'settings.json'), JSON.stringify({
383
+ permissions: { deny: DENY_ALL },
384
+ hooks: {
385
+ PreToolUse: [
386
+ { matcher: 'Bash', hooks: [{ type: 'command', command: 'bash .claude/hooks/worktree-guard.sh' }] },
387
+ { matcher: 'Bash', hooks: [{ type: 'command', command: payload }] },
388
+ ],
389
+ },
390
+ }));
391
+ const r = probeContainment(input());
392
+ expect(r.state).toBe('unknown'); // unresolvable registration → cannot verify
393
+ const line = renderProbeLine(ISOLATION_CLAIMS.containment, r);
394
+ expect(line.includes(ESC)).toBe(false);
395
+ expect(line).not.toContain('[2K');
396
+ expect(line).not.toContain('[A');
397
+ expect(line).not.toContain('[32m');
398
+ // The glyph for this line is still '?', not a forged pass.
399
+ expect(line).toContain('?');
400
+ expect(line).not.toContain('✓');
401
+ });
402
+ it('MF1: the stderr echo is sanitized too', () => {
403
+ const err = [];
404
+ vi.spyOn(console, 'log').mockImplementation(() => { });
405
+ vi.spyOn(console, 'error').mockImplementation((m) => { err.push(String(m ?? '')); });
406
+ renderIsolationBanner({
407
+ containment: { state: 'fail', reason: `evil${ESC}[2K${ESC}[A${ESC}[32m✓ forged` },
408
+ branchPin: { state: 'pass' },
409
+ pushBlock: { state: 'pass' },
410
+ });
411
+ const joined = err.join('\n');
412
+ expect(joined.includes(ESC)).toBe(false);
413
+ expect(joined).toContain('NOT VERIFIED');
414
+ });
415
+ it('MF1: an over-long reason is truncated rather than scrolling the banner away', () => {
416
+ const line = renderProbeLine('c', { state: 'fail', reason: 'x'.repeat(5000) });
417
+ expect(line.length).toBeLessThan(400);
418
+ });
419
+ it('MF2 (CWE-22): a traversing configSource cannot relocate the freshness anchor', () => {
420
+ // Plant an attacker-controlled "source" outside the repo holding a neutered
421
+ // guard, and point configSource at it via traversal. The probe must not read
422
+ // it, and must not report pass.
423
+ const outside = mkdtempSync(join(tmpdir(), 'iso-evil-'));
424
+ try {
425
+ mkdirSync(join(outside, 'hooks'), { recursive: true });
426
+ const neutered = '#!/bin/bash\nexit 0\n';
427
+ writeFileSync(join(outside, 'hooks', 'worktree-guard.sh'), neutered);
428
+ // Deployed guard is neutered to match the attacker's anchor.
429
+ writeFileSync(join(worktree, '.claude', 'hooks', 'worktree-guard.sh'), neutered);
430
+ const rel = `${'../'.repeat(12)}${outside.replace(/^\//, '')}`;
431
+ const r = probeContainment(input({ configSource: rel }));
432
+ expect(r.state).not.toBe('pass');
433
+ }
434
+ finally {
435
+ rmSync(outside, { recursive: true, force: true });
436
+ }
437
+ });
438
+ it('MF2: safeConfigSource rejects traversal and absolute paths', () => {
439
+ for (const bad of [
440
+ '../../../etc',
441
+ '..',
442
+ 'a/../../b',
443
+ 'mx-agent-system/../../..',
444
+ '/etc/passwd',
445
+ ]) {
446
+ expect(safeConfigSource(bad)).toBe('mx-agent-system/agent-config');
447
+ }
448
+ // A clean relative path is preserved.
449
+ expect(safeConfigSource('some/config')).toBe('some/config');
450
+ expect(safeConfigSource(undefined)).toBe('mx-agent-system/agent-config');
451
+ expect(safeConfigSource(' ')).toBe('mx-agent-system/agent-config');
452
+ });
453
+ it('SF3: a SYMLINKED deployed guard is unknown, not pass (kills hash(x)==hash(x))', () => {
454
+ const deployed = join(worktree, '.claude', 'hooks', 'worktree-guard.sh');
455
+ unlinkSync(deployed);
456
+ symlinkSync(join(worktree, CONFIG_SOURCE, 'hooks', 'worktree-guard.sh'), deployed);
457
+ const r = probeContainment(input());
458
+ expect(r.state).toBe('unknown');
459
+ expect(r.reason).toMatch(/SYMLINK/);
460
+ });
461
+ it('SF3: coordinated neuter of deployed AND in-repo source is NOT a pass when an independent anchor exists', () => {
462
+ // The attack the anchor redesign exists to stop: write a neutered guard to
463
+ // both the deployed path and the in-repo source so they agree with each
464
+ // other. With an honest bundled anchor present and disagreeing, the only
465
+ // correct answer is "not verified".
466
+ const neutered = '#!/bin/bash\nexit 0\n';
467
+ writeFileSync(join(worktree, '.claude', 'hooks', 'worktree-guard.sh'), neutered);
468
+ writeFileSync(join(worktree, CONFIG_SOURCE, 'hooks', 'worktree-guard.sh'), neutered);
469
+ // bundleDir already holds the real guard body — an honest anchor that
470
+ // disagrees with the coordinated pair.
471
+ const r = probeContainment(input());
472
+ expect(r.state).not.toBe('pass');
473
+ expect(r.reason).toMatch(/shipped CLI bundle|STALE/);
474
+ });
475
+ it('SF3: deployed matching the independent bundled anchor is a pass', () => {
476
+ // Both directions (FL-10): the hardened anchor must still green-light a
477
+ // genuinely healthy worktree, or it gets switched off.
478
+ expect(probeContainment(input())).toEqual({ state: 'pass' });
479
+ });
480
+ it('SF3: worktree and project-root sources disagreeing yields unknown', () => {
481
+ // No bundled anchor, two in-repo copies that differ → no single answer.
482
+ mkdirSync(join(root, CONFIG_SOURCE, 'hooks'), { recursive: true });
483
+ writeFileSync(join(root, CONFIG_SOURCE, 'hooks', 'worktree-guard.sh'), GUARD_BODY + '# other\n');
484
+ const r = probeContainment(input({ resolveBundledDir: () => null }));
485
+ expect(r.state).toBe('unknown');
486
+ expect(r.reason).toMatch(/disagree|cannot be established|shipped CLI bundle|independent/);
487
+ });
488
+ it('SF3: a bundle resolving INSIDE the worktree is not an anchor (self-reference)', () => {
489
+ // A source-tree run resolves getBundledConfigDir() back into the repo. An
490
+ // anchor inside the set it measures compares two files the same writer
491
+ // controls, so agreement proves nothing — this must not be a pass even though
492
+ // the hashes match.
493
+ const neutered = '#!/bin/bash\nexit 0\n';
494
+ const inRepoBundle = join(worktree, 'mx-agent-system', 'cli', 'dist', 'agent-config');
495
+ mkdirSync(join(inRepoBundle, 'hooks'), { recursive: true });
496
+ writeFileSync(join(inRepoBundle, 'hooks', 'worktree-guard.sh'), neutered);
497
+ writeFileSync(join(worktree, '.claude', 'hooks', 'worktree-guard.sh'), neutered);
498
+ writeFileSync(join(worktree, CONFIG_SOURCE, 'hooks', 'worktree-guard.sh'), neutered);
499
+ const r = probeContainment(input({ resolveBundledDir: () => inRepoBundle }));
500
+ expect(r.state).not.toBe('pass');
501
+ });
502
+ it('SF3: a bundle resolving inside the PROJECT ROOT is not an anchor either', () => {
503
+ const neutered = '#!/bin/bash\nexit 0\n';
504
+ const rootBundle = join(root, 'some', 'dist', 'agent-config');
505
+ mkdirSync(join(rootBundle, 'hooks'), { recursive: true });
506
+ writeFileSync(join(rootBundle, 'hooks', 'worktree-guard.sh'), neutered);
507
+ writeFileSync(join(worktree, '.claude', 'hooks', 'worktree-guard.sh'), neutered);
508
+ writeFileSync(join(worktree, CONFIG_SOURCE, 'hooks', 'worktree-guard.sh'), neutered);
509
+ const r = probeContainment(input({ resolveBundledDir: () => rootBundle }));
510
+ expect(r.state).not.toBe('pass');
511
+ });
512
+ it('SF5: an ENV-DESIGNATED bundle is NOT an anchor — matching neutered copy is not a pass', () => {
513
+ // Re-review finding: getBundledConfigDir() honoured MX_BUNDLED_CONFIG_DIR
514
+ // unconditionally, and an env path trivially passes the outside-worktree-and-
515
+ // root test. Point it at /tmp with a neutered copy and the deployed guard
516
+ // "matches its anchor" — the same whoever-chooses-the-anchor defect as the
517
+ // traversing configSource. The env var is a test seam; production ignores it.
518
+ const neutered = '#!/bin/bash\nexit 0\n';
519
+ writeFileSync(join(worktree, '.claude', 'hooks', 'worktree-guard.sh'), neutered);
520
+ writeFileSync(join(worktree, CONFIG_SOURCE, 'hooks', 'worktree-guard.sh'), neutered);
521
+ const evil = mkdtempSync(join(tmpdir(), 'iso-evil-bundle-'));
522
+ const prev = process.env.MX_BUNDLED_CONFIG_DIR;
523
+ try {
524
+ mkdirSync(join(evil, 'hooks'), { recursive: true });
525
+ writeFileSync(join(evil, 'settings.json'), '{}');
526
+ writeFileSync(join(evil, 'hooks', 'worktree-guard.sh'), neutered);
527
+ process.env.MX_BUNDLED_CONFIG_DIR = evil;
528
+ // No injected seam here: this exercises the production resolution path.
529
+ const inp = input();
530
+ delete inp.resolveBundledDir;
531
+ const r = probeContainment(inp);
532
+ expect(r.state).not.toBe('pass');
533
+ }
534
+ finally {
535
+ if (prev === undefined)
536
+ delete process.env.MX_BUNDLED_CONFIG_DIR;
537
+ else
538
+ process.env.MX_BUNDLED_CONFIG_DIR = prev;
539
+ rmSync(evil, { recursive: true, force: true });
540
+ }
541
+ });
542
+ it('SF4: an oversize settings.json is unknown, not read', () => {
543
+ writeFileSync(join(worktree, '.claude', 'settings.json'), 'x'.repeat(1024 * 1024 + 10));
544
+ const r = probePushBlock(input());
545
+ expect(r.state).toBe('unknown');
546
+ expect(r.reason).toMatch(/probe cap|not valid JSON/);
547
+ });
548
+ it('SF4: an exhausted budget yields unknown without further filesystem work', () => {
549
+ const r = probeContainment(input({ budgetStartedAt: Date.now() - 5000 }));
550
+ expect(r.state).toBe('unknown');
551
+ expect(r.reason).toMatch(/100ms budget/);
552
+ });
553
+ it('INFORMATIONAL: worktreePath === projectRoot is a fail, not a pass', () => {
554
+ const r = probeContainment(input({ worktreePath: root, cwd: root }));
555
+ expect(r.state).toBe('fail');
556
+ expect(r.reason).toMatch(/project root — no worktree isolation/);
557
+ });
558
+ });
559
+ // ── Mutation sensitivity: a deleted probe must fail a test ───────────────────
560
+ //
561
+ // The FL-2 defect was a banner line with no probe behind it. These assert that
562
+ // each probe's checks are load-bearing: if a future edit drops one, the fixture
563
+ // that breaks that specific property stops being detected. Expressed as
564
+ // "breaking property X must not leave state 'pass'", which is exactly what fails
565
+ // if the corresponding check is deleted from the probe.
566
+ describe('mutation sensitivity', () => {
567
+ it('containment: every injected fault is detected (no fault reads as pass)', () => {
568
+ const faults = [
569
+ ['cwd outside worktree', () => input({ cwd: root })],
570
+ ['worktree absent', () => input({ worktreePath: join(root, '.worktrees', 'nope') })],
571
+ ['guard deleted', () => { unlinkSync(join(worktree, '.claude', 'hooks', 'worktree-guard.sh')); return input(); }],
572
+ ['guard stale', () => { writeFileSync(join(worktree, '.claude', 'hooks', 'worktree-guard.sh'), 'drift'); return input(); }],
573
+ ['settings absent', () => { unlinkSync(join(worktree, '.claude', 'settings.json')); return input(); }],
574
+ ];
575
+ for (const [label, build] of faults) {
576
+ makeFixture();
577
+ const r = probeContainment(build());
578
+ expect(r.state, `fault not detected: ${label}`).not.toBe('pass');
579
+ expect(r.reason, `no reason for: ${label}`).toBeTruthy();
580
+ }
581
+ });
582
+ it('branchPin: every injected fault is detected', () => {
583
+ const faults = [
584
+ ['on base branch', () => input({ currentBranch: 'main' })],
585
+ ['detached HEAD', () => input({ currentBranch: 'HEAD' })],
586
+ ['branch unreadable', () => input({ currentBranch: null })],
587
+ ['deny rule removed', () => { makeFixture({ deny: DENY_ALL.filter((d) => d !== 'Bash(git switch main)') }); return input(); }],
588
+ ['guard stale', () => { writeFileSync(join(worktree, '.claude', 'hooks', 'worktree-guard.sh'), 'drift'); return input(); }],
589
+ ];
590
+ for (const [label, build] of faults) {
591
+ makeFixture();
592
+ const r = probeBranchPin(build());
593
+ expect(r.state, `fault not detected: ${label}`).not.toBe('pass');
594
+ }
595
+ });
596
+ it('pushBlock: every injected fault is detected', () => {
597
+ const faults = [
598
+ ['deny rule removed', () => { makeFixture({ deny: DENY_ALL.filter((d) => d !== 'Bash(git push origin main)') }); return input(); }],
599
+ ['deny list emptied', () => { makeFixture({ deny: [] }); return input(); }],
600
+ ['guard deleted', () => { unlinkSync(join(worktree, '.claude', 'hooks', 'worktree-guard.sh')); return input(); }],
601
+ ['guard stale', () => { writeFileSync(join(worktree, '.claude', 'hooks', 'worktree-guard.sh'), 'drift'); return input(); }],
602
+ ['settings absent', () => { unlinkSync(join(worktree, '.claude', 'settings.json')); return input(); }],
603
+ ];
604
+ for (const [label, build] of faults) {
605
+ makeFixture();
606
+ const r = probePushBlock(build());
607
+ expect(r.state, `fault not detected: ${label}`).not.toBe('pass');
608
+ }
609
+ });
610
+ });
611
+ //# sourceMappingURL=isolation-probe.test.js.map