fix(#260): enforce worktree absolute-path safety via PreToolUse hook

Closes #260

Moves the step-0b absolute-path guard from prose instructions to a harness-enforced PreToolUse hook (gsd-worktree-path-guard.js). Hard-blocks Edit/Write/MultiEdit calls whose absolute path resolves outside the active worktree root.
This commit is contained in:
Tom Boucher
2026-06-01 10:56:06 -04:00
committed by GitHub
parent 4332e1a5dd
commit faf329ecb9
10 changed files with 632 additions and 2 deletions

View File

@@ -0,0 +1,5 @@
---
type: Fixed
pr: 579
---
Worktree executor agents no longer leak writes to the main checkout: a new PreToolUse hook (gsd-worktree-path-guard.js) hard-blocks Edit/Write/MultiEdit calls whose absolute path resolves outside the active worktree root.

View File

@@ -9944,6 +9944,33 @@ function install(isGlobal, runtime = 'claude', options = {}) {
console.warn(` ${yellow}⚠${reset} Skipped workflow guard hook — gsd-workflow-guard.js not found at target`);
}
// Configure PreToolUse hook for worktree absolute-path safety (#260)
// Hard-blocks Edit/Write/MultiEdit tool calls with absolute paths that resolve
// outside the current worktree root. Prevents executor agents from
// accidentally writing to the main checkout when running in isolation="worktree".
const worktreePathGuardCommand = isGlobal
? buildHookCommand(targetDir, 'gsd-worktree-path-guard.js', hookOpts)
: localCmd('gsd-worktree-path-guard.js');
const hasWorktreePathGuardHook = settings.hooks[preToolEvent].some(entry =>
entry.hooks && entry.hooks.some(h => h.command && h.command.includes('gsd-worktree-path-guard'))
);
const worktreePathGuardFile = path.join(targetDir, 'hooks', 'gsd-worktree-path-guard.js');
if (!hasWorktreePathGuardHook && fs.existsSync(worktreePathGuardFile) && worktreePathGuardCommand) {
settings.hooks[preToolEvent].push({
matcher: 'Write|Edit|MultiEdit',
hooks: [
{
type: 'command',
command: worktreePathGuardCommand,
timeout: 5
}
]
});
console.log(` ${green}✓${reset} Configured worktree path guard hook`);
} else if (!hasWorktreePathGuardHook && !fs.existsSync(worktreePathGuardFile)) {
console.warn(` ${yellow}⚠${reset} Skipped worktree path guard hook — gsd-worktree-path-guard.js not found at target`);
}
// Configure commit validation hook (Conventional Commits enforcement, opt-in)
const validateCommitCommand = isGlobal
? buildHookCommand(targetDir, 'gsd-validate-commit.sh', hookOpts)

View File

@@ -355,7 +355,8 @@
"gsd-statusline.js",
"gsd-update-banner.js",
"gsd-validate-commit.sh",
"gsd-workflow-guard.js"
"gsd-workflow-guard.js",
"gsd-worktree-path-guard.js"
]
}
}

View File

