fix(node): mirror official Claude hooks

This commit is contained in:
ZacharyZhang-NY committed 2026-07-20 06:34:52 -04:00
1 parent 7fe99f7e5f
commit baaa71e32f
13 files changed
+1824 -149

No files matched your search

@@ -0,0 +1,44 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
createFixture,
runProcess,
} from '../test-support/claudecode-test-helpers.mjs';
const claudeBinary = process.env.ELYDORA_CLAUDE_BINARY;
test('official Claude Code accepts the installed user hook contract', {
skip: claudeBinary ? false : 'set ELYDORA_CLAUDE_BINARY to the official Claude Code executable',
}, async () => {
const fixture = await createFixture();
try {
assert.equal((await fixture.install()).code, 0);
const environment = {
HOME: fixture.homeDir,
USERPROFILE: fixture.homeDir,
CLAUDE_CONFIG_DIR: fixture.claudeConfigDir,
DISABLE_AUTOUPDATER: '1',
DISABLE_TELEMETRY: '1',
};
const version = await runProcess(
claudeBinary,
['--version'],
environment,
fixture.projectDir,
);
assert.equal(version.code, 0, version.stderr);
assert.match(version.stdout, /Claude Code/i);
const doctor = await runProcess(
claudeBinary,
['doctor'],
environment,
fixture.projectDir,
);
assert.equal(doctor.code, 0, doctor.stderr);
const output = `${doctor.stdout}\n${doctor.stderr}`;
assert.doesNotMatch(output, /invalid settings|settings validation|failed to parse/i);
} finally {
await fixture.close();
}
});
+368
View File
@@ -0,0 +1,368 @@
import assert from 'node:assert/strict';
import { lstat, mkdir, readFile, writeFile } from 'node:fs/promises';
import path from 'node:path';
import test from 'node:test';
import {
assertManagedHandler,
cliPath,
createFixture,
legacyHandler,
managedHandler,
readSettings,
registryModuleUrl,
runNode,
runPlugin,
VALID_PRIVATE_KEY,
writeJson,
} from '../test-support/claudecode-test-helpers.mjs';
const GUARD_STATUS = 'Checking Elydora agent state';
const AUDIT_STATUS = 'Recording Elydora tool use';
async function assertMissing(filePath) {
await assert.rejects(lstat(filePath), { code: 'ENOENT' });
}
function assertManagedTriple(settings, fixture) {
assertManagedHandler(
managedHandler(settings, 'PreToolUse'),
fixture.guardScriptPath,
GUARD_STATUS,
);
assertManagedHandler(
managedHandler(settings, 'PostToolUse'),
fixture.hookScriptPath,
AUDIT_STATUS,
);
assertManagedHandler(
managedHandler(settings, 'PostToolUseFailure'),
fixture.hookScriptPath,
AUDIT_STATUS,
);
}
test('Claude Code is registered in the SDK and CLI', async () => {
const { SUPPORTED_AGENTS } = await import(registryModuleUrl);
assert.deepEqual(SUPPORTED_AGENTS.get('claudecode'), {
name: 'Claude Code',
configDir: '~/.claude',
configFile: 'settings.json',
});
const fixture = await createFixture();
try {
const result = await runNode(['--no-warnings', cliPath, 'status'], {
HOME: fixture.homeDir,
USERPROFILE: fixture.homeDir,
CLAUDE_CONFIG_DIR: fixture.claudeConfigDir,
}, fixture.projectDir);
assert.equal(result.code, 0, result.stderr);
assert.match(result.stdout, /Claude Code \(claudecode\)/);
} finally {
await fixture.close();
}
});
test('Claude installs one exact managed triple and preserves user settings', async () => {
const existing = {
$schema: 'https://json.schemastore.org/claude-code-settings.json',
model: 'sonnet',
disableAllHooks: false,
hooks: {
Notification: [{
matcher: 'permission_prompt',
hooks: [{ type: 'http', url: 'https://example.test/hook', timeout: 1 }],
}],
PreToolUse: [{
matcher: 'Bash',
hooks: [{ type: 'command', command: 'existing-command', timeout: 5 }],
}],
},
};
const fixture = await createFixture({ settings: existing });
try {
const first = await fixture.install();
assert.equal(first.code, 0, first.stderr);
assert.match(first.stdout, /run \/hooks and claude doctor/i);
const installed = await readSettings(fixture.settingsPath);
assert.equal(installed.settings.model, 'sonnet');
assert.deepEqual(installed.settings.hooks.Notification, existing.hooks.Notification);
assert.deepEqual(installed.settings.hooks.PreToolUse[0], existing.hooks.PreToolUse[0]);
assertManagedTriple(installed.settings, fixture);
const second = await fixture.install();
assert.equal(second.code, 0, second.stderr);
assert.equal(await readFile(fixture.settingsPath, 'utf-8'), installed.raw);
} finally {
await fixture.close();
}
});
test('Claude resolves absolute, relative, empty, and absent CLAUDE_CONFIG_DIR values', async () => {
const custom = await createFixture();
try {
assert.equal((await custom.install()).code, 0);
assert.equal((await readSettings(custom.settingsPath)).settings.hooks !== undefined, true);
await assertMissing(path.join(custom.homeDir, '.claude', 'settings.json'));
} finally {
await custom.close();
}
const fallback = await createFixture({ explicitClaudeConfig: false });
try {
assert.equal((await fallback.install()).code, 0);
assert.equal((await readSettings(fallback.settingsPath)).settings.hooks !== undefined, true);
} finally {
await fallback.close();
}
const relative = await createFixture();
try {
relative.claudeConfigOverride = 'relative claude';
assert.equal((await relative.install()).code, 0);
const relativePath = path.join(relative.projectDir, 'relative claude', 'settings.json');
assert.equal((await readSettings(relativePath)).settings.hooks !== undefined, true);
} finally {
await relative.close();
}
const empty = await createFixture();
try {
empty.claudeConfigOverride = '';
assert.equal((await empty.install()).code, 0);
const currentDirectoryPath = path.join(empty.projectDir, 'settings.json');
assert.equal((await readSettings(currentDirectoryPath)).settings.hooks !== undefined, true);
} finally {
await empty.close();
}
});
test('Claude parses settings before creating runtime files', async () => {
const fixture = await createFixture({ settings: '{ malformed' });
try {
const result = await fixture.install();
assert.equal(result.code, 1);
assert.match(result.stderr, /parse Claude Code user settings/i);
assert.equal(await readFile(fixture.settingsPath, 'utf-8'), '{ malformed');
await assertMissing(fixture.agentDir);
} finally {
await fixture.close();
}
});
test('Claude rejects invalid official hook shapes before writes', async (t) => {
const cases = [
['duplicate', '{"hooks":{},"hooks":{}}', /duplicate field "hooks"/i],
['disabled type', JSON.stringify({ disableAllHooks: 'yes' }), /must be a boolean/i],
['hooks shape', JSON.stringify({ hooks: null }), /field "hooks" must be an object/i],
['unknown event', JSON.stringify({ hooks: { MadeUp: [] } }), /unsupported hook event/i],
['event shape', JSON.stringify({ hooks: { PreToolUse: null } }), /must be an array/i],
['group shape', JSON.stringify({ hooks: { PreToolUse: [null] } }), /group.*must be an object/i],
['group field', JSON.stringify({ hooks: { PreToolUse: [{ hooks: [], label: 'x' }] } }), /unsupported field "label"/i],
['matcher shape', JSON.stringify({ hooks: { PreToolUse: [{ matcher: 1, hooks: [] }] } }), /matcher must be a string/i],
['hooks missing', JSON.stringify({ hooks: { PreToolUse: [{}] } }), /must contain a hooks array/i],
['handler shape', JSON.stringify({ hooks: { PreToolUse: [{ hooks: [null] }] } }), /handler.*must be an object/i],
['handler type', JSON.stringify({ hooks: { PreToolUse: [{ hooks: [{ type: 'file' }] }] } }), /unsupported type/i],
['handler field', JSON.stringify({ hooks: { PreToolUse: [{ hooks: [{ type: 'command', command: 'x', invented: true }] }] } }), /unsupported field "invented"/i],
['command value', JSON.stringify({ hooks: { PreToolUse: [{ hooks: [{ type: 'command', command: '' }] }] } }), /non-empty string/i],
['argument type', JSON.stringify({ hooks: { PreToolUse: [{ hooks: [{ type: 'command', command: 'x', args: [1] }] }] } }), /array of strings/i],
['timeout zero', JSON.stringify({ hooks: { PreToolUse: [{ hooks: [{ type: 'command', command: 'x', timeout: 0 }] }] } }), /positive finite number/i],
['headers type', JSON.stringify({ hooks: { PreToolUse: [{ hooks: [{ type: 'http', url: 'https://example.test', headers: { A: 1 } }] }] } }), /map names to strings/i],
['input type', JSON.stringify({ hooks: { PreToolUse: [{ hooks: [{ type: 'mcp_tool', server: 's', tool: 't', input: [] }] }] } }), /input.*must be an object/i],
];
for (const [name, settings, pattern] of cases) {
await t.test(name, async () => {
const fixture = await createFixture({ settings });
try {
const result = await fixture.install();
assert.equal(result.code, 1);
assert.match(result.stderr, pattern);
assert.equal(await readFile(fixture.settingsPath, 'utf-8'), settings);
await assertMissing(fixture.agentDir);
} finally {
await fixture.close();
}
});
}
});
test('Claude refuses installation while user hooks are disabled', async () => {
const fixture = await createFixture({ settings: { disableAllHooks: true } });
try {
const result = await fixture.install();
assert.equal(result.code, 1);
assert.match(result.stderr, /disabled by disableAllHooks/i);
await assertMissing(fixture.agentDir);
assert.deepEqual((await readSettings(fixture.settingsPath)).settings, {
disableAllHooks: true,
});
} finally {
await fixture.close();
}
});
test('Claude migrates exact legacy hooks and preserves ownership lookalikes', async () => {
const fixture = await createFixture();
const lookalike = { ...legacyHandler(fixture.guardScriptPath) };
lookalike.command += ' --inspect';
const legacy = {
hooks: {
PreToolUse: [{ hooks: [legacyHandler(fixture.guardScriptPath)] }, { hooks: [lookalike] }],
PostToolUse: [{ hooks: [legacyHandler(fixture.hookScriptPath)] }],
},
};
try {
await writeJson(fixture.settingsPath, legacy);
const install = await fixture.install();
assert.equal(install.code, 0, install.stderr);
let { settings } = await readSettings(fixture.settingsPath);
assertManagedTriple(settings, fixture);
assert(settings.hooks.PreToolUse.some((group) => group.hooks[0].command === lookalike.command));
const managed = settings.hooks.PreToolUse.at(-1);
managed.hooks.push({ type: 'command', command: 'user-command', timeout: 5 });
await writeJson(fixture.settingsPath, settings);
const uninstall = await runPlugin(fixture, 'uninstall', 'agent-1');
assert.equal(uninstall.code, 0, uninstall.stderr);
settings = (await readSettings(fixture.settingsPath)).settings;
assert.deepEqual(settings.hooks.PreToolUse.flatMap((group) => group.hooks), [
lookalike,
{ type: 'command', command: 'user-command', timeout: 5 },
]);
assert.equal(settings.hooks.PostToolUse, undefined);
assert.equal(settings.hooks.PostToolUseFailure, undefined);
} finally {
await fixture.close();
}
});
test('Claude uninstall preserves user sources and removes a fully managed file', async () => {
const user = await createFixture({ settings: { model: 'sonnet', hooks: { Notification: [] } } });
try {
assert.equal((await user.install()).code, 0);
const result = await runPlugin(user, 'uninstall', 'agent-1');
assert.equal(result.code, 0, result.stderr);
assert.deepEqual((await readSettings(user.settingsPath)).settings, {
model: 'sonnet',
hooks: { Notification: [] },
});
} finally {
await user.close();
}
const managed = await createFixture();
try {
assert.equal((await managed.install()).code, 0);
assert.equal((await runPlugin(managed, 'uninstall', 'agent-1')).code, 0);
await assertMissing(managed.settingsPath);
} finally {
await managed.close();
}
});
test('Claude status requires one enabled complete triple and strict runtime identity', async () => {
const fixture = await createFixture();
try {
assert.equal((await fixture.install()).code, 0);
let status = await runPlugin(fixture, 'status', null);
assert.equal(JSON.parse(status.stdout).installed, true);
let { settings } = await readSettings(fixture.settingsPath);
delete settings.hooks.PostToolUseFailure;
await writeJson(fixture.settingsPath, settings);
status = await runPlugin(fixture, 'status', null);
assert.equal(JSON.parse(status.stdout).installed, false);
assert.equal((await fixture.install()).code, 0);
settings = (await readSettings(fixture.settingsPath)).settings;
settings.hooks.PostToolUseFailure.push(settings.hooks.PostToolUseFailure.at(-1));
await writeJson(fixture.settingsPath, settings);
status = await runPlugin(fixture, 'status', null);
assert.equal(JSON.parse(status.stdout).installed, false);
assert.equal((await fixture.install()).code, 0);
settings = (await readSettings(fixture.settingsPath)).settings;
settings.disableAllHooks = true;
await writeJson(fixture.settingsPath, settings);
status = await runPlugin(fixture, 'status', null);
assert.equal(JSON.parse(status.stdout).installed, false);
settings.disableAllHooks = false;
await writeJson(fixture.settingsPath, settings);
await writeFile(path.join(fixture.agentDir, 'private.key'), 'invalid');
status = await runPlugin(fixture, 'status', null);
assert.equal(status.code, 1);
assert.match(status.stderr, /private key is invalid/i);
} finally {
await fixture.close();
}
});
test('Claude leaves project and local settings unchanged', async () => {
const fixture = await createFixture();
const projectSettings = path.join(fixture.projectDir, '.claude', 'settings.json');
const localSettings = path.join(fixture.projectDir, '.claude', 'settings.local.json');
const projectSource = '{"hooks":{"PreToolUse":[]}}\n';
const localSource = '{"model":"haiku"}\n';
try {
await mkdir(path.dirname(projectSettings), { recursive: true });
await writeFile(projectSettings, projectSource);
await writeFile(localSettings, localSource);
assert.equal((await fixture.install()).code, 0);
assert.equal(await readFile(projectSettings, 'utf-8'), projectSource);
assert.equal(await readFile(localSettings, 'utf-8'), localSource);
} finally {
await fixture.close();
}
});
test('Claude CLI completes install, status, and uninstall end to end', async () => {
const fixture = await createFixture();
const privateKeyFile = path.join(fixture.rootDir, 'install-private.key');
const tokenFile = path.join(fixture.rootDir, 'install-token.txt');
const environment = {
HOME: fixture.homeDir,
USERPROFILE: fixture.homeDir,
CLAUDE_CONFIG_DIR: fixture.claudeConfigDir,
};
try {
await writeFile(privateKeyFile, `${VALID_PRIVATE_KEY}\n`, { mode: 0o600 });
await writeFile(tokenFile, 'token-1\n', { mode: 0o600 });
const install = await runNode([
'--no-warnings',
cliPath,
'install',
'--agent', 'claudecode',
'--org_id', 'org-1',
'--agent_id', 'agent-1',
'--kid', 'kid-1',
'--private_key_file', privateKeyFile,
'--token_file', tokenFile,
'--base_url', fixture.baseUrl,
], environment, fixture.projectDir);
assert.equal(install.code, 0, install.stderr);
assert.match(install.stdout, /installed for Claude Code/i);
assertManagedTriple((await readSettings(fixture.settingsPath)).settings, fixture);
const status = await runNode(
['--no-warnings', cliPath, 'status'],
environment,
fixture.projectDir,
);
assert.equal(status.code, 0, status.stderr);
assert.match(status.stdout, /Claude Code \(claudecode\) \[installed\]/);
const uninstall = await runNode([
'--no-warnings',
cliPath,
'uninstall',
'--agent', 'claudecode',
'--agent_id', 'agent-1',
], environment, fixture.projectDir);
assert.equal(uninstall.code, 0, uninstall.stderr);
assert.match(uninstall.stdout, /uninstalled for Claude Code/i);
await assertMissing(fixture.settingsPath);
await assertMissing(fixture.agentDir);
} finally {
await fixture.close();
}
});
+145
View File
@@ -0,0 +1,145 @@
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import path from 'node:path';
import test from 'node:test';
import {
createFixture,
managedHandler,
readSettings,
runClaudeHook,
startApiServer,
} from '../test-support/claudecode-test-helpers.mjs';
function officialPayload(event, overrides = {}) {
return {
session_id: 'session-1',
prompt_id: '302d811d-0d17-41ad-a359-d2cb618fd42b',
transcript_path: '/tmp/session-1.jsonl',
cwd: '/tmp/project',
permission_mode: 'default',
effort: { level: 'high' },
hook_event_name: event,
tool_name: 'Bash',
tool_input: { command: 'npm test', description: 'Run tests' },
tool_use_id: 'toolu_01ABC123',
...overrides,
};
}
test('Claude runtimes enforce active state and preserve official event payloads', async () => {
const api = await startApiServer();
const fixture = await createFixture({ baseUrl: api.baseUrl });
try {
assert.equal((await fixture.install()).code, 0);
const { settings } = await readSettings(fixture.settingsPath);
const guard = managedHandler(settings, 'PreToolUse');
const successAudit = managedHandler(settings, 'PostToolUse');
const failureAudit = managedHandler(settings, 'PostToolUseFailure');
const pre = officialPayload('PreToolUse');
const guardResult = await runClaudeHook(guard, JSON.stringify(pre), fixture);
assert.equal(guardResult.code, 0, guardResult.stderr);
assert.equal(guardResult.stdout, '');
const success = officialPayload('PostToolUse', {
tool_response: {
stdout: 'tests passed',
stderr: '',
interrupted: false,
isImage: false,
},
});
const successResult = await runClaudeHook(successAudit, JSON.stringify(success), fixture);
assert.equal(successResult.code, 0, successResult.stderr);
const failure = officialPayload('PostToolUseFailure', {
error: 'Command exited with non-zero status code 1',
is_interrupt: false,
duration_ms: 4187,
});
const failureResult = await runClaudeHook(failureAudit, JSON.stringify(failure), fixture);
assert.equal(failureResult.code, 0, failureResult.stderr);
assert.equal(api.requests.length, 3);
assert.deepEqual(
api.requests.map((request) => [request.method, request.url]),
[
['GET', '/v1/agents/agent-1'],
['POST', '/v1/operations'],
['POST', '/v1/operations'],
],
);
const successOperation = JSON.parse(api.requests[1].raw);
const failureOperation = JSON.parse(api.requests[2].raw);
assert.deepEqual(successOperation.payload, success);
assert.deepEqual(failureOperation.payload, failure);
assert.deepEqual(successOperation.subject, { session_id: 'session-1' });
assert.deepEqual(successOperation.action, { tool: 'Bash' });
assert.equal(api.requests[1].headers.authorization, 'Bearer token-1');
assert.equal(failureOperation.prev_chain_hash, successOperation.chain_hash);
} finally {
await fixture.close();
await api.close();
}
});
test('Claude guard returns official blocking exit code 2 for frozen and revoked agents', async (t) => {
for (const status of ['frozen', 'revoked']) {
await t.test(status, async () => {
const api = await startApiServer({ status });
const fixture = await createFixture({ baseUrl: api.baseUrl });
try {
assert.equal((await fixture.install()).code, 0);
const { settings } = await readSettings(fixture.settingsPath);
const guard = managedHandler(settings, 'PreToolUse');
const result = await runClaudeHook(
guard,
JSON.stringify(officialPayload('PreToolUse')),
fixture,
);
assert.equal(result.code, 2);
assert.equal(result.stdout, '');
assert.match(result.stderr, new RegExp(`Agent "claudecode" is ${status}`, 'i'));
assert.match(result.stderr, /Tool execution blocked/i);
} finally {
await fixture.close();
await api.close();
}
});
}
});
test('Claude runtime failures stay observable while guard and audit delivery remain fail-open', async () => {
const fixture = await createFixture();
try {
assert.equal((await fixture.install()).code, 0);
const { settings } = await readSettings(fixture.settingsPath);
const guard = managedHandler(settings, 'PreToolUse');
const audit = managedHandler(settings, 'PostToolUse');
const guardResult = await runClaudeHook(
guard,
JSON.stringify(officialPayload('PreToolUse')),
fixture,
);
assert.equal(guardResult.code, 0);
assert.match(guardResult.stderr, /Failed to resolve agent status/i);
const auditResult = await runClaudeHook(
audit,
JSON.stringify(officialPayload('PostToolUse', { tool_response: { stdout: '' } })),
fixture,
);
assert.equal(auditResult.code, 0);
const errorLog = await readFile(path.join(fixture.agentDir, 'error.log'), 'utf-8');
assert.match(errorLog, /\[claudecode\]/i);
assert.match(errorLog, /fetch failed|ECONNREFUSED/i);
const malformed = await runClaudeHook(audit, '{ malformed', fixture);
assert.equal(malformed.code, 0);
const updatedLog = await readFile(path.join(fixture.agentDir, 'error.log'), 'utf-8');
assert.match(updatedLog, /Hook input is invalid JSON/i);
} finally {
await fixture.close();
}
});
@@ -0,0 +1,323 @@
import assert from 'node:assert/strict';
import {
lstat,
mkdir,
readFile,
readdir,
symlink,
writeFile,
} from 'node:fs/promises';
import path from 'node:path';
import test from 'node:test';
import {
createFixture,
installationModuleUrl,
installConfig,
ioModuleUrl,
runNode,
writeJson,
} from '../test-support/claudecode-test-helpers.mjs';
const managedFileNames = ['guard.js', 'config.json', 'private.key', 'hook.js'];
async function snapshotInstallation(fixture) {
const entries = await Promise.all(managedFileNames.map(async (name) => [
path.join(fixture.agentDir, name),
await readFile(path.join(fixture.agentDir, name), 'utf-8'),
]));
entries.push([fixture.settingsPath, await readFile(fixture.settingsPath, 'utf-8')]);
return new Map(entries);
}
async function assertSnapshot(snapshot) {
for (const [filePath, expected] of snapshot) {
assert.equal(await readFile(filePath, 'utf-8'), expected, filePath);
}
}
async function assertNoTransactionFiles(fixture) {
const names = [
...await readdir(fixture.agentDir),
...await readdir(path.dirname(fixture.settingsPath)),
];
assert.equal(names.some((name) => /\.(tmp|rollback)$/.test(name)), false, names.join(', '));
}
async function preservedRollback(fixture, basename) {
const entries = await readdir(fixture.agentDir);
const matches = entries.filter(
(name) => name.startsWith(`.${basename}.`) && name.endsWith('.rollback'),
);
assert.equal(matches.length, 1, entries.join(', '));
return path.join(fixture.agentDir, matches[0]);
}
function testEnvironment(fixture, overrides = {}) {
return {
HOME: fixture.homeDir,
USERPROFILE: fixture.homeDir,
CLAUDE_CONFIG_DIR: fixture.claudeConfigDir,
ELYDORA_INSTALL_CONFIG: JSON.stringify(installConfig(fixture, overrides)),
};
}
test('Claude rolls back all five files when a transaction commit fails', async () => {
const fixture = await createFixture();
try {
assert.equal((await fixture.install()).code, 0);
const before = await snapshotInstallation(fixture);
const source = `
import { rename } from 'node:fs/promises';
import { readClaudeDocument } from ${JSON.stringify(ioModuleUrl)};
import {
commitClaudeInstallation,
prepareClaudeInstallation,
} from ${JSON.stringify(installationModuleUrl)};
const config = JSON.parse(process.env.ELYDORA_INSTALL_CONFIG);
const document = await readClaudeDocument();
const prepared = await prepareClaudeInstallation(config, { document, changed: false });
let calls = 0;
await commitClaudeInstallation(prepared, async (from, to) => {
calls += 1;
if (calls === 3) throw new Error('injected rename failure');
await rename(from, to);
});
`;
const result = await runNode(
['--input-type=module', '--eval', source],
testEnvironment(fixture, { orgId: 'org-updated', token: 'token-updated' }),
fixture.projectDir,
);
assert.equal(result.code, 1);
assert.match(result.stderr, /injected rename failure/i);
await assertSnapshot(before);
await assertNoTransactionFiles(fixture);
} finally {
await fixture.close();
}
});
test('Claude detects concurrent settings changes before committing runtime updates', async () => {
const fixture = await createFixture({ settings: { model: 'sonnet' } });
try {
assert.equal((await fixture.install()).code, 0);
const before = await snapshotInstallation(fixture);
const concurrent = '{"model":"opus","hooks":{"Notification":[]}}\n';
const source = `
import { writeFile } from 'node:fs/promises';
import { readClaudeDocument } from ${JSON.stringify(ioModuleUrl)};
import {
commitClaudeInstallation,
prepareClaudeInstallation,
} from ${JSON.stringify(installationModuleUrl)};
const document = await readClaudeDocument();
const prepared = await prepareClaudeInstallation(
JSON.parse(process.env.ELYDORA_INSTALL_CONFIG),
{ document, changed: false },
);
await writeFile(document.filePath, process.env.ELYDORA_CONCURRENT, 'utf-8');
await commitClaudeInstallation(prepared);
`;
const result = await runNode(
['--input-type=module', '--eval', source],
{
...testEnvironment(fixture, { orgId: 'updated' }),
ELYDORA_CONCURRENT: concurrent,
},
fixture.projectDir,
);
assert.equal(result.code, 1);
assert.match(result.stderr, /changed during Claude Code installation/i);
for (const [filePath, expected] of before) {
if (filePath !== fixture.settingsPath) {
assert.equal(await readFile(filePath, 'utf-8'), expected);
}
}
assert.equal(await readFile(fixture.settingsPath, 'utf-8'), concurrent);
await assertNoTransactionFiles(fixture);
} finally {
await fixture.close();
}
});
test('Claude rejects a stale settings document before staging files', async () => {
const fixture = await createFixture();
try {
assert.equal((await fixture.install()).code, 0);
const before = await snapshotInstallation(fixture);
const concurrent = '{"hooks":{"Notification":[]}}\n';
const source = `
import { writeFile } from 'node:fs/promises';
import { readClaudeDocument } from ${JSON.stringify(ioModuleUrl)};
import { prepareClaudeInstallation } from ${JSON.stringify(installationModuleUrl)};
const document = await readClaudeDocument();
await writeFile(document.filePath, process.env.ELYDORA_CONCURRENT, 'utf-8');
await prepareClaudeInstallation(
JSON.parse(process.env.ELYDORA_INSTALL_CONFIG),
{ document, changed: false },
);
`;
const result = await runNode(
['--input-type=module', '--eval', source],
{
...testEnvironment(fixture),
ELYDORA_CONCURRENT: concurrent,
},
fixture.projectDir,
);
assert.equal(result.code, 1);
assert.match(result.stderr, /changed before installation/i);
for (const [filePath, expected] of before) {
if (filePath !== fixture.settingsPath) {
assert.equal(await readFile(filePath, 'utf-8'), expected);
}
}
assert.equal(await readFile(fixture.settingsPath, 'utf-8'), concurrent);
await assertNoTransactionFiles(fixture);
} finally {
await fixture.close();
}
});
test('Claude preserves rollback data after a committed runtime changes', async () => {
const fixture = await createFixture();
try {
assert.equal((await fixture.install()).code, 0);
const original = await readFile(fixture.guardScriptPath, 'utf-8');
const source = `
import { rename, rm, writeFile } from 'node:fs/promises';
import { readClaudeDocument } from ${JSON.stringify(ioModuleUrl)};
import {
commitClaudeInstallation,
prepareClaudeInstallation,
} from ${JSON.stringify(installationModuleUrl)};
const document = await readClaudeDocument();
const prepared = await prepareClaudeInstallation(
JSON.parse(process.env.ELYDORA_INSTALL_CONFIG),
{ document, changed: false },
);
let calls = 0;
await commitClaudeInstallation(prepared, async (from, to) => {
calls += 1;
if (calls === 1) {
await rename(from, to);
await rm(to);
await writeFile(to, 'external change\\n');
return;
}
if (calls === 2) throw new Error('injected later commit failure');
await rename(from, to);
});
`;
const result = await runNode(
['--input-type=module', '--eval', source],
testEnvironment(fixture, { orgId: 'updated' }),
fixture.projectDir,
);
assert.equal(result.code, 1);
assert.match(result.stderr, /original content preserved at/i);
assert.equal(await readFile(fixture.guardScriptPath, 'utf-8'), 'external change\n');
assert.equal(await readFile(await preservedRollback(fixture, 'guard.js'), 'utf-8'), original);
} finally {
await fixture.close();
}
});
test('Claude rejects orphaned and mismatched runtime identities before writes', async (t) => {
await t.test('orphaned runtime', async () => {
const fixture = await createFixture();
try {
await mkdir(fixture.agentDir, { recursive: true });
await writeFile(fixture.guardScriptPath, 'orphaned guard\n');
const result = await fixture.install();
assert.equal(result.code, 1);
assert.match(result.stderr, /identity cannot be verified/i);
assert.equal(await readFile(fixture.guardScriptPath, 'utf-8'), 'orphaned guard\n');
await assertMissing(fixture.settingsPath);
} finally {
await fixture.close();
}
});
await t.test('mismatched identity', async () => {
const fixture = await createFixture();
try {
await writeJson(path.join(fixture.agentDir, 'config.json'), {
agent_name: 'claudecode',
agent_id: 'another-agent',
});
const configPath = path.join(fixture.agentDir, 'config.json');
const before = await readFile(configPath, 'utf-8');
const result = await fixture.install();
assert.equal(result.code, 1);
assert.match(result.stderr, /identity does not match/i);
assert.equal(await readFile(configPath, 'utf-8'), before);
await assertMissing(fixture.settingsPath);
} finally {
await fixture.close();
}
});
});
async function assertMissing(filePath) {
await assert.rejects(lstat(filePath), { code: 'ENOENT' });
}
test('Claude rejects linked configuration, settings, and runtime paths', async (t) => {
for (const kind of ['configuration', 'settings', 'runtime']) {
await t.test(kind, async () => {
const fixture = await createFixture();
try {
const target = path.join(fixture.rootDir, `${kind}-target`);
await mkdir(target, { recursive: true });
await mkdir(fixture.homeDir, { recursive: true });
let link;
let linkType = 'junction';
if (kind === 'configuration') {
link = fixture.claudeConfigDir;
} else if (kind === 'runtime') {
link = path.join(fixture.homeDir, '.elydora');
} else {
await mkdir(fixture.claudeConfigDir, { recursive: true });
const targetFile = path.join(target, 'settings.json');
await writeFile(targetFile, '{}\n');
link = fixture.settingsPath;
linkType = 'file';
await symlink(targetFile, link, linkType).catch((error) => { throw error; });
}
if (kind !== 'settings') {
try {
await symlink(target, link, linkType);
} catch (error) {
if (error?.code === 'EPERM') {
t.skip(`symbolic links unavailable: ${error.message}`);
return;
}
throw error;
}
}
const result = await fixture.install();
assert.equal(result.code, 1);
assert.match(result.stderr, /physical (directory|file)/i);
} catch (error) {
if (error?.code === 'EPERM') {
t.skip(`symbolic links unavailable: ${error.message}`);
return;
}
throw error;
} finally {
await fixture.close();
}
});
}
});
test('Claude installation leaves no transaction artifacts', async () => {
const fixture = await createFixture();
try {
assert.equal((await fixture.install()).code, 0);
await assertNoTransactionFiles(fixture);
} finally {
await fixture.close();
}
});