The agent harness performance optimization system. Skills, instincts, memory, security, and research-first development for Claude Code, Codex, Opencode, Cursor and beyond.
fix(gateguard): gate NotebookEdit and hard-linked targets
Jeffrey Montoya10639a0c9e25
diff --git a/hooks/hooks.json b/hooks/hooks.jsonindex ea3960496..8c906118a 100644--- a/hooks/hooks.json+++ b/hooks/hooks.json@@ -79,7 +79,7 @@]},{- "matcher": "Edit|Write|MultiEdit",+ "matcher": "Edit|Write|MultiEdit|NotebookEdit","hooks": [{"type": "command",diff --git a/hooks/hooks.metadata.json b/hooks/hooks.metadata.jsonindex 89028f4a3..18f70fbf7 100644--- a/hooks/hooks.metadata.json+++ b/hooks/hooks.metadata.json@@ -45,7 +45,7 @@{"id": "pre:edit-write:gateguard-fact-force","description": "Fact-forcing gate: deny the first Edit/Write/MultiEdit of each file with class-specific questions (code, test, prose, config, instruction); a completed search naming the file in the current turn, or a same-turn sibling of a new file already gated, passes with a note instead; sensitive targets (secrets, keys, auth/payment code, migrations, CI workflows) are always gated",- "fingerprint": "32c4a312b4c2"+ "fingerprint": "45fbef2d7f27"}],"PreCompact": [diff --git a/scripts/dev/gateguard-eval.js b/scripts/dev/gateguard-eval.jsindex ee805e35f..629d588d7 100644--- a/scripts/dev/gateguard-eval.js+++ b/scripts/dev/gateguard-eval.js@@ -161,6 +161,12 @@ function createSymlink(root, link, target) {else fs.symlinkSync(target, linkPath, isDir ? 'dir' : 'file');}+function createHardLink(root, link, target) {+ const linkPath = path.join(root, ...link.split('/'));+ fs.mkdirSync(path.dirname(linkPath), { recursive: true });+ fs.linkSync(path.join(root, ...target.split('/')), linkPath);+}+function prepareScenario(scenario, workDir) {const root = scenario.root || fs.realpathSync(fs.mkdtempSync(path.join(workDir, 'project-')));if (!scenario.root) {@@ -175,6 +181,11 @@ function prepareScenario(scenario, workDir) {} catch (error) {return { skipped: `symlinks unavailable: ${error.code || error.message}` };}+ try {+ for (const [link, target] of Object.entries(scenario.hardlinks || {})) createHardLink(root, link, target);+ } catch (error) {+ return { skipped: `hard links unavailable: ${error.code || error.message}` };+ }}const stateDir = fs.mkdtempSync(path.join(workDir, 'state-'));const home = fs.mkdtempSync(path.join(workDir, 'home-'));diff --git a/scripts/hooks/gateguard-fact-force.js b/scripts/hooks/gateguard-fact-force.jsindex 510301cb0..3dc9ece8e 100644--- a/scripts/hooks/gateguard-fact-force.js+++ b/scripts/hooks/gateguard-fact-force.js@@ -9,7 +9,7 @@* The act of investigation creates awareness that self-evaluation never did.** Gates:- * - Edit/Write/MultiEdit (first touch): questions chosen by target class+ * - Edit/Write/MultiEdit/NotebookEdit (first touch): questions chosen by target class* - Bash/PowerShell (destructive): list targets, rollback plan, quote instruction* - Bash/PowerShell (routine): quote current instruction (once per session)*@@ -38,7 +38,8 @@ const {classifyTarget,classifyTargetFor,collapseGateDir,- isSensitiveTargetFor+ isSensitiveTargetFor,+ isHardLinkedTargetFor} = require('../lib/gateguard-target-class');const { scanCurrentTurn, createTurnScanner, currentTurnId, transcriptPathFor } = require('../lib/gateguard-turn-scan');const { createSearchEvidence } = require('../lib/gateguard-search-evidence');@@ -146,7 +147,7 @@ function getExtraDestructiveRegex() {// Operator-supplied path exemptions. Comma-separated globs (`GATEGUARD_EXEMPT_GLOBS`)// matched against the normalized project-relative path (or full path for an// explicitly absolute glob). First-touch-// fact-forcing is skipped for a matching Edit/Write/MultiEdit target — intended for+// fact-forcing is skipped for a matching Edit/Write/MultiEdit/NotebookEdit target — intended for// low-import-value trees (tests, generated artifacts, scratch dirs) where "who imports// this / what schema" carries no signal. Memoized on the env value; malformed// patterns are dropped without granting exemptions. `*` matches within a path segment,@@ -1648,8 +1649,8 @@ function countTrivialAllow() {return saveState({ ...state, trivial_allows: getTrivialAllowCount(state) + 1 });}-function isTrivialChange(cls, sensitive, profile) {- return !sensitive && TRIVIAL_CLASSES.has(cls) && Boolean(profile) && profile.known === true && profile.trivial === true;+function isTrivialChange(cls, restricted, profile) {+ return !restricted && TRIVIAL_CLASSES.has(cls) && Boolean(profile) && profile.known === true && profile.trivial === true;}// --- Read-only first shell command ---@@ -1894,7 +1895,7 @@ function firstTouchGateMsg(filePath, isWrite, cls, profile) {* (#2142). Carries the denial ordinal so consecutive denials differ* textually, and a one-line recovery hint instead of the multi-line block.*/-function condensedGateMsg(action, filePath, ordinal, cls = 'code', sensitive = false, profile = null, missNote = '') {+function condensedGateMsg(action, filePath, ordinal, cls = 'code', targetNote = '', profile = null, missNote = '') {const safe = sanitizePath(filePath);const hint = condensedHintFor(cls, action === 'creation', profile);return (@@ -1902,12 +1903,13 @@ function condensedGateMsg(action, filePath, ordinal, cls = 'code', sensitive = f`${hint} ` +`${batchSiblingWarning(safe)} ` +(missNote ? `${missNote} ` : '') +- (sensitive ? `${SENSITIVE_TARGET_NOTE} ` : '') ++ (targetNote ? `${targetNote} ` : '') +'(Use GATEGUARD_EXEMPT_GLOBS for path-scoped exemptions; GATEGUARD_FACT_FORCE_MAX_DENIALS caps denials per session; ECC_GATEGUARD=off disables this gate.)');}const SENSITIVE_TARGET_NOTE = 'Sensitive target: prior-search credit, sibling collapse, and the denial cap do not apply.';+const HARD_LINKED_TARGET_NOTE = 'Hard-linked target: prior-search credit, sibling collapse, and the denial cap do not apply.';const RETRY_LINE = 'Present the facts, then retry the same operation.';function withNoteBeforeRetry(message, note) {@@ -1917,14 +1919,21 @@ function withNoteBeforeRetry(message, note) {return `${message.slice(0, at)}${note}\n\n${message.slice(at)}`;}-function denialReason(sensitive, missNote, miss) {+function restrictedTargetNote(sensitive, linked) {+ if (sensitive) return SENSITIVE_TARGET_NOTE;+ return linked ? HARD_LINKED_TARGET_NOTE : '';+}++function denialReason(sensitive, linked, missNote, miss) {if (sensitive) return 'sensitive';+ if (linked) return 'hard-linked';return missNote ? `near-miss:${miss.reason}` : 'first-touch';}-function firstTouchDenial(filePath, { isWrite, denials, cls, sensitive, profile, miss, reason }) {- const missNote = sensitive ? '' : closestMissNote(miss);- recordDecision('deny', reason || denialReason(sensitive, missNote, miss), {+function firstTouchDenial(filePath, { isWrite, denials, cls, sensitive, linked = false, profile, miss, reason }) {+ const targetNote = restrictedTargetNote(sensitive, linked);+ const missNote = targetNote ? '' : closestMissNote(miss);+ recordDecision('deny', reason || denialReason(sensitive, linked, missNote, miss), {target: filePath,cls,sensitive,@@ -1933,10 +1942,10 @@ function firstTouchDenial(filePath, { isWrite, denials, cls, sensitive, profile,});if (denials > getFullDenialBudget()) {const action = isWrite ? 'creation' : 'edit';- return denyResult(condensedGateMsg(action, filePath, denials, cls, sensitive, profile, missNote), { includeRecoveryHint: false });+ return denyResult(condensedGateMsg(action, filePath, denials, cls, targetNote, profile, missNote), { includeRecoveryHint: false });}const message = withNoteBeforeRetry(firstTouchGateMsg(filePath, isWrite, cls, profile), missNote);- return denyResult(sensitive ? withNoteBeforeRetry(message, SENSITIVE_TARGET_NOTE) : message, {+ return denyResult(targetNote ? withNoteBeforeRetry(message, targetNote) : message, {narrowRecoveryHint: EDIT_WRITE_NARROW_RECOVERY_HINT});}@@ -2093,6 +2102,15 @@ function siblingNote(gate) {);}+// --- Allowance eligibility ---+// see docs/gateguard/design-notes.md#hard-linked-targets++function allowanceFacts(filePath, data) {+ const sensitive = isSensitiveTargetFor(filePath, data);+ const linked = !sensitive && isHardLinkedTargetFor(filePath, data);+ return { sensitive, linked, restricted: sensitive || linked };+}+// --- Subagents ---// see docs/gateguard/design-notes.md#subagents@@ -2100,15 +2118,17 @@ function subagentGateKey(fileKey) {return `__subagent__${crypto.createHash('sha256').update(fileKey).digest('hex').slice(0, 16)}`;}-function subagentSensitiveDenial(filePath, data, isWrite) {- if (!isSensitiveTargetFor(filePath, data)) return null;+function subagentRestrictedDenial(filePath, data, isWrite) {+ const { sensitive, linked, restricted } = allowanceFacts(filePath, data);+ if (!restricted) return null;const fileKey = canonicalPathKey(filePath, data);const subKey = subagentGateKey(fileKey);if (isChecked([fileKey, filePath, subKey])) return null;const cls = classifyTargetFor(filePath, data);const { ok, denials } = markCheckedAndCountDenial(subKey, { cls });if (!ok) return allowWithStateWarning();- return firstTouchDenial(filePath, { isWrite, denials, cls, sensitive: true, profile: null, miss: null, reason: 'subagent-sensitive' });+ const reason = sensitive ? 'subagent-sensitive' : 'subagent-hard-linked';+ return firstTouchDenial(filePath, { isWrite, denials, cls, sensitive, linked, profile: null, miss: null, reason });}// --- Change profile ---@@ -2253,7 +2273,7 @@ function gate(rawInput) {const rawToolName = data.tool_name || '';const toolInput = data.tool_input || {};// Normalize: case-insensitive matching via lookup map- const TOOL_MAP = { edit: 'Edit', write: 'Write', multiedit: 'MultiEdit', bash: 'Bash', powershell: 'PowerShell' };+ const TOOL_MAP = { edit: 'Edit', write: 'Write', multiedit: 'MultiEdit', notebookedit: 'NotebookEdit', bash: 'Bash', powershell: 'PowerShell' };const toolName = TOOL_MAP[rawToolName.toLowerCase()] || rawToolName;if (isMetricsEnabled()) {pendingMetrics = { tool: toolName, data, entries: [], keys: new Set() };@@ -2261,8 +2281,8 @@ function gate(rawInput) {const inSubagent = isSubagentInvocation(data);const getTurnScan = createTurnScanner(data);- if (toolName === 'Edit' || toolName === 'Write') {- const filePath = toolInput.file_path || '';+ if (toolName === 'Edit' || toolName === 'Write' || toolName === 'NotebookEdit') {+ const filePath = (toolName === 'NotebookEdit' ? toolInput.notebook_path : toolInput.file_path) || '';const exempt = exemptReason(filePath, data);if (exempt) {recordDecision('pass-exempt', exempt, { target: filePath });@@ -2270,7 +2290,7 @@ function gate(rawInput) {}if (inSubagent) {- const denial = subagentSensitiveDenial(filePath, data, toolName === 'Write');+ const denial = subagentRestrictedDenial(filePath, data, toolName === 'Write');if (!denial) recordDecision('pass-subagent', 'subagent', { target: filePath });return denial || rawInput;}@@ -2280,8 +2300,8 @@ function gate(rawInput) {const isNewFile = toolName === 'Write' && isNewFileTarget(filePath, data);const cls = classifyTargetFor(filePath, data);// see docs/gateguard/design-notes.md#sensitive-targets- const sensitive = isSensitiveTargetFor(filePath, data);- const credit = sensitive ? null : findCreditingSearch(getTurnScan(), filePath, isNewFile, data);+ const { sensitive, linked, restricted } = allowanceFacts(filePath, data);+ const credit = restricted ? null : findCreditingSearch(getTurnScan(), filePath, isNewFile, data);if (credit) {if (!markCheckedAndCountCredit(fileKey, cls)) {return allowWithStateWarning();@@ -2289,16 +2309,16 @@ function gate(rawInput) {recordDecision('credit', 'prior-search', { target: filePath, cls, sensitive });return { additionalContext: creditNote(credit, filePath), exitCode: 0 };}- const profile = sensitive ? null : changeProfileFor(toolName, filePath, [toolInput], toolInput.content, data);- if (toolName === 'Edit' && isTrivialChange(cls, sensitive, profile)) {+ const profile = restricted || toolName === 'NotebookEdit' ? null : changeProfileFor(toolName, filePath, [toolInput], toolInput.content, data);+ if (toolName === 'Edit' && isTrivialChange(cls, restricted, profile)) {if (!countTrivialAllow()) {return allowWithStateWarning();}recordDecision('trivial', 'comment-whitespace', { target: filePath, cls, sensitive, profile });return { additionalContext: trivialNote(filePath), exitCode: 0 };}- const turnId = isNewFile && !sensitive ? currentTurnId(getTurnScan()) : null;- const collapsible = isNewFile && !sensitive && (turnId !== null || !transcriptPathFor(data));+ const turnId = isNewFile && !restricted ? currentTurnId(getTurnScan()) : null;+ const collapsible = isNewFile && !restricted && (turnId !== null || !transcriptPathFor(data));const gateKey = collapsible ? newFileGateKey(filePath, data, cls) : null;const sibling = gateKey ? findSiblingGate(gateKey, turnId) : null;if (sibling) {@@ -2309,7 +2329,7 @@ function gate(rawInput) {return { additionalContext: siblingNote(sibling), exitCode: 0 };}const dirGate = gateKey ? { key: gateKey, turn: turnId, first: sanitizePath(filePath) } : undefined;- const cap = sensitive ? Number.POSITIVE_INFINITY : getMaxDenialBudget();+ const cap = restricted ? Number.POSITIVE_INFINITY : getMaxDenialBudget();const { ok, denials } = markCheckedAndCountDenial(fileKey, { cls, dirGate, cap });if (!ok) {return allowWithStateWarning();@@ -2319,8 +2339,8 @@ function gate(rawInput) {recordDecision('cap', 'max-denials', { target: filePath, cls, sensitive, profile });return rawInput;}- const miss = sensitive ? null : findClosestMiss(getTurnScan(), filePath, isNewFile, data);- return firstTouchDenial(filePath, { isWrite: toolName === 'Write', denials, cls, sensitive, profile, miss });+ const miss = restricted ? null : findClosestMiss(getTurnScan(), filePath, isNewFile, data);+ return firstTouchDenial(filePath, { isWrite: toolName === 'Write', denials, cls, sensitive, linked, profile, miss });}recordDecision('pass-checked', 'checked', { target: filePath });@@ -2333,7 +2353,7 @@ function gate(rawInput) {for (const edit of edits) {const filePath = (edit && edit.file_path) || '';if (!filePath || isClaudeSettingsPath(filePath) || isExemptPath(filePath, data)) continue;- const denial = subagentSensitiveDenial(filePath, data, false);+ const denial = subagentRestrictedDenial(filePath, data, false);if (denial) return denial;}recordDecision('pass-subagent', 'subagent');@@ -2353,8 +2373,8 @@ function gate(rawInput) {if (trivialKeys.has(fileKey)) continue;if (!isChecked([fileKey, filePath])) {const cls = classifyTargetFor(filePath, data);- const sensitive = isSensitiveTargetFor(filePath, data);- const credit = sensitive ? null : findCreditingSearch(getTurnScan(), filePath, false, data);+ const { sensitive, linked, restricted } = allowanceFacts(filePath, data);+ const credit = restricted ? null : findCreditingSearch(getTurnScan(), filePath, false, data);if (credit) {if (!markCheckedAndCountCredit(fileKey, cls)) {return allowWithStateWarning();@@ -2363,8 +2383,8 @@ function gate(rawInput) {notes.push(creditNote(credit, filePath));continue;}- const profile = sensitive ? null : changeProfileFor('Edit', filePath, entriesFor(edits, fileKey, data), undefined, data);- if (isTrivialChange(cls, sensitive, profile)) {+ const profile = restricted ? null : changeProfileFor('Edit', filePath, entriesFor(edits, fileKey, data), undefined, data);+ if (isTrivialChange(cls, restricted, profile)) {if (!countTrivialAllow()) {return allowWithStateWarning();}@@ -2373,7 +2393,7 @@ function gate(rawInput) {notes.push(trivialNote(filePath));continue;}- const cap = sensitive ? Number.POSITIVE_INFINITY : getMaxDenialBudget();+ const cap = restricted ? Number.POSITIVE_INFINITY : getMaxDenialBudget();const { ok, denials } = markCheckedAndCountDenial(fileKey, { cls, cap });if (!ok) {return allowWithStateWarning();@@ -2383,8 +2403,8 @@ function gate(rawInput) {recordDecision('cap', 'max-denials', { target: filePath, cls, sensitive, profile, key: fileKey });continue;}- const miss = sensitive ? null : findClosestMiss(getTurnScan(), filePath, false, data);- return firstTouchDenial(filePath, { isWrite: false, denials, cls, sensitive, profile, miss });+ const miss = restricted ? null : findClosestMiss(getTurnScan(), filePath, false, data);+ return firstTouchDenial(filePath, { isWrite: false, denials, cls, sensitive, linked, profile, miss });}recordDecision('pass-checked', 'checked', { target: filePath, key: fileKey });}diff --git a/scripts/lib/gateguard-metrics.js b/scripts/lib/gateguard-metrics.jsindex 61e0182a6..4f545945d 100644--- a/scripts/lib/gateguard-metrics.js+++ b/scripts/lib/gateguard-metrics.js@@ -28,7 +28,7 @@ const DECISIONS = Object.freeze(['pass']);const DECISION_SET = new Set(DECISIONS);-const TOOLS = new Set(['Edit', 'Write', 'MultiEdit', 'Bash', 'PowerShell']);+const TOOLS = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit', 'Bash', 'PowerShell']);function isCode(value) {return typeof value === 'string' && value.length <= CODE_MAX_LENGTH && CODE_PATTERN.test(value);diff --git a/scripts/lib/gateguard-target-class.js b/scripts/lib/gateguard-target-class.jsindex 17e03825d..30cd89405 100644--- a/scripts/lib/gateguard-target-class.js+++ b/scripts/lib/gateguard-target-class.js@@ -300,6 +300,29 @@ function isSensitiveRealTarget(filePath, data) {return isSensitiveTarget(normalizeWindowsSegments(realKey, target.isWin));}+// --- Hard-linked targets ---+// see docs/gateguard/design-notes.md#hard-linked-targets++const MISSING_TARGET_CODES = new Set(['ENOENT', 'ENOTDIR']);++function hasOtherLinks(stat) {+ return !stat.isDirectory() && stat.nlink > 1;+}++/** True when the target file has more than one hard link; a stat error other than a missing file counts as linked. */+function isHardLinkedTargetFor(filePath, data) {+ try {+ const target = resolveTargetPath(filePath, data);+ if (!target) return true;+ if (!isHostPathStyle(target.isWin)) return false;+ const stat = fs.lstatSync(target.resolved);+ if (!stat.isSymbolicLink()) return hasOtherLinks(stat);+ return hasOtherLinks(fs.statSync(target.resolved));+ } catch (error) {+ return !(error && MISSING_TARGET_CODES.has(error.code));+ }+}+// --- Sibling collapse eligibility ---// see docs/gateguard/design-notes.md#sibling-collapse@@ -401,5 +424,6 @@ module.exports = {isCollapsibleTarget,collapseGateDir,isSensitiveTarget,- isSensitiveTargetFor+ isSensitiveTargetFor,+ isHardLinkedTargetFor};diff --git a/tests/fixtures/gateguard-scenarios/19-notebook-edits.json b/tests/fixtures/gateguard-scenarios/19-notebook-edits.jsonnew file mode 100644index 000000000..a304ba8b5--- /dev/null+++ b/tests/fixtures/gateguard-scenarios/19-notebook-edits.json@@ -0,0 +1,497 @@+{+ "name": "notebook-edits",+ "description": "Jupyter notebook edits: a cold edit, its retry, a credited test notebook, a comment-only cell, and sensitive notebooks in the parent and a subagent.",+ "files": {+ "notebooks/forecast.ipynb": "{\n \"cells\": [\n {\n \"cell_type\": \"code\",\n \"id\": \"c1\",\n \"metadata\": {},\n \"source\": [\n \"import pandas as pd\\nsales = pd.read_csv('data/sales.csv')\\n\"\n ],\n \"outputs\": [],\n \"execution_count\": null\n }\n ],\n \"metadata\": {},\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n",+ "notebooks/cleanup.ipynb": "{\n \"cells\": [\n {\n \"cell_type\": \"code\",\n \"id\": \"c1\",\n \"metadata\": {},\n \"source\": [\n \"# drop empty rows\\nrows = [r for r in rows if r]\\n\"\n ],\n \"outputs\": [],\n \"execution_count\": null\n }\n ],\n \"metadata\": {},\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n",+ "tests/notebooks/check_model.ipynb": "{\n \"cells\": [\n {\n \"cell_type\": \"code\",\n \"id\": \"c1\",\n \"metadata\": {},\n \"source\": [\n \"assert model.score(X, y) > 0.8\\n\"\n ],\n \"outputs\": [],\n \"execution_count\": null\n }\n ],\n \"metadata\": {},\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n",+ "src/auth/session_audit.ipynb": "{\n \"cells\": [\n {\n \"cell_type\": \"code\",\n \"id\": \"c1\",\n \"metadata\": {},\n \"source\": [\n \"sessions = load_sessions()\\n\"\n ],\n \"outputs\": [],\n \"execution_count\": null\n }\n ],\n \"metadata\": {},\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n",+ "src/payments/ledger.ipynb": "{\n \"cells\": [\n {\n \"cell_type\": \"code\",\n \"id\": \"c1\",\n \"metadata\": {},\n \"source\": [\n \"ledger = load_ledger()\\n\"\n ],\n \"outputs\": [],\n \"execution_count\": null\n }\n ],\n \"metadata\": {},\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n",+ "data/sales.csv": "month,total\n2026-01,10\n"+ },+ "steps": [+ {+ "id": "cold-forecast",+ "note": "First NotebookEdit with no investigation; the change profile is unknown, so the full code questions are asked.",+ "transcript": [+ {+ "type": "user",+ "uuid": "notebook-edits-001",+ "sessionId": "sess-notebook",+ "isSidechain": false,+ "promptId": "prompt-notebook-1",+ "message": {+ "role": "user",+ "content": "Group the forecast by quarter instead of by month."+ }+ },+ {+ "type": "assistant",+ "uuid": "notebook-edits-002",+ "sessionId": "sess-notebook",+ "isSidechain": false,+ "message": {+ "id": "msg_notebookedits_01",+ "type": "message",+ "role": "assistant",+ "model": "claude-sonnet-4-5",+ "content": [+ {+ "type": "tool_use",+ "id": "toolu_notebookedits_001",+ "name": "NotebookEdit",+ "input": {+ "notebook_path": "{{root}}/notebooks/forecast.ipynb",+ "cell_id": "c1",+ "new_source": "sales = pd.read_csv('data/sales.csv')\nsales.groupby('quarter').sum()\n"+ }+ }+ ]+ }+ }+ ],+ "payload": {+ "session_id": "sess-notebook",+ "transcript_path": "{{transcript}}",+ "cwd": "{{root}}",+ "permission_mode": "default",+ "hook_event_name": "PreToolUse",+ "tool_name": "NotebookEdit",+ "tool_input": {+ "notebook_path": "{{root}}/notebooks/forecast.ipynb",+ "cell_id": "c1",+ "new_source": "sales = pd.read_csv('data/sales.csv')\nsales.groupby('quarter').sum()\n"+ },+ "tool_use_id": "toolu_notebookedits_001"+ },+ "expect": "deny",+ "mustDeny": false,+ "redundant": false,+ "relevantQuestions": [+ "importers",+ "public-api",+ "data-schema",+ "quote-instruction"+ ]+ },+ {+ "id": "retry-forecast",+ "note": "Retry after the facts are presented.",+ "transcript": [+ {+ "type": "user",+ "uuid": "notebook-edits-003",+ "sessionId": "sess-notebook",+ "isSidechain": false,+ "promptId": "prompt-notebook-1",+ "message": {+ "role": "user",+ "content": [+ {+ "type": "tool_result",+ "tool_use_id": "toolu_notebookedits_001",+ "content": "denied"+ }+ ]+ }+ },+ {+ "type": "assistant",+ "uuid": "notebook-edits-004",+ "sessionId": "sess-notebook",+ "isSidechain": false,+ "message": {+ "id": "msg_notebookedits_02",+ "type": "message",+ "role": "assistant",+ "model": "claude-sonnet-4-5",+ "content": [+ {+ "type": "tool_use",+ "id": "toolu_notebookedits_002",+ "name": "NotebookEdit",+ "input": {+ "notebook_path": "{{root}}/notebooks/forecast.ipynb",+ "cell_id": "c1",+ "new_source": "sales.groupby('quarter').sum()\n"+ }+ }+ ]+ }+ }+ ],+ "payload": {+ "session_id": "sess-notebook",+ "transcript_path": "{{transcript}}",+ "cwd": "{{root}}",+ "permission_mode": "default",+ "hook_event_name": "PreToolUse",+ "tool_name": "NotebookEdit",+ "tool_input": {+ "notebook_path": "{{root}}/notebooks/forecast.ipynb",+ "cell_id": "c1",+ "new_source": "sales.groupby('quarter').sum()\n"+ },+ "tool_use_id": "toolu_notebookedits_002"+ },+ "expect": "allow",+ "mustDeny": false,+ "redundant": false+ },+ {+ "id": "credited-test-notebook",+ "note": "A scoped Grep that names the notebook earlier in the turn credits the first touch.",+ "transcript": [+ {+ "type": "user",+ "uuid": "notebook-edits-005",+ "sessionId": "sess-notebook",+ "isSidechain": false,+ "promptId": "prompt-notebook-1",+ "message": {+ "role": "user",+ "content": [+ {+ "type": "tool_result",+ "tool_use_id": "toolu_notebookedits_002",+ "content": "ok"+ }+ ]+ }+ },+ {+ "type": "user",+ "uuid": "notebook-edits-006",+ "sessionId": "sess-notebook",+ "isSidechain": false,+ "promptId": "prompt-notebook-2",+ "message": {+ "role": "user",+ "content": "Tighten the model check threshold to 0.85."+ }+ },+ {+ "type": "assistant",+ "uuid": "notebook-edits-007",+ "sessionId": "sess-notebook",+ "isSidechain": false,+ "message": {+ "id": "msg_notebookedits_03",+ "type": "message",+ "role": "assistant",+ "model": "claude-sonnet-4-5",+ "content": [+ {+ "type": "tool_use",+ "id": "toolu_notebookedits_003",+ "name": "Grep",+ "input": {+ "pattern": "check_model",+ "path": "{{root}}/tests",+ "output_mode": "files_with_matches"+ }+ }+ ]+ }+ },+ {+ "type": "user",+ "uuid": "notebook-edits-008",+ "sessionId": "sess-notebook",+ "isSidechain": false,+ "promptId": "prompt-notebook-2",+ "message": {+ "role": "user",+ "content": [+ {+ "type": "tool_result",+ "tool_use_id": "toolu_notebookedits_003",+ "content": "tests/notebooks/check_model.ipynb"+ }+ ]+ }+ },+ {+ "type": "assistant",+ "uuid": "notebook-edits-009",+ "sessionId": "sess-notebook",+ "isSidechain": false,+ "message": {+ "id": "msg_notebookedits_04",+ "type": "message",+ "role": "assistant",+ "model": "claude-sonnet-4-5",+ "content": [+ {+ "type": "tool_use",+ "id": "toolu_notebookedits_004",+ "name": "NotebookEdit",+ "input": {+ "notebook_path": "{{root}}/tests/notebooks/check_model.ipynb",+ "cell_id": "c1",+ "new_source": "assert model.score(X, y) > 0.85\n"+ }+ }+ ]+ }+ }+ ],+ "payload": {+ "session_id": "sess-notebook",+ "transcript_path": "{{transcript}}",+ "cwd": "{{root}}",+ "permission_mode": "default",+ "hook_event_name": "PreToolUse",+ "tool_name": "NotebookEdit",+ "tool_input": {+ "notebook_path": "{{root}}/tests/notebooks/check_model.ipynb",+ "cell_id": "c1",+ "new_source": "assert model.score(X, y) > 0.85\n"+ },+ "tool_use_id": "toolu_notebookedits_004"+ },+ "expect": "allow",+ "mustDeny": false,+ "redundant": true+ },+ {+ "id": "comment-only-cleanup",+ "note": "A comment-only cell source is not a trivial pass for a notebook.",+ "transcript": [+ {+ "type": "user",+ "uuid": "notebook-edits-010",+ "sessionId": "sess-notebook",+ "isSidechain": false,+ "promptId": "prompt-notebook-2",+ "message": {+ "role": "user",+ "content": [+ {+ "type": "tool_result",+ "tool_use_id": "toolu_notebookedits_004",+ "content": "ok"+ }+ ]+ }+ },+ {+ "type": "assistant",+ "uuid": "notebook-edits-011",+ "sessionId": "sess-notebook",+ "isSidechain": false,+ "message": {+ "id": "msg_notebookedits_05",+ "type": "message",+ "role": "assistant",+ "model": "claude-sonnet-4-5",+ "content": [+ {+ "type": "tool_use",+ "id": "toolu_notebookedits_005",+ "name": "NotebookEdit",+ "input": {+ "notebook_path": "{{root}}/notebooks/cleanup.ipynb",+ "cell_id": "c1",+ "new_source": "# drop empty and blank rows\nrows = [r for r in rows if r]\n"+ }+ }+ ]+ }+ }+ ],+ "payload": {+ "session_id": "sess-notebook",+ "transcript_path": "{{transcript}}",+ "cwd": "{{root}}",+ "permission_mode": "default",+ "hook_event_name": "PreToolUse",+ "tool_name": "NotebookEdit",+ "tool_input": {+ "notebook_path": "{{root}}/notebooks/cleanup.ipynb",+ "cell_id": "c1",+ "new_source": "# drop empty and blank rows\nrows = [r for r in rows if r]\n"+ },+ "tool_use_id": "toolu_notebookedits_005"+ },+ "expect": "deny",+ "mustDeny": false,+ "redundant": false,+ "relevantQuestions": [+ "importers",+ "public-api",+ "data-schema",+ "quote-instruction"+ ]+ },+ {+ "id": "sensitive-notebook-after-search",+ "note": "A notebook under auth/ is sensitive: the crediting search does not count.",+ "transcript": [+ {+ "type": "user",+ "uuid": "notebook-edits-012",+ "sessionId": "sess-notebook",+ "isSidechain": false,+ "promptId": "prompt-notebook-2",+ "message": {+ "role": "user",+ "content": [+ {+ "type": "tool_result",+ "tool_use_id": "toolu_notebookedits_005",+ "content": "denied"+ }+ ]+ }+ },+ {+ "type": "user",+ "uuid": "notebook-edits-013",+ "sessionId": "sess-notebook",+ "isSidechain": false,+ "promptId": "prompt-notebook-3",+ "message": {+ "role": "user",+ "content": "Add a column for the session origin to the audit notebook."+ }+ },+ {+ "type": "assistant",+ "uuid": "notebook-edits-014",+ "sessionId": "sess-notebook",+ "isSidechain": false,+ "message": {+ "id": "msg_notebookedits_06",+ "type": "message",+ "role": "assistant",+ "model": "claude-sonnet-4-5",+ "content": [+ {+ "type": "tool_use",+ "id": "toolu_notebookedits_006",+ "name": "Grep",+ "input": {+ "pattern": "session_audit",+ "path": "{{root}}/src"+ }+ }+ ]+ }+ },+ {+ "type": "user",+ "uuid": "notebook-edits-015",+ "sessionId": "sess-notebook",+ "isSidechain": false,+ "promptId": "prompt-notebook-3",+ "message": {+ "role": "user",+ "content": [+ {+ "type": "tool_result",+ "tool_use_id": "toolu_notebookedits_006",+ "content": "src/auth/session_audit.ipynb"+ }+ ]+ }+ },+ {+ "type": "assistant",+ "uuid": "notebook-edits-016",+ "sessionId": "sess-notebook",+ "isSidechain": false,+ "message": {+ "id": "msg_notebookedits_07",+ "type": "message",+ "role": "assistant",+ "model": "claude-sonnet-4-5",+ "content": [+ {+ "type": "tool_use",+ "id": "toolu_notebookedits_007",+ "name": "NotebookEdit",+ "input": {+ "notebook_path": "{{root}}/src/auth/session_audit.ipynb",+ "cell_id": "c1",+ "new_source": "sessions = load_sessions(columns=['origin'])\n"+ }+ }+ ]+ }+ }+ ],+ "payload": {+ "session_id": "sess-notebook",+ "transcript_path": "{{transcript}}",+ "cwd": "{{root}}",+ "permission_mode": "default",+ "hook_event_name": "PreToolUse",+ "tool_name": "NotebookEdit",+ "tool_input": {+ "notebook_path": "{{root}}/src/auth/session_audit.ipynb",+ "cell_id": "c1",+ "new_source": "sessions = load_sessions(columns=['origin'])\n"+ },+ "tool_use_id": "toolu_notebookedits_007"+ },+ "expect": "deny",+ "mustDeny": true,+ "redundant": false,+ "relevantQuestions": [+ "importers",+ "public-api",+ "data-schema",+ "quote-instruction"+ ]+ },+ {+ "id": "subagent-sensitive-notebook",+ "note": "A subagent touching a sensitive notebook is gated like the parent.",+ "transcript": [+ {+ "type": "user",+ "uuid": "notebook-edits-017",+ "sessionId": "sess-notebook",+ "isSidechain": false,+ "promptId": "prompt-notebook-3",+ "message": {+ "role": "user",+ "content": [+ {+ "type": "tool_result",+ "tool_use_id": "toolu_notebookedits_007",+ "content": "denied"+ }+ ]+ }+ }+ ],+ "payload": {+ "session_id": "sess-notebook",+ "transcript_path": "{{transcript}}",+ "cwd": "{{root}}",+ "permission_mode": "default",+ "hook_event_name": "PreToolUse",+ "tool_name": "NotebookEdit",+ "tool_input": {+ "notebook_path": "{{root}}/src/payments/ledger.ipynb",+ "cell_id": "c1",+ "new_source": "ledger = load_ledger(currency='EUR')\n"+ },+ "tool_use_id": "toolu_notebookedits_008",+ "agent_id": "agent-ledger",+ "agent_type": "general-purpose"+ },+ "expect": "deny",+ "mustDeny": true,+ "redundant": false,+ "relevantQuestions": [+ "importers",+ "public-api",+ "data-schema",+ "quote-instruction"+ ]+ }+ ]+}diff --git a/tests/fixtures/gateguard-scenarios/20-hard-linked-targets.json b/tests/fixtures/gateguard-scenarios/20-hard-linked-targets.jsonnew file mode 100644index 000000000..b62fce549--- /dev/null+++ b/tests/fixtures/gateguard-scenarios/20-hard-linked-targets.json@@ -0,0 +1,301 @@+{+ "name": "hard-linked-targets",+ "description": "Edits of files with a second hard-linked name: a credited-looking alias, a comment-only change and a subagent edit, with a single-link control.",+ "files": {+ "src/reports/writer.py": "def write_report(rows):\n # one row per line\n return '\\n'.join(rows)\n",+ "src/reports/format_rows.py": "def format_rows(rows):\n return [str(r) for r in rows]\n",+ "src/cache/keys.py": "def cache_key(user):\n return f'user:{user}'\n"+ },+ "hardlinks": {+ "tools/report_writer.py": "src/reports/writer.py",+ "vendor/cache_keys.py": "src/cache/keys.py"+ },+ "steps": [+ {+ "id": "edit-linked-alias-after-search",+ "note": "tools/report_writer.py is a second name for src/reports/writer.py; the Grep that names it does not count.",+ "transcript": [+ {+ "type": "user",+ "uuid": "hard-linked-targets-001",+ "sessionId": "sess-hardlink",+ "isSidechain": false,+ "promptId": "prompt-hardlink-1",+ "message": {+ "role": "user",+ "content": "Make the report writer join rows with CRLF."+ }+ },+ {+ "type": "assistant",+ "uuid": "hard-linked-targets-002",+ "sessionId": "sess-hardlink",+ "isSidechain": false,+ "message": {+ "id": "msg_hardlinkedtargets_01",+ "type": "message",+ "role": "assistant",+ "model": "claude-sonnet-4-5",+ "content": [+ {+ "type": "tool_use",+ "id": "toolu_hardlinkedtargets_001",+ "name": "Grep",+ "input": {+ "pattern": "report_writer|format_rows",+ "path": "{{root}}"+ }+ }+ ]+ }+ },+ {+ "type": "user",+ "uuid": "hard-linked-targets-003",+ "sessionId": "sess-hardlink",+ "isSidechain": false,+ "promptId": "prompt-hardlink-1",+ "message": {+ "role": "user",+ "content": [+ {+ "type": "tool_result",+ "tool_use_id": "toolu_hardlinkedtargets_001",+ "content": "tools/report_writer.py\nsrc/reports/format_rows.py"+ }+ ]+ }+ },+ {+ "type": "assistant",+ "uuid": "hard-linked-targets-004",+ "sessionId": "sess-hardlink",+ "isSidechain": false,+ "message": {+ "id": "msg_hardlinkedtargets_02",+ "type": "message",+ "role": "assistant",+ "model": "claude-sonnet-4-5",+ "content": [+ {+ "type": "tool_use",+ "id": "toolu_hardlinkedtargets_002",+ "name": "Edit",+ "input": {+ "file_path": "{{root}}/tools/report_writer.py",+ "old_string": "'\\n'.join(rows)",+ "new_string": "'\\r\\n'.join(rows)"+ }+ }+ ]+ }+ }+ ],+ "payload": {+ "session_id": "sess-hardlink",+ "transcript_path": "{{transcript}}",+ "cwd": "{{root}}",+ "permission_mode": "default",+ "hook_event_name": "PreToolUse",+ "tool_name": "Edit",+ "tool_input": {+ "file_path": "{{root}}/tools/report_writer.py",+ "old_string": "'\\n'.join(rows)",+ "new_string": "'\\r\\n'.join(rows)"+ },+ "tool_use_id": "toolu_hardlinkedtargets_002"+ },+ "expect": "deny",+ "mustDeny": true,+ "redundant": false,+ "relevantQuestions": [+ "importers",+ "public-api",+ "data-schema",+ "quote-instruction"+ ]+ },+ {+ "id": "edit-single-link-control",+ "note": "Control: a single-link file named by the same search is credited.",+ "transcript": [+ {+ "type": "user",+ "uuid": "hard-linked-targets-005",+ "sessionId": "sess-hardlink",+ "isSidechain": false,+ "promptId": "prompt-hardlink-1",+ "message": {+ "role": "user",+ "content": [+ {+ "type": "tool_result",+ "tool_use_id": "toolu_hardlinkedtargets_002",+ "content": "denied"+ }+ ]+ }+ },+ {+ "type": "assistant",+ "uuid": "hard-linked-targets-006",+ "sessionId": "sess-hardlink",+ "isSidechain": false,+ "message": {+ "id": "msg_hardlinkedtargets_03",+ "type": "message",+ "role": "assistant",+ "model": "claude-sonnet-4-5",+ "content": [+ {+ "type": "tool_use",+ "id": "toolu_hardlinkedtargets_003",+ "name": "Edit",+ "input": {+ "file_path": "{{root}}/src/reports/format_rows.py",+ "old_string": "str(r)",+ "new_string": "repr(r)"+ }+ }+ ]+ }+ }+ ],+ "payload": {+ "session_id": "sess-hardlink",+ "transcript_path": "{{transcript}}",+ "cwd": "{{root}}",+ "permission_mode": "default",+ "hook_event_name": "PreToolUse",+ "tool_name": "Edit",+ "tool_input": {+ "file_path": "{{root}}/src/reports/format_rows.py",+ "old_string": "str(r)",+ "new_string": "repr(r)"+ },+ "tool_use_id": "toolu_hardlinkedtargets_003"+ },+ "expect": "allow",+ "mustDeny": false,+ "redundant": true+ },+ {+ "id": "comment-only-linked-original",+ "note": "Comment-only change to the other name of the linked file: no trivial pass.",+ "transcript": [+ {+ "type": "user",+ "uuid": "hard-linked-targets-007",+ "sessionId": "sess-hardlink",+ "isSidechain": false,+ "promptId": "prompt-hardlink-1",+ "message": {+ "role": "user",+ "content": [+ {+ "type": "tool_result",+ "tool_use_id": "toolu_hardlinkedtargets_003",+ "content": "ok"+ }+ ]+ }+ },+ {+ "type": "assistant",+ "uuid": "hard-linked-targets-008",+ "sessionId": "sess-hardlink",+ "isSidechain": false,+ "message": {+ "id": "msg_hardlinkedtargets_04",+ "type": "message",+ "role": "assistant",+ "model": "claude-sonnet-4-5",+ "content": [+ {+ "type": "tool_use",+ "id": "toolu_hardlinkedtargets_004",+ "name": "Edit",+ "input": {+ "file_path": "{{root}}/src/cache/keys.py",+ "old_string": "def cache_key(user):",+ "new_string": "def cache_key(user): # stable across deploys"+ }+ }+ ]+ }+ }+ ],+ "payload": {+ "session_id": "sess-hardlink",+ "transcript_path": "{{transcript}}",+ "cwd": "{{root}}",+ "permission_mode": "default",+ "hook_event_name": "PreToolUse",+ "tool_name": "Edit",+ "tool_input": {+ "file_path": "{{root}}/src/cache/keys.py",+ "old_string": "def cache_key(user):",+ "new_string": "def cache_key(user): # stable across deploys"+ },+ "tool_use_id": "toolu_hardlinkedtargets_004"+ },+ "expect": "deny",+ "mustDeny": true,+ "redundant": false,+ "relevantQuestions": [+ "importers",+ "public-api",+ "data-schema",+ "quote-instruction"+ ]+ },+ {+ "id": "subagent-linked-vendor-copy",+ "note": "A subagent editing a hard-linked file is gated; ordinary subagent edits still pass.",+ "transcript": [+ {+ "type": "user",+ "uuid": "hard-linked-targets-009",+ "sessionId": "sess-hardlink",+ "isSidechain": false,+ "promptId": "prompt-hardlink-1",+ "message": {+ "role": "user",+ "content": [+ {+ "type": "tool_result",+ "tool_use_id": "toolu_hardlinkedtargets_004",+ "content": "denied"+ }+ ]+ }+ }+ ],+ "payload": {+ "session_id": "sess-hardlink",+ "transcript_path": "{{transcript}}",+ "cwd": "{{root}}",+ "permission_mode": "default",+ "hook_event_name": "PreToolUse",+ "tool_name": "Edit",+ "tool_input": {+ "file_path": "{{root}}/vendor/cache_keys.py",+ "old_string": "f'user:{user}'",+ "new_string": "f'u:{user}'"+ },+ "tool_use_id": "toolu_hardlinkedtargets_005",+ "agent_id": "agent-cache",+ "agent_type": "general-purpose"+ },+ "expect": "deny",+ "mustDeny": true,+ "redundant": false,+ "relevantQuestions": [+ "importers",+ "public-api",+ "data-schema",+ "quote-instruction"+ ]+ }+ ]+}diff --git a/tests/hooks/gateguard-fact-force.test.js b/tests/hooks/gateguard-fact-force.test.jsindex da31b6ba4..8b0100748 100644--- a/tests/hooks/gateguard-fact-force.test.js+++ b/tests/hooks/gateguard-fact-force.test.js@@ -7089,6 +7089,213 @@ function runTests() {assert.strictEqual(roDecision(capped), 'deny');});+ // --- NotebookEdit ---+ const notebookInput = (rel, extra = {}) => ({ notebook_path: sensAbs(rel), new_source: 'x = 1', cell_id: 'c1', ...extra });+ const notebookRun = (rel, transcriptPath, env, extra) => projectRun('NotebookEdit', notebookInput(rel, extra), transcriptPath, env);+ const FULL_CODE_QUESTIONS = [+ 'List ALL files that import/require this file',+ 'List the public functions/classes affected by this change',+ 'If this file reads/writes data files',+ "Quote the user's current instruction verbatim"+ ];++ gateCase('a first NotebookEdit is denied with the full code questions, then its retry passes', () => {+ const first = notebookRun('nb/analysis.ipynb');+ assert.strictEqual(first.decision, 'deny', first.result.stdout);+ assert.ok(first.reason.includes(`Before editing ${sensAbs('nb/analysis.ipynb')}`), first.reason);+ for (const line of FULL_CODE_QUESTIONS) assert.ok(first.reason.includes(line), `${line}: ${first.reason}`);+ assert.ok(!first.reason.includes(sensLine), 'ordinary notebook has no sensitive line');+ const retry = notebookRun('nb/analysis.ipynb');+ assert.strictEqual(retry.decision, undefined, retry.result.stdout);+ assert.strictEqual(readState().fact_force_denials, 1);+ });++ gateCase('NotebookEdit and Edit share one checked key for a notebook', () => {+ assert.strictEqual(notebookRun('nb/shared.ipynb').decision, 'deny');+ assert.strictEqual(projectEdit(sensAbs('nb/shared.ipynb')).decision, undefined, 'Edit after a NotebookEdit denial passes');+ assert.strictEqual(projectEdit(sensAbs('nb/other.ipynb')).decision, 'deny');+ assert.strictEqual(notebookRun('nb/other.ipynb').decision, undefined, 'NotebookEdit after an Edit denial passes');+ });++ gateCase('NotebookEdit is gated by notebook_path, not by a file_path field', () => {+ projectEdit(sensAbs('src/checked.py'));+ const out = notebookRun('nb/target.ipynb', undefined, {}, { file_path: sensAbs('src/checked.py') });+ assert.strictEqual(out.decision, 'deny', out.result.stdout);+ assert.ok(out.reason.includes('target.ipynb'), out.reason);+ const exempt = notebookRun('nb/exempt-by-file-path.ipynb', undefined, { GATEGUARD_EXEMPT_GLOBS: '**/other.py' }, { file_path: sensAbs('src/other.py') });+ assert.strictEqual(exempt.decision, 'deny', 'an exempt file_path does not exempt the notebook');+ });++ gateCase('a NotebookEdit is never a trivial pass', () => {+ const out = notebookRun('nb/comment.ipynb', undefined, {}, { new_source: '# just a comment', edit_mode: 'replace' });+ assert.strictEqual(out.decision, 'deny', out.result.stdout);+ assert.ok(!out.context.includes('Comment or whitespace-only'), out.context);+ assert.ok(!readState().trivial_allows, 'no trivial pass counted');+ });++ gateCase('a notebook under tests/ gets the test questions', () => {+ const out = notebookRun('tests/notebooks/check.ipynb');+ assert.strictEqual(out.decision, 'deny');+ assert.ok(out.reason.includes('Name what behaviour is under test'), out.reason);+ });++ gateCase('a search naming the notebook credits its first NotebookEdit', () => {+ const t = writeTranscript([humanRecord('update the notebook'), ...searchRecords('toolu_nb1', 'Grep', { pattern: 'forecast', path: projectRoot })]);+ const out = notebookRun('nb/forecast.ipynb', t);+ assert.notStrictEqual(out.decision, 'deny', out.result.stdout);+ assert.ok(out.context.includes('Prior search seen in this turn'), out.result.stdout);+ });++ gateCase('a sensitive notebook is denied despite a crediting search and past the denial cap', () => {+ const t = writeTranscript([humanRecord('update it'), ...searchRecords('toolu_nb2', 'Grep', { pattern: 'tokens', path: projectRoot })]);+ sensAssertDenied(notebookRun('src/auth/tokens.ipynb', t), 'credited sensitive notebook');+ clearState();+ sensAssertDenied(notebookRun('src/auth/tokens.ipynb', undefined, { GATEGUARD_FACT_FORCE_MAX_DENIALS: '0' }), 'sensitive notebook past cap 0');+ const control = notebookRun('nb/capped.ipynb', undefined, { GATEGUARD_FACT_FORCE_MAX_DENIALS: '0' });+ assert.strictEqual(control.decision, undefined, 'ordinary notebook passes the cap like Edit');+ });++ gateCase('NotebookEdit honours exempt globs', () => {+ const out = notebookRun('scratch/play.ipynb', undefined, { GATEGUARD_EXEMPT_GLOBS: '**/scratch/**' });+ assert.strictEqual(out.decision, undefined, out.result.stdout);+ assert.strictEqual(out.context, '');+ });++ gateCase('a subagent NotebookEdit passes for an ordinary notebook and is denied for a sensitive one', () => {+ const agent = { agent_id: 'agent-notebook' };+ assert.strictEqual(roDecision(subRun('NotebookEdit', { notebook_path: '/src/nb/plain.ipynb', new_source: 'x' }, agent)), undefined);+ const sensitive = subRun('NotebookEdit', { notebook_path: '/src/payments/ledger.ipynb', new_source: 'x' }, agent);+ assert.strictEqual(roDecision(sensitive), 'deny');+ assert.ok(roReason(sensitive).includes(sensLine));+ });++ gateCase('a lower-case notebookedit tool name is gated the same way', () => {+ assert.strictEqual(projectRun('notebookedit', notebookInput('nb/lower.ipynb')).decision, 'deny');+ });++ // --- Hard-linked targets ---+ const linkedLine = 'Hard-linked target: prior-search credit, sibling collapse, and the denial cap do not apply.';+ const linkPair = (rel, alias, content = '// old\nfoo();\n') => {+ fs.mkdirSync(path.dirname(sensAbs(rel)), { recursive: true });+ fs.mkdirSync(path.dirname(sensAbs(alias)), { recursive: true });+ fs.writeFileSync(sensAbs(rel), content);+ try {+ fs.linkSync(sensAbs(rel), sensAbs(alias));+ return true;+ } catch (e) {+ if (['EPERM', 'ENOTSUP', 'EXDEV', 'ENOSYS', 'EOPNOTSUPP'].includes(e.code)) return false;+ throw e;+ }+ };+ const linksReady = linkPair('linked/src/report.js', 'linked/vendor/report.js')+ && linkPair('linked/src/auth/token.js', 'linked/vendor/token.js')+ && linkPair('linked/src/sub.js', 'linked/vendor/sub.js')+ && linkPair('linked/scratch/tmp.js', 'linked/vendor/tmp.js');+ for (const rel of ['linked/src/plain.js', 'linked/src/plain_two.js']) fs.writeFileSync(sensAbs(rel), '// old\nfoo();\n');+ const assertLinkedDenied = (out, label) => {+ assert.strictEqual(out.decision, 'deny', `${label}: expected deny, got ${out.result.stdout}`);+ assert.ok(!out.context, `${label}: no credit, trivial or sibling note`);+ assert.ok(out.reason.includes(linkedLine), `${label}: hard-link line expected: ${out.reason}`);+ assert.ok(!out.reason.includes(sensLine), `${label}: no sensitive wording`);+ };+ const linkedSearch = n => writeTranscript([+ humanRecord('update the report'),+ ...searchRecords(`toolu_linked_${n}`, 'Grep', { pattern: 'report|plain|tmp', path: projectRoot })+ ]);++ gateCase('an Edit of a hard-linked file is denied despite a crediting search (control credited)', () => {+ if (!linksReady) return;+ const t = linkedSearch(1);+ assertLinkedDenied(projectEdit(sensAbs('linked/src/report.js'), t), 'original name');+ assertLinkedDenied(projectEdit(sensAbs('linked/vendor/report.js'), t), 'second name');+ assertCredited(projectEdit(sensAbs('linked/src/plain.js'), t), 'single-link control');+ const state = readState();+ assert.strictEqual(state.fact_force_denials, 2);+ assert.strictEqual(state.fact_force_credited, 1);+ });++ gateCase('the full code questions are asked for a hard-linked file', () => {+ if (!linksReady) return;+ const out = projectRun('Edit', { file_path: sensAbs('linked/src/report.js'), old_string: 'foo();', new_string: 'bar();' });+ assertLinkedDenied(out, 'body-only change');+ for (const line of FULL_CODE_QUESTIONS) assert.ok(out.reason.includes(line), `${line}: ${out.reason}`);+ });++ gateCase('a comment-only Edit of a hard-linked file is denied (control passes as trivial)', () => {+ if (!linksReady) return;+ const input = rel => ({ file_path: sensAbs(rel), old_string: '// old', new_string: '// new' });+ assertLinkedDenied(projectRun('Edit', input('linked/src/report.js')), 'Edit');+ const multi = projectRun('MultiEdit', { file_path: sensAbs('linked/vendor/tmp.js'), edits: [{ old_string: '// old', new_string: '// new' }] });+ assertLinkedDenied(multi, 'MultiEdit');+ const control = projectRun('Edit', input('linked/src/plain_two.js'));+ assert.notStrictEqual(control.decision, 'deny', control.result.stdout);+ assert.ok(control.context.includes('Comment or whitespace-only change'), control.context);+ });++ gateCase('a hard-linked file is denied past the denial cap (control passes)', () => {+ if (!linksReady) return;+ const env = { GATEGUARD_FACT_FORCE_MAX_DENIALS: '0' };+ assertLinkedDenied(projectEdit(sensAbs('linked/src/report.js'), undefined, env), 'Edit past cap 0');+ const multi = projectRun('MultiEdit', { edits: [+ { file_path: sensAbs('linked/src/plain.js'), old_string: 'foo();', new_string: 'bar();' },+ { file_path: sensAbs('linked/vendor/tmp.js'), old_string: 'foo();', new_string: 'bar();' }+ ] }, undefined, env);+ assertLinkedDenied(multi, 'MultiEdit entry past cap 0');+ assert.ok(multi.reason.includes('tmp.js'), multi.reason);+ const control = projectEdit(sensAbs('linked/src/plain_two.js'), undefined, env);+ assert.strictEqual(control.decision, undefined, control.result.stdout);+ });++ gateCase('a MultiEdit with a hard-linked entry is denied despite a crediting search', () => {+ if (!linksReady) return;+ const t = linkedSearch(2);+ const multi = projectRun('MultiEdit', { edits: [+ { file_path: sensAbs('linked/src/plain.js'), old_string: 'foo();', new_string: 'bar();' },+ { file_path: sensAbs('linked/src/report.js'), old_string: 'foo();', new_string: 'bar();' }+ ] }, t);+ assertLinkedDenied(multi, 'MultiEdit');+ assert.ok(multi.reason.includes('report.js'), multi.reason);+ });++ gateCase('a subagent Edit of a hard-linked file is denied once; single-link targets still pass', () => {+ if (!linksReady) return;+ const agent = { agent_id: 'agent-linked', cwd: projectRoot };+ const first = subEdit(sensAbs('linked/vendor/sub.js'), agent);+ assert.strictEqual(roDecision(first), 'deny', first.stdout);+ assert.ok(roReason(first).includes(linkedLine), roReason(first));+ assert.strictEqual(roDecision(subEdit(sensAbs('linked/vendor/sub.js'), agent)), undefined, 'subagent retry passes');+ assert.strictEqual(roDecision(subEdit(sensAbs('linked/src/plain.js'), agent)), undefined);+ });++ gateCase('a hard-linked sensitive file carries the sensitive wording', () => {+ if (!linksReady) return;+ const out = projectEdit(sensAbs('linked/src/auth/token.js'));+ sensAssertDenied(out, 'sensitive and hard-linked');+ assert.ok(!out.reason.includes(linkedLine), out.reason);+ const alias = projectEdit(sensAbs('linked/vendor/token.js'));+ assertLinkedDenied(alias, 'ordinary name of a hard link into auth/');+ });++ gateCase('a new file next to a hard-linked file keeps its allowances', () => {+ if (!linksReady) return;+ const t = writeTranscript([humanRecord('add a module'), ...searchRecords('toolu_linked_ls', 'LS', { path: sensAbs('linked/src') })]);+ const out = projectWrite(sensAbs('linked/src/new_module.js'), t);+ assertCredited(out, 'missing new file');+ });++ gateCase('an exempt glob still exempts a hard-linked file', () => {+ if (!linksReady) return;+ const out = projectEdit(sensAbs('linked/scratch/tmp.js'), undefined, { GATEGUARD_EXEMPT_GLOBS: 'linked/scratch/**' });+ assert.strictEqual(out.decision, undefined, out.result.stdout);+ });++ gateCase('no hard-link output carries permissionDecision "allow"', () => {+ for (const stdout of siblingOutputs) {+ const output = parseOutput(stdout);+ assert.notStrictEqual(output && output.hookSpecificOutput ? output.hookSpecificOutput.permissionDecision : undefined, 'allow', stdout);+ }+ });+fs.rmSync(classBase, { recursive: true, force: true });fs.rmSync(scopeRoot, { recursive: true, force: true });diff --git a/tests/hooks/gateguard-scenarios.test.js b/tests/hooks/gateguard-scenarios.test.jsindex df8b53607..2530262ad 100644--- a/tests/hooks/gateguard-scenarios.test.js+++ b/tests/hooks/gateguard-scenarios.test.js@@ -66,8 +66,8 @@ async function main() {assert.strictEqual(summary.totals.unmappedQuestions, 0);});- test('only scenarios that need symlinks may be skipped', () => {- const skipped = runs.filter(run => run.skipped && !run.scenario.symlinks).map(run => run.scenario.name);+ test('only scenarios that need symlinks or hard links may be skipped', () => {+ const skipped = runs.filter(run => run.skipped && !run.scenario.symlinks && !run.scenario.hardlinks).map(run => run.scenario.name);assert.deepStrictEqual(skipped, []);});diff --git a/tests/hooks/hooks.test.js b/tests/hooks/hooks.test.jsindex a1e53d737..dc27907bc 100644--- a/tests/hooks/hooks.test.js+++ b/tests/hooks/hooks.test.js@@ -2812,6 +2812,23 @@ async function runTests() {passed++;else failed++;+ if (+ test('hooks.json routes NotebookEdit to the edit-write GateGuard entry only', () => {+ const hooks = readHooksConfig(path.join(__dirname, '..', '..', 'hooks', 'hooks.json'));+ const gateRoute = hooks.hooks.PreToolUse.find(entry => entry.id === 'pre:edit-write:gateguard-fact-force');+ assert.ok(gateRoute, 'edit-write GateGuard route should exist');+ assert.deepStrictEqual(gateRoute.matcher.split('|').sort(), ['Edit', 'MultiEdit', 'NotebookEdit', 'Write']);+ assert.strictEqual(gateRoute.hooks.length, 1, 'the GateGuard entry runs no other hook');+ assert.ok(gateRoute.hooks[0].command.includes('pre:edit-write:gateguard-fact-force'));+ const others = hooks.hooks.PreToolUse.filter(entry => entry !== gateRoute && entry.matcher !== '.*');+ for (const entry of others) {+ assert.ok(!entry.matcher.split('|').includes('NotebookEdit'), `${entry.id} should not start matching NotebookEdit`);+ }+ })+ )+ passed++;+ else failed++;+if (test('configured PowerShell routes enforce denial and emit redacted governance evidence', () => {const root = path.join(__dirname, '..', '..');diff --git a/tests/lib/gateguard-metrics.test.js b/tests/lib/gateguard-metrics.test.jsindex 4f30007d4..dd3272090 100644--- a/tests/lib/gateguard-metrics.test.js+++ b/tests/lib/gateguard-metrics.test.js@@ -81,6 +81,14 @@ test('drops any class, reason, question or language that is not a short code', (assert.strictEqual(event.profile.language, null);});+test('records NotebookEdit decisions and the hard-linked reason codes', () => {+ const event = metricsEvent({ ...base, tool: 'NotebookEdit', reason: 'hard-linked' });+ assert.strictEqual(event.tool, 'NotebookEdit');+ assert.strictEqual(event.reason, 'hard-linked');+ assert.ok(isMetricsEvent(event));+ assert.strictEqual(metricsEvent({ ...base, reason: 'subagent-hard-linked' }).reason, 'subagent-hard-linked');+});+test('keeps near-miss reason codes', () => {assert.strictEqual(metricsEvent({ ...base, reason: 'near-miss:out-of-scope' }).reason, 'near-miss:out-of-scope');});diff --git a/tests/lib/gateguard-target-class.test.js b/tests/lib/gateguard-target-class.test.jsindex d6bc7d014..7a09cc983 100644--- a/tests/lib/gateguard-target-class.test.js+++ b/tests/lib/gateguard-target-class.test.js@@ -28,7 +28,8 @@ const {isCollapsibleTarget,collapseGateDir,isSensitiveTarget,- isSensitiveTargetFor+ isSensitiveTargetFor,+ isHardLinkedTargetFor} = require(libPath);console.log('=== Testing gateguard-target-class.js ===\n');@@ -539,6 +540,74 @@ test('isSensitiveTargetFor fails safe on bad input', () => {assert.strictEqual(isSensitiveTargetFor({ toString() { throw new Error('x'); } }, {}), true);});+function tryHardLink(existing, link) {+ try {+ fs.linkSync(existing, link);+ return true;+ } catch (e) {+ if (['EPERM', 'ENOTSUP', 'EXDEV', 'ENOSYS', 'EOPNOTSUPP'].includes(e.code)) return false;+ throw e;+ }+}++test('isHardLinkedTargetFor is true for a file with more than one link', () => {+ const root = tempProject();+ try {+ withProjectDir(root, () => {+ const data = { cwd: root };+ const at = rel => path.join(root, rel);+ fs.mkdirSync(at('src/lib'), { recursive: true });+ fs.writeFileSync(at('src/lib/report.py'), 'x');+ fs.writeFileSync(at('src/lib/single.py'), 'x');+ if (!tryHardLink(at('src/lib/report.py'), at('src/report_alias.py'))) return;+ assert.strictEqual(isHardLinkedTargetFor(at('src/lib/report.py'), data), true, 'original name');+ assert.strictEqual(isHardLinkedTargetFor('src/report_alias.py', data), true, 'second name, relative spelling');+ assert.strictEqual(isHardLinkedTargetFor(at('src/lib/single.py'), data), false, 'single link');+ assert.strictEqual(isHardLinkedTargetFor(at('src/lib/new_file.py'), data), false, 'a missing new file');+ assert.strictEqual(isHardLinkedTargetFor(at('src/lib'), data), false, 'a directory');+ fs.writeFileSync(at('src/plainfile'), 'x');+ assert.strictEqual(isHardLinkedTargetFor(at('src/plainfile/a.py'), data), false, 'ENOTDIR is a missing file');+ if (trySymlink(at('src/lib/report.py'), at('src/report_symlink.py'))) {+ assert.strictEqual(isHardLinkedTargetFor(at('src/report_symlink.py'), data), true, 'symlink to a hard-linked file');+ }+ if (trySymlink(at('src/lib/single.py'), at('src/single_symlink.py'))) {+ assert.strictEqual(isHardLinkedTargetFor(at('src/single_symlink.py'), data), false, 'symlink to a single-link file');+ }+ });+ } finally {+ fs.rmSync(root, { recursive: true, force: true });+ }+});++test('isHardLinkedTargetFor fails closed on stat errors other than a missing file', () => {+ const root = tempProject();+ const savedLstat = fs.lstatSync;+ try {+ withProjectDir(root, () => {+ const data = { cwd: root };+ const target = path.join(root, 'src', 'a.py');+ for (const code of ['EACCES', 'EIO', 'ELOOP', 'EPERM']) {+ fs.lstatSync = () => {+ const error = new Error(code);+ error.code = code;+ throw error;+ };+ assert.strictEqual(isHardLinkedTargetFor(target, data), true, code);+ }+ fs.lstatSync = () => {+ throw new Error('no code');+ };+ assert.strictEqual(isHardLinkedTargetFor(target, data), true, 'error without a code');+ fs.lstatSync = savedLstat;+ assert.strictEqual(isHardLinkedTargetFor(undefined, data), true, 'non-string path');+ assert.strictEqual(isHardLinkedTargetFor(target, { cwd: 'relative/dir' }), true, 'unresolvable target');+ });+ } finally {+ fs.lstatSync = savedLstat;+ fs.rmSync(root, { recursive: true, force: true });+ }+});+test('the hook re-exports the lib classification functions', () => {// The hook prunes stale state files on load: point it at a scratch dir.const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gateguard-target-class-'));