Skip to content

armgit / ECC

Public Imported from GitHub
0

The agent harness performance optimization system. Skills, instincts, memory, security, and research-first development for Claude Code, Codex, Opencode, Cursor and beyond.

docs(gateguard): document NotebookEdit, hard links and exempt precedence

Jeffrey Montoyad4045c7370ca
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 672efd7f5..a44fd7a2b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,17 +4,22 @@
### Changed
-- GateGuard first-touch Edit/Write/MultiEdit denials now ask questions that fit the target's class (instruction, test, prose, config, or code), classified on its project-relative path. Code targets keep the existing questions word for word.
-- GateGuard credits investigation that already happened: a completed, non-error `Glob`, `Grep`, `LS`, or search-style Bash/PowerShell command in the current human turn that names the target and whose scope contains it satisfies the first-touch check with a note instead of a denial. `Read` never counts; searches in the gated call's own batch, before a compaction, with error results, or behind exclusion globs never count; and any transcript problem falls back to the denial.
-- GateGuard asks once for a batch of new files: after a Write of a new file is denied, later new files of the same class in the same real directory within the same human turn pass with a note. Edits, config and instruction files, and any dotfile or dot-directory are always gated one by one.
-- Add opt-in `GATEGUARD_FACT_FORCE_MAX_DENIALS`, a per-session denial cap: once that many first-touch denials have been issued, further new paths pass through (counted in `cap_allows`). Unset keeps the current behaviour, credit and sibling allows never consume it, destructive and routine shell gates are unaffected, and a malformed value is reported once on stderr and leaves the gate uncapped (#2755, thanks @SulimanAbdulrazzaq; closes #2608).
-- Sensitive targets (`.env*`, keys and certificates, `credentials*`, `secrets.*`, `auth`/`security`/`payment(s)`/`billing`/`migrations` path segments, `.github/workflows/`) are always gated on first touch, judged on both the path as written and its real (symlink-resolved) location; the denial says so.
-- Session state records `fact_force_credited`, `denials_by_class`, `credited_by_class`, `sibling_allows`, `dir_gates`, and `cap_allows`; older state files load unchanged. These rules only remove redundant denials: nothing previously allowed is now denied. See `skills/gateguard/SKILL.md`.
+- GateGuard first-touch denials ask questions that fit the target: by class (instruction, test, prose, config, code) on its project-relative path, and for code by what the change touches. An edit that changes no public declaration asks for the in-module call sites instead of importers and public API, and the data-schema question is dropped when the change handles no data. Changes the hook cannot read with confidence keep the original four questions word for word.
+- GateGuard credits investigation that already happened: a completed, non-error `Glob`, `Grep`, `LS`, or search-style Bash/PowerShell command in the current human turn that names the target and whose scope contains it passes the first touch with a note. `Read` never counts, nor do searches in the same batch, before a compaction, with error results, or whose filters exclude the target. When a denial follows a search that nearly counted, it names that search and why it did not count.
+- GateGuard passes comment and whitespace-only edits of code, test and prose files with a note, without marking the file checked, so the next change that alters code is still gated.
+- GateGuard asks once for a batch of new files: after a new file is denied, later new files of the same class in the same real directory within the same human turn pass with a note.
+- Read-only shell commands (`ls`, `cat`, `rg`, `git status`/`log`/`diff`, `Get-ChildItem`, …) no longer use up the once-per-session routine shell gate; the first other command is still gated (#2573).
+- GateGuard session state keyed by a session id or transcript path now expires after 8 idle hours instead of 30 minutes; the project-directory fallback keeps 30 minutes.
+- Add opt-in `GATEGUARD_FACT_FORCE_MAX_DENIALS`, a per-session denial cap: once that many first-touch denials have been issued, further new paths pass through (counted in `cap_allows`). Unset keeps the current behaviour; a malformed value is reported once on stderr and leaves the gate uncapped (#2755, thanks @SulimanAbdulrazzaq; closes #2608).
+- Add opt-in `GATEGUARD_METRICS` decision metrics (codes only, never paths, commands or content) and `scripts/gateguard-report.js` to summarise them.
+- Sensitive targets (`.env*`, keys and certificates, `credentials*`, `secrets.*`, `auth`/`security`/`payment(s)`/`billing`/`migrations` path segments, `.github/workflows/`) and files with more than one hard link get none of these allowances, judged on the path as written and its real location, and are gated in subagents too. `GATEGUARD_EXEMPT_GLOBS` still takes precedence.
+- Newly denied: a subagent's first touch of a sensitive or hard-linked file, and the first NotebookEdit of each notebook. Every other rule only removes denials and never returns an `allow` decision. See `skills/gateguard/SKILL.md`.
### Fixed
- GateGuard keys checked files by canonical path, resolving relative targets against the tool `cwd`, so `a.py`, `./a.py`, and the absolute path (or differently cased and separated Windows spellings) share one first touch. Keys from earlier state files are still honoured.
-- GateGuard gates a MultiEdit call as its `tool_input.file_path` when its entries do not name their own path, which is the tool's own shape; such calls were never gated before, including on sensitive files and from subagents.
+- GateGuard gates a MultiEdit call as its `tool_input.file_path` when its entries do not name their own path, which is the tool's own shape; such calls were never gated before, including on sensitive files.
+- GateGuard gates NotebookEdit as a first-touch edit of its `notebook_path`; notebooks were never gated before.
## 2.2.2 - 2026-09-15
diff --git a/docs/gateguard/design-notes.md b/docs/gateguard/design-notes.md
index 4f525b43c..d0bc90a03 100644
--- a/docs/gateguard/design-notes.md
+++ b/docs/gateguard/design-notes.md
@@ -5,6 +5,42 @@ Rationale for the decisions in the GateGuard fact-forcing gate
Code comments point here as `docs/gateguard/design-notes.md#<anchor>`; keep
headings stable, since they are the anchors.
+## Index
+
+- Structure: [Module layout](#module-layout), [Fail to deny](#fail-to-deny).
+- Which targets are gated and how strictly:
+ [Exempt globs](#exempt-globs), [NotebookEdit](#notebookedit),
+ [MultiEdit paths](#multiedit-paths), [Sensitive targets](#sensitive-targets),
+ [Hard-linked targets](#hard-linked-targets),
+ [Target resolution](#target-resolution), [Target classes](#target-classes),
+ [Worktree prefix](#worktree-prefix),
+ [Windows name normalization](#windows-name-normalization).
+- Right question: [Change profile](#change-profile),
+ [Public surface](#public-surface), [Data handling](#data-handling),
+ [Shell scripts](#shell-scripts), [File context](#file-context),
+ [Questions from the change profile](#questions-from-the-change-profile),
+ [Trivial edits](#trivial-edits), [Directive comments](#directive-comments),
+ [Closest search that did not count](#closest-search-that-did-not-count).
+- Right time, prior-search credit: [Read is not evidence](#read-is-not-evidence),
+ [Turn boundaries](#turn-boundaries), [Turn identity](#turn-identity),
+ [Tool result pairing](#tool-result-pairing),
+ [Same-batch searches](#same-batch-searches),
+ [Ambiguous shell is not evidence](#ambiguous-shell-is-not-evidence),
+ [Directory changes](#directory-changes),
+ [Stdin is not a tree search](#stdin-is-not-a-tree-search),
+ [Search scope](#search-scope), [Stem matching](#stem-matching),
+ [Test stems](#test-stems), [Search filters](#search-filters),
+ [Include filters](#include-filters),
+ [Glob matching without RegExp](#glob-matching-without-regexp),
+ [Flag parsing](#flag-parsing),
+ [PowerShell parameter binding](#powershell-parameter-binding).
+- Right time, other allowances: [New-file detection](#new-file-detection),
+ [Sibling collapse](#sibling-collapse), [Denial cap](#denial-cap),
+ [Read-only first shell command](#read-only-first-shell-command),
+ [Idle window](#idle-window), [Subagents](#subagents).
+- State and measurement: [State file is untrusted](#state-file-is-untrusted),
+ [Metrics](#metrics).
+
## Module layout
- `scripts/hooks/gateguard-fact-force.js`: the hook. Owns the shell parser
@@ -12,10 +48,11 @@ headings stable, since they are the anchors.
destructive Bash/PowerShell detector uses, the state file I/O, the gate
messages, and `run()`.
- `scripts/lib/gateguard-target-class.js`: target identity and classification
- for first-touch Edit/Write/MultiEdit targets: canonical path keys, target
- classes and their questions, sensitive-target detection and sibling-collapse
- eligibility. Stateless; filesystem access is limited to worktree `.git`
- checks and realpath/lstat of the target's parent chain.
+ for first-touch Edit/Write/MultiEdit/NotebookEdit targets: canonical path
+ keys, target classes and their questions, sensitive-target and hard-link
+ detection and sibling-collapse eligibility. Stateless; filesystem access is
+ limited to worktree `.git` checks, realpath/lstat of the target's parent
+ chain, and lstat/stat of the target for its link count.
- `scripts/lib/gateguard-turn-scan.js`: one bounded tail read of the Claude Code
JSONL transcript, walked back to the start of the current turn. Yields the
turn id, the turn's completed non-error search calls (newest first), their
@@ -43,10 +80,11 @@ headings stable, since they are the anchors.
## Fail to deny
Every allowance other than a retry of an already-gated target (prior-search
-credit, the trivial-edit pass, sibling collapse, the denial cap, the read-only
-first shell command) is an exception to the first-touch or routine
-denial, so each one falls back to the denial on any doubt: an unreadable
-transcript, a parse failure, an unresolvable path, or an exception. The lib
+credit, the trivial-edit pass, sibling collapse, the denial cap, the subagent
+bypass, the read-only first shell command) is an exception to the first-touch
+or routine denial, so each one falls back to the denial on any doubt: an
+unreadable transcript, a parse failure, an unresolvable path, a stat error on
+the target, or an exception. The lib
exports that feed those decisions never throw (they catch and return a
fallback that denies, or no scan at all), so an error cannot escape into credit or
sibling logic. Allowances are never an `allow` permission decision: credit,
@@ -75,6 +113,56 @@ exceptions).
- A real location that cannot be resolved (dangling symlink, `ENOTDIR`,
`EACCES`, loops), a non-string path, or any error counts as sensitive.
+## Hard-linked targets
+
+A file with more than one hard link can be changed through any of its names,
+and the other names may be sensitive (`vendor/token.js` linked to
+`src/auth/token.js`), belong to another class, or live outside the project.
+Neither the lexical path nor `realpath` reveals them, and finding every name
+would mean walking the filesystem. So the allowances trust no name of such a
+file: a target whose `lstat` (or, for a symlink, `stat`) reports
+`nlink > 1` gets no prior-search credit, change profile, trivial-edit pass,
+sibling collapse, denial cap or subagent bypass, exactly as a sensitive target.
+
+- Directories are skipped (their link count counts subdirectories).
+- A missing file (`ENOENT`, `ENOTDIR`) is a new file with one name, so a Write
+ that creates one keeps its allowances; any other stat error, an unresolvable
+ target, or a non-string path counts as hard-linked. The stat is only used for
+ this allowance decision; it never turns an allowed retry into a denial.
+- A Windows-style path on a POSIX host (or the reverse) has no file to stat and
+ is judged by its path alone, as for the real-path checks.
+- The denial names the rule ("Hard-linked target: …") rather than calling the
+ file sensitive; a target that is both gets the sensitive note. Metrics record
+ the reason `hard-linked` (or `subagent-hard-linked`) with `sensitive: false`.
+- The check runs at decision time; a link created after the first touch is not
+ seen, which is the same limit as for sensitive real paths.
+
+## Exempt globs
+
+`GATEGUARD_EXEMPT_GLOBS` is an operator decision and stays authoritative: an
+exempt target passes before the subagent, checked, sensitive and hard-link
+rules are consulted, so a glob that covers `src/auth/**` or a hard-linked file
+turns its check off. The alternative (sensitive rules overriding exemptions)
+would make a documented control silently ineffective for the paths an
+operator is most likely to be deliberate about, and would change behaviour
+for existing configurations. The precedence is documented in the skill's
+order of checks, and the table row warns that exemptions apply to sensitive
+and hard-linked targets too.
+
+## NotebookEdit
+
+NotebookEdit writes a `.ipynb` file named by `tool_input.notebook_path` (not
+`file_path`), so it is routed to the edit-write gate by adding it to that
+entry's matcher only; the other PreToolUse entries are unchanged. The hook
+treats it as an Edit of `notebook_path`: the same canonical checked key (an
+Edit and a NotebookEdit of one notebook share a first touch), class by path
+(`.ipynb` falls through to code; under `tests/` it is a test), and the same
+sensitive, hard-link, credit, cap, subagent and exempt rules. A `file_path`
+field on the call is ignored. The change profile only understands source text,
+not a cell edit, so a NotebookEdit always gets the full questions and is never
+a trivial pass. It is never a new-file Write, so it never opens or joins a
+sibling gate.
+
## Target resolution
Relative targets resolve against the tool's `cwd` first, then
@@ -273,7 +361,7 @@ malformed value leaves the gate uncapped and says so once on stderr. Once the
session's denials reach the cap, a first touch passes with the input unchanged
and is counted in `cap_allows`. The cap check reads the state the same write
persists, so a lost concurrent update can add a denial but never passes a
-target early. Sensitive targets are never capped.
+target early. Sensitive and hard-linked targets are never capped.
## State file is untrusted
@@ -499,7 +587,8 @@ before sibling collapse and the denial cap. It is not marked checked and does
not touch the denial count or ordinal, so the next change that alters code is
gated as a first touch; `trivial_allows` counts the passes (merged by maximum
like the other counters). The trivial pass never marks the target checked and
-never applies to sensitive, instruction or config targets, so the next
+never applies to sensitive, hard-linked, instruction or config targets or to
+a NotebookEdit, so the next
non-trivial change still meets the full gate.
## File context
@@ -510,7 +599,7 @@ that opens above it, follow a line that continues onto it, or lose its line
break so the next line joins it. So an Edit is trivial only when checked
against the file it applies to.
-- The hook reads the current target (never a sensitive one) itself: the path
+- The hook reads the current target (never a sensitive or hard-linked one) itself: the path
is resolved like every other target, opened read-only and non-blocking,
and used only if `fstat` says it is a regular file of at most 1 MiB; CRLF
is folded to LF, as the Edit tool does. A missing, unreadable, larger or
@@ -569,8 +658,9 @@ questions were asked without storing text.
| config | any | `config-reader`, `config-effect`, `no-plaintext-secrets`, `quote-instruction` |
`[data-schema]` is asked only when `touchesData`. With an unknown profile the
-code text is byte-identical to the fixed four questions. Sensitive targets are
-never profiled, so they always get the full code questions. Instruction and
+code text is byte-identical to the fixed four questions. Sensitive and
+hard-linked targets and NotebookEdit calls are never profiled, so they always
+get the full code questions. Instruction and
config questions carry no change-dependent item, and the test and prose items
do not depend on what the change touches, so the profile leaves those classes
alone. For a MultiEdit, the denied file's profile covers every entry for that
@@ -585,7 +675,8 @@ names `callers`, `no-duplicate` and `data-schema` like its full denial.
## Closest search that did not count
-When a non-sensitive first touch is denied and the turn holds a search (or a
+When an ordinary (not sensitive or hard-linked) first touch is denied and the
+turn holds a search (or a
`Read`, or a non-search shell command) that mentions the target but did not
credit it, the denial adds one line naming the closest one, so the agent does
the missing step instead of restating facts:
@@ -611,8 +702,8 @@ closest to farthest (the closest wins, then the newest):
reading past it would cost a second, larger scan. Ambiguous shell commands
(substitutions, heredocs, over 8192 characters) give no line. The tool name
comes from a fixed set; the detail is the tool input, sanitized like a path,
-whitespace-folded and cut to 60 characters. Sensitive targets never get the
-line, since no search could have credited them. In a condensed denial the line
+whitespace-folded and cut to 60 characters. Sensitive and hard-linked targets
+never get the line, since no search could have credited them. In a condensed denial the line
follows the batch warning.
## Read-only first shell command
@@ -685,9 +776,9 @@ the work it delegated, and a subagent writing many files would otherwise draw
one denial per file. Shell gates were never skipped, so a subagent can
already receive a denial, present facts and retry.
-Sensitive targets are the exception. A subagent Edit, Write or MultiEdit
-entry on a sensitive target is denied once per path with the full sensitive
-denial, unless the parent already gated that path. Prior-search credit, the
+Sensitive and hard-linked targets are the exception. A subagent Edit, Write,
+NotebookEdit or MultiEdit entry on such a target is denied once per path with
+the full denial and its note, unless the parent already gated that path. Prior-search credit, the
change profile, sibling collapse and the denial cap never apply, as at top
level. The subagent's denial marks a separate subagent key, not the file's
key, so a subagent's retry never unlocks the path for the parent, whose own
diff --git a/docs/gateguard/evaluation.md b/docs/gateguard/evaluation.md
index 983571a63..b5476ceb3 100644
--- a/docs/gateguard/evaluation.md
+++ b/docs/gateguard/evaluation.md
@@ -46,8 +46,8 @@ Metrics per hook:
- **Hook latency p50/p95**: wall time of `run()` per step, in process. The
only non-deterministic metric.
-Each scenario runs in its own temp project (files and symlinks created from
-the fixture), with its own transcript, `GATEGUARD_STATE_DIR`, `HOME` and a
+Each scenario runs in its own temp project (files, symlinks and hard links
+created from the fixture), with its own transcript, `GATEGUARD_STATE_DIR`, `HOME` and a
clean environment (`PATH`, `CLAUDE_PROJECT_DIR`, plus the scenario's `env`),
in a fresh worker thread, so module state and state files never leak between
scenarios or hooks. A baseline hook is materialised from `git show
@@ -56,29 +56,29 @@ relatively at that ref, into a temp tree that mirrors the repo layout.
## Results
-Working tree = branch `gateguard-full`; `upstream/main` = `bd9402f7`;
+Working tree = branch `gateguard-full`; `upstream/main` = `d30588f9`;
`58a4a0d0` = the pull request head before this round. Node 22, Linux.
```text
-Corpus: 18 scenarios, 172 steps.
+Corpus: 20 scenarios, 182 steps.
```
| Metric | working tree | upstream/main | 58a4a0d0 |
| --- | ---: | ---: | ---: |
-| Steps | 172 | 172 | 172 |
-| Denials | 124 | 152 | 130 |
-| Redundant denials | 0 | 36 | 16 |
-| Must-deny bypasses | 0 | 5 | 5 |
-| Expectation mismatches | 0 | 48 | 26 |
+| Steps | 182 | 182 | 182 |
+| Denials | 131 | 155 | 131 |
+| Redundant denials | 0 | 37 | 16 |
+| Must-deny bypasses | 0 | 8 | 9 |
+| Expectation mismatches | 0 | 54 | 32 |
| Irrelevant questions asked | 2 | 181 | 146 |
| Irrelevant questions in condensed denials | 2 | 105 | 84 |
| Warranted questions not asked | 1 | 55 | 42 |
-| Estimated denial tokens | 23584 | 26724 | 24549 |
-| Allows with a credit note | 9 | 0 | 8 |
+| Estimated denial tokens | 25455 | 27524 | 24813 |
+| Allows with a credit note | 11 | 0 | 10 |
| Allows with a sibling note | 11 | 0 | 11 |
| Allows with a trivial-edit note | 5 | 0 | 0 |
-| Hook latency p50 (ms) | 1.71 | 0.86 | 1.45 |
-| Hook latency p95 (ms) | 7.89 | 2.95 | 5.99 |
+| Hook latency p50 (ms) | 1.68 | 0.76 | 1.23 |
+| Hook latency p95 (ms) | 7.67 | 2.13 | 5.38 |
| Scenario | Steps | Denials: working tree | Denials: upstream/main | Denials: 58a4a0d0 |
| --- | ---: | ---: | ---: | ---: |
@@ -100,18 +100,22 @@ Corpus: 18 scenarios, 172 steps.
| cap-with-sensitive | 6 | 4 | 6 | 4 |
| bypass-comment-context | 22 | 21 | 19 | 19 |
| exported-members | 6 | 6 | 6 | 6 |
+| notebook-edits | 6 | 4 | 0 | 0 |
+| hard-linked-targets | 4 | 3 | 3 | 1 |
### Reading the results
Against `upstream/main`:
-- 18% fewer denials (152 to 124) and 12% fewer denial tokens, with every
- redundant denial in the corpus gone (36 to 0).
-- All five must-deny bypasses closed: `upstream/main` lets a subagent edit
- `src/auth/oauth.js` and `config/secrets.yaml` without a question, and never
- gates a MultiEdit call that names its file in `tool_input.file_path` (the
- tool's own shape), so `.env`, `config/.env.local` from a subagent and a
- first-touch code file all pass.
+- 15% fewer denials (155 to 131) and 8% fewer denial tokens, with every
+ redundant denial in the corpus gone (37 to 0).
+- All eight must-deny bypasses closed: `upstream/main` lets a subagent edit
+ `src/auth/oauth.js`, `config/secrets.yaml` and a hard-linked file without a
+ question, never gates a MultiEdit call that names its file in
+ `tool_input.file_path` (the tool's own shape), so `.env`,
+ `config/.env.local` from a subagent and a first-touch code file all pass,
+ and never gates NotebookEdit, so notebooks under `auth/` and `payments/`
+ pass from the parent and from a subagent.
- Irrelevant questions drop from 181 to 2 and warranted-but-unasked from 55
to 1: edits without a public-surface line ask for local call sites instead
of importers, members of exported interfaces, enums, export lists,
@@ -119,20 +123,22 @@ Against `upstream/main`:
question is asked only when the change touches data, and condensed denials
name the same questions as full ones.
- Denials rise only where they should: the subagent's first touch of a
- sensitive file, MultiEdit calls, the first mutating shell command after a
- read-only one (`upstream/main` spends its once-per-session routine gate on
- `ls`), and the first code-changing edit after a comment-only one (the
- comment edit no longer spends the file's first touch).
-
-Against `58a4a0d0` (the pull request head before this round): 6 fewer
-denials net. The first 16 scenarios account for 8 fewer (3 in the
-comment-only scenario, 6 from read-only first shell commands and 1 from the
-test edit credited by its stem, less 2 more for subagent edits of sensitive
-files); `bypass-comment-context` adds 2 (three MultiEdit calls now gated, one
-comment edit passed). Redundant denials drop from 16 to 0, all five bypasses
-close, and irrelevant questions drop from 146 to 2.
-
-The security review of this round's allowances added two scenarios.
+ sensitive or hard-linked file, MultiEdit calls, NotebookEdit calls, the first
+ mutating shell command after a read-only one (`upstream/main` spends its
+ once-per-session routine gate on `ls`), and the first code-changing edit
+ after a comment-only one (the comment edit no longer spends the file's first
+ touch).
+
+Against `58a4a0d0` (the pull request head before this round): the same 131
+denials with 16 fewer redundant ones and nine bypasses closed. The first 16
+scenarios account for 8 fewer denials (3 in the comment-only scenario, 6 from
+read-only first shell commands and 1 from the test edit credited by its stem,
+less 2 more for subagent edits of sensitive files); `bypass-comment-context`
+adds 2 (three MultiEdit calls now gated, one comment edit passed),
+`notebook-edits` adds 4 and `hard-linked-targets` adds 2. Irrelevant
+questions drop from 146 to 2.
+
+The security reviews of this round added four scenarios.
`bypass-comment-context` holds 21 must-deny steps: comment-looking edits that
change code in their file (a comment line after a continued C macro, a line
break dropped so the next line joins a comment, lines inside a template
@@ -148,19 +154,32 @@ Before the fixes the branch let 20 of those 21 through (every edit and
`exported-members` holds six member edits whose container declaration sits
outside the snippet; before the fixes the branch asked for local call sites
on the five public ones (5 irrelevant questions, 10 warranted ones not asked).
+`notebook-edits` covers a cold NotebookEdit, its retry, a credited test
+notebook, a comment-only cell and sensitive notebooks in the parent and a
+subagent; every earlier hook allows all six calls. `hard-linked-targets`
+edits a second name of a file after a search that names it, makes a
+comment-only change to another linked file and edits a linked file from a
+subagent, with a single-link control; before the fix the branch allowed all
+three (credit, trivial pass, subagent bypass), and `58a4a0d0` allowed the
+credited alias and the subagent edit.
What the working tree still gets wrong, by the corpus's own labels:
- Sensitive targets are never profiled, so a sensitive code Write always asks
the data-schema question (`symlinked-auth-first`, `symlinked-auth-sibling`:
the 2 irrelevant questions).
+- NotebookEdit and hard-linked targets always get the full questions; the
+ corpus labels all four as warranted for them, so this costs nothing in the
+ table, but a notebook cell that handles no data still gets the data-schema
+ question.
- The C edit that turns a declaration into a comment continuation
(`c-comment-continuation`) has no data words, so the condensed hint no
longer mentions data schemas; the corpus labels that question as warranted
(the 1 unasked one).
-- Latency roughly doubles against `upstream/main` (p50 about 2 ms, p95 about
- 8 ms) with the added transcript scanning and path resolution; both stay far
- below the 200 ms budget for blocking hooks. Checking a comment-only edit
+- Latency rises against `upstream/main` (p50 1.7 ms against 0.8 ms, p95
+ 7.7 ms against 2.1 ms) with the added transcript scanning, path resolution
+ and the target's link-count check; both stay far below the 200 ms budget
+ for blocking hooks. Checking a comment-only edit
reads and scans the target file, which costs up to about 50 ms for a 1 MiB
file (the largest one read).
@@ -185,8 +204,9 @@ mismatch, a must-deny bypass, an explicit `allow` decision or a thrown error.
One JSON file per scenario in `tests/fixtures/gateguard-scenarios/`:
- `name`, `description`;
-- `files` (project-relative path to content), optional `dirs` and `symlinks`
- (link path to target, relative to the link), created in a temp project;
+- `files` (project-relative path to content), optional `dirs`, `symlinks`
+ (link path to target, relative to the link) and `hardlinks` (link path to
+ an existing project file, both project-relative), created in a temp project;
- optional `root` (a fixed project path, used for Windows-style paths, where
nothing is created on disk) and `env` (extra environment variables);
- `steps`, in order. Each step has an `id`, an optional `note`, the
@@ -200,8 +220,9 @@ project and transcript paths. Transcripts are the same for every hook: a
step's call is assumed to succeed eventually, so the next step's records start
with its `tool_result`.
-A scenario with `symlinks` is skipped (and reported) where symlinks cannot be
-created, such as Windows without the privilege.
+A scenario with `symlinks` or `hardlinks` is skipped (and reported) where the
+links cannot be created, such as Windows without the symlink privilege or a
+file system without hard links.
## Limits
diff --git a/docs/ja-JP/skills/gateguard/SKILL.md b/docs/ja-JP/skills/gateguard/SKILL.md
index 3bc67f3dd..0a7fde34b 100644
--- a/docs/ja-JP/skills/gateguard/SKILL.md
+++ b/docs/ja-JP/skills/gateguard/SKILL.md
@@ -49,6 +49,8 @@ Both agents produce code that runs and passes tests. The difference is design de
MultiEdit is handled identically — each file in the batch is gated individually.
+NotebookEdit は `notebook_path` への Edit として扱われます(同じクラス・チェック済みキー・クレジット・上限の規則。セル内容は読まないため常に完全な質問になり、コメントのみの通過はありません)。
+
質問内容は対象ファイルのクラスによって変わります([対象クラス別の質問](#対象クラス別の質問)を参照)。以下は **code** クラスの Edit ゲートの質問です。
```
@@ -137,9 +139,10 @@ Triggers on: `rm -rf`, `git reset --hard`, `git push --force`, `drop table`, etc
- **正規化パスキー:** 相対パスはツールの `cwd` を基準に解決され、`a.py`、`./a.py`、絶対パスは同じファイルとして扱われ、初回タッチは 1 回だけです。
- **セッション内カウンター:** 状態ファイルに `fact_force_credited`、`denials_by_class`、`credited_by_class`、`sibling_allows`、`dir_gates`、`cap_allows` を記録します(クラス名のみ記録し、パスは記録しません。`dir_gates` はサニタイズ済みの最初のファイル名のみ保持、最大 50 件)。
- **拒否の上限(オプトイン):** `GATEGUARD_FACT_FORCE_MAX_DENIALS` を設定すると、セッション内の初回タッチ拒否がその回数に達した後の新しいパスは拒否されずに通過します(`cap_allows` に記録)。`GATEGUARD_FACT_FORCE_FULL_DENIALS` はメッセージの詳しさ(メッセージ予算)だけを変えますが、こちらはブロックするかどうか(拒否予算)を変えます。事前検索のクレジットと兄弟ファイル集約が先に判定され、上限を消費しません。不正な値は上限なしとして扱い、stderr に 1 回警告します。
-- **機密対象:** `.env`/`.env.*`、`*.pem`・`*.key`・`*.p12`・`*.pfx`、`id_rsa*`・`id_ed25519*`・`id_ecdsa*`・`id_dsa*`・`.netrc`・`.pgpass`・`credentials*`・`secrets.*`、パスセグメントが `auth`・`authn`・`authz`・`security`・`secrets`・`payment`・`payments`・`billing`・`migrations` のいずれかと完全一致するもの、`.github/workflows/` 配下は、クレジット・集約・上限のいずれも適用されず、初回タッチで必ず拒否されます。判定は字句上のパスとシンボリックリンクを解決した実体の両方で行い(`src/tools -> ../auth` なら `src/tools/login.py` も機密)、実体を解決できない場合は機密とみなします。判定順は exempt → subagent → checked → 機密? → クレジット → 兄弟集約 → 上限 → 拒否です。
+- **機密対象:** `.env`/`.env.*`、`*.pem`・`*.key`・`*.p12`・`*.pfx`、`id_rsa*`・`id_ed25519*`・`id_ecdsa*`・`id_dsa*`・`.netrc`・`.pgpass`・`credentials*`・`secrets.*`、パスセグメントが `auth`・`authn`・`authz`・`security`・`secrets`・`payment`・`payments`・`billing`・`migrations` のいずれかと完全一致するもの、`.github/workflows/` 配下は、クレジット・集約・上限のいずれも適用されず、初回タッチで必ず拒否されます。判定は字句上のパスとシンボリックリンクを解決した実体の両方で行い(`src/tools -> ../auth` なら `src/tools/login.py` も機密)、実体を解決できない場合は機密とみなします。判定順は exempt → subagent → checked → 機密またはハードリンク? → クレジット → 兄弟集約 → 上限 → 拒否です。`GATEGUARD_EXEMPT_GLOBS` による除外は最優先で、機密対象やハードリンク対象にも適用されます。
+- **ハードリンク対象:** リンク数が 2 以上のファイル(またはそれを指すシンボリックリンク)は別名から到達できるため、機密対象と同じくクレジット・変更プロファイル・コメントのみの通過・兄弟集約・上限・サブエージェントの通過が適用されません。拒否には機密の行の代わりに「Hard-linked target: ...」の行が付きます。存在しない新規ファイル以外の stat エラーはハードリンクとみなします。
- **判定メトリクス(オプトイン):** `GATEGUARD_METRICS=1` で各判定を `<GATEGUARD_STATE_DIR>/metrics.jsonl` に 1 行ずつ記録します(パス・コマンド・内容は記録せず、1 MiB で `.1` にローテーション)。集計は `node scripts/gateguard-report.js [--dir <path>] [--json]` です。
-- **互換性:** 新しい環境変数はオプトインの `GATEGUARD_FACT_FORCE_MAX_DENIALS` と `GATEGUARD_METRICS` のみです。以前許可されていた操作が拒否されることはありません。
+- **互換性:** 新しい環境変数はオプトインの `GATEGUARD_FACT_FORCE_MAX_DENIALS` と `GATEGUARD_METRICS` のみです。サブエージェントによる機密・ハードリンク対象への初回タッチと、各ノートブックへの最初の NotebookEdit(以前はゲート対象外)を除き、以前許可されていた操作が拒否されることはありません。
- **信頼の限界:** クレジットはローカルのトランスクリプトを読むため、エージェントが理論上それを書き換えられます。検証するのは行動(検索が実行され結果が返ったこと)であり、意図ではありません。
## Quick Start
diff --git a/docs/zh-CN/skills/gateguard/SKILL.md b/docs/zh-CN/skills/gateguard/SKILL.md
index 9d6c62d1d..f6669fa4f 100644
--- a/docs/zh-CN/skills/gateguard/SKILL.md
+++ b/docs/zh-CN/skills/gateguard/SKILL.md
@@ -97,10 +97,12 @@ LLM 的自我评估不起作用。问"你是否违反了任何策略?"答案
* **拒绝中指出最接近的未计入搜索:** 非敏感目标被拒绝且本回合有提及该文件却未能抵免的调用时,拒绝消息追加一行"Closest search this turn did not count (...)",说明最接近的一个及原因(同批次、被排除、范围外、读取 stdin、`Read` 等非搜索、文件名过于通用);细节经净化并截断至 60 个字符。
* **同回合同级文件合并:** 同一目录、同一类别(仅 code、test、prose)的新文件在同一回合内(完全没有 transcript 路径时为 120 秒内)只拒绝第一个,其余以附注放行。config、instruction,以及任何以 `.` 开头的路径段(点文件和所有点目录)或 8.3 短文件名下的文件从不合并;目录按解析符号链接后的真实位置判定和记录;有 transcript 路径但文件缺失、无法读取或得不到回合 ID 时不合并;编辑从不合并。
* **拒绝上限(可选):** 设置 `GATEGUARD_FACT_FORCE_MAX_DENIALS` 后,会话内首次触碰的拒绝次数达到该值后,新路径直接放行(计入 `cap_allows`)。`GATEGUARD_FACT_FORCE_FULL_DENIALS` 只决定消息详略(消息预算),而此变量决定是否拦截(拒绝预算)。事先搜索抵免和同级合并先于上限判定,不消耗上限;格式错误的值视为无上限,并在 stderr 警告一次。
-* **敏感目标:** `.env`/`.env.*`、`*.pem`/`*.key`/`*.p12`/`*.pfx`、`id_rsa*`/`id_ed25519*`/`id_ecdsa*`/`id_dsa*`/`.netrc`/`.pgpass`/`credentials*`/`secrets.*`、任一路径段恰为 `auth`、`authn`、`authz`、`security`、`secrets`、`payment`、`payments`、`billing`、`migrations`,以及 `.github/workflows/` 下的文件,不适用抵免、合并和上限,首次触碰总是拒绝。按字面路径和解析符号链接后的真实位置同时判定(`src/tools -> ../auth` 时 `src/tools/login.py` 也是敏感目标),真实位置无法解析时视为敏感。判定顺序:exempt → subagent → checked → 敏感? → 抵免 → 同级合并 → 上限 → 拒绝。
+* **敏感目标:** `.env`/`.env.*`、`*.pem`/`*.key`/`*.p12`/`*.pfx`、`id_rsa*`/`id_ed25519*`/`id_ecdsa*`/`id_dsa*`/`.netrc`/`.pgpass`/`credentials*`/`secrets.*`、任一路径段恰为 `auth`、`authn`、`authz`、`security`、`secrets`、`payment`、`payments`、`billing`、`migrations`,以及 `.github/workflows/` 下的文件,不适用抵免、合并和上限,首次触碰总是拒绝。按字面路径和解析符号链接后的真实位置同时判定(`src/tools -> ../auth` 时 `src/tools/login.py` 也是敏感目标),真实位置无法解析时视为敏感。判定顺序:exempt → subagent → checked → 敏感或硬链接? → 抵免 → 同级合并 → 上限 → 拒绝。`GATEGUARD_EXEMPT_GLOBS` 的豁免优先于一切规则,对敏感目标和硬链接目标同样生效。
+* **硬链接目标:** 链接数大于 1 的文件(或指向此类文件的符号链接)可经其他名称访问,因此与敏感目标一样不适用抵免、变更画像、仅注释放行、同级合并、上限和子代理放行;拒绝消息附带 "Hard-linked target: ..." 一行而非敏感目标一行。除文件不存在外的任何 stat 错误都视为硬链接。
+* **NotebookEdit:** 按对 `notebook_path` 的编辑门控(相同的类别、已检查键、抵免与上限规则;不读取单元格内容,因此总是完整问题,也从不按仅注释放行)。
* **例行 shell 门控与会话:** 门控触发前,只读命令(`ls`、`cat`、`rg`、`git status`/`log`/`diff`、`Get-ChildItem` 等,不含重定向、替换、`tee`、`xargs` 或未知命令)直接放行且不消耗门控,计入 `routine_readonly_passes`;以会话 ID 或 transcript 路径为键的状态空闲 8 小时失效,项目目录回退键仍为 30 分钟;子代理对敏感目标每个路径拒绝一次(不会为父会话解锁)。
* **判定指标(可选):** 设置 `GATEGUARD_METRICS=1` 后,每次判定向 `<GATEGUARD_STATE_DIR>/metrics.jsonl` 追加一行(不记录路径、命令或内容,超过 1 MiB 轮转为 `.1`);用 `node scripts/gateguard-report.js [--dir <path>] [--json]` 汇总。
-* **兼容性:** 新增的环境变量只有可选的 `GATEGUARD_FACT_FORCE_MAX_DENIALS` 和 `GATEGUARD_METRICS`;除子代理首次触碰敏感目标外,以前允许的操作不会变为拒绝,且从不返回 `permissionDecision: "allow"`。
+* **兼容性:** 新增的环境变量只有可选的 `GATEGUARD_FACT_FORCE_MAX_DENIALS` 和 `GATEGUARD_METRICS`;除子代理首次触碰敏感或硬链接目标、以及每个笔记本的首次 NotebookEdit(此前不受门控)外,以前允许的操作不会变为拒绝,且从不返回 `permissionDecision: "allow"`。
## 快速开始
diff --git a/hooks/hooks.metadata.json b/hooks/hooks.metadata.json
index 18f70fbf7..9760d32da 100644
--- a/hooks/hooks.metadata.json
+++ b/hooks/hooks.metadata.json
@@ -44,7 +44,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",
+ "description": "Fact-forcing gate: deny the first Edit/Write/MultiEdit/NotebookEdit of each file with questions chosen by target class and by what the change touches; a completed search naming the file in the current turn, a comment or whitespace-only edit, 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) and hard-linked files are always gated, also in subagents",
"fingerprint": "45fbef2d7f27"
}
],
diff --git a/manifests/context-packs/[email protected] b/manifests/context-packs/[email protected]
index f5e93a3c5..247d31253 100644
--- a/manifests/context-packs/[email protected]
+++ b/manifests/context-packs/[email protected]
@@ -1 +1 @@
-{"coverage":{"skills":293,"withTriggers":32},"generatedAt":"2026-09-24T23:51:22.784Z","id":"skill-triggers@1","model":{"effort":null,"id":"hand-seeded","source":"manual-curation-pending-regeneration"},"registryDigest":"aeceb8c5bc18354a1ebb30aff8d03800b188765f445d1ebe06969c4d2ff0da34","schemaVersion":1,"triggers":{"skill:api-connector-builder":["add api integration","new provider connector","match existing integration pattern"],"skill:api-design":["rest endpoint design","pagination api","status codes","api versioning","rate limiting api","resource naming","filtering api","api error responses","offset pagination","limit query parameter","pagination defaults"],"skill:backend-patterns":["express api","node backend architecture","nextjs api routes","server side patterns","data access layer","static file server","url path handling","file server"],"skill:browser-qa":["deployed feature test","visual regression screenshots","core web vitals check","axe accessibility audit","ship do not ship","staging verification"],"skill:canary-watch":["post deploy monitoring","smoke test url","production url check","console errors production","sse stream check","after deploy verification"],"skill:code-tour":["onboarding walkthrough","explain subsystem","architecture tour","pr walkthrough","rca tour"],"skill:coding-standards":["code review standards","naming conventions","readability review","immutability conventions","fix naming typo","export naming","consistent exports"],"skill:content-hash-cache-pattern":["cache file processing","content addressed cache","sha256 hash cache"],"skill:database-migrations":["zero downtime migration","schema change production","add column large table","backfill data","expand contract","concurrent index","migration rollback","prisma migration","django migration"],"skill:deployment-patterns":["ci cd setup","dockerize app","health checks","rollback strategy","production readiness","deploy pipeline","containerize application"],"skill:design-system":["design tokens","visual consistency audit","css custom properties","ui audit","design system bootstrap"],"skill:django-patterns":["django orm","drf api","django rest framework","django caching","django signals","django middleware"],"skill:django-security":["django authentication","csrf protection","sql injection prevention","xss prevention","django deployment security","role based access control","authorization middleware","permissions checks"],"skill:docker-patterns":["dockerfile review","docker compose setup","container security","multi service orchestration"],"skill:error-handling":["error types","retry logic","circuit breaker","user facing errors","exception handling patterns","typed errors","error boundaries","go error handling","custom error class","error codes","config validation"],"skill:evm-token-decimals":["token decimals","wei conversion","erc20 balance off","bridge token precision"],"skill:frontend-a11y":["aria attributes","screen reader support","focus management","semantic html","form labeling","keyboard navigation react","a11y lint errors"],"skill:git-workflow":["merge vs rebase","commit conventions","resolve merge conflict","branching strategy","clean up commits","pull request cleanup","git history tidy"],"skill:hexagonal-architecture":["ports and adapters","dependency injection boundaries","decouple domain from io"],"skill:kubernetes-patterns":["kubernetes manifests","kubectl debugging","pod probes","k8s rbac","autoscaling config","configmap secrets"],"skill:orch-fix-defect":["fix a bug","broken behavior","regression fix","reproduce bug","defect repair"],"skill:postgres-patterns":["slow postgres query","query optimization","index design","rls policies","supabase schema","postgres indexing","database performance","schema design postgres","postgres driver","node postgres","query planner"],"skill:python-patterns":["pythonic code","pep 8","type hints python","python code review","idiomatic python"],"skill:python-testing":["pytest fixtures","mocking python","parametrized tests","coverage python","tdd python"],"skill:redis-patterns":["cache aside pattern","distributed lock","redis rate limiting","cache invalidation"],"skill:regex-vs-llm-structured-text":["parse invoice","extract receipt data","text extraction pipeline","parse form fields","cheap document parser","extract table data","parse log lines","parse access logs","common log format","log line parsing"],"skill:rust-patterns":["rust ownership","borrow checker","rust error handling","traits rust","rust concurrency","idiomatic rust"],"skill:search-first":["find existing library","npm package research","before writing custom code","evaluate existing tools","add dependency research"],"skill:security-review":["security audit","authentication review","sanitize user input","secrets handling","payment security checklist","prevent injection attacks","secure api endpoints","authn authz review","vulnerability checklist","input validation security","parameterized queries","sql injection"],"skill:security-scan":["audit claude config","claudemd security","mcp server audit","agentshield scan","hook configuration audit","settings json security"],"skill:tdd-workflow":["write test first","failing test","red green refactor","test driven development","regression test first","write a regression test"],"skill:verification-loop":["pre pr checks","verification report","quality gates","build lint test coverage","before creating a pr"]},"triggersDigest":"25b97a9e06fc336c7cf95ab854ed1a41033a54bcd6e1fb1cf69dc906332462aa"}
+{"coverage":{"skills":293,"withTriggers":32},"generatedAt":"2026-09-24T23:51:22.784Z","id":"skill-triggers@1","model":{"effort":null,"id":"hand-seeded","source":"manual-curation-pending-regeneration"},"registryDigest":"99577fd3a841c82e0c254b85cb4746034372169e750a3e0977862f13656e1a8b","schemaVersion":1,"triggers":{"skill:api-connector-builder":["add api integration","new provider connector","match existing integration pattern"],"skill:api-design":["rest endpoint design","pagination api","status codes","api versioning","rate limiting api","resource naming","filtering api","api error responses","offset pagination","limit query parameter","pagination defaults"],"skill:backend-patterns":["express api","node backend architecture","nextjs api routes","server side patterns","data access layer","static file server","url path handling","file server"],"skill:browser-qa":["deployed feature test","visual regression screenshots","core web vitals check","axe accessibility audit","ship do not ship","staging verification"],"skill:canary-watch":["post deploy monitoring","smoke test url","production url check","console errors production","sse stream check","after deploy verification"],"skill:code-tour":["onboarding walkthrough","explain subsystem","architecture tour","pr walkthrough","rca tour"],"skill:coding-standards":["code review standards","naming conventions","readability review","immutability conventions","fix naming typo","export naming","consistent exports"],"skill:content-hash-cache-pattern":["cache file processing","content addressed cache","sha256 hash cache"],"skill:database-migrations":["zero downtime migration","schema change production","add column large table","backfill data","expand contract","concurrent index","migration rollback","prisma migration","django migration"],"skill:deployment-patterns":["ci cd setup","dockerize app","health checks","rollback strategy","production readiness","deploy pipeline","containerize application"],"skill:design-system":["design tokens","visual consistency audit","css custom properties","ui audit","design system bootstrap"],"skill:django-patterns":["django orm","drf api","django rest framework","django caching","django signals","django middleware"],"skill:django-security":["django authentication","csrf protection","sql injection prevention","xss prevention","django deployment security","role based access control","authorization middleware","permissions checks"],"skill:docker-patterns":["dockerfile review","docker compose setup","container security","multi service orchestration"],"skill:error-handling":["error types","retry logic","circuit breaker","user facing errors","exception handling patterns","typed errors","error boundaries","go error handling","custom error class","error codes","config validation"],"skill:evm-token-decimals":["token decimals","wei conversion","erc20 balance off","bridge token precision"],"skill:frontend-a11y":["aria attributes","screen reader support","focus management","semantic html","form labeling","keyboard navigation react","a11y lint errors"],"skill:git-workflow":["merge vs rebase","commit conventions","resolve merge conflict","branching strategy","clean up commits","pull request cleanup","git history tidy"],"skill:hexagonal-architecture":["ports and adapters","dependency injection boundaries","decouple domain from io"],"skill:kubernetes-patterns":["kubernetes manifests","kubectl debugging","pod probes","k8s rbac","autoscaling config","configmap secrets"],"skill:orch-fix-defect":["fix a bug","broken behavior","regression fix","reproduce bug","defect repair"],"skill:postgres-patterns":["slow postgres query","query optimization","index design","rls policies","supabase schema","postgres indexing","database performance","schema design postgres","postgres driver","node postgres","query planner"],"skill:python-patterns":["pythonic code","pep 8","type hints python","python code review","idiomatic python"],"skill:python-testing":["pytest fixtures","mocking python","parametrized tests","coverage python","tdd python"],"skill:redis-patterns":["cache aside pattern","distributed lock","redis rate limiting","cache invalidation"],"skill:regex-vs-llm-structured-text":["parse invoice","extract receipt data","text extraction pipeline","parse form fields","cheap document parser","extract table data","parse log lines","parse access logs","common log format","log line parsing"],"skill:rust-patterns":["rust ownership","borrow checker","rust error handling","traits rust","rust concurrency","idiomatic rust"],"skill:search-first":["find existing library","npm package research","before writing custom code","evaluate existing tools","add dependency research"],"skill:security-review":["security audit","authentication review","sanitize user input","secrets handling","payment security checklist","prevent injection attacks","secure api endpoints","authn authz review","vulnerability checklist","input validation security","parameterized queries","sql injection"],"skill:security-scan":["audit claude config","claudemd security","mcp server audit","agentshield scan","hook configuration audit","settings json security"],"skill:tdd-workflow":["write test first","failing test","red green refactor","test driven development","regression test first","write a regression test"],"skill:verification-loop":["pre pr checks","verification report","quality gates","build lint test coverage","before creating a pr"]},"triggersDigest":"25b97a9e06fc336c7cf95ab854ed1a41033a54bcd6e1fb1cf69dc906332462aa"}
diff --git a/skills/gateguard/SKILL.md b/skills/gateguard/SKILL.md
index 8e56950cd..53566ec59 100644
--- a/skills/gateguard/SKILL.md
+++ b/skills/gateguard/SKILL.md
@@ -1,6 +1,6 @@
---
name: gateguard
-description: "PreToolUse fact-forcing gate that denies the first Edit/Write/Bash (including MultiEdit) attempt until the agent presents concrete facts (importers, data schemas, verbatim user instruction), then allows retry; A/B-tested at +2.25 quality points. Use when enabling or configuring the GateGuard hook, exempting paths via env vars, or handling first-touch denials."
+description: "PreToolUse fact-forcing gate that denies the first Edit/Write/Bash (including MultiEdit and NotebookEdit) attempt until the agent presents concrete facts (importers, data schemas, verbatim user instruction), then allows retry; A/B-tested at +2.25 quality points. Use when enabling or configuring the GateGuard hook, exempting paths via env vars, or handling first-touch denials."
metadata:
origin: community
---
@@ -50,6 +50,9 @@ Both agents produce code that runs and passes tests. The difference is design de
MultiEdit is handled identically — each file in the batch is gated individually;
entries without their own `file_path` are gated as the call's `file_path`.
+NotebookEdit is gated as an Edit of its `notebook_path`: same class, checked
+key, credit and cap rules, the full questions (the cell change is not read),
+and never a comment-only pass.
The questions depend on the target's class (see
[Questions by target class](#questions-by-target-class)). For **code**
@@ -122,7 +125,7 @@ Supported extensions: `.js .mjs .cjs .jsx .ts .tsx .mts .cts .py .pyi .go .rs
.bat .cmd`. Any other extension, a
missing or non-string field, more than 64 MultiEdit entries, a side over
64 KiB, or 256 KiB in total means the full questions, word for word. Sensitive
-targets always get the full questions. Other classes keep their class
+and hard-linked targets and NotebookEdit calls always get the full questions. Other classes keep their class
questions. Each question has a stable id (`importers`, `public-api`,
`local-callers`, `callers`, `no-duplicate`, `data-schema`,
`quote-instruction`, and one per class question), listed in
@@ -244,16 +247,22 @@ anything is ambiguous.
### Order of checks
-For each Edit/Write target (and each MultiEdit entry) the gate decides in
-this order; the first rule that applies wins:
+For each Edit/Write/NotebookEdit target (and each MultiEdit entry) the gate
+decides in this order; the first rule that applies wins:
1. **Exempt** (`GATEGUARD_EXEMPT_GLOBS`, Claude settings files) — allowed.
+ Operator exemptions are authoritative: they win over every later rule,
+ including the sensitive and hard-link rules, so a glob that covers
+ `src/auth/**` or a hard-linked file turns its check off. Exempt only
+ paths that may be edited without the check.
2. **Subagent** call — allowed (the parent session was already gated),
- except a [sensitive target](#sensitive-targets): denied once per path
+ except a [sensitive](#sensitive-targets) or
+ [hard-linked](#hard-linked-targets) target: denied once per path
unless the parent already gated it. A subagent's retry does not unlock
the path for the parent.
3. **Already checked** this session — allowed.
-4. **Sensitive target?** — if so, skip straight to the denial (step 9).
+4. **Sensitive or hard-linked target?** — if so, skip straight to the
+ denial (step 9).
5. **Prior-search credit** — allowed with a note.
6. **Comment or whitespace-only Edit** — allowed with a note, not marked
checked.
@@ -292,9 +301,21 @@ on its absolute path. Any error while deciding (a dangling symlink, a file
where a directory should be, a permission error) counts as sensitive.
Destructive and routine shell gates are unaffected.
+### Hard-linked targets
+
+A file with more than one hard link (`nlink > 1`, or a symlink to such a file)
+is also reachable under another name, which may be sensitive or in another
+class, so the path being edited says little about what changes. It gets the
+same treatment as a sensitive target — no prior-search credit, change profile,
+comment-only pass, sibling collapse, denial cap, or subagent bypass — and its
+denial carries "Hard-linked target: prior-search credit, sibling collapse, and
+the denial cap do not apply." instead of the sensitive line (a target that is
+both says "Sensitive target"). A stat error other than a missing file counts as
+hard-linked; a new file that does not exist yet is not.
+
### Prior-search credit
-An Edit, Write, or MultiEdit entry is allowed, with an
+An Edit, Write, NotebookEdit, or MultiEdit entry is allowed, with an
`additionalContext` note naming the search, when a qualifying search in the
**current human turn** already covered the file:
@@ -397,7 +418,8 @@ An Edit, Write, or MultiEdit entry is allowed, with an
as before.
- **Falls back to deny:** a missing, unreadable, or non-file transcript,
garbage records, or any internal error mean no credit.
-- **Closest miss in the denial:** when a non-sensitive first touch is denied
+- **Closest miss in the denial:** when an ordinary (not sensitive or
+ hard-linked) first touch is denied
and a call in the turn mentioned the file without crediting it, the denial
adds one line, "Closest search this turn did not count (`<tool>`
`<detail>`): `<why>`.", naming the closest such call and why it failed: sent
@@ -437,7 +459,8 @@ entry reads cleanly:
division), JSX-like tags, and `-->`; in shell scripts heredocs, backticks,
`$(` inside double quotes, `$'...'`, line continuations and here-strings
(see the design notes for the full list);
-- config, instruction, and sensitive targets never pass this way.
+- config, instruction, sensitive and hard-linked targets, and NotebookEdit
+ calls never pass this way.
The edit is also checked against the current file (a regular file of at
most 1 MiB, read by the hook and never stored): `old_string` must be found as
@@ -517,7 +540,9 @@ working.
`GATEGUARD_METRICS` (unset means no metrics). The existing controls are
unchanged.
- **Nothing previously allowed is now denied**, except a subagent's first
- touch of a sensitive target. The other rules only remove denials, and never return `permissionDecision: "allow"`, so other hooks
+ touch of a sensitive or hard-linked target, and the first NotebookEdit of
+ each notebook (NotebookEdit was not gated before). The other rules only
+ remove denials, and never return `permissionDecision: "allow"`, so other hooks
and permission rules still apply.
- **Trust limit:** prior-search credit reads the local transcript file,
which the agent could in principle write to. The credit verifies observed
@@ -552,12 +577,12 @@ load-bearing destructive-Bash checks keep running:
| Variable | Default | Effect |
|---|---|---|
| `GATEGUARD_BASH_ROUTINE_DISABLED` | unset (gate on) | Disables the **routine-Bash** gate only. The destructive-Bash gate (`rm -rf`, `git reset --hard`, `drop table`, `dd if=`, …) is unaffected. |
-| `GATEGUARD_EXEMPT_GLOBS` | unset (no exemptions) | Comma-separated globs; a matching Edit/Write/MultiEdit target skips first-touch fact-forcing. Intended for low-import-value trees (tests, generated artifacts, scratch dirs) where "who imports this / what schema" carries no signal. |
+| `GATEGUARD_EXEMPT_GLOBS` | unset (no exemptions) | Comma-separated globs; a matching Edit/Write/MultiEdit/NotebookEdit target skips first-touch fact-forcing, even when it is sensitive or hard-linked. Intended for low-import-value trees (tests, generated artifacts, scratch dirs) where "who imports this / what schema" carries no signal. |
| `GATEGUARD_FACT_FORCE_FULL_DENIALS` | `3` | How many denials emit the full fact block before later ones condense to a single line. `0` condenses from the very first denial. |
-| `GATEGUARD_FACT_FORCE_MAX_DENIALS` | unset (no cap) | A **denial budget**: caps how many first-touch Edit/Write/MultiEdit denials a session draws. Once that many denials have been issued, further new paths pass through instead of being denied (counted in `cap_allows`, not as denials); `0` passes from the first. Prior-search credit and sibling collapse run first and never use it up, and [sensitive targets](#sensitive-targets) are always denied. Destructive and routine Bash stay gated. The cap is best effort when hooks run concurrently: a lost count update can add a denial, but never lets a new path through early. Opt-in: unset, or any value that is not a whole non-negative integer (surrounding spaces allowed), keeps the deny-every-new-path behaviour; a malformed value is reported once on stderr (`ignoring malformed GATEGUARD_FACT_FORCE_MAX_DENIALS=…; the denial cap is not active.`). Unlike `GATEGUARD_FACT_FORCE_FULL_DENIALS`, a **message budget** that only changes how much text a denial carries, this changes whether the operation is blocked. Condensed denials name this variable. |
+| `GATEGUARD_FACT_FORCE_MAX_DENIALS` | unset (no cap) | A **denial budget**: caps how many first-touch Edit/Write/MultiEdit/NotebookEdit denials a session draws. Once that many denials have been issued, further new paths pass through instead of being denied (counted in `cap_allows`, not as denials); `0` passes from the first. Prior-search credit and sibling collapse run first and never use it up, and [sensitive](#sensitive-targets) and [hard-linked](#hard-linked-targets) targets are always denied. Destructive and routine Bash stay gated. The cap is best effort when hooks run concurrently: a lost count update can add a denial, but never lets a new path through early. Opt-in: unset, or any value that is not a whole non-negative integer (surrounding spaces allowed), keeps the deny-every-new-path behaviour; a malformed value is reported once on stderr (`ignoring malformed GATEGUARD_FACT_FORCE_MAX_DENIALS=…; the denial cap is not active.`). Unlike `GATEGUARD_FACT_FORCE_FULL_DENIALS`, a **message budget** that only changes how much text a denial carries, this changes whether the operation is blocked. Condensed denials name this variable. |
| `GATEGUARD_BASH_EXTRA_DESTRUCTIVE` | unset | Extra destructive-command patterns, as regex source, added to the built-in set. A malformed regex is treated as unset (built-ins still apply) and logged once to stderr. |
| `GATEGUARD_STATE_DIR` | `~/.gateguard` | Where per-session gate state is kept. If state cannot be persisted the gate allows the operation rather than looping, and names this variable in the warning. |
-| `GATEGUARD_METRICS` | unset (off) | Records one line per Edit/Write/MultiEdit/Bash/PowerShell decision in `<GATEGUARD_STATE_DIR>/metrics.jsonl` (see [Decision metrics](#decision-metrics)). Never changes a decision. |
+| `GATEGUARD_METRICS` | unset (off) | Records one line per Edit/Write/MultiEdit/NotebookEdit/Bash/PowerShell decision in `<GATEGUARD_STATE_DIR>/metrics.jsonl` (see [Decision metrics](#decision-metrics)). Never changes a decision. |
`GATEGUARD_BASH_ROUTINE_DISABLED` and `GATEGUARD_METRICS` accept `1`, `true`,
`on`, `enabled`, `enable`, or `yes` (case- and whitespace-insensitive); any
@@ -577,10 +602,10 @@ file it decided):
|---|---|
| `v` | Schema version (`1`) |
| `session` | First 12 hex characters of the sha256 of the session key |
-| `tool` | `Edit`, `Write`, `MultiEdit`, `Bash` or `PowerShell` |
+| `tool` | `Edit`, `Write`, `MultiEdit`, `NotebookEdit`, `Bash` or `PowerShell` |
| `class` | Target class, or `null` for shell commands |
| `decision` | `deny`, `credit`, `sibling`, `cap`, `trivial`, `pass-checked`, `pass-exempt`, `pass-subagent`, `routine-deny`, `routine-readonly`, `destructive-deny` or `pass` |
-| `reason` | Short code: `first-touch`, `sensitive`, `near-miss:<code>`, `subagent-sensitive`, `prior-search`, `comment-whitespace`, `same-turn-dir`, `max-denials`, `checked`, `exempt-glob`, `claude-settings`, `no-path`, `subagent`, `readonly-git`, `readonly`, `first-command`, `routine-checked`, `routine-disabled`, `destructive`, `destructive-retry`, `state-error` |
+| `reason` | Short code: `first-touch`, `sensitive`, `hard-linked`, `near-miss:<code>`, `subagent-sensitive`, `subagent-hard-linked`, `prior-search`, `comment-whitespace`, `same-turn-dir`, `max-denials`, `checked`, `exempt-glob`, `claude-settings`, `no-path`, `subagent`, `readonly-git`, `readonly`, `first-command`, `routine-checked`, `routine-disabled`, `destructive`, `destructive-retry`, `state-error` |
| `questions` | Question ids of a first-touch denial; `null` otherwise |
| `sensitive` | Whether the target is a [sensitive target](#sensitive-targets) |
| `profile` | Change-profile flags when the profile was computed; `null` otherwise |
@@ -624,6 +649,8 @@ Both patterns and paths use `/` separators and lowercase matching. `*` matches
within a segment, `**` across segments, and `?` one non-separator character.
`**/` includes zero directories, so `**/tests/**` also matches `tests/foo.js`.
Malformed patterns are dropped without granting an exemption.
+An exemption applies before every other rule, including the sensitive and
+hard-link rules (see [Order of checks](#order-of-checks)).
Since 2.2.1, `services/**` only covers the project's root services tree, and
`*.md` only covers its root Markdown files. Use `**/*.md` for all Markdown