mirror of
https://github.com/affaan-m/ECC.git
synced 2026-12-06 23:24:01 +09:00
Merge reviewed hook logging, batch warning and project cache repairs
This commit is contained in:
11 files changed
+535
-31
No files matched your search
@@ -0,0 +1,17 @@
|
||||
# Command log retention
|
||||
|
||||
The optional audit and development command hooks write private command logs
|
||||
using the standalone `scripts/hooks/post-bash-command-log.js` helper. Commands
|
||||
pass through the existing secret redaction before being recorded.
|
||||
|
||||
Rotation keeps the active log and one archive. Writers coordinate the size
|
||||
check, rotation, and append with a cross-process lock so simultaneous rotations
|
||||
do not overwrite newly archived history. Only a lock whose owner is verifiably
|
||||
dead can be reclaimed; elapsed time alone never establishes ownership.
|
||||
|
||||
Logging waits at most 500 milliseconds for ownership, then appends without
|
||||
rotating. The size limit is best effort: rotation resumes when ownership becomes
|
||||
available. Unsupported lock operations or an orphaned recovery guard can defer
|
||||
rotation indefinitely while command recording continues. The recovery guard is
|
||||
not recursively reclaimed, so operators should investigate persistent lock files
|
||||
and establish that all writers have stopped before removing an orphan guard.
|
||||
@@ -458,6 +458,8 @@ is the batch.
|
||||
`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.
|
||||
- Earlier permitted siblings, such as comment-only edits, are never rolled back.
|
||||
Every batch denial keeps a re-read warning; a lock cannot prove the file is unchanged.
|
||||
- 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
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
"id": "hand-seeded",
|
||||
"source": "manual-curation-pending-regeneration"
|
||||
},
|
||||
"registryDigest": "27e0424730a1ad30f57f210cdfc8f8d72493cfe8f5ffc9d3ead4b2943e1131ed",
|
||||
"registryDigest": "fa3a274aab6419623612f8121d18995b1ea9220411252e6a68b75974451ef5ce",
|
||||
"schemaVersion": 1,
|
||||
"triggers": {
|
||||
"skill:agent-runtime-gateway-smoke-test": [
|
||||
|
||||
@@ -2105,7 +2105,8 @@ const READ_ONLY_GIT_SUBCOMMANDS = new Map([
|
||||
* 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
|
||||
* later siblings are denied too (`locked`), but earlier allowed edits are
|
||||
* never rolled back. 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
|
||||
@@ -2113,8 +2114,8 @@ const READ_ONLY_GIT_SUBCOMMANDS = new Map([
|
||||
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.'
|
||||
`Other edits to ${safePath} from this batch are denied too. Earlier edits may already have been applied. ` +
|
||||
'Re-read the file and resend every denied edit with the retry.'
|
||||
);
|
||||
}
|
||||
return (
|
||||
@@ -2127,8 +2128,8 @@ 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.'
|
||||
`so this one is denied too. Earlier edits may already have been applied. ` +
|
||||
'Re-read the file, present the facts that denial asked for, then resend every denied edit to this file from this batch.'
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#!/usr/bin/env node
|
||||
'use strict';
|
||||
|
||||
const crypto = require('crypto');
|
||||
const fs = require('fs');
|
||||
const os = require('os');
|
||||
const path = require('path');
|
||||
@@ -197,38 +198,154 @@ function sanitizeCommand(command) {
|
||||
const LOG_MAX_BYTES = 10 * 1024 * 1024;
|
||||
const LOG_FILE_MODE = 0o600;
|
||||
|
||||
// Keep this hook standalone: managed copies may omit scripts/lib. Lock
|
||||
// publication and release use descriptor identities, as the installer does.
|
||||
const LOG_LOCK_WAIT_MS = 500;
|
||||
function sameLogLock(left, right) {
|
||||
return left.ino === right.ino && (left.dev === right.dev
|
||||
|| (process.platform === 'win32' && (!left.dev || !right.dev)));
|
||||
}
|
||||
|
||||
function restoreLogLock(quarantine, lockPath) {
|
||||
// Exclusive publication never overwrites a replacement owner's lock. Keep
|
||||
// the displaced file for inspection if another owner already holds the path.
|
||||
fs.linkSync(quarantine, lockPath);
|
||||
fs.unlinkSync(quarantine);
|
||||
}
|
||||
|
||||
function reserveLogQuarantine(lockPath, phase) {
|
||||
const quarantine = `${lockPath}.${phase}-${process.pid}-${crypto.randomBytes(8).toString('hex')}`;
|
||||
// Reserve exclusively before rename, which otherwise overwrites a colliding
|
||||
// foreign file. A failed reservation must never enter path cleanup.
|
||||
const descriptor = fs.openSync(quarantine, 'wx', LOG_FILE_MODE);
|
||||
fs.closeSync(descriptor);
|
||||
return quarantine;
|
||||
}
|
||||
|
||||
function publishLogLock(lockPath) {
|
||||
const temporary = `${lockPath}.create-${process.pid}-${crypto.randomBytes(8).toString('hex')}`;
|
||||
let descriptor = fs.openSync(temporary, 'wx', LOG_FILE_MODE);
|
||||
let identity;
|
||||
try {
|
||||
fs.writeFileSync(descriptor, JSON.stringify({ pid: process.pid }));
|
||||
fs.fsyncSync(descriptor);
|
||||
identity = fs.fstatSync(descriptor, { bigint: true });
|
||||
fs.closeSync(descriptor);
|
||||
descriptor = undefined;
|
||||
fs.linkSync(temporary, lockPath);
|
||||
} finally {
|
||||
if (descriptor !== undefined) fs.closeSync(descriptor);
|
||||
fs.rmSync(temporary, { force: true });
|
||||
}
|
||||
return () => {
|
||||
const quarantine = reserveLogQuarantine(lockPath, 'release');
|
||||
fs.renameSync(lockPath, quarantine);
|
||||
if (!sameLogLock(fs.lstatSync(quarantine, { bigint: true }), identity)) {
|
||||
restoreLogLock(quarantine, lockPath);
|
||||
throw new Error('Command log lock changed owner before release');
|
||||
}
|
||||
fs.unlinkSync(quarantine);
|
||||
};
|
||||
}
|
||||
|
||||
function inspectLogLock(lockPath) {
|
||||
const descriptor = fs.openSync(lockPath, fs.constants.O_RDONLY
|
||||
| (fs.constants.O_NOFOLLOW || 0) | (fs.constants.O_NONBLOCK || 0));
|
||||
try {
|
||||
const identity = fs.fstatSync(descriptor, { bigint: true });
|
||||
const named = fs.lstatSync(lockPath, { bigint: true });
|
||||
if (!identity.isFile() || named.isSymbolicLink() || !sameLogLock(identity, named)
|
||||
|| identity.size > 4096n) return null;
|
||||
const bytes = Buffer.alloc(4097);
|
||||
const count = fs.readSync(descriptor, bytes, 0, bytes.length, 0);
|
||||
if (count > 4096) return null;
|
||||
const owner = JSON.parse(bytes.subarray(0, count).toString('utf8'));
|
||||
if (!Number.isSafeInteger(owner.pid) || owner.pid <= 0) return null;
|
||||
try { process.kill(owner.pid, 0); return null; }
|
||||
catch (error) { return error.code === 'ESRCH' ? identity : null; }
|
||||
} finally { fs.closeSync(descriptor); }
|
||||
}
|
||||
|
||||
function recoverLogLock(lockPath) {
|
||||
let releaseGuard;
|
||||
try { releaseGuard = publishLogLock(`${lockPath}.recover`); }
|
||||
catch { return null; }
|
||||
// The recovery guard is not recursively reclaimed. A crash here may leave
|
||||
// it behind, so later calls preserve events through append-only fallback.
|
||||
try {
|
||||
const identity = inspectLogLock(lockPath);
|
||||
if (!identity) return null; // Never take a live or unverifiable owner's lock.
|
||||
const quarantine = reserveLogQuarantine(lockPath, 'stale');
|
||||
fs.renameSync(lockPath, quarantine);
|
||||
if (!sameLogLock(fs.lstatSync(quarantine, { bigint: true }), identity)) {
|
||||
restoreLogLock(quarantine, lockPath);
|
||||
return null;
|
||||
}
|
||||
fs.unlinkSync(quarantine);
|
||||
return publishLogLock(lockPath);
|
||||
} finally { releaseGuard(); }
|
||||
}
|
||||
|
||||
function acquireLogLock(filePath) {
|
||||
const lockPath = `${filePath}.lock`;
|
||||
const deadline = performance.now() + LOG_LOCK_WAIT_MS;
|
||||
const sleeper = new Int32Array(new SharedArrayBuffer(4));
|
||||
while (true) {
|
||||
try { return publishLogLock(lockPath); }
|
||||
catch (error) { if (error.code !== 'EEXIST') return null; }
|
||||
try {
|
||||
const release = recoverLogLock(lockPath);
|
||||
if (release) return release;
|
||||
} catch { /* A writer can finish while recovery inspects the path. */ }
|
||||
const remaining = deadline - performance.now();
|
||||
if (remaining <= 0) return null;
|
||||
Atomics.wait(sleeper, 0, 0, Math.min(10, remaining));
|
||||
}
|
||||
}
|
||||
|
||||
function appendOnly(filePath, data) {
|
||||
const descriptor = fs.openSync(filePath, 'a', LOG_FILE_MODE);
|
||||
try {
|
||||
if (process.platform !== 'win32') fs.fchmodSync(descriptor, LOG_FILE_MODE);
|
||||
fs.writeSync(descriptor, data);
|
||||
} finally { fs.closeSync(descriptor); }
|
||||
}
|
||||
|
||||
function appendLine(filePath, line) {
|
||||
const data = `${line}\n`;
|
||||
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
||||
|
||||
let stat = null;
|
||||
const release = acquireLogLock(filePath);
|
||||
if (!release) {
|
||||
// Preserve the command after a bounded wait or unsupported lock operation.
|
||||
// Only the lock owner rotates; size enforcement resumes when the lock
|
||||
// becomes available. An orphan recovery guard can defer this indefinitely.
|
||||
appendOnly(filePath, data);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
stat = fs.statSync(filePath);
|
||||
} catch {
|
||||
// No log yet.
|
||||
}
|
||||
// Logs written by earlier versions were group/world readable. Tighten an
|
||||
// existing log before it can be rotated, so the `.1` copy is private too.
|
||||
// Windows has no POSIX permission bits to tighten.
|
||||
if (stat && stat.isFile() && process.platform !== 'win32' && (stat.mode & 0o077) !== 0) {
|
||||
fs.chmodSync(filePath, LOG_FILE_MODE);
|
||||
}
|
||||
if (stat && stat.isFile() && stat.size > 0 && stat.size + Buffer.byteLength(data) > LOG_MAX_BYTES) {
|
||||
let stat = null;
|
||||
try {
|
||||
fs.renameSync(filePath, `${filePath}.1`);
|
||||
stat = fs.statSync(filePath);
|
||||
} catch {
|
||||
// Rotation is best effort (another process may have rotated first, or
|
||||
// Windows may refuse the rename); still record this command.
|
||||
// No log yet.
|
||||
}
|
||||
}
|
||||
|
||||
// The mode only applies when this call creates the file; an existing log
|
||||
// was tightened above.
|
||||
const fd = fs.openSync(filePath, 'a', LOG_FILE_MODE);
|
||||
try {
|
||||
fs.writeSync(fd, data);
|
||||
// Logs written by earlier versions were group/world readable. Tighten an
|
||||
// existing log before it can be rotated, so the `.1` copy is private too.
|
||||
// Windows has no POSIX permission bits to tighten.
|
||||
if (stat && stat.isFile() && process.platform !== 'win32' && (stat.mode & 0o077) !== 0) {
|
||||
fs.chmodSync(filePath, LOG_FILE_MODE);
|
||||
}
|
||||
if (stat && stat.isFile() && stat.size > 0 && stat.size + Buffer.byteLength(data) > LOG_MAX_BYTES) {
|
||||
try {
|
||||
fs.renameSync(filePath, `${filePath}.1`);
|
||||
} catch {
|
||||
// Rotation is best effort (another process may have rotated first, or
|
||||
// Windows may refuse the rename); still record this command.
|
||||
}
|
||||
}
|
||||
appendOnly(filePath, data);
|
||||
} finally {
|
||||
fs.closeSync(fd);
|
||||
try { release(); } catch { /* Preserve the write result and foreign locks. */ }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -355,6 +355,7 @@ atomic_write_json(registry_path, registry)
|
||||
# decides the root or the id, such as core.worktree, was changed)
|
||||
# - git no longer reports the origin the entry was derived from (remote
|
||||
# added, changed or removed, which changes the project id)
|
||||
# - a nearer .git marker changes discovery from the explicit project or cwd
|
||||
# - the project storage directory or the project root no longer exists
|
||||
# - the stored id is not a shape detection can produce
|
||||
#
|
||||
@@ -410,6 +411,25 @@ _clv2_project_cache_prepare() {
|
||||
return 0
|
||||
}
|
||||
|
||||
# Confirm that discovery still selects the cached root without another Git
|
||||
# launch. A newly initialized repo, worktree marker, or even broken .git link
|
||||
# between the selected starting directory and that root requires fresh Git.
|
||||
_clv2_project_cache_same_root() {
|
||||
local expected="$1"
|
||||
local start="${CLAUDE_PROJECT_DIR:-}"
|
||||
[ -n "$start" ] && [ -d "$start" ] || start="."
|
||||
local probe="$start" depth=0
|
||||
while [ "$depth" -lt 512 ]; do
|
||||
[ "$probe" -ef "$expected" ] && return 0
|
||||
if [ -e "$probe/.git" ] || [ -L "$probe/.git" ]; then return 1; fi
|
||||
[ "$probe" -ef "$probe/.." ] && return 1
|
||||
# Let the filesystem resolve aliases and .. without a cd/pwd subprocess.
|
||||
probe="$probe/.."
|
||||
depth=$((depth + 1))
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
_clv2_project_cache_load() {
|
||||
local file="$_CLV2_PROJECT_CACHE_FILE"
|
||||
[ -n "$file" ] && [ -f "$file" ] || return 1
|
||||
@@ -448,6 +468,7 @@ _clv2_project_cache_load() {
|
||||
# and still a repository with its own .git/config file (see the store side).
|
||||
[ -n "$root" ] && [ -d "$root" ] || return 1
|
||||
[ -f "${root}/.git/config" ] || return 1
|
||||
_clv2_project_cache_same_root "$root" || return 1
|
||||
# Settings in the repository's own config (core.worktree moves the root,
|
||||
# a remote changes the id) are trusted only while the entry is strictly
|
||||
# newer than that file. Equal timestamps count as stale so a change in the
|
||||
|
||||
@@ -227,6 +227,92 @@ test('a cache hit launches git once, only to ask for the origin', () => {
|
||||
}
|
||||
});
|
||||
|
||||
test('a newly initialized nested repository replaces the cached parent, even with the same origin', () => {
|
||||
for (const sameOrigin of [false, true]) {
|
||||
for (const explicit of [false, true]) {
|
||||
const tmp = createTempDir();
|
||||
try {
|
||||
const home = path.join(tmp, 'home');
|
||||
fs.mkdirSync(home);
|
||||
const remote = 'https://github.com/example/parent.git';
|
||||
const parent = makeRepo(tmp, 'parent', remote);
|
||||
const nested = path.join(parent, 'nested');
|
||||
fs.mkdirSync(nested);
|
||||
const env = explicit ? { CLAUDE_PROJECT_DIR: nested } : {};
|
||||
const before = detect(nested, home, env);
|
||||
assert.strictEqual(before.root, fs.realpathSync(parent));
|
||||
assert.strictEqual(detect(nested, home, env).hit, '1');
|
||||
git(nested, 'init', '-q');
|
||||
git(nested, 'remote', 'add', 'origin', sameOrigin ? remote : 'https://github.com/example/nested.git');
|
||||
const after = detect(nested, home, env);
|
||||
assert.strictEqual(after.hit, '0', 'a nearer repository must invalidate the cached root');
|
||||
assert.strictEqual(after.root, fs.realpathSync(nested));
|
||||
assert.strictEqual(after.id === before.id, sameOrigin);
|
||||
const control = detect(nested, home, { ...env, CLV2_PROJECT_CACHE: '0' });
|
||||
assert.strictEqual(after.id, control.id, 'cached discovery must match fresh Git detection');
|
||||
} finally { cleanupDir(tmp); }
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('an explicit parent project still wins after the current directory becomes a nested repository', () => {
|
||||
const tmp = createTempDir();
|
||||
try {
|
||||
const home = path.join(tmp, 'home');
|
||||
fs.mkdirSync(home);
|
||||
const parent = makeRepo(tmp, 'explicit-parent', 'https://github.com/example/parent.git');
|
||||
const nested = path.join(parent, 'nested');
|
||||
fs.mkdirSync(nested);
|
||||
const env = { CLAUDE_PROJECT_DIR: parent };
|
||||
const before = detect(nested, home, env);
|
||||
git(nested, 'init', '-q');
|
||||
git(nested, 'remote', 'add', 'origin', 'https://github.com/example/nested.git');
|
||||
const after = detect(nested, home, env);
|
||||
assert.strictEqual(after.hit, '1', 'an explicit project must retain priority over cwd');
|
||||
assert.strictEqual(after.root, before.root);
|
||||
assert.strictEqual(after.id, before.id);
|
||||
} finally { cleanupDir(tmp); }
|
||||
});
|
||||
|
||||
test('a nearer malformed .git file or broken link invalidates cached parent discovery', () => {
|
||||
for (const link of [false, true]) {
|
||||
const tmp = createTempDir();
|
||||
try {
|
||||
const home = path.join(tmp, 'home'); fs.mkdirSync(home);
|
||||
const parent = makeRepo(tmp, 'marker-parent', 'https://github.com/example/parent.git');
|
||||
const nested = path.join(parent, 'nested'); fs.mkdirSync(nested);
|
||||
detect(nested, home);
|
||||
assert.strictEqual(detect(nested, home).hit, '1');
|
||||
if (link) fs.symlinkSync(path.join(tmp, 'missing-git-dir'), path.join(nested, '.git'));
|
||||
else fs.writeFileSync(path.join(nested, '.git'), 'gitdir: /missing-git-dir\n');
|
||||
const after = detect(nested, home);
|
||||
const control = detect(nested, home, { CLV2_PROJECT_CACHE: '0' });
|
||||
assert.strictEqual(after.hit, '0');
|
||||
assert.strictEqual(after.root, control.root);
|
||||
assert.strictEqual(after.id, control.id);
|
||||
} finally { cleanupDir(tmp); }
|
||||
}
|
||||
});
|
||||
|
||||
test('cached discovery follows physical ancestors through an explicit symlinked directory', () => {
|
||||
const tmp = createTempDir();
|
||||
try {
|
||||
const home = path.join(tmp, 'home'); fs.mkdirSync(home);
|
||||
const parent = makeRepo(tmp, 'alias-parent', 'https://github.com/example/parent.git');
|
||||
const middle = path.join(parent, 'middle');
|
||||
const nested = path.join(middle, 'nested'); fs.mkdirSync(nested, { recursive: true });
|
||||
const alias = path.join(tmp, 'alias'); fs.symlinkSync(nested, alias);
|
||||
const env = { CLAUDE_PROJECT_DIR: alias };
|
||||
const before = detect(parent, home, env);
|
||||
assert.strictEqual(before.root, fs.realpathSync(parent));
|
||||
assert.strictEqual(detect(parent, home, env).hit, '1');
|
||||
git(middle, 'init', '-q');
|
||||
const after = detect(parent, home, env);
|
||||
assert.strictEqual(after.hit, '0');
|
||||
assert.strictEqual(after.root, fs.realpathSync(middle));
|
||||
} finally { cleanupDir(tmp); }
|
||||
});
|
||||
|
||||
test('a cached "global" result launches no git process', () => {
|
||||
const tmp = createTempDir();
|
||||
try {
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
'use strict';
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
const { spawnSync } = require('node:child_process');
|
||||
const test = require('node:test');
|
||||
const runner = path.resolve(__dirname, '../../scripts/hooks/run-with-flags.js');
|
||||
|
||||
test('comment-first batch edits retain a re-read warning after later first-touch and sibling denials', () => {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-batch-message-'));
|
||||
try {
|
||||
const file = path.join(root, 'table.js');
|
||||
const state = path.join(root, 'state');
|
||||
fs.mkdirSync(state);
|
||||
fs.writeFileSync(file, '// old\nconst value = 1;\n');
|
||||
const comment = { file_path: file, old_string: '// old\n', new_string: '// revised\n' };
|
||||
const edit = { file_path: file, old_string: '1', new_string: '2' };
|
||||
const calls = [['comment', comment], ['code', edit], ['sibling', { ...edit, new_string: '3' }]];
|
||||
const transcript = path.join(root, 'transcript.jsonl');
|
||||
const message = (id, entries) => ({ type: 'assistant', message: { id, role: 'assistant', content:
|
||||
entries.map(([toolId, input]) => ({ type: 'tool_use', id: toolId, name: 'Edit', input })) } });
|
||||
const initial = [{ type: 'user', message: { role: 'user', content: 'Update the table' } }, message('batch-one', calls)];
|
||||
fs.writeFileSync(transcript, initial.map(JSON.stringify).join('\n') + '\n');
|
||||
const run = (id, input) => {
|
||||
const result = spawnSync(process.execPath, [runner, 'pre:edit-write:gateguard-fact-force',
|
||||
'scripts/hooks/gateguard-fact-force.js', 'standard,strict'], {
|
||||
input: JSON.stringify({ tool_name: 'Edit', tool_use_id: id, tool_input: input, cwd: root, transcript_path: transcript }),
|
||||
encoding: 'utf8', timeout: 15000,
|
||||
env: { ...process.env, CLAUDE_PROJECT_DIR: root, GATEGUARD_STATE_DIR: state,
|
||||
CLAUDE_SESSION_ID: 'batch-message', ECC_HOOK_PROFILE: 'standard', ECC_HOOKS_ENABLED: 'true', ECC_DISABLED_HOOKS: '',
|
||||
GATEGUARD_EXEMPT_GLOBS: '', GATEGUARD_FACT_FORCE_FULL_DENIALS: '3',
|
||||
ECC_GATEGUARD: 'on', GATEGUARD_DISABLED: '', GATEGUARD_FACT_FORCE_MAX_DENIALS: '',
|
||||
GATEGUARD_EXTERNAL_CONTRACT_QUESTION: '', CLAUDE_TRANSCRIPT_PATH: '' },
|
||||
});
|
||||
assert.ifError(result.error);
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
const output = JSON.parse(result.stdout);
|
||||
return output.hookSpecificOutput || {};
|
||||
};
|
||||
assert.notEqual(run('comment', comment).permissionDecision, 'deny');
|
||||
// Apply exactly the edit the hook permitted, as the harness would.
|
||||
fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace(comment.old_string, comment.new_string));
|
||||
const afterComment = fs.readFileSync(file, 'utf8');
|
||||
assert.match(afterComment, /revised/);
|
||||
for (const [id, input] of calls.slice(1)) {
|
||||
const denial = run(id, input);
|
||||
assert.equal(denial.permissionDecision, 'deny');
|
||||
assert.doesNotMatch(denial.permissionDecisionReason, /(?:file|table\.js) is unchanged/);
|
||||
assert.match(denial.permissionDecisionReason, /may already have been applied/);
|
||||
assert.match(denial.permissionDecisionReason, /re-read/i);
|
||||
assert.equal(fs.readFileSync(file, 'utf8'), afterComment);
|
||||
}
|
||||
const saved = JSON.parse(fs.readFileSync(path.join(state, 'state-batch-message.json'), 'utf8'));
|
||||
assert.equal(saved.fact_force_denials, 1, 'sibling denial must not spend another first-touch denial');
|
||||
fs.writeFileSync(transcript, [...initial, message('batch-two', [['retry', edit]])].map(JSON.stringify).join('\n') + '\n');
|
||||
assert.notEqual(run('retry', edit).permissionDecision, 'deny');
|
||||
fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace(edit.old_string, edit.new_string));
|
||||
assert.equal(fs.readFileSync(file, 'utf8'), '// revised\nconst value = 2;\n');
|
||||
} finally { fs.rmSync(root, { recursive: true, force: true }); }
|
||||
});
|
||||
@@ -4512,7 +4512,8 @@ function runTests() {
|
||||
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');
|
||||
assert.ok(first.reason.includes('may already have been applied'), 'locked denial still requires re-reading earlier edits');
|
||||
assert.ok(!first.reason.includes('file is unchanged'), 'a lock cannot prove no earlier sibling applied');
|
||||
|
||||
const sibling = batchRun('Edit', batch[1][2], t, 'toolu_tbl_b');
|
||||
assert.strictEqual(sibling.decision, 'deny', 'same-batch sibling is denied');
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
'use strict';
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const [root, role] = process.argv.slice(2);
|
||||
const file = path.join(root, '.claude', 'bash-commands.log');
|
||||
if (['collision', 'release-collision', 'stale-collision'].includes(role)) {
|
||||
require('crypto').randomBytes = size => Buffer.alloc(size);
|
||||
const phase = { collision: 'create', 'release-collision': 'release', 'stale-collision': 'stale' }[role];
|
||||
fs.writeFileSync(`${file}.lock.${phase}-${process.pid}-${'00'.repeat(8)}`, `foreign-${phase}`, { flag: 'wx', mode: 0o600 });
|
||||
}
|
||||
const signal = name => fs.writeFileSync(path.join(root, name), '', { mode: 0o600 });
|
||||
const rename = fs.renameSync;
|
||||
let paused = false;
|
||||
fs.renameSync = function (source, destination, ...args) {
|
||||
if (!paused && source === file && destination === `${file}.1` && ['owner', 'contender'].includes(role)) {
|
||||
paused = true;
|
||||
signal(`${role}-rotate-ready`);
|
||||
const sleep = new Int32Array(new SharedArrayBuffer(4));
|
||||
const deadline = Date.now() + 15000;
|
||||
while (!fs.existsSync(path.join(root, `${role}-release`))) {
|
||||
if (Date.now() > deadline) throw new Error('Rotation release deadline exceeded');
|
||||
Atomics.wait(sleep, 0, 0, 10);
|
||||
}
|
||||
}
|
||||
if (role === 'replacement' && source === `${file}.lock` && destination.startsWith(`${file}.lock.release-`)) {
|
||||
rename.call(fs, source, `${file}.original-lock`);
|
||||
fs.writeFileSync(source, JSON.stringify({ pid: process.ppid }), { flag: 'wx', mode: 0o600 });
|
||||
}
|
||||
return rename.call(fs, source, destination, ...args);
|
||||
};
|
||||
const link = fs.linkSync;
|
||||
fs.linkSync = function (source, destination, ...args) {
|
||||
try { return link.call(fs, source, destination, ...args); }
|
||||
catch (error) {
|
||||
if (destination === `${file}.lock` && error.code === 'EEXIST') signal(`${role}-contended`);
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
process.env.HOME = root;
|
||||
process.env.USERPROFILE = root;
|
||||
process.env.CLAUDE_CONFIG_DIR = path.join(root, '.claude');
|
||||
require('../../../scripts/hooks/post-bash-command-log').run(JSON.stringify({ tool_input: { command: `echo ${role}` } }), 'audit');
|
||||
signal(`${role}-finished`);
|
||||
@@ -0,0 +1,155 @@
|
||||
'use strict';
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
const { spawn } = require('node:child_process');
|
||||
const test = require('node:test');
|
||||
const { LOG_MAX_BYTES } = require('../../scripts/hooks/post-bash-command-log');
|
||||
const worker = path.resolve(__dirname, '../lib/helpers/command-log-worker.js');
|
||||
const signal = (root, name) => fs.writeFileSync(path.join(root, name), '', { mode: 0o600 });
|
||||
async function waitFor(root, names) {
|
||||
const until = Date.now() + 10000;
|
||||
while (!names.some(name => fs.existsSync(path.join(root, name)))) {
|
||||
if (Date.now() > until) throw new Error(`Timed out waiting for ${names.join(' or ')}`);
|
||||
await new Promise(resolve => setTimeout(resolve, 10));
|
||||
}
|
||||
}
|
||||
function start(root, role, children) {
|
||||
const child = spawn(process.execPath, [worker, root, role], { stdio: ['ignore', 'ignore', 'pipe'] });
|
||||
let stderr = '';
|
||||
child.stderr.on('data', bytes => { stderr += bytes; });
|
||||
child.done = new Promise((resolve, reject) => {
|
||||
child.once('error', reject);
|
||||
child.once('close', (code, stop) => resolve({ code, stop, stderr }));
|
||||
});
|
||||
child.done.catch(() => {});
|
||||
children.push(child);
|
||||
return child;
|
||||
}
|
||||
async function finished(child) {
|
||||
const result = await child.done;
|
||||
assert.equal(result.code, 0, result.stderr);
|
||||
}
|
||||
async function fixture(run) {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-log-writers-'));
|
||||
const children = [];
|
||||
const file = path.join(root, '.claude', 'bash-commands.log');
|
||||
fs.mkdirSync(path.dirname(file));
|
||||
fs.writeFileSync(file, 'old-history\n', { mode: 0o600 });
|
||||
fs.truncateSync(file, LOG_MAX_BYTES);
|
||||
try { await run(root, file, children); }
|
||||
finally {
|
||||
for (const child of children) {
|
||||
if (child.exitCode === null && child.signalCode === null) child.kill('SIGKILL');
|
||||
await child.done;
|
||||
}
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
function archivePrefix(file) {
|
||||
const descriptor = fs.openSync(`${file}.1`, 'r');
|
||||
try {
|
||||
const bytes = Buffer.alloc(12);
|
||||
fs.readSync(descriptor, bytes, 0, bytes.length, 0);
|
||||
return bytes.toString('utf8');
|
||||
} finally { fs.closeSync(descriptor); }
|
||||
}
|
||||
|
||||
test('two writers cannot rotate a fresh log over the history another writer just archived', () => fixture(async (root, file, children) => {
|
||||
const owner = start(root, 'owner', children);
|
||||
await waitFor(root, ['owner-rotate-ready']);
|
||||
const contender = start(root, 'contender', children);
|
||||
await waitFor(root, ['contender-rotate-ready', 'contender-contended', 'contender-finished']);
|
||||
signal(root, 'owner-release');
|
||||
await finished(owner);
|
||||
signal(root, 'contender-release');
|
||||
await finished(contender);
|
||||
assert.equal(archivePrefix(file), 'old-history\n');
|
||||
const current = fs.readFileSync(file, 'utf8');
|
||||
const retained = current + fs.readFileSync(`${file}.1`, 'utf8');
|
||||
assert.match(retained, /echo owner/);
|
||||
assert.match(retained, /echo contender/);
|
||||
assert.equal(fs.existsSync(`${file}.lock`), false);
|
||||
}));
|
||||
|
||||
test('a terminated rotating writer does not strand subsequent logging', () => fixture(async (root, file, children) => {
|
||||
const owner = start(root, 'owner', children);
|
||||
await waitFor(root, ['owner-rotate-ready']);
|
||||
owner.kill('SIGKILL');
|
||||
await owner.done;
|
||||
await finished(start(root, 'recovered', children));
|
||||
assert.equal(archivePrefix(file), 'old-history\n');
|
||||
assert.match(fs.readFileSync(file, 'utf8'), /echo recovered/);
|
||||
assert.equal(fs.existsSync(`${file}.lock`), false);
|
||||
}));
|
||||
|
||||
test('contention stays bounded and records the command without racing a rotation', () => fixture(async (root, file, children) => {
|
||||
const owner = start(root, 'owner', children);
|
||||
await waitFor(root, ['owner-rotate-ready']);
|
||||
if (fs.existsSync(`${file}.lock`)) fs.utimesSync(`${file}.lock`, new Date(0), new Date(0));
|
||||
await finished(start(root, 'busy', children));
|
||||
assert.equal(fs.existsSync(`${file}.1`), false, 'the waiting writer must not rotate outside the lock');
|
||||
signal(root, 'owner-release');
|
||||
await finished(owner);
|
||||
assert.equal(archivePrefix(file), 'old-history\n');
|
||||
assert.match(fs.readFileSync(`${file}.1`, 'utf8'), /echo busy/);
|
||||
assert.match(fs.readFileSync(file, 'utf8'), /echo owner/);
|
||||
}));
|
||||
|
||||
test('release preserves a replacement owner lock instead of deleting it', () => fixture(async (root, file, children) => {
|
||||
await finished(start(root, 'replacement', children));
|
||||
assert.equal(fs.readFileSync(`${file}.lock`, 'utf8'), JSON.stringify({ pid: process.pid }));
|
||||
assert.match(fs.readFileSync(file, 'utf8'), /echo replacement/);
|
||||
assert.equal(archivePrefix(file), 'old-history\n');
|
||||
}));
|
||||
|
||||
test('an exclusive-create collision never removes another file', () => fixture(async (root, file, children) => {
|
||||
const child = start(root, 'collision', children);
|
||||
await finished(child);
|
||||
const temporary = `${file}.lock.create-${child.pid}-${'00'.repeat(8)}`;
|
||||
assert.equal(fs.readFileSync(temporary, 'utf8'), 'foreign-create');
|
||||
assert.match(fs.readFileSync(file, 'utf8'), /echo collision/);
|
||||
}));
|
||||
|
||||
test('an orphan recovery guard preserves its locks and records later commands without rotation', () => fixture(async (root, file, children) => {
|
||||
const owner = start(root, 'owner', children);
|
||||
await waitFor(root, ['owner-rotate-ready']);
|
||||
owner.kill('SIGKILL');
|
||||
await owner.done;
|
||||
const lockBytes = fs.readFileSync(`${file}.lock`, 'utf8');
|
||||
const guard = `${file}.lock.recover`;
|
||||
fs.writeFileSync(guard, JSON.stringify({ pid: owner.pid }), { flag: 'wx', mode: 0o600 });
|
||||
const guardBytes = fs.readFileSync(guard, 'utf8');
|
||||
await finished(start(root, 'orphan-guard', children));
|
||||
assert.equal(fs.existsSync(`${file}.1`), false);
|
||||
assert.equal(fs.readFileSync(`${file}.lock`, 'utf8'), lockBytes);
|
||||
assert.equal(fs.readFileSync(guard, 'utf8'), guardBytes);
|
||||
const retained = fs.readFileSync(file, 'utf8');
|
||||
assert.ok(retained.startsWith('old-history\n'));
|
||||
assert.match(retained, /echo orphan-guard/);
|
||||
}));
|
||||
|
||||
test('release quarantine collisions preserve foreign bytes and the owned lock', () => fixture(async (root, file, children) => {
|
||||
const child = start(root, 'release-collision', children);
|
||||
await finished(child);
|
||||
const quarantine = `${file}.lock.release-${child.pid}-${'00'.repeat(8)}`;
|
||||
assert.equal(fs.readFileSync(quarantine, 'utf8'), 'foreign-release');
|
||||
assert.equal(fs.readFileSync(`${file}.lock`, 'utf8'), JSON.stringify({ pid: child.pid }));
|
||||
assert.match(fs.readFileSync(file, 'utf8'), /echo release-collision/);
|
||||
}));
|
||||
|
||||
test('stale quarantine collisions preserve foreign bytes and defer recovery without losing the event', () => fixture(async (root, file, children) => {
|
||||
const owner = start(root, 'owner', children);
|
||||
await waitFor(root, ['owner-rotate-ready']);
|
||||
owner.kill('SIGKILL');
|
||||
await owner.done;
|
||||
const lockBytes = fs.readFileSync(`${file}.lock`, 'utf8');
|
||||
const child = start(root, 'stale-collision', children);
|
||||
await finished(child);
|
||||
const quarantine = `${file}.lock.stale-${child.pid}-${'00'.repeat(8)}`;
|
||||
assert.equal(fs.readFileSync(quarantine, 'utf8'), 'foreign-stale');
|
||||
assert.equal(fs.readFileSync(`${file}.lock`, 'utf8'), lockBytes);
|
||||
assert.equal(fs.existsSync(`${file}.1`), false);
|
||||
assert.match(fs.readFileSync(file, 'utf8'), /echo stale-collision/);
|
||||
}));
|
||||
Reference in new issue
Block a user