fix(gateguard): deny same-batch siblings of a first-touch denial

A first-touch denial marks its file checked so the retry passes, which
also let the other edits to that file in the same parallel batch apply
and left the file half-edited (#3136 only warned about this).

When the denied call's own tool_use_id is found in the transcript, the
denial now records the batch (assistant message id) for that file in
the same state write. A later Edit/Write/MultiEdit/NotebookEdit of the
file from that batch is denied with a message that says to resend every
edit with the retry. Calls from any other message pass, including the
retry. There is no newest-message fallback, so a guessed batch can never
deny the retry; without a located batch the #3136 warning still applies.

Same-batch denials are recorded as the new `batch-deny` metrics
decision and do not count toward fact_force_denials. batch_locks is
validated on read, merged by newest `at` and capped at 50 entries.

Fixes #3936

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Gaurav DubeyandClaude Opus 5.5 committed 2026-11-15 04:08:27 +00:00
1 parent d2ef268059
commit b2fa2d93ee
9 files changed
+347 -28

No files matched your search

+2 -1
View File
@@ -8,6 +8,7 @@
- GateGuard's external-contract question ("name what outside this repository decides the format, units, timezone or protocol semantics") is opt-in through `GATEGUARD_EXTERNAL_CONTRACT_QUESTION`. Hidden-intent trials did not show it helps, so by default a code change that handles data asks only the data-schema question, and an unreadable change gets the original four questions and condensed hint.
- 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 or limit the search to another directory. 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 no longer leaves a file half-edited after a first-touch denial in a parallel batch: when the denied call's `tool_use_id` is in the transcript, the other edits to that file from the same batch are denied too (`batch-deny`), and the retry from the next message passes. Without a located batch the denial keeps the warning that siblings may already have been applied (#3936).
- 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.
@@ -17,7 +18,7 @@
- Report that harness's pilot: 72 sessions in which every arm passed every trial, so it measured the gate's cost (about 45% more turns) and nothing about its effect. Add a second runner, `run-intent.js`, for exploratory effectiveness measurements: the deciding fact exists only in a simulated user's hidden intent and sessions are multi-turn. Scenario files omit declared gate-question targets, but the authors knew the taxonomy and this is not blind authorship.
- 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`.
- Newly denied: a subagent's first touch of a sensitive or hard-linked file, the first NotebookEdit of each notebook, and the other edits to a file from the same batch as its denied first touch (#3936). Every other rule only removes denials and never returns an `allow` decision. See `skills/gateguard/SKILL.md`.
### Fixed
+29 -3
View File
@@ -37,7 +37,8 @@ and trivial edits) is in [change-profile.md](change-profile.md).
[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),
[Sibling collapse](#sibling-collapse), [Same-batch siblings](#same-batch-siblings),
[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),
@@ -441,6 +442,30 @@ instead of a repeat denial.
transcript never collapses.
- A gate stamped in the future, or not created by a denial, is ignored.
## Same-batch siblings
A first-touch denial marks its file checked, so the retry passes. Without more
care, the other edits to that file in the same parallel batch pass too and the
file is left half-edited (#3136). Hooks see calls one at a time, but the
transcript links each call's `tool_use_id` to its assistant message id, which
is the batch.
- When the denied call's own `tool_use_id` is in the transcript, the denial
records `batch_locks[<file key>] = { batch, at }` in the same state write
that marks the file checked.
- A later Edit, Write, MultiEdit entry or NotebookEdit of that file is denied
when its own `tool_use_id` is in the same batch. The denial is recorded as
`batch-deny`. It does not add to `fact_force_denials`, so the denial cap and
the condensed ordinals are unchanged.
- A call from any other message passes, including the retry in the next turn.
- There is no fallback to the newest assistant message: a guessed batch could
match the retry and deny it forever. With no `tool_use_id`, no transcript, or
the pending call missing from the transcript, nothing is locked. The denial
then keeps the #3136 warning that siblings may already have been applied, and
that warning is the ceiling.
- The transcript is read for a checked file only when a lock exists for its
key.
## Denial cap
`GATEGUARD_FACT_FORCE_MAX_DENIALS` is validated whole (digits only, a safe
@@ -457,9 +482,10 @@ 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
`{ turn, at, first, ordinal }` and keeps the 50 newest entries. `batch_locks`
maps a file key to `{ batch, at }` 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
newest `at`, batch locks by newest `at`). Marking a target checked and recording its event happen in one
state write, so an event is never half-recorded.
## MultiEdit paths
+1 -1
View File
@@ -5,7 +5,7 @@ const fs = require('fs');
const path = require('path');
const { METRICS_FILE_NAME, isMetricsEvent } = require('./lib/gateguard-metrics');
const DENIAL_DECISIONS = new Set(['deny', 'routine-deny', 'destructive-deny']);
const DENIAL_DECISIONS = new Set(['deny', 'routine-deny', 'destructive-deny', 'batch-deny']);
const FIRST_TOUCH_DECISIONS = ['deny', 'credit', 'sibling', 'cap', 'trivial'];
const NEAR_MISS_PREFIX = 'near-miss:';
const TOP_QUESTIONS = 10;
+77 -21
View File
@@ -85,7 +85,10 @@ const {
dirGateKey,
getDirGates,
mergeDirGates,
capDirGates
capDirGates,
getBatchLocks,
mergeBatchLocks,
capBatchLocks
} = require('../lib/gateguard-state');
// Session state — scoped per session to avoid cross-session races.
@@ -1668,6 +1671,7 @@ function saveState(state) {
let mergedDenials = getDenialCount(state);
let mergedCredited = getCreditedCount(state);
let mergedDirGates = getDirGates(state);
let mergedBatchLocks = getBatchLocks(state);
let mergedDenialsByClass = getClassCounts(state, 'denials_by_class');
let mergedCreditedByClass = getClassCounts(state, 'credited_by_class');
let mergedSiblingAllows = getSiblingAllowCount(state);
@@ -1687,6 +1691,7 @@ function saveState(state) {
mergedDenials = Math.max(mergedDenials, getDenialCount(diskState));
mergedCredited = Math.max(mergedCredited, getCreditedCount(diskState));
mergedDirGates = mergeDirGates(getDirGates(diskState), mergedDirGates);
mergedBatchLocks = mergeBatchLocks(getBatchLocks(diskState), mergedBatchLocks);
mergedDenialsByClass = mergeClassCounts(getClassCounts(diskState, 'denials_by_class'), mergedDenialsByClass);
mergedCreditedByClass = mergeClassCounts(getClassCounts(diskState, 'credited_by_class'), mergedCreditedByClass);
mergedSiblingAllows = Math.max(mergedSiblingAllows, getSiblingAllowCount(diskState));
@@ -1704,6 +1709,7 @@ function saveState(state) {
fact_force_denials: mergedDenials,
fact_force_credited: mergedCredited,
dir_gates: capDirGates(mergedDirGates),
batch_locks: capBatchLocks(mergedBatchLocks),
denials_by_class: mergedDenialsByClass,
credited_by_class: mergedCreditedByClass,
sibling_allows: mergedSiblingAllows,
@@ -1815,7 +1821,7 @@ function markCheckedWith(key, update) {
return { ok: saveState(state), value };
}
function markCheckedAndCountDenial(key, { cls, dirGate, cap = Number.POSITIVE_INFINITY } = {}) {
function markCheckedAndCountDenial(key, { cls, dirGate, batchId = null, cap = Number.POSITIVE_INFINITY } = {}) {
const { ok, value: denials } = markCheckedWith(key, state => {
if (getDenialCount(state) >= cap) {
return { state: { ...state, cap_allows: getCapAllowCount(state) + 1 }, value: null };
@@ -1827,7 +1833,8 @@ function markCheckedAndCountDenial(key, { cls, dirGate, cap = Number.POSITIVE_IN
...(cls ? { denials_by_class: incrementClassCount(getClassCounts(state, 'denials_by_class'), cls) } : {}),
...(dirGate
? { dir_gates: withEntry(getDirGates(state), dirGate.key, { turn: dirGate.turn || null, at: Date.now(), first: dirGate.first, ordinal }) }
: {})
: {}),
...(batchId ? { batch_locks: withEntry(getBatchLocks(state), key, { batch: batchId, at: Date.now() }) } : {})
};
return { state: next, value: ordinal };
});
@@ -2059,26 +2066,42 @@ const READ_ONLY_GIT_SUBCOMMANDS = new Map([
// --- Gate messages ---
/**
* Batch-consistency warning (#3136). A first-touch denial marks the file
* checked so the retry passes; a parallel batch of edits to one
* not-yet-touched file therefore partially applies (first call denied,
* siblings allowed). Hooks see calls one at a time and cannot lock a
* batch, so the denial must say this out loud: name the file and tell
* the agent that siblings may already have been applied.
* Batch-consistency note (#3136, #3936). A first-touch denial marks the
* file checked so the retry passes. When the pending call's batch is found
* in the transcript, the denial also locks the file for that batch, so the
* siblings are denied too and the file stays whole (`locked`). Otherwise
* the hook cannot tell siblings from the retry, so the denial says out
* loud that siblings may already have been applied.
* see docs/gateguard/design-notes.md#same-batch-siblings
*/
function batchSiblingWarning(safePath) {
function batchSiblingWarning(safePath, locked = false) {
if (locked) {
return (
`Other edits to ${safePath} from this batch are denied too, so the file is unchanged. ` +
'Resend all of them with the retry.'
);
}
return (
`If this call was sent in a parallel batch, other edits to ${safePath} from that batch ` +
'may already have been applied. Re-read the file before building on them.'
);
}
function sameBatchGateMsg(filePath) {
const safe = sanitizePath(filePath);
return (
`[Fact-Forcing Gate] An earlier edit to ${safe} in this same batch was denied at first touch, ` +
`so this one is denied too and ${safe} is unchanged. ` +
'Present the facts that denial asked for, then resend every edit to this file from this batch.'
);
}
// see docs/gateguard/change-profile.md#external-contract-question
function questionOptions() {
return { externalContract: ECC_ENABLE_VALUES.has(normalizeEnvValue(process.env.GATEGUARD_EXTERNAL_CONTRACT_QUESTION)) };
}
function firstTouchGateMsg(filePath, isWrite, cls, profile) {
function firstTouchGateMsg(filePath, isWrite, cls, profile, locked = false) {
const safe = sanitizePath(filePath);
const questions = questionIdsFor(cls, isWrite, profile, questionOptions()).map(questionText);
return [
@@ -2088,7 +2111,7 @@ function firstTouchGateMsg(filePath, isWrite, cls, profile) {
'',
...questions.map((question, index) => `${index + 1}. ${question}`),
'',
batchSiblingWarning(safe),
batchSiblingWarning(safe, locked),
'',
'Present the facts, then retry the same operation.'
].join('\n');
@@ -2099,13 +2122,13 @@ function firstTouchGateMsg(filePath, isWrite, cls, profile) {
* (#2142). Carries the denial ordinal so consecutive denials differ
* textually, and a one-line recovery hint instead of the multi-line block.
*/
function condensedGateMsg(action, filePath, ordinal, { cls = 'code', targetNote = '', profile = null, missNote = '' } = {}) {
function condensedGateMsg(action, filePath, ordinal, { cls = 'code', targetNote = '', profile = null, missNote = '', locked = false } = {}) {
const safe = sanitizePath(filePath);
const hint = condensedHintFor(cls, action === 'creation', profile, questionOptions());
return (
`[Fact-Forcing Gate] (denial #${ordinal} this session) First ${action} of ${safe}: ` +
`${hint} ` +
`${batchSiblingWarning(safe)} ` +
`${batchSiblingWarning(safe, locked)} ` +
(missNote ? `${missNote} ` : '') +
(targetNote ? `${targetNote} ` : '') +
'(Use GATEGUARD_EXEMPT_GLOBS for path-scoped exemptions; GATEGUARD_FACT_FORCE_MAX_DENIALS caps denials per session; ECC_GATEGUARD=off disables this gate.)'
@@ -2134,7 +2157,7 @@ function denialReason(sensitive, linked, missNote, miss) {
return missNote ? `near-miss:${miss.reason}` : 'first-touch';
}
function firstTouchDenial(filePath, { isWrite, denials, cls, sensitive, linked = false, profile, miss, reason }) {
function firstTouchDenial(filePath, { isWrite, denials, cls, sensitive, linked = false, profile, miss, reason, locked = false }) {
const targetNote = restrictedTargetNote(sensitive, linked);
const missNote = targetNote ? '' : closestMissNote(miss);
recordDecision('deny', reason || denialReason(sensitive, linked, missNote, miss), {
@@ -2146,9 +2169,9 @@ function firstTouchDenial(filePath, { isWrite, denials, cls, sensitive, linked =
});
if (denials > getFullDenialBudget()) {
const action = isWrite ? 'creation' : 'edit';
return denyResult(condensedGateMsg(action, filePath, denials, { cls, targetNote, profile, missNote }), { includeRecoveryHint: false });
return denyResult(condensedGateMsg(action, filePath, denials, { cls, targetNote, profile, missNote, locked }), { includeRecoveryHint: false });
}
const message = withNoteBeforeRetry(firstTouchGateMsg(filePath, isWrite, cls, profile), missNote);
const message = withNoteBeforeRetry(firstTouchGateMsg(filePath, isWrite, cls, profile, locked), missNote);
return denyResult(targetNote ? withNoteBeforeRetry(message, targetNote) : message, {
narrowRecoveryHint: EDIT_WRITE_NARROW_RECOVERY_HINT
});
@@ -2520,10 +2543,39 @@ function gateSingleEdit(ctx) {
const fileKey = canonicalPathKey(filePath, data);
if (!isChecked([fileKey, filePath])) return firstTouchSingleEdit(ctx, filePath, fileKey);
const sameBatch = sameBatchDenial(ctx, filePath, fileKey);
if (sameBatch) return sameBatch;
recordDecision('pass-checked', 'checked', { target: filePath });
return rawInput; // allow
}
// --- Same-batch siblings ---
// see docs/gateguard/design-notes.md#same-batch-siblings
/**
* Message id of the pending call's batch, only when the pending
* `tool_use_id` is found in the transcript. No newest-message fallback:
* a guessed batch could match the retry and deny it forever.
*/
function pendingBatchId(ctx) {
const pendingId = turnScan().pendingToolUseId(ctx.data);
if (!pendingId) return null;
const scan = ctx.getTurnScan();
if (!scan || !(scan.batchIds instanceof Map)) return null;
const batch = scan.batchIds.get(pendingId);
return typeof batch === 'string' && batch ? batch : null;
}
/** Deny a checked file's edit when it comes from the batch whose first touch was denied. */
function sameBatchDenial(ctx, filePath, fileKey) {
const locks = getBatchLocks(loadState());
if (!Object.hasOwn(locks, fileKey)) return null;
if (pendingBatchId(ctx) !== locks[fileKey].batch) return null;
recordDecision('batch-deny', 'same-batch', { target: filePath, key: fileKey });
return denyResult(sameBatchGateMsg(filePath), { includeRecoveryHint: false });
}
function singleEditProfile(ctx, filePath, cls, restricted) {
const { toolName, toolInput, data } = ctx;
if (restricted || toolName === 'NotebookEdit' || !needsProfile(toolName, cls)) return null;
@@ -2572,7 +2624,8 @@ function firstTouchSingleEdit(ctx, filePath, fileKey) {
return { additionalContext: siblingNote(sibling), exitCode: 0 };
}
const cap = restricted ? Number.POSITIVE_INFINITY : getMaxDenialBudget();
const { ok, denials } = markCheckedAndCountDenial(fileKey, { cls, dirGate, cap });
const batchId = pendingBatchId(ctx);
const { ok, denials } = markCheckedAndCountDenial(fileKey, { cls, dirGate, batchId, cap });
if (!ok) {
return allowWithStateWarning();
}
@@ -2582,7 +2635,7 @@ function firstTouchSingleEdit(ctx, filePath, fileKey) {
return rawInput;
}
const miss = restricted ? null : findClosestMiss(getTurnScan(), filePath, isNewFile, data);
return firstTouchDenial(filePath, { isWrite: toolName === 'Write', denials, cls, sensitive, linked, profile, miss });
return firstTouchDenial(filePath, { isWrite: toolName === 'Write', denials, cls, sensitive, linked, profile, miss, locked: batchId !== null });
}
// --- MultiEdit ---
@@ -2603,6 +2656,8 @@ function gateMultiEdit(ctx) {
const fileKey = canonicalPathKey(filePath, data);
if (batch.trivialKeys.has(fileKey)) continue;
if (isChecked([fileKey, filePath])) {
const sameBatch = sameBatchDenial(ctx, filePath, fileKey);
if (sameBatch) return sameBatch;
recordDecision('pass-checked', 'checked', { target: filePath, key: fileKey });
continue;
}
@@ -2654,7 +2709,8 @@ function firstTouchMultiEdit(ctx, edits, filePath, fileKey, batch) {
return null;
}
const cap = restricted ? Number.POSITIVE_INFINITY : getMaxDenialBudget();
const { ok, denials } = markCheckedAndCountDenial(fileKey, { cls, cap });
const batchId = pendingBatchId(ctx);
const { ok, denials } = markCheckedAndCountDenial(fileKey, { cls, batchId, cap });
if (!ok) {
return allowWithStateWarning();
}
@@ -2664,7 +2720,7 @@ function firstTouchMultiEdit(ctx, edits, filePath, fileKey, batch) {
return null;
}
const miss = restricted ? null : findClosestMiss(getTurnScan(), filePath, false, data);
return firstTouchDenial(filePath, { isWrite: false, denials, cls, sensitive, linked, profile, miss });
return firstTouchDenial(filePath, { isWrite: false, denials, cls, sensitive, linked, profile, miss, locked: batchId !== null });
}
// --- Bash / PowerShell ---
+1
View File
@@ -25,6 +25,7 @@ const DECISIONS = Object.freeze([
'routine-deny',
'routine-readonly',
'destructive-deny',
'batch-deny',
'pass'
]);
const DECISION_SET = new Set(DECISIONS);
+38 -1
View File
@@ -125,6 +125,40 @@ function capDirGates(gates) {
return nullMap(entries.sort((a, b) => b[1].at - a[1].at).slice(0, MAX_DIR_GATES));
}
// --- Same-batch locks ---
// see docs/gateguard/design-notes.md#same-batch-siblings
const MAX_BATCH_LOCKS = 50;
function isBatchLockEntry(entry) {
return isPlainObject(entry) && typeof entry.batch === 'string' && entry.batch !== '' && typeof entry.at === 'number' && Number.isFinite(entry.at);
}
/** File key -> { batch, at } for files denied at first touch whose batch was located. */
function getBatchLocks(state) {
const raw = state && state.batch_locks;
if (!isPlainObject(raw)) return nullMap([]);
const entries = Object.keys(raw)
.filter(key => isSafeKey(key) && isBatchLockEntry(raw[key]))
.map(key => [key, { batch: raw[key].batch, at: raw[key].at }]);
return nullMap(entries);
}
/** Merge two batch-lock maps; the newer `at` wins per key. */
function mergeBatchLocks(older, newer) {
const merged = nullMap(Object.entries(older));
for (const [key, entry] of Object.entries(newer)) {
if (!Object.hasOwn(merged, key) || entry.at >= merged[key].at) merged[key] = entry;
}
return merged;
}
function capBatchLocks(locks) {
const entries = Object.entries(locks);
if (entries.length <= MAX_BATCH_LOCKS) return locks;
return nullMap(entries.sort((a, b) => b[1].at - a[1].at).slice(0, MAX_BATCH_LOCKS));
}
module.exports = {
getDenialCount,
getCreditedCount,
@@ -139,5 +173,8 @@ module.exports = {
dirGateKey,
getDirGates,
mergeDirGates,
capDirGates
capDirGates,
getBatchLocks,
mergeBatchLocks,
capBatchLocks
};
+169
View File
@@ -4347,6 +4347,175 @@ function runTests() {
passed++;
else failed++;
// --- Same-batch siblings (#3936): when the denied call's batch is found ---
// by its tool_use_id, the other edits to that file in the same batch are
// denied too, so the file is not left half-edited. The retry from a later
// message passes. Without a located batch, the #3136 behavior holds.
{
const batchDir = fs.mkdtempSync(path.join(tmpRoot, 'gateguard-batch-'));
const batchEnv = { CLAUDE_PROJECT_DIR: '/proj-batch', CLAUDE_TRANSCRIPT_PATH: '' };
let batchSeq = 0;
const userText = text => ({ type: 'user', message: { role: 'user', content: text } });
const assistantCalls = (messageId, calls) => ({
type: 'assistant',
message: { id: messageId, role: 'assistant', content: calls.map(([id, name, input]) => ({ type: 'tool_use', id, name, input })) }
});
const deniedResults = ids => ({
type: 'user',
message: { role: 'user', content: ids.map(id => ({ type: 'tool_result', tool_use_id: id, is_error: true, content: 'denied' })) }
});
const writeBatchTranscript = records => {
batchSeq += 1;
const file = path.join(batchDir, `batch-${batchSeq}.jsonl`);
fs.writeFileSync(file, records.map(r => JSON.stringify(r)).join('\n') + '\n', 'utf8');
return file;
};
const editInput = (file_path, old_string) => ({ file_path, old_string, new_string: `${old_string}2` });
const batchRun = (toolName, toolInput, transcriptPath, toolUseId) => {
const payload = { tool_name: toolName, tool_input: toolInput, cwd: '/proj-batch' };
if (transcriptPath) payload.transcript_path = transcriptPath;
if (toolUseId) payload.tool_use_id = toolUseId;
const output = parseOutput(runHook(payload, batchEnv).stdout);
const hso = output && output.hookSpecificOutput ? output.hookSpecificOutput : {};
return { decision: hso.permissionDecision, reason: hso.permissionDecisionReason || '' };
};
const readBatchState = () => JSON.parse(fs.readFileSync(stateFile, 'utf8'));
const batchCase = (name, fn) => {
clearState();
if (test(name, fn)) passed++;
else failed++;
};
const target = '/proj-batch/src/table.js';
batchCase('same-batch sibling of a first-touch denial is denied; the retry passes (#3936)', () => {
const batch = [
['toolu_tbl_a', 'Edit', editInput(target, 'head')],
['toolu_tbl_b', 'Edit', editInput(target, 'body')]
];
const t = writeBatchTranscript([userText('fix the table'), assistantCalls('msg_tbl_1', batch)]);
const first = batchRun('Edit', batch[0][2], t, 'toolu_tbl_a');
assert.strictEqual(first.decision, 'deny', 'first touch is denied');
assert.ok(first.reason.includes(`Other edits to ${target} from this batch are denied too`), `locked note expected, got: ${first.reason}`);
assert.ok(!first.reason.includes('may already have been applied'), 'no partial-application warning when locked');
const sibling = batchRun('Edit', batch[1][2], t, 'toolu_tbl_b');
assert.strictEqual(sibling.decision, 'deny', 'same-batch sibling is denied');
assert.ok(sibling.reason.includes('in this same batch was denied at first touch'), sibling.reason);
assert.ok(sibling.reason.includes(target), 'sibling denial names the file');
assert.strictEqual(readBatchState().fact_force_denials, 1, 'a same-batch denial is not a new first-touch denial');
const retryBatch = [
['toolu_tbl_c', 'Edit', editInput(target, 'head')],
['toolu_tbl_d', 'Edit', editInput(target, 'body')]
];
const later = writeBatchTranscript([
userText('fix the table'),
assistantCalls('msg_tbl_1', batch),
deniedResults(['toolu_tbl_a', 'toolu_tbl_b']),
assistantCalls('msg_tbl_2', retryBatch)
]);
assert.notStrictEqual(batchRun('Edit', retryBatch[0][2], later, 'toolu_tbl_c').decision, 'deny', 'retry from a later message passes');
assert.notStrictEqual(batchRun('Edit', retryBatch[1][2], later, 'toolu_tbl_d').decision, 'deny', 'resent sibling passes');
assert.strictEqual(readBatchState().fact_force_denials, 1, 'still one denial');
});
batchCase('one record per tool_use with a shared message id is one batch (#3936)', () => {
const a = ['toolu_split_a', 'Edit', editInput(target, 'x')];
const b = ['toolu_split_b', 'Edit', editInput(target, 'y')];
const t = writeBatchTranscript([userText('go'), assistantCalls('msg_split', [a]), assistantCalls('msg_split', [b])]);
assert.strictEqual(batchRun('Edit', a[2], t, a[0]).decision, 'deny');
assert.strictEqual(batchRun('Edit', b[2], t, b[0]).decision, 'deny', 'sibling in a separate record of the same message is denied');
});
batchCase('the lock is per file: another file in the same batch gets its own first-touch gate (#3936)', () => {
const other = '/proj-batch/src/other.js';
const batch = [
['toolu_pf_a', 'Edit', editInput(target, 'x')],
['toolu_pf_b', 'Edit', editInput(other, 'y')]
];
const t = writeBatchTranscript([userText('go'), assistantCalls('msg_pf', batch)]);
assert.strictEqual(batchRun('Edit', batch[0][2], t, batch[0][0]).decision, 'deny');
const second = batchRun('Edit', batch[1][2], t, batch[1][0]);
assert.strictEqual(second.decision, 'deny', 'other file is gated on its own first touch');
assert.ok(!second.reason.includes('in this same batch was denied'), 'not a same-batch denial');
assert.strictEqual(readBatchState().fact_force_denials, 2);
});
batchCase('no located batch keeps the #3136 behavior: siblings pass (#3936)', () => {
const batch = [
['toolu_nl_a', 'Edit', editInput(target, 'x')],
['toolu_nl_b', 'Edit', editInput(target, 'y')]
];
const t = writeBatchTranscript([userText('go'), assistantCalls('msg_nl', batch)]);
// No tool_use_id on either call.
const first = batchRun('Edit', batch[0][2], t, '');
assert.strictEqual(first.decision, 'deny');
assert.ok(first.reason.includes('may already have been applied'), 'unlocked denial keeps the partial-application warning');
assert.notStrictEqual(batchRun('Edit', batch[1][2], t, '').decision, 'deny', 'sibling without tool_use_id passes');
assert.ok(!('batch_locks' in readBatchState()) || Object.keys(readBatchState().batch_locks).length === 0, 'nothing locked');
clearState();
// tool_use_id given but the pending call is not in the transcript yet.
const stale = writeBatchTranscript([userText('go')]);
assert.strictEqual(batchRun('Edit', batch[0][2], stale, 'toolu_nl_a').decision, 'deny');
assert.notStrictEqual(batchRun('Edit', batch[1][2], stale, 'toolu_nl_b').decision, 'deny', 'unlocated sibling passes');
});
batchCase('MultiEdit and NotebookEdit siblings of a locked file are denied (#3936)', () => {
const notebook = '/proj-batch/nb/analysis.ipynb';
const batch = [
['toolu_me_a', 'Edit', editInput(target, 'x')],
['toolu_me_b', 'MultiEdit', { edits: [editInput(target, 'y')] }],
['toolu_me_c', 'NotebookEdit', { notebook_path: notebook, new_source: 'x' }],
['toolu_me_d', 'NotebookEdit', { notebook_path: notebook, new_source: 'y' }]
];
const t = writeBatchTranscript([userText('go'), assistantCalls('msg_me', batch)]);
assert.strictEqual(batchRun('Edit', batch[0][2], t, batch[0][0]).decision, 'deny');
const multi = batchRun('MultiEdit', batch[1][2], t, batch[1][0]);
assert.strictEqual(multi.decision, 'deny', 'MultiEdit entry for the locked file is denied');
assert.ok(multi.reason.includes('in this same batch was denied'), multi.reason);
assert.strictEqual(batchRun('NotebookEdit', batch[2][2], t, batch[2][0]).decision, 'deny', 'notebook first touch');
assert.strictEqual(batchRun('NotebookEdit', batch[3][2], t, batch[3][0]).decision, 'deny', 'notebook sibling denied');
});
batchCase('a Write sibling of a denied Write in the same batch is denied (#3936)', () => {
const created = '/proj-batch/src/new-module.js';
const batch = [
['toolu_w_a', 'Write', { file_path: created, content: 'a' }],
['toolu_w_b', 'Edit', editInput(created, 'a')]
];
const t = writeBatchTranscript([userText('go'), assistantCalls('msg_w', batch)]);
const first = batchRun('Write', batch[0][2], t, batch[0][0]);
assert.strictEqual(first.decision, 'deny');
assert.ok(first.reason.includes('are denied too'), first.reason);
assert.strictEqual(batchRun('Edit', batch[1][2], t, batch[1][0]).decision, 'deny');
});
batchCase('condensed denial carries the locked note on one line (#3936)', () => {
writeState({ checked: [], last_active: Date.now(), fact_force_denials: 3 });
const a = ['toolu_cd_a', 'Edit', editInput(target, 'x')];
const t = writeBatchTranscript([userText('go'), assistantCalls('msg_cd', [a])]);
const out = batchRun('Edit', a[2], t, a[0]);
assert.strictEqual(out.decision, 'deny');
assert.ok(out.reason.includes('are denied too'), out.reason);
assert.ok(!out.reason.includes('\n'), 'condensed denial stays a single line');
});
batchCase('malformed batch_locks in the state file are ignored (#3936)', () => {
const key = stateKey(target);
const t = writeBatchTranscript([userText('go'), assistantCalls('msg_bad', [['toolu_bad', 'Edit', editInput(target, 'x')]])]);
for (const bad of [{ batch: 5, at: 1 }, { batch: '', at: 1 }, { batch: 'msg_bad' }, 'msg_bad', null]) {
writeState({ checked: [key], last_active: Date.now(), fact_force_denials: 1, batch_locks: { [key]: bad } });
assert.notStrictEqual(batchRun('Edit', editInput(target, 'x'), t, 'toolu_bad').decision, 'deny', `ignored: ${JSON.stringify(bad)}`);
}
writeState({ checked: [key], last_active: Date.now(), fact_force_denials: 1, batch_locks: JSON.parse('{"__proto__":{"batch":"msg_bad","at":1}}') });
assert.notStrictEqual(batchRun('Edit', editInput(target, 'x'), t, 'toolu_bad').decision, 'deny', 'prototype key ignored');
});
fs.rmSync(batchDir, { recursive: true, force: true });
}
// --- Canonical checked-path keys ---
const decisionOf = result => {
const output = parseOutput(result.stdout);
+1
View File
@@ -95,6 +95,7 @@ test('keeps near-miss reason codes', () => {
test('lists every decision the hook records', () => {
assert.deepStrictEqual([...DECISIONS].sort(), [
'batch-deny',
'cap',
'credit',
'deny',
+29 -1
View File
@@ -19,7 +19,10 @@ const {
dirGateKey,
getDirGates,
mergeDirGates,
capDirGates
capDirGates,
getBatchLocks,
mergeBatchLocks,
capBatchLocks
} = require(path.join(__dirname, '..', '..', 'scripts', 'lib', 'gateguard-state.js'));
console.log('=== Testing gateguard-state.js ===\n');
@@ -91,5 +94,30 @@ test('dir gates keep valid class-prefixed entries, newest wins on merge, capped
assert.ok(!(dirGateKey('code', '/p/d0') in capped), 'oldest evicted');
});
test('batch locks keep valid { batch, at } entries, newest wins on merge, capped at 50', () => {
const locks = getBatchLocks(JSON.parse(JSON.stringify({
batch_locks: {
'/p/a.js': { batch: 'msg_1', at: 10, extra: true },
'/p/b.js': { batch: '', at: 10 },
'/p/c.js': { batch: 7, at: 10 },
'/p/d.js': { batch: 'msg_2', at: 'soon' },
'/p/e.js': 'msg_3',
constructor: { batch: 'msg_4', at: 10 }
}
})));
assert.deepStrictEqual(Object.entries(locks), [['/p/a.js', { batch: 'msg_1', at: 10 }]]);
assert.strictEqual(Object.getPrototypeOf(locks), null);
assert.deepStrictEqual(Object.keys(getBatchLocks(JSON.parse('{"batch_locks":{"__proto__":{"batch":"m","at":1}}}'))), []);
assert.deepStrictEqual(Object.keys(getBatchLocks({ batch_locks: [] })), []);
assert.deepStrictEqual(Object.keys(getBatchLocks(null)), []);
assert.strictEqual(mergeBatchLocks(locks, { '/p/a.js': { batch: 'msg_9', at: 20 } })['/p/a.js'].batch, 'msg_9');
assert.strictEqual(mergeBatchLocks({ '/p/a.js': { batch: 'msg_9', at: 20 } }, locks)['/p/a.js'].batch, 'msg_9', 'older entry never wins');
const many = {};
for (let i = 0; i < 60; i++) many[`/p/f${i}.js`] = { batch: `msg_${i}`, at: i };
const capped = capBatchLocks(many);
assert.strictEqual(Object.keys(capped).length, 50);
assert.ok(!('/p/f0.js' in capped), 'oldest evicted');
});
console.log(`\nResults: Passed: ${passed}, Failed: ${failed}`);
process.exit(failed > 0 ? 1 : 0);