mirror of
https://github.com/affaan-m/ECC.git
synced 2026-11-23 08:15:29 +00:00
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:
1 parent
d2ef268059
commit
b2fa2d93ee
9 files changed
+347
-28
No files matched your search
@@ -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;
|
||||
|
||||
@@ -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 ---
|
||||
|
||||
@@ -25,6 +25,7 @@ const DECISIONS = Object.freeze([
|
||||
'routine-deny',
|
||||
'routine-readonly',
|
||||
'destructive-deny',
|
||||
'batch-deny',
|
||||
'pass'
|
||||
]);
|
||||
const DECISION_SET = new Set(DECISIONS);
|
||||
|
||||
@@ -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
|
||||
};
|
||||
Reference in new issue
Block a user