@@ -455,7 +455,7 @@ Full listing: `get-shit-done/bin/lib/*.cjs`.
---
## Hooks (13 shipped)
## Hooks (14 shipped)
Full listing: `hooks/`.
@@ -470,6 +470,7 @@ Full listing: `hooks/`.
| `gsd-workflow-guard.js` | `PreToolUse` | Detects file edits outside GSD workflow context (advisory, opt-in) |
| `gsd-read-guard.js` | `PreToolUse` | Advisory guard preventing Edit/Write on unread files |
| `gsd-read-injection-scanner.js` | `PostToolUse` | Scans tool Read results for prompt-injection patterns (v1.36+, PR #2201) |
| `gsd-worktree-path-guard.js` | `PreToolUse` | Hard-blocks Edit/Write/MultiEdit with absolute paths outside the worktree root (PR #579, #260) |
| `gsd-session-state.sh` | `PostToolUse` | Session-state tracking for shell-based runtimes |
| `gsd-validate-commit.sh` | `PostToolUse` | Commit validation for conventional-commit enforcement |
| `gsd-phase-boundary.sh` | `PostToolUse` | Phase-boundary detection for workflow transitions |

View File

@@ -122,6 +122,7 @@ const BUNDLED_GSD_HOOK_FILES = Object.freeze(new Set([
'hooks/gsd-update-banner.js',
'hooks/gsd-validate-commit.sh',
'hooks/gsd-workflow-guard.js',
'hooks/gsd-worktree-path-guard.js',
]));
// Classify a blocked prompt-user action into one of the safe-default

View File

@@ -0,0 +1,169 @@
#!/usr/bin/env node
// gsd-hook-version: {{GSD_VERSION}}
// GSD Worktree Path Guard — PreToolUse hook
// Blocks Edit/Write/MultiEdit tool calls that target absolute paths outside the worktree root.
//
// Problem: gsd-executor agents spawned with isolation="worktree" sometimes issue
// Edit/Write calls with absolute paths rooted at the MAIN repository instead of
// the worktree (issue #260). The prose guard in agents/gsd-executor.md step 0b
// is never enforced because the model under load skips it.
//
// This hook enforces the constraint at the tooling layer, making it HARD-BLOCKING.
//
// Triggers on: Edit, Write, and MultiEdit tool calls
// Action: BLOCK (exit 2) if file_path is absolute and outside the worktree root
// No-op: relative paths, non-worktree CWDs, hook errors (silent fail)
const fs = require('fs');
const path = require('path');
const { spawnSync } = require('child_process');
const SPAWNOPT = { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 2000 };
function git(args, cwd) {
return spawnSync('git', args, { ...SPAWNOPT, cwd });
}
// Walk up from `start` to find the nearest existing directory.
// Returns null if we reach the filesystem root without finding one.
function nearestExistingDir(start) {
let dir = start;
let prev;
do {
prev = dir;
try { fs.accessSync(dir, fs.constants.F_OK); return dir; } catch { /* keep walking */ }
dir = path.dirname(dir);
} while (dir !== prev);
return null;
}
let input = '';
const stdinTimeout = setTimeout(() => process.exit(0), 3000);
process.stdin.setEncoding('utf8');
process.stdin.on('data', chunk => input += chunk);
process.stdin.on('end', () => {
clearTimeout(stdinTimeout);
try {
const data = JSON.parse(input);
const toolName = data.tool_name;
// Only guard Edit, Write, and MultiEdit tool calls
if (toolName !== 'Edit' && toolName !== 'Write' && toolName !== 'MultiEdit') {
process.exit(0);
}
const cwd = data.cwd || process.cwd();
// Detect whether CWD is inside a linked git worktree by inspecting
// the git-dir path. In a linked worktree, git rev-parse --git-dir
// returns a path containing .git/worktrees/ as a component.
// In the main repo or a submodule it returns .git (or a path without /worktrees/).
// This approach works even when cwd is a subdirectory of the worktree.
const gitDirResult = git(['rev-parse', '--git-dir'], cwd);
if (gitDirResult.status !== 0 || !gitDirResult.stdout) {
process.exit(0); // not a git repo — pass through
}
const gitDir = gitDirResult.stdout.trim();
// A linked worktree's --git-dir contains .git/worktrees/ as a path component
const isLinkedWorktree = /[/\\]\.git[/\\]worktrees[/\\]/.test(gitDir);
if (!isLinkedWorktree) {
process.exit(0); // main repo, submodule, or separate-git-dir — no-op
}
// Get the raw --show-toplevel output for the worktree (cwd).
// We keep it raw (not path.resolve'd) to compare directly with the
// file's toplevel — same git binary, same format, no normalization needed.
const wtTopResult = git(['rev-parse', '--show-toplevel'], cwd);
if (wtTopResult.status !== 0 || !wtTopResult.stdout) {
process.exit(0); // can't determine root — fail open
}
const wtTopRaw = wtTopResult.stdout.trim();
const rawFilePath = data.tool_input?.file_path || '';
if (!rawFilePath) {
process.exit(0);
}
// Relative paths are always safe — they resolve relative to CWD inside the worktree
if (!path.isAbsolute(rawFilePath)) {
process.exit(0);
}
// Normalise .. traversal so /worktree/src/../../../main/file
// resolves to its true location before we check containment.
const filePath = path.resolve(rawFilePath);
// Find the nearest existing ancestor of filePath so we can ask git
// for its toplevel. The file itself may not exist yet (Write creates
// new files), but at least one ancestor directory must exist.
// We check the file itself first in case it already exists.
const checkDir = nearestExistingDir(
(() => {
try {
return fs.statSync(filePath).isDirectory() ? filePath : path.dirname(filePath);
} catch {
return path.dirname(filePath);
}
})()
);
if (!checkDir) {
// Walked to root without finding any directory — path is synthetic.
// Block conservatively.
const output = {
decision: 'block',
reason:
`Worktree path guard: '${filePath}' has no existing ancestor directory — ` +
`cannot verify it is inside the worktree '${wtTopRaw}'. Use a relative path instead.`,
};
process.stdout.write(JSON.stringify(output));
process.exit(2);
}
// Ask git for the toplevel of the file's location.
// Comparing two raw git --show-toplevel outputs avoids every
// platform-specific path normalisation pitfall (Windows 8.3 short names,
// case differences between realpathSync and path.resolve, forward- vs
// back-slash inconsistencies) — both values come from the same git binary
// in the same format by definition.
const fileTopResult = git(['rev-parse', '--show-toplevel'], checkDir);
if (fileTopResult.status !== 0 || !fileTopResult.stdout) {
// checkDir is not inside any git repo → cannot be inside the worktree.
const output = {
decision: 'block',
reason:
`Worktree path guard: '${filePath}' is not inside any git repository — ` +
`it cannot be inside the worktree at '${wtTopRaw}'. Use a relative path instead.`,
};
process.stdout.write(JSON.stringify(output));
process.exit(2);
}
const fileTopRaw = fileTopResult.stdout.trim();
// Same git toplevel → file is inside the worktree → allow
if (fileTopRaw === wtTopRaw) {
process.exit(0);
}
// BLOCK: file resolves to a different git root than the active worktree
const output = {
decision: 'block',
reason:
`Worktree path guard: '${filePath}' resolves to git root '${fileTopRaw}' which ` +
`differs from the active worktree root '${wtTopRaw}'. This likely means an ` +
`absolute path was derived from the orchestrator's main repository instead of ` +
`the active worktree. To fix: use a relative path, or re-derive the base ` +
`directory with \`git rev-parse --show-toplevel\` from within the worktree ` +
`(hook cwd: '${cwd}').`,
};
process.stdout.write(JSON.stringify(output));
process.exit(2);
} catch {
// Silent fail — never block valid tool calls due to hook errors
process.exit(0);
}
});

View File

@@ -29,6 +29,7 @@ const MANAGED_HOOKS = [
'gsd-update-banner.js',
'gsd-validate-commit.sh',
'gsd-workflow-guard.js',
'gsd-worktree-path-guard.js',
];
module.exports = { MANAGED_HOOKS };

View File

@@ -33,6 +33,7 @@ const HOOKS_TO_COPY = [
'gsd-statusline.js',
'gsd-update-banner.js',
'gsd-workflow-guard.js',
'gsd-worktree-path-guard.js',
// Community hooks (bash, opt-in via .planning/config.json hooks.community)
'gsd-session-state.sh',
'gsd-validate-commit.sh',

View File

@@ -27,6 +27,7 @@ const JS_HOOKS = [
{ name: 'gsd-prompt-guard.js', registrationAnchor: 'hasPromptGuardHook' },
{ name: 'gsd-read-guard.js', registrationAnchor: 'hasReadGuardHook' },
{ name: 'gsd-workflow-guard.js', registrationAnchor: 'hasWorkflowGuardHook' },
{ name: 'gsd-worktree-path-guard.js', registrationAnchor: 'hasWorktreePathGuardHook' },
];
describe('bug #1754: .js hook registration guards', () => {

View File

@@ -0,0 +1,423 @@
/**
* Regression tests for bug #260 — gsd-worktree-path-guard.js
*
* Executor agents spawned with isolation="worktree" sometimes issue Edit/Write
* calls with absolute paths rooted at the MAIN repository instead of the
* worktree. The prose guard in gsd-executor.md step 0b is skipped under load,
* so we enforce the constraint at the tooling layer with a PreToolUse hook.
*
* This file verifies all guard behaviours:
* 1. No-op in the main repo (.git is a directory)
* 2. Relative path always passes
* 3. Non-Edit/Write tools always pass
* 4. Absolute path inside worktree root passes
* 5. Absolute path outside worktree root is BLOCKED (exit 2)
* 6. Sibling path that merely shares a prefix is BLOCKED (/ boundary check)
* 7. install.js has an fs.existsSync guard for gsd-worktree-path-guard.js
*/
'use strict';
const { describe, test, before, after } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { spawnSync, execFileSync } = require('node:child_process');
const HOOK_PATH = path.join(__dirname, '..', 'hooks', 'gsd-worktree-path-guard.js');
const INSTALL_SRC = path.join(__dirname, '..', 'bin', 'install.js');
/**
* Resolve symlinks in a path so that we compare the same canonical form
* that `git rev-parse --show-toplevel` returns. On macOS /tmp is a symlink
* to /private/tmp, which causes path prefix checks to fail without this.
*/
function realp(p) {
try { return fs.realpathSync(p); } catch { return p; }
}
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
function git(cwd, args) {
return execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
}
/**
* Create a plain git repo (main repo — .git is a directory).
*/
function makeMainRepo() {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-260-main-'));
git(dir, ['init', '-q']);
git(dir, ['config', 'user.email', 'test@example.com']);
git(dir, ['config', 'user.name', 'Test User']);
git(dir, ['config', 'commit.gpgsign', 'false']);
fs.writeFileSync(path.join(dir, 'README.md'), '# test\n');
git(dir, ['add', 'README.md']);
git(dir, ['commit', '-q', '-m', 'chore: init']);
return dir;
}
/**
* Create a worktree off mainRepo and return its path.
* In the worktree, .git is a FILE (the gitdir pointer).
*/
function makeWorktree(mainRepo) {
const wtDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-260-wt-'));
fs.rmdirSync(wtDir); // git worktree add creates the dir itself
git(mainRepo, ['worktree', 'add', '-q', '-b', 'wt-test-branch', wtDir]);
return wtDir;
}
/**
* Run the hook with a given payload, returning the spawnSync result.
*/
function runHook(cwd, payload) {
return spawnSync(process.execPath, [HOOK_PATH], {
cwd,
input: JSON.stringify(payload),
encoding: 'utf8',
});
}
// ---------------------------------------------------------------------------
// Fixture lifecycle
// ---------------------------------------------------------------------------
let mainRepo;
let worktreeDir;
before(() => {
mainRepo = realp(makeMainRepo());
worktreeDir = realp(makeWorktree(mainRepo));
});
after(() => {
// Remove worktree registration before deleting the directory
try { git(mainRepo, ['worktree', 'remove', '--force', worktreeDir]); } catch { /* ignore */ }
try { fs.rmSync(mainRepo, { recursive: true, force: true }); } catch { /* ignore */ }
try { fs.rmSync(worktreeDir, { recursive: true, force: true }); } catch { /* ignore */ }
});
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
describe('bug #260: gsd-worktree-path-guard.js', () => {
// 1. No-op in main repo
describe('no-op in main repo', () => {
test('Edit call in main repo (.git is a directory) exits 0', () => {
const payload = {
cwd: mainRepo,
tool_name: 'Edit',
tool_input: { file_path: path.join(mainRepo, 'src', 'foo.ts') },
};
const result = runHook(mainRepo, payload);
assert.strictEqual(result.status, 0, `Expected exit 0 in main repo, got ${result.status}. stderr: ${result.stderr}`);
assert.strictEqual(result.stdout, '', 'Expected no stdout in main repo no-op');
});
test('Write call in main repo exits 0', () => {
const payload = {
cwd: mainRepo,
tool_name: 'Write',
tool_input: { file_path: path.join(mainRepo, 'out.txt') },
};
const result = runHook(mainRepo, payload);
assert.strictEqual(result.status, 0);
assert.strictEqual(result.stdout, '');
});
});
// 2. Relative path always passes
describe('relative path', () => {
test('Edit with relative file_path exits 0 even in worktree', () => {
const payload = {
cwd: worktreeDir,
tool_name: 'Edit',
tool_input: { file_path: 'src/foo.ts' },
};
const result = runHook(worktreeDir, payload);
assert.strictEqual(result.status, 0, `Relative path should always pass. stderr: ${result.stderr}`);
assert.strictEqual(result.stdout, '');
});
test('Write with relative file_path exits 0 in worktree', () => {
const payload = {
cwd: worktreeDir,
tool_name: 'Write',
tool_input: { file_path: 'dist/bundle.js' },
};
const result = runHook(worktreeDir, payload);
assert.strictEqual(result.status, 0);
assert.strictEqual(result.stdout, '');
});
});
// 3. Non-Edit/Write tools always pass
describe('non-Edit/Write tools', () => {
test('Bash tool exits 0', () => {
const payload = {
cwd: worktreeDir,
tool_name: 'Bash',
tool_input: { command: 'ls' },
};
const result = runHook(worktreeDir, payload);
assert.strictEqual(result.status, 0);
});
test('Read tool exits 0', () => {
const payload = {
cwd: worktreeDir,
tool_name: 'Read',
tool_input: { file_path: path.join(mainRepo, 'README.md') },
};
const result = runHook(worktreeDir, payload);
assert.strictEqual(result.status, 0);
});
test('Grep tool exits 0', () => {
const payload = {
cwd: worktreeDir,
tool_name: 'Grep',
tool_input: { pattern: 'foo', path: mainRepo },
};
const result = runHook(worktreeDir, payload);
assert.strictEqual(result.status, 0);
});
});
// 4. Absolute path inside worktree passes
describe('path inside worktree', () => {
test('Edit with absolute path inside worktree root exits 0', () => {
const payload = {
cwd: worktreeDir,
tool_name: 'Edit',
tool_input: { file_path: path.join(worktreeDir, 'src', 'foo.ts') },
};
const result = runHook(worktreeDir, payload);
assert.strictEqual(result.status, 0, `Path inside worktree should pass. stderr: ${result.stderr}`);
assert.strictEqual(result.stdout, '');
});
test('Edit targeting exactly the worktree root exits 0', () => {
const payload = {
cwd: worktreeDir,
tool_name: 'Edit',
tool_input: { file_path: worktreeDir },
};
const result = runHook(worktreeDir, payload);
assert.strictEqual(result.status, 0);
});
});
// 5. Absolute path outside worktree is BLOCKED
describe('path outside worktree is blocked', () => {
test('Edit targeting main repo root exits 2 with block decision', () => {
const payload = {
cwd: worktreeDir,
tool_name: 'Edit',
tool_input: { file_path: path.join(mainRepo, 'src', 'index.ts') },
};
const result = runHook(worktreeDir, payload);
assert.strictEqual(result.status, 2, `Expected exit 2 (block), got ${result.status}. stderr: ${result.stderr}`);
let parsed;
assert.doesNotThrow(() => { parsed = JSON.parse(result.stdout); }, 'stdout must be valid JSON');
assert.strictEqual(parsed.decision, 'block', 'Expected decision:"block" in output');
});
test('Write targeting main repo root exits 2 with block decision', () => {
const payload = {
cwd: worktreeDir,
tool_name: 'Write',
tool_input: { file_path: path.join(mainRepo, 'out.txt') },
};
const result = runHook(worktreeDir, payload);
assert.strictEqual(result.status, 2);
const parsed = JSON.parse(result.stdout);
assert.strictEqual(parsed.decision, 'block');
});
test('block output includes the offending path in reason', () => {
const offendingPath = path.join(mainRepo, 'src', 'leak.ts');
const payload = {
cwd: worktreeDir,
tool_name: 'Edit',
tool_input: { file_path: offendingPath },
};
const result = runHook(worktreeDir, payload);
assert.strictEqual(result.status, 2);
const parsed = JSON.parse(result.stdout);
assert.ok(
parsed.reason && parsed.reason.includes(offendingPath),
`block reason should include the offending path. Got: ${parsed.reason}`
);
});
});
// 6. Sibling directory path is BLOCKED (validates the '/' boundary check)
describe('sibling path is blocked', () => {
test('path that shares prefix with worktree root but is a sibling exits 2', () => {
// e.g. worktreeDir = /tmp/gsd-260-wt-XXXXX
// sibling = /tmp/gsd-260-wt-XXXXXsibling/file.ts
// This would pass a naive startsWith(wtRoot) check without the '/' suffix.
const siblingPath = worktreeDir + '-sibling/file.ts';
const payload = {
cwd: worktreeDir,
tool_name: 'Edit',
tool_input: { file_path: siblingPath },
};
const result = runHook(worktreeDir, payload);
assert.strictEqual(result.status, 2,
`Sibling path "${siblingPath}" must be blocked (exit 2), got ${result.status}. ` +
`This validates the '/' boundary check in startsWith(wtRoot + '/'). stderr: ${result.stderr}`
);
const parsed = JSON.parse(result.stdout);
assert.strictEqual(parsed.decision, 'block');
});
});
// 7. Adversarial: subdirectory cwd still guards correctly (Codex finding #2)
describe('subdirectory cwd', () => {
test('hook fires when cwd is a subdirectory of the worktree, not just its root', () => {
// The orchestrator may set cwd to a subdirectory. The hook must still
// detect the worktree context via git rev-parse --git-dir and block.
const subDir = path.join(worktreeDir, 'src');
fs.mkdirSync(subDir, { recursive: true });
const payload = {
cwd: subDir,
tool_name: 'Edit',
tool_input: { file_path: path.join(mainRepo, 'src', 'index.ts') },
};
const result = runHook(subDir, payload);
assert.strictEqual(result.status, 2,
`Hook must block even when cwd is a subdirectory of the worktree. ` +
`Got exit ${result.status}. stderr: ${result.stderr}`
);
const parsed = JSON.parse(result.stdout);
assert.strictEqual(parsed.decision, 'block');
});
test('path inside worktree passes even when cwd is a subdirectory', () => {
const subDir = path.join(worktreeDir, 'src');
fs.mkdirSync(subDir, { recursive: true });
const payload = {
cwd: subDir,
tool_name: 'Edit',
tool_input: { file_path: path.join(worktreeDir, 'src', 'foo.ts') },
};
const result = runHook(subDir, payload);
assert.strictEqual(result.status, 0,
`Absolute path inside worktree should pass regardless of cwd. ` +
`Got exit ${result.status}. stderr: ${result.stderr}`
);
});
});
// 8. Adversarial: `..` traversal is normalised before the containment check (Codex finding #1)
describe('dot-dot traversal is blocked', () => {
test('path with .. that escapes the worktree is blocked', () => {
// /worktree/src/../../../main-repo/file.ts resolves outside the worktree
const traversalPath = path.join(worktreeDir, 'src', '..', '..', '..', mainRepo.replace(/^\//, ''), 'file.ts');
const payload = {
cwd: worktreeDir,
tool_name: 'Edit',
tool_input: { file_path: traversalPath },
};
const result = runHook(worktreeDir, payload);
// After path.resolve, the path should equal something outside the worktree
const resolved = path.resolve(traversalPath);
if (resolved.startsWith(worktreeDir + path.sep) || resolved === worktreeDir) {
// The traversal happened to stay inside — skip this assertion
assert.ok(true, 'traversal resolved inside worktree (environment-dependent)');
} else {
assert.strictEqual(result.status, 2,
`Traversal path "${traversalPath}" resolves to "${resolved}" which is outside the worktree. ` +
`Must be blocked. Got exit ${result.status}. stderr: ${result.stderr}`
);
const parsed = JSON.parse(result.stdout);
assert.strictEqual(parsed.decision, 'block');
}
});
});
// 9. MultiEdit is also guarded (Codex finding #5)
describe('MultiEdit tool is guarded', () => {
test('MultiEdit with outside absolute path is blocked', () => {
const payload = {
cwd: worktreeDir,
tool_name: 'MultiEdit',
tool_input: { file_path: path.join(mainRepo, 'src', 'index.ts') },
};
const result = runHook(worktreeDir, payload);
assert.strictEqual(result.status, 2,
`MultiEdit targeting outside path must be blocked. Got ${result.status}. stderr: ${result.stderr}`
);
const parsed = JSON.parse(result.stdout);
assert.strictEqual(parsed.decision, 'block');
});
test('MultiEdit with inside absolute path passes', () => {
const payload = {
cwd: worktreeDir,
tool_name: 'MultiEdit',
tool_input: { file_path: path.join(worktreeDir, 'src', 'foo.ts') },
};
const result = runHook(worktreeDir, payload);
assert.strictEqual(result.status, 0,
`MultiEdit inside worktree should pass. Got ${result.status}. stderr: ${result.stderr}`
);
});
});
});
// ---------------------------------------------------------------------------
// Static analysis: install.js guard
// ---------------------------------------------------------------------------
describe('install.js guard for gsd-worktree-path-guard.js', () => {
let src;
before(() => {
src = fs.readFileSync(INSTALL_SRC, 'utf-8');
});
test('install.js has hasWorktreePathGuardHook variable', () => {
assert.ok(
src.includes('hasWorktreePathGuardHook'),
'hasWorktreePathGuardHook variable not found in install.js'
);
});
test('install.js checks fs.existsSync before registering gsd-worktree-path-guard.js', () => {
const anchorIdx = src.indexOf('hasWorktreePathGuardHook');
assert.ok(anchorIdx !== -1, 'hasWorktreePathGuardHook not found in install.js');
const blockStart = anchorIdx;
const blockEnd = Math.min(src.length, anchorIdx + 1200);
const block = src.slice(blockStart, blockEnd);
assert.ok(
block.includes('fs.existsSync') || block.includes('existsSync'),
'install.js must call fs.existsSync on the target path before registering ' +
'gsd-worktree-path-guard.js in settings.json. Without this guard, the hook ' +
'is registered even when the .js file was never copied (root cause of #1754).'
);
});
test('install.js emits a skip warning when gsd-worktree-path-guard.js is missing', () => {
const anchorIdx = src.indexOf('hasWorktreePathGuardHook');
assert.ok(anchorIdx !== -1, 'hasWorktreePathGuardHook not found in install.js');
const block = src.slice(anchorIdx, Math.min(src.length, anchorIdx + 1200));
assert.ok(
block.includes('Skipped') && block.includes('gsd-worktree-path-guard'),
'install.js must emit a skip warning mentioning gsd-worktree-path-guard when the file is not found'
);
});
});