pi-odd-worktree 3.1.0 → 3.2.0

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,516 @@
1
+ 'use strict';
2
+ // S4 (L2): the `edit`/`write` guard, decided from the paths a call touches, plus the
3
+ // `tool_call` wiring the host actually receives.
4
+ //
5
+ // The rule is one sentence: a path that lies inside the PRINCIPAL checkout of the
6
+ // session's own repository, while that checkout is on the repository's default branch,
7
+ // is refused before it is written. Everything else passes — and the pass list is the
8
+ // bigger half of this file, because L2 is what the human asked for: a path outside
9
+ // every repository, a path under the OS temp directories (even a scratch repository
10
+ // there), a path in another repository, a path in a linked worktree, a session outside
11
+ // version control, an unreadable identity, a detached HEAD, another branch, a default
12
+ // branch that does not resolve, and a path that cannot be placed at all.
13
+ //
14
+ // The block cases need a directory that really exists and is NOT under a temp
15
+ // directory, because a temp path is exempt by the rule itself. They use the checkout
16
+ // this suite runs in: the guard only realpaths directories, so nothing is written and
17
+ // no fixture repository is created for them. The linked/temp cases use throwaway
18
+ // directories under the system temp directory, removed in teardown.
19
+ //
20
+ // The wiring half stubs the two git answers the extension reads (the checkout's
21
+ // identity and its branch), because a repository cannot be created outside the temp
22
+ // directories a test may write to, and a temp repository must pass (L2). What is
23
+ // under test there is the plumbing: the registered handler, the paths it reads, the
24
+ // reason it returns, the switch, and the fact that `bash` is judged exactly as before.
25
+
26
+ const { test, describe, before, after } = require('node:test');
27
+ const assert = require('node:assert/strict');
28
+ const fs = require('node:fs');
29
+ const os = require('node:os');
30
+ const path = require('node:path');
31
+
32
+ const { decideWriteGuard } = require('../lib/worktree-guard.js');
33
+ const { loadExtension } = require('./fixtures/load-extension.js');
34
+
35
+ const WORKTREE_ADD_REFUSAL = '`git worktree add` did not run: create the ODD\'s checkout with `worktree_create`.';
36
+ const BRANCH_SWITCH_REFUSAL = 'The branch switch did not run: the principal checkout stays on its default branch. Create the ODD\'s checkout with `worktree_create`.';
37
+
38
+ // The one sentence S4 states, written out here: a reworded sentence fails this file.
39
+ function refusal(file, branch = 'main') {
40
+ return `${file} is in the primary checkout on \`${branch}\`. Work in a worktree (\`worktree_list\` / \`worktree_create\`).`;
41
+ }
42
+
43
+ // A real checkout that is NOT under an OS temp directory: the one this suite runs in.
44
+ // Only directories are realpath'd; nothing is written there.
45
+ const PRINCIPAL = fs.realpathSync(path.resolve(__dirname, '..'));
46
+ // The guard exempts every temp path by rule (L2), so a suite that itself runs from a temp
47
+ // directory cannot use its own checkout as a refused fixture: those cases skip there, and
48
+ // the virtual-principal cases at the bottom of this file still cover the refusal.
49
+ const UNDER_TEMP = [...new Set(['/tmp', '/var/tmp', os.tmpdir(), process.env.TMPDIR].filter(Boolean).flatMap((dir) => {
50
+ const spellings = [path.resolve(dir)];
51
+ try { spellings.push(fs.realpathSync(dir)); } catch { /* an absent temp dir contributes its spelling only */ }
52
+ return spellings;
53
+ }))].some((root) => PRINCIPAL === root || PRINCIPAL.startsWith(`${root}${path.sep}`));
54
+ const NEEDS_NON_TEMP = UNDER_TEMP ? 'the suite checkout lives under a temp directory, which the guard exempts' : false;
55
+ const PRINCIPAL_FILE = path.join(PRINCIPAL, 'lib', 'not-yet-there.js');
56
+ // The one directory the fake identities spell as the shared git dir of PRINCIPAL.
57
+ const PRINCIPAL_COMMON = path.join(PRINCIPAL, '.git');
58
+
59
+ const scratchDirs = [];
60
+
61
+ function scratch(tag) {
62
+ const dir = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), `odd-write-guard-${tag}-`)));
63
+ scratchDirs.push(dir);
64
+ return dir;
65
+ }
66
+
67
+ after(() => {
68
+ for (const dir of scratchDirs) {
69
+ try {
70
+ fs.rmSync(dir, { recursive: true, force: true });
71
+ } catch {
72
+ // Best effort: a directory that is already gone is fine.
73
+ }
74
+ }
75
+ });
76
+
77
+ // The module's one entry point over fake seams. Each seam counts its reads, so "read
78
+ // only when the rule needs it" is observable, and a seam may be an Error to prove the
79
+ // guard fails open.
80
+ function harness(options = {}) {
81
+ const reads = { identity: 0, defaultBranch: 0, currentBranch: 0 };
82
+ const identity = 'identity' in options
83
+ ? options.identity
84
+ : { root: PRINCIPAL, commonDir: PRINCIPAL_COMMON };
85
+ const defaultBranch = 'defaultBranch' in options ? options.defaultBranch : 'main';
86
+ const currentBranch = 'currentBranch' in options ? options.currentBranch : 'main';
87
+ const run = (paths, callOptions = {}) => decideWriteGuard({
88
+ toolName: 'toolName' in callOptions ? callOptions.toolName : 'edit',
89
+ paths,
90
+ cwd: 'cwd' in callOptions ? callOptions.cwd : PRINCIPAL,
91
+ repoIdentity: (cwd) => {
92
+ reads.identity += 1;
93
+ if (identity instanceof Error) throw identity;
94
+ return typeof identity === 'function' ? identity(cwd) : identity;
95
+ },
96
+ defaultBranch: (root) => {
97
+ reads.defaultBranch += 1;
98
+ if (defaultBranch instanceof Error) throw defaultBranch;
99
+ return typeof defaultBranch === 'function' ? defaultBranch(root) : defaultBranch;
100
+ },
101
+ currentBranch: (root) => {
102
+ reads.currentBranch += 1;
103
+ if (currentBranch instanceof Error) throw currentBranch;
104
+ return typeof currentBranch === 'function' ? currentBranch(root) : currentBranch;
105
+ },
106
+ });
107
+ return { run, reads };
108
+ }
109
+
110
+ // ---- S4: the refusal itself ----
111
+
112
+ describe('the refusal is one sentence (S4)', () => {
113
+ test('a path inside the primary checkout on the default branch is refused with the exact sentence', { skip: NEEDS_NON_TEMP }, () => {
114
+ const { run } = harness();
115
+ assert.deepEqual(run([PRINCIPAL_FILE]), { block: true, reason: refusal(PRINCIPAL_FILE) });
116
+ });
117
+
118
+ test('the sentence carries the real path and the real default branch, and nothing else', { skip: NEEDS_NON_TEMP }, () => {
119
+ const { run } = harness({ defaultBranch: 'trunk', currentBranch: 'trunk' });
120
+ const decision = run([PRINCIPAL_FILE]);
121
+ assert.equal(decision.reason, refusal(PRINCIPAL_FILE, 'trunk'));
122
+ assert.equal(decision.reason.includes('main'), false, 'no `main` is assumed');
123
+ assert.equal(decision.reason.split('. ').length, 2, 'one sentence, then the reminder');
124
+ assert.equal(decision.reason.includes('!'), false, 'no exclamation');
125
+ assert.equal(/[\u{1F300}-\u{1FAFF}\u{2600}-\u{27BF}]/u.test(decision.reason), false, 'no emoji');
126
+ assert.ok(decision.reason.endsWith('.'), 'ends with a period');
127
+ for (const tool of ['`worktree_list`', '`worktree_create`']) {
128
+ assert.ok(decision.reason.includes(tool), `names ${tool}`);
129
+ }
130
+ });
131
+
132
+ test('both writing tools are guarded, and a `write` of a new file is judged by its directory', { skip: NEEDS_NON_TEMP }, () => {
133
+ // A nested path whose own directory exists and whose file does not: nothing is
134
+ // created, and the directory is still what places it.
135
+ const nested = path.join(PRINCIPAL, 'lib', 'odd-prompt', 'child-probe.md');
136
+ for (const toolName of ['edit', 'write']) {
137
+ const { run } = harness();
138
+ assert.deepEqual(run([nested], { toolName }), { block: true, reason: refusal(nested) }, toolName);
139
+ }
140
+ });
141
+
142
+ test('a relative path is resolved against the session cwd and reported absolute', { skip: NEEDS_NON_TEMP }, () => {
143
+ const { run } = harness();
144
+ assert.deepEqual(run(['lib/not-yet-there.js']), { block: true, reason: refusal(PRINCIPAL_FILE) });
145
+ });
146
+
147
+ test('one path inside the checkout refuses the call even when another passes', { skip: NEEDS_NON_TEMP }, () => {
148
+ const loose = scratch('loose');
149
+ const { run } = harness();
150
+ assert.deepEqual(run([path.join(loose, 'a.txt'), PRINCIPAL_FILE]), { block: true, reason: refusal(PRINCIPAL_FILE) });
151
+ });
152
+ });
153
+
154
+ // ---- L2: everything else passes ----
155
+
156
+ describe('L2: a path the guard cannot place in the session\'s repository passes', () => {
157
+ test('a path outside every repository passes, and a temp path reads no repository state', () => {
158
+ const loose = scratch('outside');
159
+ fs.writeFileSync(path.join(loose, 'plan.txt'), 'x\n');
160
+ const { run, reads } = harness();
161
+ assert.deepEqual(run([path.join(loose, 'plan.txt')]), { block: false });
162
+ assert.deepEqual(run([path.join(loose, 'new-file.txt')]), { block: false });
163
+ assert.deepEqual(reads, { identity: 0, defaultBranch: 0, currentBranch: 0 },
164
+ 'a path a checkout cannot own is settled before any git answer is asked for');
165
+ });
166
+
167
+ test('a path under the OS temp directory passes even when a scratch repository lives there', { skip: NEEDS_NON_TEMP }, () => {
168
+ const repo = scratch('scratch-repo');
169
+ fs.mkdirSync(path.join(repo, '.git'), { recursive: true });
170
+ const identity = { root: repo, commonDir: path.join(repo, '.git') };
171
+ const temp = harness({ identity, cwd: repo });
172
+ assert.deepEqual(temp.run([path.join(repo, 'scratch.txt')], { cwd: repo }), { block: false });
173
+ assert.deepEqual(temp.run(['scratch.txt'], { cwd: repo }), { block: false });
174
+ assert.deepEqual(temp.reads, { identity: 0, defaultBranch: 0, currentBranch: 0 },
175
+ 'a temp path costs no git at all, whatever repository it is in');
176
+ // The very same path shape outside the temp directories is placed, and then it is
177
+ // another repository's file, so it passes for that reason instead.
178
+ const outside = harness({ identity, cwd: repo });
179
+ assert.deepEqual(outside.run([PRINCIPAL_FILE], { cwd: repo }), { block: false });
180
+ assert.equal(outside.reads.identity, 1, 'a non-temp path asks which checkout the session stands in');
181
+ });
182
+
183
+ test('a path under TMPDIR passes, and so does one under /tmp', () => {
184
+ const saved = process.env.TMPDIR;
185
+ const dir = scratch('tmpdir');
186
+ process.env.TMPDIR = dir;
187
+ try {
188
+ const identity = { root: dir, commonDir: path.join(dir, '.git') };
189
+ const { run } = harness({ identity, cwd: dir });
190
+ assert.deepEqual(run([path.join(dir, 'a.txt')], { cwd: dir }), { block: false });
191
+ assert.deepEqual(run([path.join(os.tmpdir(), 'odd-write-guard-probe', 'a.txt')]), { block: false });
192
+ assert.deepEqual(run(['/tmp/odd-write-guard-probe.txt']), { block: false });
193
+ assert.deepEqual(run(['/var/tmp/odd-write-guard-probe.txt']), { block: false });
194
+ } finally {
195
+ if (saved === undefined) delete process.env.TMPDIR;
196
+ else process.env.TMPDIR = saved;
197
+ }
198
+ });
199
+
200
+ test('a path in another repository than the session\'s cwd passes', () => {
201
+ const other = scratch('other-repo');
202
+ fs.mkdirSync(path.join(other, '.git'), { recursive: true });
203
+ // The session stands in the other repository, and the path is in PRINCIPAL: another
204
+ // repository's file, so nothing is judged.
205
+ const identity = (cwd) => (path.resolve(String(cwd)) === other
206
+ ? { root: other, commonDir: path.join(other, '.git') }
207
+ : undefined);
208
+ const { run } = harness({ identity, cwd: other });
209
+ assert.deepEqual(run([PRINCIPAL_FILE], { cwd: other }), { block: false });
210
+ assert.deepEqual(run([path.join(other, 'a.txt')], { cwd: other }), { block: false });
211
+ });
212
+
213
+ test('a path inside a linked worktree passes, and so does any path when the session stands in one', () => {
214
+ const linked = scratch('linked');
215
+ const identity = { root: linked, commonDir: PRINCIPAL_COMMON };
216
+ const { run } = harness({ identity, cwd: linked });
217
+ assert.deepEqual(run([path.join(linked, 'note.md')], { cwd: linked }), { block: false });
218
+ assert.deepEqual(run([path.join(linked, 'odd', 'tasks', 'plan.md')], { cwd: linked }), { block: false });
219
+ });
220
+
221
+ test('a linked worktree or a nested repository that lives INSIDE the principal directory passes: the path\'s own checkout decides', { skip: NEEDS_NON_TEMP }, () => {
222
+ const nested = path.join(PRINCIPAL, 'lib');
223
+ const identity = (cwd) => (cwd === nested
224
+ ? { root: nested, commonDir: PRINCIPAL_COMMON }
225
+ : { root: PRINCIPAL, commonDir: PRINCIPAL_COMMON });
226
+ const { run } = harness({ identity });
227
+ assert.deepEqual(run([path.join(nested, 'a.js')]), { block: false });
228
+ assert.equal(run([PRINCIPAL_FILE.replace(`${path.sep}lib${path.sep}`, `${path.sep}docs${path.sep}`)]).block, true, 'the principal\'s own directories still block');
229
+ });
230
+
231
+ test('a session cwd outside version control passes, and reads no branch', () => {
232
+ const loose = scratch('no-repo');
233
+ for (const identity of [new Error('not a git repository'), undefined, null, {}, { root: '/' }, { commonDir: 'x' }]) {
234
+ const { run, reads } = harness({ identity, cwd: loose });
235
+ assert.deepEqual(run([path.join(loose, 'a.txt')], { cwd: loose }), { block: false }, String(identity));
236
+ assert.deepEqual(run([PRINCIPAL_FILE], { cwd: loose }), { block: false }, String(identity));
237
+ assert.equal(reads.currentBranch, 0, `${String(identity)}: no branch is read`);
238
+ assert.equal(reads.defaultBranch, 0, `${String(identity)}: no default branch is read`);
239
+ }
240
+ });
241
+
242
+ test('a detached HEAD, an unreadable branch and another branch never block', () => {
243
+ for (const currentBranch of [undefined, '', new Error('detached HEAD'), 'feat/odd-a', 'develop']) {
244
+ const { run } = harness({ currentBranch });
245
+ assert.deepEqual(run([PRINCIPAL_FILE]), { block: false }, String(currentBranch));
246
+ }
247
+ });
248
+
249
+ test('a default branch that does not resolve blocks nothing', () => {
250
+ for (const defaultBranch of [undefined, '', new Error('git config failed')]) {
251
+ const { run } = harness({ defaultBranch });
252
+ assert.deepEqual(run([PRINCIPAL_FILE]), { block: false }, String(defaultBranch));
253
+ }
254
+ });
255
+
256
+ test('a principal checkout named by a common dir that is not a `.git` fails open', () => {
257
+ const separate = { root: PRINCIPAL, commonDir: path.join(PRINCIPAL, 'git-dir') };
258
+ const { run } = harness({ identity: separate });
259
+ assert.deepEqual(run([PRINCIPAL_FILE]), { block: false });
260
+ });
261
+
262
+ test('a path whose directory cannot be resolved passes', () => {
263
+ const absent = path.join(PRINCIPAL, 'not-a-directory-of-this-repository', 'file.md');
264
+ const { run } = harness();
265
+ assert.deepEqual(run([absent]), { block: false });
266
+ });
267
+
268
+ test('a symlink into the primary checkout is judged by the real directory, and one out of it too', { skip: NEEDS_NON_TEMP }, () => {
269
+ const links = scratch('links');
270
+ fs.symlinkSync(path.join(PRINCIPAL, 'lib'), path.join(links, 'into-lib'), 'dir');
271
+ const tempRepo = scratch('linked-target');
272
+ fs.mkdirSync(path.join(tempRepo, '.git'), { recursive: true });
273
+ fs.symlinkSync(tempRepo, path.join(links, 'into-temp'), 'dir');
274
+ try {
275
+ // A temp spelling of a primary path does not dodge the check...
276
+ const { run } = harness();
277
+ assert.deepEqual(
278
+ run([path.join(links, 'into-lib', 'not-yet-there.js')]),
279
+ { block: true, reason: refusal(PRINCIPAL_FILE) },
280
+ );
281
+ // ...and a primary-looking spelling of a temp path does not false-trip it.
282
+ const identity = { root: PRINCIPAL, commonDir: PRINCIPAL_COMMON };
283
+ const other = harness({ identity });
284
+ assert.deepEqual(other.run([path.join(links, 'into-temp', 'a.txt')]), { block: false });
285
+ } finally {
286
+ for (const name of ['into-lib', 'into-temp']) {
287
+ try {
288
+ fs.unlinkSync(path.join(links, name));
289
+ } catch {
290
+ // The scratch directory is removed in teardown anyway.
291
+ }
292
+ }
293
+ }
294
+ });
295
+
296
+ test('every other tool passes, reading no repository state at all', () => {
297
+ for (const toolName of ['read', 'bash', 'grep', 'find', 'ls', 'worktree_create', 'worktree_list', 'odd_write']) {
298
+ const { run, reads } = harness();
299
+ assert.deepEqual(run([PRINCIPAL_FILE], { toolName }), { block: false }, toolName);
300
+ assert.deepEqual(reads, { identity: 0, defaultBranch: 0, currentBranch: 0 }, `${toolName} reads nothing`);
301
+ }
302
+ });
303
+ });
304
+
305
+ // ---- S8: honest failure, never a throw and never a false block ----
306
+
307
+ describe('S8: an unreadable repository fails open, and nothing throws', () => {
308
+ test('a seam that throws never escapes and never blocks', () => {
309
+ for (const options of [
310
+ { identity: new Error('boom') },
311
+ { defaultBranch: new Error('boom') },
312
+ { currentBranch: new Error('boom') },
313
+ { identity: new Error('boom'), defaultBranch: new Error('boom'), currentBranch: new Error('boom') },
314
+ ]) {
315
+ const { run } = harness(options);
316
+ assert.deepEqual(run([PRINCIPAL_FILE]), { block: false }, JSON.stringify(Object.keys(options)));
317
+ }
318
+ });
319
+
320
+ test('input that names nothing decides nothing', () => {
321
+ const { run } = harness();
322
+ for (const paths of [undefined, null, [], [''], [42], [{}]]) {
323
+ assert.deepEqual(run(paths), { block: false }, String(paths));
324
+ }
325
+ assert.deepEqual(decideWriteGuard(undefined), { block: false });
326
+ assert.deepEqual(decideWriteGuard({}), { block: false });
327
+ assert.deepEqual(decideWriteGuard({ toolName: 'write', paths: [PRINCIPAL_FILE] }), { block: false },
328
+ 'no cwd, no identity seam: nothing is judged');
329
+ });
330
+
331
+ test('an unknown cwd decides nothing', () => {
332
+ const { run, reads } = harness();
333
+ for (const cwd of [undefined, null, '', 0]) {
334
+ assert.deepEqual(run([PRINCIPAL_FILE], { cwd }), { block: false }, String(cwd));
335
+ }
336
+ assert.deepEqual(reads, { identity: 0, defaultBranch: 0, currentBranch: 0 }, 'nothing is read');
337
+ });
338
+
339
+ test('a block reads the session identity, the owner of the path and each branch once, and only after a path was placed', { skip: NEEDS_NON_TEMP }, () => {
340
+ const { run, reads } = harness();
341
+ assert.deepEqual(run([PRINCIPAL_FILE, path.join(PRINCIPAL, 'README.md')]), { block: true, reason: refusal(PRINCIPAL_FILE) });
342
+ assert.deepEqual(reads, { identity: 2, defaultBranch: 1, currentBranch: 1 });
343
+ });
344
+ });
345
+
346
+ // ---- S4: the handler the host actually receives ----
347
+
348
+ const bash = (command) => ({ toolName: 'bash', input: { command } });
349
+ const edit = (file) => ({ toolName: 'edit', input: { path: file } });
350
+ const write = (file) => ({ toolName: 'write', input: { path: file, content: 'x\n' } });
351
+
352
+ describe('the tool_call handler the extension registers (S4)', () => {
353
+ let loaded;
354
+ let git;
355
+ let linked;
356
+ let principalBranch;
357
+ let savedIdentity;
358
+ let savedRunArgv;
359
+
360
+ // The first block answer is the block the host sees, exactly as the host walks its
361
+ // handlers.
362
+ async function callTool(event, cwd) {
363
+ for (const [name, handler] of loaded.hooks) {
364
+ if (name !== 'tool_call') continue;
365
+ const answer = await handler(event, { cwd });
366
+ if (answer !== undefined) return answer;
367
+ }
368
+ return undefined;
369
+ }
370
+
371
+ const principalIdentity = { root: PRINCIPAL, commonDir: PRINCIPAL_COMMON };
372
+ const linkedIdentity = () => ({ root: linked, commonDir: PRINCIPAL_COMMON });
373
+
374
+ before(async () => {
375
+ loaded = await loadExtension({});
376
+ // The lib instance the extension itself calls: its git answers are the seams the
377
+ // guard reads, so the fake world below reaches the real handler.
378
+ git = require('../lib/worktree-git.js');
379
+ linked = scratch('wiring-linked');
380
+ fs.writeFileSync(path.join(linked, 'note.md'), '# note\n');
381
+ principalBranch = 'main';
382
+ savedIdentity = git.repoIdentity;
383
+ savedRunArgv = git.runArgv;
384
+ git.repoIdentity = (cwd) => {
385
+ const resolved = path.resolve(String(cwd));
386
+ if (resolved === PRINCIPAL || resolved.startsWith(`${PRINCIPAL}${path.sep}`)) return principalIdentity;
387
+ if (resolved === linked) return linkedIdentity();
388
+ throw new Error(`not a git repository: ${cwd}`);
389
+ };
390
+ git.runArgv = (_bin, args, opts = {}) => {
391
+ const key = Array.isArray(args) ? args.join(' ') : '';
392
+ const cwd = typeof opts.cwd === 'string' ? path.resolve(opts.cwd) : '';
393
+ if (key === 'rev-parse --verify --quiet refs/heads/main') {
394
+ return { status: 0, stdout: 'a1b2c3\n', stderr: '', error: null };
395
+ }
396
+ if (key === 'symbolic-ref --quiet --short HEAD') {
397
+ // Read fresh on every call, exactly as the guard asks it.
398
+ const name = cwd === PRINCIPAL ? principalBranch : 'feat/linked';
399
+ return name.length === 0
400
+ ? { status: 1, stdout: '', stderr: '', error: null }
401
+ : { status: 0, stdout: `${name}\n`, stderr: '', error: null };
402
+ }
403
+ return { status: 1, stdout: '', stderr: '', error: null };
404
+ };
405
+ });
406
+
407
+ after(() => {
408
+ if (git && savedIdentity !== undefined) git.repoIdentity = savedIdentity;
409
+ if (git && savedRunArgv !== undefined) git.runArgv = savedRunArgv;
410
+ });
411
+
412
+ test('an edit and a write into the primary checkout on main are refused with the sentence', { skip: NEEDS_NON_TEMP }, async () => {
413
+ principalBranch = 'main';
414
+ const target = path.join(PRINCIPAL, 'lib', 'wiring-probe.js');
415
+ const second = path.join(PRINCIPAL, 'lib', 'wiring-probe-2.js');
416
+ assert.deepEqual(await callTool(edit(target), PRINCIPAL), { block: true, reason: refusal(target) });
417
+ assert.deepEqual(await callTool(write(second), PRINCIPAL), { block: true, reason: refusal(second) });
418
+ assert.deepEqual(await callTool(edit('lib/wiring-probe.js'), PRINCIPAL), { block: true, reason: refusal(target) });
419
+ });
420
+
421
+ test('the same call in a linked worktree passes', async () => {
422
+ principalBranch = 'main';
423
+ assert.equal(await callTool(edit(path.join(linked, 'note.md')), linked), undefined);
424
+ assert.equal(await callTool(write(path.join(linked, 'other.md')), linked), undefined);
425
+ });
426
+
427
+ test('a primary checkout on another branch passes, and the branch is read fresh', { skip: NEEDS_NON_TEMP }, async () => {
428
+ const target = path.join(PRINCIPAL, 'lib', 'wiring-probe.js');
429
+ principalBranch = 'feat/elsewhere';
430
+ assert.equal(await callTool(edit(target), PRINCIPAL), undefined);
431
+ principalBranch = 'main';
432
+ assert.deepEqual(await callTool(edit(target), PRINCIPAL), { block: true, reason: refusal(target) });
433
+ principalBranch = '';
434
+ assert.equal(await callTool(edit(target), PRINCIPAL), undefined, 'a detached HEAD blocks nothing');
435
+ });
436
+
437
+ test('a read anywhere, and a bash call, are judged exactly as before', async () => {
438
+ principalBranch = 'main';
439
+ const target = path.join(PRINCIPAL, 'README.md');
440
+ assert.equal(await callTool({ toolName: 'read', input: { path: target } }, PRINCIPAL), undefined);
441
+ assert.equal(await callTool({ toolName: 'grep', input: { pattern: 'x', path: PRINCIPAL } }, PRINCIPAL), undefined);
442
+ assert.deepEqual(await callTool(bash('git worktree add ../odd-b'), PRINCIPAL), { block: true, reason: WORKTREE_ADD_REFUSAL });
443
+ assert.deepEqual(await callTool(bash('git worktree list --porcelain'), PRINCIPAL), { block: true, reason: '`git worktree list` did not run: use `worktree_list` (`all: true` also shows checkouts outside `<repo-name>-worktrees`).' });
444
+ assert.deepEqual(await callTool(bash('git switch develop'), PRINCIPAL), { block: true, reason: BRANCH_SWITCH_REFUSAL });
445
+ assert.equal(await callTool(bash('git switch develop'), linked), undefined);
446
+ assert.equal(await callTool(bash('git status'), PRINCIPAL), undefined);
447
+ });
448
+
449
+ test('ODD_WORKTREE_GUARD=0 turns the write guard off, and only that value', { skip: NEEDS_NON_TEMP }, async () => {
450
+ const previous = process.env.ODD_WORKTREE_GUARD;
451
+ principalBranch = 'main';
452
+ const target = path.join(PRINCIPAL, 'lib', 'wiring-probe.js');
453
+ try {
454
+ for (const value of ['0', 'false', '', '1']) {
455
+ process.env.ODD_WORKTREE_GUARD = value;
456
+ const answer = await callTool(edit(target), PRINCIPAL);
457
+ if (value === '0') assert.equal(answer, undefined, 'value "0" turns it off with the bash guards');
458
+ else assert.deepEqual(answer, { block: true, reason: refusal(target) }, `value ${JSON.stringify(value)}`);
459
+ }
460
+ delete process.env.ODD_WORKTREE_GUARD;
461
+ assert.deepEqual(await callTool(edit(target), PRINCIPAL), { block: true, reason: refusal(target) }, 'unset keeps it on');
462
+ } finally {
463
+ if (previous === undefined) delete process.env.ODD_WORKTREE_GUARD;
464
+ else process.env.ODD_WORKTREE_GUARD = previous;
465
+ }
466
+ });
467
+ });
468
+
469
+ // ---- S4: two defects the independent verification found, pinned where they cannot hide ----
470
+
471
+ // A virtual principal checkout that is NOT under a temp directory and does not exist on
472
+ // disk: `fs.realpathSync` is mocked for its two directories only, and the extension's git
473
+ // answers are faked, so these cases run from any checkout location (a temp one included).
474
+ async function virtualPrimary(t) {
475
+ const { hooks } = await loadExtension({});
476
+ const git = require('../lib/worktree-git.js');
477
+ const root = path.join(path.parse(process.cwd()).root, '__odd_virtual_primary__');
478
+ const dir = path.join(root, 'nested');
479
+ const file = path.join(dir, 'note.md');
480
+ const commonDir = path.join(root, '.git');
481
+ const realpath = fs.realpathSync;
482
+ let nested = false;
483
+ t.mock.method(fs, 'realpathSync', (p, ...args) => (p === root || p === dir ? p : realpath(p, ...args)));
484
+ t.mock.method(git, 'repoIdentity', (p) => ({ root: nested && path.resolve(String(p)) === dir ? dir : root, commonDir }));
485
+ t.mock.method(git, 'runArgv', (_bin, args) => {
486
+ const command = args.join(' ');
487
+ if (command === 'symbolic-ref --quiet --short HEAD') return { status: 0, stdout: 'main\n' };
488
+ if (command === 'rev-parse --verify --quiet refs/heads/main') return { status: 0, stdout: 'abc\n' };
489
+ return { status: 1, stdout: '' };
490
+ });
491
+ return {
492
+ file,
493
+ makeNested: () => { nested = true; },
494
+ async call(raw) {
495
+ for (const [name, hook] of hooks) {
496
+ if (name !== 'tool_call') continue;
497
+ const result = await hook(edit(raw), { cwd: root });
498
+ if (result !== undefined) return result;
499
+ }
500
+ return undefined;
501
+ },
502
+ };
503
+ }
504
+
505
+ test('S4: the `@` prefix Pi strips from a path does not change the guard decision', async (t) => {
506
+ const { call, file } = await virtualPrimary(t);
507
+ assert.deepEqual(await call(`@${file}`), { block: true, reason: refusal(file) });
508
+ assert.deepEqual(await call(file), { block: true, reason: refusal(file) });
509
+ });
510
+
511
+ test('S4: who owns the path\'s directory is asked again, never remembered, after a nested worktree appears', async (t) => {
512
+ const { call, file, makeNested } = await virtualPrimary(t);
513
+ assert.deepEqual(await call(file), { block: true, reason: refusal(file) });
514
+ makeNested();
515
+ assert.equal(await call(file), undefined);
516
+ });