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): move code rationale to design notes

Jeffrey Montoya979d5be8221a
diff --git a/docs/gateguard/design-notes.md b/docs/gateguard/design-notes.md
new file mode 100644
index 000000000..025ded3ee
--- /dev/null
+++ b/docs/gateguard/design-notes.md
@@ -0,0 +1,256 @@
+# GateGuard design notes
+
+Rationale for the decisions in the GateGuard fact-forcing gate
+(`scripts/hooks/gateguard-fact-force.js` and `scripts/lib/gateguard-*.js`).
+Code comments point here as `docs/gateguard/design-notes.md#<anchor>`; keep
+headings stable, since they are the anchors.
+
+## Module layout
+
+- `scripts/hooks/gateguard-fact-force.js`: the hook. Owns the shell parser
+ (`quoteAwareSegments`, `commandBasename`, `SHELL_SEGMENT_SEPARATORS`) that the
+ 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.
+- `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
+ batch ids and the turn's shell commands.
+- `scripts/lib/gateguard-search-evidence.js`: decides whether a search in the
+ current turn covers a target (prior-search credit). Its shell-dependent part
+ is built by `createSearchEvidence()` from the hook's shell parser, so the
+ parser the destructive detector relies on is shared, not copied or moved.
+- `scripts/lib/gateguard-state.js`: pure helpers for the session-state fields
+ (counters, per-class counts, sibling dir gates). Reading and writing the
+ state file, and the one-write event helpers built on it, stay in the hook.
+
+## Fail to deny
+
+Every allowance other than a retry of an already-gated target (prior-search
+credit, sibling collapse, the denial cap) is an exception to the first-touch
+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
+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 and
+sibling passes return `additionalContext`, and the cap pass returns the input
+unchanged.
+
+## Read is not evidence
+
+`Read` never earns prior-search credit. Claude Code already requires a Read of
+a file before an Edit of it, so crediting Read would switch the Edit gate off.
+Only `Glob`, `Grep`, `LS` and shell search commands count.
+
+## Sensitive targets
+
+Secrets, keys, auth/payment code, migrations and CI workflows always draw the
+first-touch denial: prior-search credit, sibling collapse and the denial cap do
+not apply to them, and the denial says so.
+
+- Basename, extension and segment rules are exact, never substrings.
+- `.github/workflows/` is also matched below an ancestor (an unverified
+ worktree, or a target outside the project root).
+- A target is sensitive on its lexical path or on its real (symlink-resolved)
+ location, so `src/tools -> ../auth` cannot launder `src/tools/login.py`.
+- A real location that cannot be resolved (dangling symlink, `ENOTDIR`,
+ `EACCES`, loops), a non-string path, or any error counts as sensitive.
+
+## Target resolution
+
+Relative targets resolve against the tool's `cwd` first, then
+`CLAUDE_PROJECT_DIR`, then the process cwd. This deliberately differs from
+`GATEGUARD_EXEMPT_GLOBS`, whose globs are project-relative (`CLAUDE_PROJECT_DIR`
+first). The canonical checked-state key folds `a.py`, `./a.py` and the absolute
+path to one gate; Windows-style paths also fold separators and case.
+
+A target is classified by its project-relative path, so an ancestor such as
+`/home/me/tests/proj` never leaks into the class; targets outside the root keep
+their absolute path. A Windows-style path has no real location on a POSIX host
+(and vice versa), so real-path checks are skipped for it.
+
+## Target classes
+
+The first matching class wins: instruction, test, prose, config, code (the
+fallback). Cursor `.mdc` rule files are instructions wherever they live. A
+basename starting with `.env` is config unless it has a code extension
+(`.env.example.ts` is source). Code targets keep the original four questions;
+other classes get class-specific questions and a class-specific condensed hint.
+
+## Worktree prefix
+
+A `.claude/worktrees/<name>/` prefix is stripped only when that worktree is real
+(its `.git` exists). Otherwise the path stays under `.claude`, which is an
+instruction directory and blocks sibling collapse.
+
+## Windows name normalization
+
+Windows ignores trailing dots and spaces in a name and treats `name:stream` as
+`name`, so segments are normalized the same way before classification:
+`CLAUDE.md.` and `CLAUDE.md::$DATA` both name `CLAUDE.md`.
+
+## Turn boundaries
+
+The scan walks the transcript tail backwards to the latest human message or
+compaction. Only a user record whose content is a non-empty array of
+`tool_result` blocks is a tool result; any other user record is a turn
+boundary, which can only shrink the credit window. A compaction summary or
+`compact_boundary` record discards the earlier turn and starts a new one. The
+tail read is bounded (bytes and lines) to keep the hook fast.
+
+## Turn identity
+
+Claude Code stamps every user record of a turn with the same `promptId`, so it
+identifies the turn even after the boundary has scrolled out of the tail
+window; without one, the boundary record's `uuid` (or a hash of its line) is
+used. When no boundary is found, a clipped window is the current turn only if
+its `promptId`s agree; two or more mean an unrecognised turn start, and an
+unclipped file has no turn at all.
+
+## Tool result pairing
+
+A search counts only when it completed without error. A tool-use id that occurs
+more than once in the window cannot be tied to one result, so it never counts.
+
+## Same-batch searches
+
+Searches in the pending call's own assistant message never count: their results
+were not seen when the edit was decided. The batch is located by the pending
+`tool_use_id`, or else taken to be the newest assistant message.
+
+## Ambiguous shell is not evidence
+
+Command substitution, process substitution, heredocs and PowerShell backtick
+escapes make the searched text ambiguous, so a shell command containing any of
+them yields no evidence. Commands over 8192 characters yield none either.
+
+## Directory changes
+
+A `cd` (or its PowerShell equivalents) in any other shell call of the turn
+leaves the cwd of every shell search unknown: shell searches then give no
+directory evidence, and their relative operands scope nothing. Within one command, a plain literal `cd <dir>` rebases
+later relative operands; any other directory change makes them unresolvable.
+Operands that are variables, `~`, or relative to an unknown cwd scope nothing.
+
+## Stdin is not a tree search
+
+A search segment that reads stdin (input redirection, a pipe into it, or no
+path operand without recursion) searched piped text, not the tree, so it gives
+no evidence. A quoted `<` cannot be told from a redirection and is treated as
+one. `||` also marks the next segment as piped, which only ever removes
+evidence.
+
+## Search scope
+
+Each search offers stem texts, candidate directories, the scope the target must
+lie in, and path operands. The target must lie inside the scope. A search whose
+operands are all the target itself read the target rather than searched for it,
+and gives nothing. A `Glob` without glob characters is a single-file lookup: it
+names no directory. A `Glob` with an empty literal prefix and no explicit path
+names only the implicit cwd, so it gives no directory credit. Directory
+evidence from shell operands must name a directory that exists now.
+PowerShell `-Path`/`-LiteralPath` values count as operands but never as
+directory evidence.
+
+## Stem matching
+
+A target's stem (basename without extension) credits it only when it has at
+least four characters and is not generic (`index`, `utils`, `config`, ...).
+Matching is a word-boundary `indexOf` scan; a `RegExp` is never built from
+transcript text.
+
+## Search filters
+
+A search that excluded the target never saw it:
+
+- exclusion values, and the flags that introduce them, are never a stem source;
+- an exclusion that names the stem, or matches the file or any directory above
+ it, blocks credit;
+- unreadable exclusion lists (`--exclude-from`, `--ignore-file`,
+ `git ls-files -X`) and more than 32 exclusions block credit;
+- an exclusion glob past the matching bounds, or malformed, counts as covering
+ the target.
+
+find: a negated or pruned name test is an exclusion; a plain `-name`/`-iname` is
+an include. `--ignore`/`--hide` exclude names only for `ls` (rg's `--ignore` is
+a switch).
+
+## Include filters
+
+Basename include globs (`--include`, `-g`, `--glob`, `-name`, PowerShell
+`-Filter`/`-Include`) that all miss the target stop its stem from crediting. An
+include glob past the matching bounds admits the target (the stem, scope and
+exclusion checks still apply); a malformed one does not.
+
+## Glob matching without RegExp
+
+Filter globs are matched by dynamic programming over glob tokens, never by a
+`RegExp`, so a hostile glob cannot cause regex backtracking. Globs are bounded
+to 256 characters and 32 brace alternatives. Bracket classes support members,
+ranges, `!`/`^` negation and a leading literal `]`; an unclosed class is
+malformed. An unbalanced `{` is literal.
+
+## Flag parsing
+
+Only path operands can scope a search:
+
+- flags that consume a value are skipped with it; single-dash clusters
+ (`-rne PAT`) are read letter by letter, and a value flag ends the cluster;
+- for grep-family tools, `rg`, `git grep`, `Select-String` and `fd`, the first
+ positional is the pattern unless `-e`/`-f` (grep family, `rg`, `git grep`
+ only; fd's `-e` is an extension) supplied it;
+- fd's `-E/--exclude` takes a value; rg's `-r/--replace` takes a value.
+
+## PowerShell parameter binding
+
+PowerShell binds a parameter by any unambiguous prefix, by `-Name:value`, and by
+comma lists across arguments, so `-Exclude` has many spellings. A parameter that
+cannot be resolved may be an exclusion in disguise: neither it nor a value it
+may carry is a stem source.
+
+## New-file detection
+
+A Write target is new only when `lstat` reports `ENOENT`; any other error counts
+as an existing file. Only a new file may earn directory credit or sibling
+collapse.
+
+## Sibling collapse
+
+A new file whose directory had a sibling gated moments ago passes with a note
+instead of a repeat denial.
+
+- Only code, test and prose targets collapse. Harness and tooling directories
+ are dot-directories, so any dot segment blocks collapse, as do 8.3 short names
+ (`CLAUDE~1`), which can alias any directory.
+- The gate is keyed by the real directory. A symlinked directory must keep the
+ class and pass the same screen, and must not be sensitive, so
+ `src/tools -> .claude/hooks` never collapses.
+- A gate opens for the same turn id; without a turn id on either side, for 120 s.
+ The 120 s rule applies only when there is no transcript at all; an unusable
+ transcript never collapses.
+- A gate stamped in the future, or not created by a denial, is ignored.
+
+## Denial cap
+
+`GATEGUARD_FACT_FORCE_MAX_DENIALS` is validated whole (digits only, a safe
+integer), not with `parseInt`: a prefix parse would turn `3oops` into a cap. A
+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.
+
+## State file is untrusted
+
+The session state file can be edited or corrupted, so every field is validated
+on read: counters clamp to non-negative integers, maps are null-prototype and
+reject `__proto__`, `constructor` and `prototype` keys, and malformed or
+old-shape entries are dropped. `dir_gates` maps `<class>\u0000<canonicalDir>` to
+`{ turn, at, first, ordinal }` and keeps the 50 newest entries. Concurrent
+writers are merged on save (checked keys by union, counts by maximum, gates by
+newest `at`). Marking a target checked and recording its event happen in one
+state write, so an event is never half-recorded.
diff --git a/scripts/hooks/gateguard-fact-force.js b/scripts/hooks/gateguard-fact-force.js
index 3bf5361a8..1608ccfff 100644
--- a/scripts/hooks/gateguard-fact-force.js
+++ b/scripts/hooks/gateguard-fact-force.js
@@ -9,17 +9,10 @@
* The act of investigation creates awareness that self-evaluation never did.
*
* Gates:
- * - Edit/Write/MultiEdit (first touch of each file): questions chosen by
- * target class (code: list importers, affected API, verify data schemas,
- * quote instruction)
+ * - Edit/Write/MultiEdit (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)
*
- * A first touch already covered by a completed search in the current turn,
- * or a new sibling of a file just gated, passes with an additionalContext
- * note (never an "allow" decision). Sensitive targets are always denied, and
- * anything ambiguous falls back to the denial.
- *
* Compatible with run-with-flags.js via module.exports.run().
* Cross-platform (Windows, macOS, Linux).
*
@@ -1553,9 +1546,7 @@ function getFullDenialBudget() {
return DEFAULT_FULL_DENIALS;
}
-// --- Opt-in session cap on first-touch denials (GATEGUARD_FACT_FORCE_MAX_DENIALS) ---
-// Validated whole, not with parseInt: a prefix parse would turn '3oops' into a
-// cap. A malformed value leaves the gate uncapped and says so once on stderr.
+// --- Session cap on first-touch denials ---
const MAX_DENIALS_PATTERN = /^\d+$/;
const MAX_DENIALS_WARN_VALUE_CHARS = 64;
@@ -1589,7 +1580,6 @@ function getMaxDenialBudget() {
return Number.POSITIVE_INFINITY;
}
-/** Mark a target checked and apply `update` in one state write, so an event is never half-recorded. */
function markCheckedWith(key, update) {
const loaded = loadState();
const withKey = loaded.checked.includes(key) ? loaded : { ...loaded, checked: [...loaded.checked, key] };
@@ -1597,11 +1587,6 @@ function markCheckedWith(key, update) {
return { ok: saveState(state), value };
}
-/**
- * Record a denial (returns its ordinal) or, once denials reach `cap`, a cap pass
- * (`denials` null). The cap check reads the state the write persists, so a lost
- * concurrent update can add a denial but never passes a target early.
- */
function markCheckedAndCountDenial(key, { cls, dirGate, cap = Number.POSITIVE_INFINITY } = {}) {
const { ok, value: denials } = markCheckedWith(key, state => {
if (getDenialCount(state) >= cap) {
@@ -1632,7 +1617,7 @@ function markCheckedAndCountCredit(key, cls) {
})).ok;
}
-// --- Sibling gates and per-class counters ---
+// --- Sibling gates ---
const SIBLING_NO_TURN_WINDOW_MS = 120 * 1000;
@@ -1643,10 +1628,7 @@ function markCheckedAndCountSibling(key) {
})).ok;
}
-/**
- * Open sibling gate for this key: same turn id, or (no turn id on either side)
- * within 120 s. A gate stamped in the future or without a denial is ignored.
- */
+// see docs/gateguard/design-notes.md#sibling-collapse
function findSiblingGate(key, turnId, now = Date.now()) {
const gates = getDirGates(loadState());
if (!Object.hasOwn(gates, key)) return null;
@@ -1899,7 +1881,6 @@ function classGateMsg(filePath, cls, isWrite) {
].join('\n');
}
-/** Full first-touch denial; code targets keep the editGateMsg/writeGateMsg text. */
function firstTouchGateMsg(filePath, isWrite, cls) {
if (!CLASS_QUESTIONS[cls]) {
return isWrite ? writeGateMsg(filePath) : editGateMsg(filePath);
@@ -1911,7 +1892,6 @@ function firstTouchGateMsg(filePath, isWrite, cls) {
* Condensed single-line denial used after the full-block budget is spent
* (#2142). Carries the denial ordinal so consecutive denials differ
* textually, and a one-line recovery hint instead of the multi-line block.
- * Non-code classes swap the middle clause for a class-specific hint.
*/
function condensedGateMsg(action, filePath, ordinal, cls = 'code', sensitive = false) {
const safe = sanitizePath(filePath);
@@ -2038,7 +2018,6 @@ function creditNote(match, filePath) {
);
}
-/** Only a positively absent target is new; any other fs error counts as existing. */
function isMissingOnDisk(resolved) {
try {
fs.lstatSync(resolved);
@@ -2112,7 +2091,7 @@ function run(rawInput) {
if (!isChecked([fileKey, filePath])) {
const isNewFile = toolName === 'Write' && isNewFileTarget(filePath, data);
const cls = classifyTargetFor(filePath, data);
- // Sensitive targets skip credit, sibling collapse and the cap.
+ // see docs/gateguard/design-notes.md#sensitive-targets
const sensitive = isSensitiveTargetFor(filePath, data);
const credit = sensitive ? null : findCreditingSearch(getTurnScan(), filePath, isNewFile, data);
if (credit) {
@@ -2122,7 +2101,6 @@ function run(rawInput) {
return { additionalContext: creditNote(credit, filePath), exitCode: 0 };
}
const turnId = isNewFile && !sensitive ? currentTurnId(getTurnScan()) : null;
- // The 120 s no-turn rule applies only without any transcript; an unusable one never collapses.
const collapsible = isNewFile && !sensitive && (turnId !== null || !transcriptPathFor(data));
const gateKey = collapsible ? newFileGateKey(filePath, data, cls) : null;
const sibling = gateKey ? findSiblingGate(gateKey, turnId) : null;
@@ -2139,7 +2117,8 @@ function run(rawInput) {
return allowWithStateWarning();
}
if (denials === null) {
- return rawInput; // session denial cap reached (GATEGUARD_FACT_FORCE_MAX_DENIALS)
+ // see docs/gateguard/design-notes.md#denial-cap
+ return rawInput;
}
return firstTouchDenial(filePath, { isWrite: toolName === 'Write', denials, cls, sensitive });
}
@@ -2175,7 +2154,8 @@ function run(rawInput) {
return allowWithStateWarning();
}
if (denials === null) {
- continue; // session denial cap reached (GATEGUARD_FACT_FORCE_MAX_DENIALS)
+ // see docs/gateguard/design-notes.md#denial-cap
+ continue;
}
return firstTouchDenial(filePath, { isWrite: false, denials, cls, sensitive });
}
diff --git a/scripts/lib/gateguard-search-evidence.js b/scripts/lib/gateguard-search-evidence.js
index 38ddec1d0..7d0f9231f 100644
--- a/scripts/lib/gateguard-search-evidence.js
+++ b/scripts/lib/gateguard-search-evidence.js
@@ -5,9 +5,7 @@ const path = require('path');
const { WINDOWS_PATH_PATTERN } = require('./gateguard-target-class');
const { excludedBatchId } = require('./gateguard-turn-scan');
-// --- Prior-search credit ---
-// `Read` never counts: Claude Code already requires a Read before an Edit, so
-// crediting it would disable the Edit gate. Any ambiguity or failure means no credit.
+// --- Search commands and flags ---
const SHELL_SEARCH_COMMANDS = new Set([
'rg',
@@ -26,31 +24,23 @@ const SHELL_SEARCH_COMMANDS = new Set([
]);
const GIT_SEARCH_SUBCOMMANDS = new Set(['grep', 'ls-files']);
const DIRECTORY_CHANGE_COMMANDS = new Set(['cd', 'pushd', 'popd', 'chdir', 'set-location', 'sl', 'push-location', 'pop-location']);
-// Search kinds whose first positional argument is the pattern, not a path.
const PATTERN_FIRST_SEARCHES = new Set(['grep', 'egrep', 'fgrep', 'rg', 'git grep', 'select-string', 'sls', 'fd']);
const RECURSIVE_BY_DEFAULT = new Set(['rg', 'git grep', 'git ls-files', 'find', 'fd', 'tree']);
const GREP_FAMILY = new Set(['grep', 'egrep', 'fgrep']);
const POWERSHELL_SEARCHES = new Set(['get-childitem', 'gci', 'select-string', 'sls']);
-// Flags whose value is the search pattern (so the first positional is a path).
const PATTERN_VALUE_FLAGS = new Set(['-e', '-f', '--regexp', '--file']);
-// Flags that consume the next argument; that argument is never a path operand.
const VALUE_FLAGS = new Set([
'-e', '-f', '-g', '-t', '-T', '-m', '-A', '-B', '-C',
'--regexp', '--file', '--type', '--glob', '--iglob', '--include', '--exclude', '--exclude-dir', '--exclude-from',
'--ignore-file', '--max-count', '--replace',
'-name', '-iname', '-path', '-ipath', '-type', '-maxdepth', '-mindepth', '-newer', '-regex', '-size', '-user', '-group', '-perm'
]);
-// PowerShell parameters are case-insensitive. -Path/-LiteralPath values are paths
-// (they count as operands for the stdin/target-only checks) but never directory evidence.
const LS_VALUE_FLAGS = new Set(['-I', '--ignore', '--hide']);
const TREE_VALUE_FLAGS = new Set(['-L', '-P', '-I', '-o']);
-// fd: `-E/--exclude <glob>` take a value (fd's `-e` is an extension, also a value).
const FD_VALUE_FLAGS = new Set([...VALUE_FLAGS, '-E']);
-// Only these tools take the search pattern from -e/-f (fd's -e is an extension).
const PATTERN_FLAG_SEARCHES = new Set(['grep', 'egrep', 'fgrep', 'rg', 'git grep']);
const POWERSHELL_VALUE_FLAGS = new Set(['-path', '-literalpath', '-depth', '-pattern']);
const POWERSHELL_PATH_FLAGS = new Set(['-path', '-literalpath']);
-// PowerShell binds a parameter by any unambiguous prefix, `-Name:value`, and comma lists across arguments.
const POWERSHELL_FILTER_PARAMS = new Set(['filter', 'include', 'exclude']);
const POWERSHELL_COMMON_PARAMS = [
'verbose', 'debug', 'erroraction', 'warningaction', 'informationaction', 'progressaction',
@@ -90,8 +80,7 @@ const GENERIC_STEMS = new Set([
]);
const MIN_STEM_LENGTH = 4;
const MAX_SEARCH_COMMAND_CHARS = 8192;
-// Command substitution, process substitution, heredocs and PowerShell
-// backtick escapes make the searched text ambiguous: never credit them.
+// see docs/gateguard/design-notes.md#ambiguous-shell-is-not-evidence
const AMBIGUOUS_SHELL_PATTERN = /`|\$\(|[<>]\(|<</;
const GLOB_CHARS_PATTERN = /[*?[{]/;
@@ -102,7 +91,7 @@ function eligibleStem(filePath) {
return stem.length >= MIN_STEM_LENGTH && !GENERIC_STEMS.has(stem) ? stem : null;
}
-/** Word-boundary stem matcher; an indexOf scan, never a RegExp built from untrusted text. */
+// see docs/gateguard/design-notes.md#stem-matching
function stemMatcher(stem) {
if (!stem) return null;
return { test: text => containsWord(String(text), stem) };
@@ -119,7 +108,6 @@ function containsWord(text, word) {
return false;
}
-/** Path-resolution context for a target; relative paths resolve against the tool `cwd`. */
function dirContext(targetPath, data) {
const base = (data && typeof data.cwd === 'string' && data.cwd) || process.env.CLAUDE_PROJECT_DIR || process.cwd();
const isWin = WINDOWS_PATH_PATTERN.test(base) || WINDOWS_PATH_PATTERN.test(targetPath);
@@ -158,7 +146,6 @@ function stringsOf(...values) {
return values.filter(value => typeof value === 'string' && value);
}
-/** Base for relative operands after a directory change; null unless it is a plain literal `cd <dir>`. */
function baseAfterDirectoryChange(base, lead, tokens) {
if (!['cd', 'chdir', 'set-location', 'sl'].includes(lead) || tokens.length !== 2) return null;
const dir = tokens[1];
@@ -179,7 +166,6 @@ function operandScopePath(arg) {
return literal.join('/') || '/';
}
-/** Scopes a shell segment searched; unresolvable operands (variables, `~`, unknown cwd) scope nothing. */
function shellSearchScopes(parsed, base) {
if (parsed.operands.length === 0) return base === null ? [] : [base];
const scopes = [];
@@ -208,7 +194,6 @@ function valueFlagsFor(kind) {
return VALUE_FLAGS;
}
-/** Arguments a flag consumes; single-dash clusters (`-rne PAT`) are read letter by letter. */
function flagEffect(kind, args, i) {
const arg = args[i];
if (POWERSHELL_SEARCHES.has(kind)) {
@@ -231,7 +216,6 @@ function flagEffect(kind, args, i) {
return { consumes: 0, patternFlag: false, pathFlag: false };
}
-/** Path operands of a search command, skipping flag values and the pattern positional. */
function parseSearchArgs(kind, args) {
const positionals = [];
const pathValues = [];
@@ -246,7 +230,7 @@ function parseSearchArgs(kind, args) {
break;
}
if (arg.includes('<')) {
- inputRedirect = true; // a quoted `<` cannot be told from a redirection
+ inputRedirect = true;
break;
}
if (arg.length > 1 && arg.startsWith('-')) {
@@ -289,8 +273,9 @@ function evidenceInScope(item, ctx) {
if (scope === ctx.targetKey || !isInsideDir(ctx.targetKey, scope)) return false;
if (item.scopeExact && ctx.targetDir !== scope) return false;
}
+ // see docs/gateguard/design-notes.md#search-scope
if (item.operands && item.operands.length > 0 && item.operands.every(parts => ctx.resolveDir(...parts) === ctx.targetKey)) {
- return false; // reading the target itself is not a search
+ return false;
}
return true;
}
@@ -302,9 +287,7 @@ function evidenceNamesDir(item, ctx) {
}
// --- Search filters ---
-// A search that excluded the target never saw it, so exclusions are never a stem
-// source and one covering the target blocks credit; unreadable exclusion lists
-// block it too. Globs are matched without RegExp and bounded; past the bounds they cover the target.
+// see docs/gateguard/design-notes.md#search-filters
const MAX_FILTER_GLOB_CHARS = 256;
const MAX_BRACE_ALTERNATIVES = 32;
@@ -353,7 +336,7 @@ function expandBraces(glob) {
return results;
}
}
- return [glob]; // unbalanced: `{` is literal
+ return [glob];
}
function globTokens(glob) {
@@ -380,7 +363,6 @@ function globTokens(glob) {
return tokens;
}
-/** `[...]` with members, ranges, `!`/`^` negation and a leading literal `]`; null when unclosed. */
function bracketClass(glob, open) {
let i = open + 1;
const negated = glob[i] === '!' || glob[i] === '^';
@@ -406,7 +388,7 @@ function classMatches(token, ch) {
return member !== token.negated;
}
-/** Glob match by dynamic programming, so a hostile glob cannot cause regex backtracking; null when malformed. */
+// see docs/gateguard/design-notes.md#glob-matching-without-regexp
function wildcardMatch(glob, text) {
const tokens = globTokens(glob);
if (!tokens) return null;
@@ -416,7 +398,7 @@ function wildcardMatch(glob, text) {
for (let t = tokens.length - 1; t >= 0; t--) {
const token = tokens[t];
const row = new Array(n + 1).fill(false);
- let afterSlash = false; // for 'dirs': some k > j with text[k-1] === '/' and next[k]
+ let afterSlash = false;
for (let j = n; j >= 0; j--) {
if (token.type === 'lit') row[j] = j < n && text[j] === token.ch && next[j + 1];
else if (token.type === 'one') row[j] = j < n && text[j] !== '/' && next[j + 1];
@@ -437,7 +419,6 @@ function normalizeFilterGlob(glob) {
return String(glob).toLowerCase().replace(/\\/g, '/').replace(/^(?:\.\/)+/, '').replace(/^\/+/, '').replace(/\/+$/, '');
}
-/** Null when the glob is past the length or brace bounds; a malformed alternative counts as `malformed`. */
function globMatches(glob, text, malformed) {
if (glob.length > MAX_FILTER_GLOB_CHARS) return null;
const alternatives = expandBraces(glob);
@@ -452,7 +433,6 @@ function targetSegments(ctx) {
return ctx.targetKey.toLowerCase().split('/').filter(Boolean);
}
-/** An exclusion covers the target when it names the stem or matches the file or any directory above it. */
function exclusionCoversTarget(exclusion, segments, stem) {
const glob = normalizeFilterGlob(exclusion);
if (!glob) return true;
@@ -475,7 +455,7 @@ function filtersAdmitTarget(item, ctx, stem) {
return !exclusions.some(exclusion => exclusionCoversTarget(exclusion, segments, stem));
}
-/** Basename include globs that all miss the target stop its stem from crediting; oversized globs admit, malformed ones do not. */
+// see docs/gateguard/design-notes.md#include-filters
function includesAdmitTarget(item, ctx) {
const includes = Array.isArray(item.includes) ? item.includes : [];
if (includes.length === 0) return true;
@@ -549,7 +529,6 @@ function applyShellFilterArg(kind, args, i, filters) {
include(value);
return consumed;
}
- // `--ignore`/`--hide` hide names only for ls (rg's `--ignore` is a switch).
if (EXCLUDE_LONG_FLAGS.has(name) && (kind === 'ls' || !LS_ONLY_EXCLUDE_FLAGS.has(name))) {
exclude(value, indexes);
return consumed;
@@ -562,7 +541,6 @@ function applyShellFilterArg(kind, args, i, filters) {
for (let k = 1; k < arg.length; k++) {
const letter = arg[k];
if (!letters.has(letter)) {
- // Another value flag ends the cluster: the rest (or the next argument) is its value.
if (valueFlags.has(`-${letter}`)) return k === arg.length - 1 ? 1 : 0;
continue;
}
@@ -598,7 +576,6 @@ function applyShortFilter(kind, letter, value, indexes, { filters, exclude, incl
}
}
-/** find: a negated or pruned name test is an exclusion; a plain `-name`/`-iname` is an include. */
function findSearchFilters(args, filters) {
let negateNext = false;
let negatedDepth = 0;
@@ -674,7 +651,7 @@ function powershellSearchFilters(kind, args, filters) {
}
i = filter.end;
} else if (/^-[A-Za-z]/.test(args[i]) && powershellParam(kind, args[i]).name === null) {
- // An unresolvable parameter may be an exclusion in disguise: neither it nor a value it may carry is a stem source.
+ // see docs/gateguard/design-notes.md#powershell-parameter-binding
filters.dropped.add(i);
if (!args[i].includes(':') && i + 1 < args.length && !args[i + 1].startsWith('-')) filters.dropped.add(i + 1);
}
@@ -682,12 +659,10 @@ function powershellSearchFilters(kind, args, filters) {
return filters;
}
+// --- Prior-search credit ---
+
/** Build the prior-search matcher around the hook's shell segmenter. */
function createSearchEvidence({ quoteAwareSegments, commandBasename, SHELL_SEGMENT_SEPARATORS }) {
- /**
- * Evidence a search offers: stem `texts`, candidate `dirs`, the `scope`/`scopes`
- * the target must lie in, and `operands` that must not all be the target itself.
- */
function searchEvidence(search, shellDirsTrusted) {
const input = search.input;
if (search.name === 'Glob') {
@@ -696,11 +671,9 @@ function createSearchEvidence({ quoteAwareSegments, commandBasename, SHELL_SEGME
const prefix = globLiteralPrefix(input.pattern);
const scope = [explicit || '.', prefix || '.'];
if (!GLOB_CHARS_PATTERN.test(input.pattern)) {
- // A single-file lookup names no directory, and looking up the target itself is not a search.
const lookup = [explicit || '.', input.pattern];
return [{ texts: [input.pattern], dirs: [], scope, scopeExact: true, operands: [lookup], detail: input.pattern }];
}
- // An empty literal prefix with no explicit path names only the implicit cwd.
const dirs = prefix || explicit ? [scope] : [];
return [{ texts: [input.pattern], dirs, scope, detail: input.pattern }];
}
@@ -723,10 +696,6 @@ function createSearchEvidence({ quoteAwareSegments, commandBasename, SHELL_SEGME
return shellSearchEvidence(input.command, shellDirsTrusted);
}
- /**
- * Per segment, whether it reads piped input. Mirrors `quoteAwareSegments`
- * splitting; `||` also marks the next segment, which only ever removes evidence.
- */
function segmentPipeFlags(input) {
const flags = [];
let quote = null;
@@ -759,14 +728,13 @@ function createSearchEvidence({ quoteAwareSegments, commandBasename, SHELL_SEGME
return flags;
}
- /** Evidence for each search segment of a shell command; ambiguous or oversized commands yield none. */
function shellSearchEvidence(command, dirsTrusted) {
if (typeof command !== 'string' || !command || command.length > MAX_SEARCH_COMMAND_CHARS) return [];
if (AMBIGUOUS_SHELL_PATTERN.test(command)) return [];
const pipeFlags = segmentPipeFlags(command);
const evidence = [];
let trusted = dirsTrusted;
- // A cd in any other call of the turn leaves the cwd of this one unknown.
+ // see docs/gateguard/design-notes.md#directory-changes
let base = dirsTrusted ? [] : null;
quoteAwareSegments(command).forEach((tokens, index) => {
const lead = commandBasename(tokens[0]);
@@ -784,13 +752,13 @@ function createSearchEvidence({ quoteAwareSegments, commandBasename, SHELL_SEGME
args = tokens.slice(2);
}
const parsed = parseSearchArgs(kind, args);
- // A segment that reads stdin (redirection, pipe, or no operand without recursion) is not a tree search.
+ // see docs/gateguard/design-notes.md#stdin-is-not-a-tree-search
if (parsed.stdin) return;
if (parsed.operands.length === 0 && (!parsed.recursive || pipeFlags[index] !== false)) return;
const scopes = shellSearchScopes(parsed, base);
if (scopes.length === 0) return;
const filters = shellSearchFilters(kind, args);
- // Exclusion values (and the flags that introduce them) are never a stem source.
+ // see docs/gateguard/design-notes.md#search-filters
const stemText = tokens.slice(0, tokens.length - args.length).concat(args.filter((_, i) => !filters.dropped.has(i))).join(' ');
const dirs = trusted ? parsed.dirOperands.map(shellDirCandidate).filter(Boolean).map(dir => [dir]) : [];
evidence.push({
@@ -808,7 +776,6 @@ function createSearchEvidence({ quoteAwareSegments, commandBasename, SHELL_SEGME
return evidence;
}
- /** A directory change anywhere in the turn makes relative shell paths unreliable. */
function turnChangesDirectory(shellCommands) {
if (!Array.isArray(shellCommands)) return false;
return shellCommands.some(command => {
@@ -818,11 +785,7 @@ function createSearchEvidence({ quoteAwareSegments, commandBasename, SHELL_SEGME
});
}
- /**
- * A completed search in the current turn that names the target by stem (or by
- * directory, for a new-file Write). Searches in the pending call's own batch
- * never count: their results were not seen when the edit was decided.
- */
+ /** First completed search of the current turn that credits the target, else null. */
function findCreditingSearch(scan, targetPath, allowDirMatch, data) {
try {
if (!scan || !Array.isArray(scan.searches) || scan.searches.length === 0) return null;
@@ -830,6 +793,7 @@ function createSearchEvidence({ quoteAwareSegments, commandBasename, SHELL_SEGME
const ctx = dirContext(targetPath, data);
if (!ctx) return null;
const stem = stemMatcher(eligibleStem(targetPath));
+ // see docs/gateguard/design-notes.md#same-batch-searches
const excluded = excludedBatchId(scan, data);
const shellDirsTrusted = !turnChangesDirectory(scan.shellCommands);
for (const search of scan.searches) {
diff --git a/scripts/lib/gateguard-state.js b/scripts/lib/gateguard-state.js
index 65609f597..41b23425f 100644
--- a/scripts/lib/gateguard-state.js
+++ b/scripts/lib/gateguard-state.js
@@ -2,7 +2,9 @@
const { COLLAPSIBLE_CLASSES } = require('./gateguard-target-class');
-/** A non-negative integer count from untrusted state; anything else is 0. */
+// --- Counters ---
+// see docs/gateguard/design-notes.md#state-file-is-untrusted
+
function toCount(value) {
const n = Number(value);
return Number.isFinite(n) && n >= 0 ? Math.floor(n) : 0;
@@ -20,8 +22,7 @@ function getCapAllowCount(state) {
return toCount(state && state.cap_allows);
}
-// dir_gates maps `<class>\u0000<canonicalDir>` to { turn, at, first, ordinal }.
-// The state file is untrusted, so every map is null-prototype and rejects prototype keys.
+// --- Sibling dir gates ---
const MAX_DIR_GATES = 50;
const DIR_GATE_KEY_SEPARATOR = '\u0000';
@@ -103,7 +104,7 @@ function getDirGates(state) {
return nullMap(entries);
}
-/** Union by key; the newer `at` wins, so concurrent writers keep the latest gate. */
+/** Merge two dir-gate maps; the newer `at` wins per key. */
function mergeDirGates(older, newer) {
const merged = nullMap(Object.entries(older));
for (const [key, entry] of Object.entries(newer)) {
diff --git a/scripts/lib/gateguard-target-class.js b/scripts/lib/gateguard-target-class.js
index dcff8b090..f0d1df8f3 100644
--- a/scripts/lib/gateguard-target-class.js
+++ b/scripts/lib/gateguard-target-class.js
@@ -1,11 +1,3 @@
-/**
- * GateGuard 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.
- */
-
'use strict';
const fs = require('fs');
@@ -13,7 +5,7 @@ const path = require('path');
const WINDOWS_PATH_PATTERN = /^[a-z]:[\\/]|^\\\\/i;
-/** Canonical checked-state key, so `a.py`, `./a.py` and the absolute path share one gate. */
+/** Canonical checked-state key for a target. */
function canonicalPathKey(filePath, data) {
try {
const target = resolveTargetPath(filePath, data);
@@ -25,11 +17,8 @@ function canonicalPathKey(filePath, data) {
}
}
-/**
- * Resolve a target to the file the tool will touch. Relative paths resolve
- * against the tool's `cwd` first; this deliberately differs from
- * `isExemptPath`, whose globs are project-relative.
- */
+/** Resolve a target to the file the tool will touch. */
+// see docs/gateguard/design-notes.md#target-resolution
function resolveTargetPath(filePath, data) {
const base = (data && data.cwd) || process.env.CLAUDE_PROJECT_DIR || process.cwd();
if (typeof base !== 'string' || typeof filePath !== 'string') return null;
@@ -51,7 +40,6 @@ const INSTRUCTION_BASENAMES = new Set([
'.cursorrules',
'.windsurfrules'
]);
-// Cursor rule files are instructions wherever they live.
const INSTRUCTION_ANYWHERE_EXTS = new Set(['.mdc']);
const INSTRUCTION_DIRS = new Set(['.claude', 'agents', 'commands', 'skills', 'rules', 'hooks', '.cursor', '.codex', '.opencode']);
const INSTRUCTION_EXTS = new Set(['.md', '.mdx', '.txt']);
@@ -60,7 +48,6 @@ const TEST_BASENAME_PATTERN = /\.(test|spec)\.|^test_.*\.py$|_test\.(py|go)$/;
const PROSE_EXTS = new Set(['.md', '.mdx', '.txt', '.rst', '.adoc']);
const CONFIG_EXTS = new Set(['.json', '.jsonc', '.yaml', '.yml', '.toml', '.ini']);
const ENV_BASENAME_PATTERN = /^\.env($|\.)/;
-// `.env.example.ts` and friends are source files that happen to start with `.env`.
const CODE_EXTS = new Set(['.ts', '.js', '.mjs', '.cjs', '.py', '.go', '.rs', '.java', '.rb']);
/** Classify a path; first match wins: instruction, test, prose, config, code (the fallback). */
@@ -84,7 +71,6 @@ function classifyTarget(filePath) {
const WORKTREE_PREFIX_PATTERN = /^\.claude\/worktrees\/([^/]+)\//;
-/** A Windows-style path has no real location on a POSIX host, and vice versa. */
function isHostPathStyle(isWin) {
return isWin === (process.platform === 'win32');
}
@@ -94,7 +80,6 @@ function foldKey(nativePath, isWin) {
return isWin ? key.toLowerCase() : key;
}
-/** Project root, resolved the way `isExemptPath` resolves it (CLAUDE_PROJECT_DIR first). */
function canonicalProjectRoot(data) {
const root = process.env.CLAUDE_PROJECT_DIR || (data && data.cwd) || process.cwd();
if (typeof root !== 'string') return null;
@@ -105,17 +90,16 @@ function canonicalProjectRoot(data) {
return { key: foldKey(native, isWin), native, isWin };
}
-/** Only a real worktree (its `.git` exists) has its prefix stripped; otherwise the path stays under `.claude`. */
+// see docs/gateguard/design-notes.md#worktree-prefix
function isRealWorktree(rootNative, isWin, name) {
if (!isHostPathStyle(isWin)) return false;
const paths = isWin ? path.win32 : path.posix;
return fs.existsSync(paths.join(rootNative, '.claude', 'worktrees', name, '.git'));
}
-// Windows ignores trailing dots/spaces and treats `name:stream` as `name`.
const STREAM_MARKER = '::$';
-/** Normalize segments as Windows resolves them, so `CLAUDE.md.` and `CLAUDE.md::$DATA` name `CLAUDE.md`. */
+// see docs/gateguard/design-notes.md#windows-name-normalization
function normalizeWindowsSegments(classPath, isWin) {
const segments = classPath.split('/');
const last = segments.length - 1;
@@ -131,7 +115,6 @@ function normalizeWindowsSegments(classPath, isWin) {
.join('/');
}
-/** Project-relative class path for a canonical key, or null when it is outside the root. */
function projectRelativeClassPath(key, root, isWin) {
const target = isWin ? key.toLowerCase() : key;
const rootKey = isWin ? root.key.toLowerCase() : root.key;
@@ -143,11 +126,7 @@ function projectRelativeClassPath(key, root, isWin) {
return normalizeWindowsSegments(relative, isWin);
}
-/**
- * The path a target is classified by: project-relative, so an ancestor such as
- * `/home/me/tests/proj` never leaks into the class, with a real worktree prefix
- * stripped. Targets outside the root keep their absolute path.
- */
+/** Project-relative path a target is classified by. */
function classPathFor(filePath, data) {
try {
const key = canonicalPathKey(filePath, data);
@@ -211,8 +190,7 @@ const CLASS_CONDENSED_HINTS = {
};
// --- Sensitive targets ---
-// Secrets, keys, auth/payment code, migrations and CI workflows always draw the
-// first-touch denial. Basename and segment rules are exact, never substrings.
+// see docs/gateguard/design-notes.md#sensitive-targets
const SENSITIVE_EXTS = new Set(['.pem', '.key', '.p12', '.pfx']);
const SENSITIVE_BASENAME_PATTERN = /^(\.env($|\.)|id_rsa|id_ed25519|id_ecdsa|id_dsa|\.netrc$|\.pgpass$|credentials|secrets\.)/;
@@ -228,17 +206,13 @@ function isSensitiveTarget(classPath) {
const base = segments[segments.length - 1] || '';
if (SENSITIVE_BASENAME_PATTERN.test(base) || SENSITIVE_EXTS.has(path.posix.extname(base))) return true;
if (segments.some(segment => SENSITIVE_SEGMENTS.has(segment))) return true;
- // Also matched below an ancestor (unverified worktree, target outside the root): fail safe.
return `/${segments.join('/')}`.includes(`/${SENSITIVE_PREFIX}`);
} catch (_) {
return true;
}
}
-/**
- * Sensitive on the lexical path or on the real (symlink-resolved) location, so
- * `src/tools -> ../auth` cannot launder `src/tools/login.py`. Any error is sensitive.
- */
+/** Sensitive on the lexical or the real (symlink-resolved) path; any error is sensitive. */
function isSensitiveTargetFor(filePath, data) {
try {
if (typeof filePath !== 'string' || !filePath) return true;
@@ -249,7 +223,6 @@ function isSensitiveTargetFor(filePath, data) {
}
}
-/** Unresolvable real locations (dangling symlink, ENOTDIR, EACCES, loops) count as sensitive. */
function isSensitiveRealTarget(filePath, data) {
const target = resolveTargetPath(filePath, data);
if (!target || !isHostPathStyle(target.isWin)) return false;
@@ -270,12 +243,11 @@ function isSensitiveRealTarget(filePath, data) {
}
// --- Sibling collapse eligibility ---
+// see docs/gateguard/design-notes.md#sibling-collapse
const COLLAPSIBLE_CLASSES = new Set(['code', 'test', 'prose']);
-// 8.3 short names (`CLAUDE~1`) can alias any directory, including dot-directories.
const SHORT_NAME_PATTERN = /~\d/;
-/** Harness and tooling directories are dot-directories, so any dot segment blocks collapse. */
function isCollapsibleClassPath(classPath, cls) {
if (!COLLAPSIBLE_CLASSES.has(cls)) return false;
const segments = String(classPath).toLowerCase().split('/').filter(Boolean);
@@ -288,7 +260,6 @@ function isCollapsibleTarget(filePath, data, cls) {
return isCollapsibleClassPath(classPathFor(filePath, data), cls);
}
-/** Realpath of a directory via its nearest existing ancestor; null on any error but a plain missing entry. */
function realpathOfNearestAncestor(nativePath, paths) {
const realpath = fs.realpathSync.native || fs.realpathSync;
const missing = [];
@@ -308,7 +279,6 @@ function realpathOfNearestAncestor(nativePath, paths) {
}
}
-/** Real path of a file target, or of its nearest existing ancestor plus the missing tail. */
function realTargetPath(resolved, paths) {
const realpath = fs.realpathSync.native || fs.realpathSync;
try {
@@ -320,7 +290,6 @@ function realTargetPath(resolved, paths) {
return realDir ? paths.join(realDir, paths.basename(resolved)) : null;
}
-/** True when nothing (not even a dangling symlink) exists at the path. */
function isMissingEntry(nativePath) {
try {
fs.lstatSync(nativePath);
@@ -330,11 +299,7 @@ function isMissingEntry(nativePath) {
}
}
-/**
- * Real directory a new file's sibling gate is keyed by, or null when it may not
- * collapse. A symlinked directory must keep the class and pass the same screen,
- * so `src/tools -> .claude/hooks` never collapses.
- */
+/** Real directory a new file's sibling gate is keyed by, or null when it may not collapse. */
function collapseGateDir(filePath, data, cls) {
try {
if (!isCollapsibleTarget(filePath, data, cls)) return null;
diff --git a/scripts/lib/gateguard-turn-scan.js b/scripts/lib/gateguard-turn-scan.js
index 30764abb6..5659f46fd 100644
--- a/scripts/lib/gateguard-turn-scan.js
+++ b/scripts/lib/gateguard-turn-scan.js
@@ -1,11 +1,3 @@
-/**
- * GateGuard current-turn transcript scan: one bounded tail read of a Claude
- * Code JSONL transcript, walked back to the latest human message or
- * compaction. Yields the turn id and the turn's completed, non-error search
- * calls. Shell parsing stays in the hook, which shares it with the
- * destructive-command gate.
- */
-
'use strict';
const crypto = require('crypto');
@@ -13,6 +5,7 @@ const fs = require('fs');
const { readFileTail, DEFAULT_TRANSCRIPT_TAIL_BYTES } = require('./transcript-context');
const TRANSCRIPT_SCAN_MAX_LINES = 2000;
+// see docs/gateguard/design-notes.md#read-is-not-evidence
const SEARCH_TOOL_NAMES = new Set(['Glob', 'Grep', 'LS', 'Bash', 'PowerShell']);
const SHELL_TOOL_NAMES = new Set(['Bash', 'PowerShell']);
const TOOL_USE_ERROR_PREFIX = '<tool_use_error>';
@@ -21,7 +14,7 @@ function isObject(value) {
return Boolean(value) && typeof value === 'object';
}
-/** Exports never throw: an error here must not escape into the hook's credit or sibling logic. */
+// see docs/gateguard/design-notes.md#fail-to-deny
function neverThrows(fn, fallback) {
return (...args) => {
try {
@@ -57,7 +50,7 @@ function isSkippedTranscriptRecord(record) {
);
}
-/** Compaction discards the earlier turn: its summary (or boundary marker) starts a new one. */
+/** True for a compaction summary or boundary record. */
function isCompactionBoundary(record) {
return (
Boolean(record) &&
@@ -69,8 +62,6 @@ function isCompactionBoundary(record) {
const MAX_PROMPT_ID_CHARS = 128;
-// Claude Code stamps every user record of a turn with the same `promptId`, so it
-// identifies the turn even when the boundary has scrolled out of the tail window.
function recordPromptId(record) {
const id = isObject(record) ? record.promptId : undefined;
return typeof id === 'string' && id && id.length <= MAX_PROMPT_ID_CHARS ? id : null;
@@ -81,10 +72,8 @@ function boundaryTurnId(record, line) {
return `h:${crypto.createHash('sha256').update(line).digest('hex').slice(0, 16)}`;
}
-/**
- * Only a non-empty array of `tool_result` blocks is a tool-result record; any
- * other user record is a turn boundary, which can only shrink the credit window.
- */
+/** True for a user record made only of `tool_result` blocks. */
+// see docs/gateguard/design-notes.md#turn-boundaries
function isToolResultRecord(record) {
const content = recordContent(record);
return (
@@ -107,11 +96,7 @@ function isErrorToolResult(block) {
return toolResultText(block.content).trimStart().startsWith(TOOL_USE_ERROR_PREFIX);
}
-/**
- * Scan the transcript tail back to the latest human turn. Returns null when the
- * transcript is unavailable, else the turn id, the turn's searches (newest
- * first), batch ids, and shell commands. The tail is bounded to keep the hook fast.
- */
+/** Scan the transcript tail back to the start of the current turn; null when unavailable. */
function scanCurrentTurn(transcriptPath, pendingId = '') {
if (typeof transcriptPath !== 'string' || !transcriptPath) return null;
let stat;
@@ -177,15 +162,13 @@ function scanCurrentTurn(transcriptPath, pendingId = '') {
if (messageId && typeof block.id === 'string') batchIds.set(block.id, messageId);
}
}
- // No boundary: a clipped window is the current turn only if its promptIds agree;
- // two or more mean an unrecognised turn start. An unclipped file has no turn.
+ // see docs/gateguard/design-notes.md#turn-identity
if ((tail.truncated || firstLine > 0) && windowPromptIds.size <= 1) {
return finish(windowPromptIds.size === 1 ? [...windowPromptIds][0] : null);
}
return { turnId: null, searches: [], batchIds: new Map(), newestMessageId: null, shellCommands: [] };
}
-/** Completed, non-error search calls whose id occurs once, newest first. */
function collectTurnSearches(toolUsesNewestFirst, okResultIds, pendingId) {
const idCounts = new Map();
for (const { block } of toolUsesNewestFirst) {
@@ -195,7 +178,8 @@ function collectTurnSearches(toolUsesNewestFirst, okResultIds, pendingId) {
const priorCalls = toolUsesNewestFirst.filter(({ block }) => !pendingId || block.id !== pendingId);
priorCalls.forEach(({ block, messageId }, index) => {
if (typeof block.id !== 'string' || !okResultIds.has(block.id)) return;
- if (idCounts.get(block.id) !== 1) return; // a reused id cannot be tied to one result
+ // see docs/gateguard/design-notes.md#tool-result-pairing
+ if (idCounts.get(block.id) !== 1) return;
if (!SEARCH_TOOL_NAMES.has(block.name)) return;
if (!block.input || typeof block.input !== 'object') return;
searches.push({ name: block.name, input: block.input, callsAgo: index + 1, messageId });
@@ -209,7 +193,7 @@ function collectShellCommands(toolUses) {
.map(({ block }) => (typeof block.input.command === 'string' ? block.input.command : ''));
}
-/** Assistant message whose searches share the pending call's batch (their results were not yet seen). */
+/** Message id of the pending call's batch, whose searches never credit. */
function excludedBatchId(scan, data) {
if (!isObject(scan)) return null;
const pendingId = pendingToolUseId(data);