fix(gemini): implement official hook contract
This commit is contained in:
1 parent
e011003680
commit
586ffa0278
13 files changed
+1950
-142
No files matched your search
@@ -0,0 +1,48 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
createFixture,
|
||||
runProcess,
|
||||
} from '../test-support/gemini-test-helpers.mjs';
|
||||
|
||||
const geminiEntry = process.env.ELYDORA_GEMINI_ENTRY;
|
||||
|
||||
test('official Gemini CLI accepts the installed user hook contract', {
|
||||
skip: geminiEntry ? false : 'set ELYDORA_GEMINI_ENTRY to the official Gemini CLI entry file',
|
||||
}, async () => {
|
||||
const fixture = await createFixture();
|
||||
try {
|
||||
const install = await fixture.install();
|
||||
assert.equal(install.code, 0, install.stderr);
|
||||
const environment = {
|
||||
HOME: fixture.homeDir,
|
||||
USERPROFILE: fixture.homeDir,
|
||||
GEMINI_CLI_HOME: fixture.geminiCliHome,
|
||||
GEMINI_API_KEY: 'official-loader-test-key',
|
||||
GEMINI_TELEMETRY_ENABLED: 'false',
|
||||
OTEL_SDK_DISABLED: 'true',
|
||||
};
|
||||
const version = await runProcess(
|
||||
process.execPath,
|
||||
[geminiEntry, '--version'],
|
||||
environment,
|
||||
fixture.projectDir,
|
||||
);
|
||||
assert.equal(version.code, 0, version.stderr);
|
||||
assert.match(version.stdout, /0\.51\.0/);
|
||||
|
||||
const load = await runProcess(
|
||||
process.execPath,
|
||||
[geminiEntry, '--skip-trust', '--list-extensions'],
|
||||
environment,
|
||||
fixture.projectDir,
|
||||
);
|
||||
assert.equal(load.code, 0, load.stderr);
|
||||
assert.doesNotMatch(
|
||||
`${load.stdout}\n${load.stderr}`,
|
||||
/invalid settings|settings validation|failed to parse|hook configuration error/i,
|
||||
);
|
||||
} finally {
|
||||
await fixture.close();
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,338 @@
|
||||
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,
|
||||
parseSettings,
|
||||
readSettings,
|
||||
registryModuleUrl,
|
||||
runNode,
|
||||
runPlugin,
|
||||
VALID_PRIVATE_KEY,
|
||||
writeSettings,
|
||||
} from '../test-support/gemini-test-helpers.mjs';
|
||||
|
||||
const GUARD_NAME = 'elydora-guard';
|
||||
const AUDIT_NAME = 'elydora-audit';
|
||||
|
||||
async function assertMissing(filePath) {
|
||||
await assert.rejects(lstat(filePath), { code: 'ENOENT' });
|
||||
}
|
||||
|
||||
function assertManagedPair(settings) {
|
||||
const guard = managedHandler(settings, 'BeforeTool', GUARD_NAME);
|
||||
const audit = managedHandler(settings, 'AfterTool', AUDIT_NAME);
|
||||
assertManagedHandler(guard, GUARD_NAME);
|
||||
assertManagedHandler(audit, AUDIT_NAME);
|
||||
return { guard, audit };
|
||||
}
|
||||
|
||||
test('Gemini CLI is registered in the SDK and CLI', async () => {
|
||||
const { SUPPORTED_AGENTS } = await import(registryModuleUrl);
|
||||
assert.deepEqual(SUPPORTED_AGENTS.get('gemini'), {
|
||||
name: 'Gemini CLI',
|
||||
configDir: '~/.gemini',
|
||||
configFile: 'settings.json',
|
||||
});
|
||||
const fixture = await createFixture();
|
||||
try {
|
||||
const result = await runNode(['--no-warnings', cliPath, 'status'], {
|
||||
HOME: fixture.homeDir,
|
||||
USERPROFILE: fixture.homeDir,
|
||||
GEMINI_CLI_HOME: fixture.geminiCliHome,
|
||||
}, fixture.projectDir);
|
||||
assert.equal(result.code, 0, result.stderr);
|
||||
assert.match(result.stdout, /Gemini CLI \(gemini\)/);
|
||||
} finally {
|
||||
await fixture.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('Gemini installs an exact managed pair and preserves JSONC settings', async () => {
|
||||
const existing = [
|
||||
'{',
|
||||
' // Keep this user preference.',
|
||||
' "theme": "GitHub",',
|
||||
' "hooks": {',
|
||||
' "FutureEvent": [null],',
|
||||
' "BeforeTool": [{ "matcher": "read_file", "hooks": [{ "type": "command", "command": "user-hook" }] }]',
|
||||
' }',
|
||||
'}',
|
||||
'',
|
||||
].join('\r\n');
|
||||
const fixture = await createFixture({ settings: existing });
|
||||
const projectSettings = path.join(fixture.projectDir, '.gemini', 'settings.json');
|
||||
const systemSettings = path.join(fixture.rootDir, 'system-settings.json');
|
||||
await writeSettings(projectSettings, '{ "owner": "project" }\n');
|
||||
await writeSettings(systemSettings, '{ "owner": "system" }\n');
|
||||
try {
|
||||
const environment = { GEMINI_CLI_SYSTEM_SETTINGS_PATH: systemSettings };
|
||||
const first = await fixture.install({}, environment);
|
||||
assert.equal(first.code, 0, first.stderr);
|
||||
assert.match(first.stdout, /run \/hooks list/i);
|
||||
const installed = await readSettings(fixture.settingsPath);
|
||||
assert.match(installed.raw, /Keep this user preference/);
|
||||
assert.match(installed.raw, /\r\n/);
|
||||
assert.equal(installed.settings.theme, 'GitHub');
|
||||
assert.deepEqual(installed.settings.hooks.FutureEvent, [null]);
|
||||
assert.equal(installed.settings.hooks.BeforeTool[0].hooks[0].command, 'user-hook');
|
||||
assertManagedPair(installed.settings);
|
||||
|
||||
const second = await fixture.install({}, environment);
|
||||
assert.equal(second.code, 0, second.stderr);
|
||||
assert.equal(await readFile(fixture.settingsPath, 'utf-8'), installed.raw);
|
||||
assert.equal(await readFile(projectSettings, 'utf-8'), '{ "owner": "project" }\n');
|
||||
assert.equal(await readFile(systemSettings, 'utf-8'), '{ "owner": "system" }\n');
|
||||
} finally {
|
||||
await fixture.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('Gemini resolves official GEMINI_CLI_HOME path semantics', async () => {
|
||||
const fallback = await createFixture({ explicitGeminiHome: false });
|
||||
try {
|
||||
assert.equal((await fallback.install()).code, 0);
|
||||
assertManagedPair((await readSettings(fallback.settingsPath)).settings);
|
||||
} finally {
|
||||
await fallback.close();
|
||||
}
|
||||
|
||||
for (const [value, expected] of [
|
||||
['', (fixture) => fixture.settingsPath],
|
||||
['relative gemini', (fixture) => path.join(
|
||||
fixture.projectDir,
|
||||
'relative gemini',
|
||||
'.gemini',
|
||||
'settings.json',
|
||||
)],
|
||||
['~', (fixture) => path.join(fixture.projectDir, '~', '.gemini', 'settings.json')],
|
||||
]) {
|
||||
const fixture = await createFixture();
|
||||
fixture.geminiCliHomeOverride = value;
|
||||
try {
|
||||
const result = await fixture.install();
|
||||
assert.equal(result.code, 0, result.stderr);
|
||||
assertManagedPair((await readSettings(expected(fixture))).settings);
|
||||
} finally {
|
||||
await fixture.close();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('Gemini rejects malformed official settings before every write', async (t) => {
|
||||
const cases = [
|
||||
['syntax', '{ malformed', /parse Gemini CLI user settings/i],
|
||||
['root', '[]', /must contain a JSON object/i],
|
||||
['trailing comma', '{ "theme": true, }', /parse Gemini CLI user settings/i],
|
||||
['duplicate', '{ "hooks": {}, "hooks": {} }', /duplicate field "hooks"/i],
|
||||
['hooks shape', '{ "hooks": null }', /field "hooks" must be an object/i],
|
||||
['event shape', '{ "hooks": { "BeforeTool": null } }', /must be an array/i],
|
||||
['group shape', '{ "hooks": { "BeforeTool": [null] } }', /group.*must be an object/i],
|
||||
['matcher shape', '{ "hooks": { "BeforeTool": [{ "matcher": 1, "hooks": [] }] } }', /matcher must be a string/i],
|
||||
['sequential shape', '{ "hooks": { "BeforeTool": [{ "sequential": 1, "hooks": [] }] } }', /sequential must be a boolean/i],
|
||||
['hooks missing', '{ "hooks": { "BeforeTool": [{}] } }', /must contain a hooks array/i],
|
||||
['handler shape', '{ "hooks": { "BeforeTool": [{ "hooks": [null] }] } }', /handler.*must be an object/i],
|
||||
['handler type', '{ "hooks": { "BeforeTool": [{ "hooks": [{ "type": "http" }] }] } }', /unsupported type/i],
|
||||
['internal handler type', '{ "hooks": { "BeforeTool": [{ "hooks": [{ "type": "runtime", "name": "x" }] }] } }', /unsupported type/i],
|
||||
['command value', '{ "hooks": { "BeforeTool": [{ "hooks": [{ "type": "command", "command": "" }] }] } }', /non-empty command/i],
|
||||
['timeout value', '{ "hooks": { "BeforeTool": [{ "hooks": [{ "type": "command", "command": "x", "timeout": -1 }] }] } }', /non-negative finite number/i],
|
||||
['environment value', '{ "hooks": { "BeforeTool": [{ "hooks": [{ "type": "command", "command": "x", "env": { "A": 1 } }] }] } }', /env must map names to strings/i],
|
||||
['controls shape', '{ "hooksConfig": null }', /hooksConfig.*must be an object/i],
|
||||
['controls field', '{ "hooksConfig": { "future": true } }', /unsupported field "future"/i],
|
||||
['enabled shape', '{ "hooksConfig": { "enabled": "yes" } }', /enabled.*must be a boolean/i],
|
||||
['disabled shape', '{ "hooksConfig": { "disabled": [1] } }', /array of strings/i],
|
||||
['notifications shape', '{ "hooksConfig": { "notifications": 1 } }', /notifications.*must be a boolean/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('Gemini respects canonical hook controls', async () => {
|
||||
for (const [settings, pattern] of [
|
||||
[{ hooksConfig: { enabled: false } }, /hooksConfig.enabled/i],
|
||||
[{ hooksConfig: { disabled: [GUARD_NAME] } }, /elydora-guard/i],
|
||||
[{ hooksConfig: { disabled: [AUDIT_NAME] } }, /elydora-audit/i],
|
||||
]) {
|
||||
const fixture = await createFixture({ settings });
|
||||
try {
|
||||
const result = await fixture.install();
|
||||
assert.equal(result.code, 1);
|
||||
assert.match(result.stderr, pattern);
|
||||
await assertMissing(fixture.agentDir);
|
||||
} finally {
|
||||
await fixture.close();
|
||||
}
|
||||
}
|
||||
|
||||
const legacy = await createFixture();
|
||||
try {
|
||||
await writeSettings(legacy.settingsPath, {
|
||||
hooksConfig: { disabled: [legacyHandler(legacy.guardScriptPath).command] },
|
||||
});
|
||||
const result = await legacy.install();
|
||||
assert.equal(result.code, 1);
|
||||
assert.match(result.stderr, /hooksConfig.disabled/i);
|
||||
await assertMissing(legacy.agentDir);
|
||||
} finally {
|
||||
await legacy.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('Gemini migrates exact legacy handlers and preserves ownership lookalikes', async () => {
|
||||
const fixture = await createFixture();
|
||||
const lookalike = { ...legacyHandler(fixture.guardScriptPath) };
|
||||
lookalike.command += ' --inspect';
|
||||
await writeSettings(fixture.settingsPath, {
|
||||
hooks: {
|
||||
BeforeTool: [
|
||||
{ hooks: [legacyHandler(fixture.guardScriptPath)] },
|
||||
{ hooks: [lookalike] },
|
||||
],
|
||||
AfterTool: [{ hooks: [legacyHandler(fixture.hookScriptPath)] }],
|
||||
},
|
||||
});
|
||||
try {
|
||||
const install = await fixture.install();
|
||||
assert.equal(install.code, 0, install.stderr);
|
||||
let settings = (await readSettings(fixture.settingsPath)).settings;
|
||||
assertManagedPair(settings);
|
||||
assert(settings.hooks.BeforeTool.some((group) => group.hooks[0].command === lookalike.command));
|
||||
|
||||
const managed = settings.hooks.BeforeTool.at(-1);
|
||||
managed.hooks.push({ type: 'command', command: 'user-command' });
|
||||
await writeSettings(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.BeforeTool.flatMap((group) => group.hooks), [
|
||||
lookalike,
|
||||
{ type: 'command', command: 'user-command' },
|
||||
]);
|
||||
assert.equal(settings.hooks.AfterTool, undefined);
|
||||
} finally {
|
||||
await fixture.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('Gemini uninstall preserves user settings and removes an owned file', async () => {
|
||||
const user = await createFixture({ settings: { theme: 'GitHub', hooks: { Notification: [] } } });
|
||||
try {
|
||||
assert.equal((await user.install()).code, 0);
|
||||
assert.equal((await runPlugin(user, 'uninstall', 'agent-1')).code, 0);
|
||||
assert.deepEqual((await readSettings(user.settingsPath)).settings, {
|
||||
theme: 'GitHub',
|
||||
hooks: { Notification: [] },
|
||||
});
|
||||
} finally {
|
||||
await user.close();
|
||||
}
|
||||
|
||||
const owned = await createFixture();
|
||||
try {
|
||||
assert.equal((await owned.install()).code, 0);
|
||||
assert.match(await readFile(owned.settingsPath, 'utf-8'), /^\/\/ Managed by Elydora/);
|
||||
assert.equal((await runPlugin(owned, 'uninstall', 'agent-1')).code, 0);
|
||||
await assertMissing(owned.settingsPath);
|
||||
} finally {
|
||||
await owned.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('Gemini status requires enabled exact hooks and strict runtime identity', async () => {
|
||||
const fixture = await createFixture();
|
||||
try {
|
||||
assert.equal((await fixture.install()).code, 0);
|
||||
let status = JSON.parse((await runPlugin(fixture, 'status', null)).stdout);
|
||||
assert.equal(status.installed, true);
|
||||
|
||||
let settings = (await readSettings(fixture.settingsPath)).settings;
|
||||
settings.hooks.AfterTool.push(settings.hooks.AfterTool.at(-1));
|
||||
await writeSettings(fixture.settingsPath, settings);
|
||||
status = JSON.parse((await runPlugin(fixture, 'status', null)).stdout);
|
||||
assert.equal(status.installed, false);
|
||||
|
||||
assert.equal((await fixture.install()).code, 0);
|
||||
settings = (await readSettings(fixture.settingsPath)).settings;
|
||||
settings.hooksConfig = { disabled: [AUDIT_NAME] };
|
||||
await writeSettings(fixture.settingsPath, settings);
|
||||
status = JSON.parse((await runPlugin(fixture, 'status', null)).stdout);
|
||||
assert.equal(status.installed, false);
|
||||
assert.equal(status.hookConfigured, false);
|
||||
|
||||
settings.hooksConfig = { disabled: [] };
|
||||
await writeSettings(fixture.settingsPath, settings);
|
||||
await writeFile(path.join(fixture.agentDir, 'private.key'), 'invalid');
|
||||
const invalid = await runPlugin(fixture, 'status', null);
|
||||
assert.equal(invalid.code, 1);
|
||||
assert.match(invalid.stderr, /private key is invalid/i);
|
||||
} finally {
|
||||
await fixture.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('Gemini 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,
|
||||
GEMINI_CLI_HOME: fixture.geminiCliHome,
|
||||
};
|
||||
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', 'gemini',
|
||||
'--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);
|
||||
assertManagedPair((await readSettings(fixture.settingsPath)).settings);
|
||||
|
||||
const status = await runNode(
|
||||
['--no-warnings', cliPath, 'status'],
|
||||
environment,
|
||||
fixture.projectDir,
|
||||
);
|
||||
assert.equal(status.code, 0, status.stderr);
|
||||
assert.match(status.stdout, /Gemini CLI \(gemini\) \[installed\]/);
|
||||
|
||||
const uninstall = await runNode([
|
||||
'--no-warnings',
|
||||
cliPath,
|
||||
'uninstall',
|
||||
'--agent', 'gemini',
|
||||
'--agent_id', 'agent-1',
|
||||
], environment, fixture.projectDir);
|
||||
assert.equal(uninstall.code, 0, uninstall.stderr);
|
||||
await assertMissing(fixture.settingsPath);
|
||||
await assertMissing(fixture.agentDir);
|
||||
} finally {
|
||||
await fixture.close();
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,148 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFile, stat } from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
createFixture,
|
||||
managedHandler,
|
||||
readSettings,
|
||||
runGeminiHook,
|
||||
startApiServer,
|
||||
} from '../test-support/gemini-test-helpers.mjs';
|
||||
|
||||
const GUARD_NAME = 'elydora-guard';
|
||||
const AUDIT_NAME = 'elydora-audit';
|
||||
|
||||
function officialInput(fixture, event) {
|
||||
return {
|
||||
session_id: 'session-1',
|
||||
transcript_path: path.join(fixture.projectDir, 'transcript.jsonl'),
|
||||
cwd: fixture.projectDir,
|
||||
hook_event_name: event,
|
||||
timestamp: '2026-07-19T00:00:00.000Z',
|
||||
tool_name: 'run_shell_command',
|
||||
tool_input: { command: 'echo test' },
|
||||
...(event === 'AfterTool' ? {
|
||||
tool_response: { output: 'test', error: null },
|
||||
} : {}),
|
||||
};
|
||||
}
|
||||
|
||||
async function installedHandlers(fixture) {
|
||||
const settings = (await readSettings(fixture.settingsPath)).settings;
|
||||
return {
|
||||
guard: managedHandler(settings, 'BeforeTool', GUARD_NAME),
|
||||
audit: managedHandler(settings, 'AfterTool', AUDIT_NAME),
|
||||
};
|
||||
}
|
||||
|
||||
test('Gemini guard accepts active agents with valid JSON stdout', async () => {
|
||||
const api = await startApiServer({ status: 'active' });
|
||||
const fixture = await createFixture({ baseUrl: api.baseUrl });
|
||||
try {
|
||||
const install = await fixture.install();
|
||||
assert.equal(install.code, 0, install.stderr);
|
||||
const { guard } = await installedHandlers(fixture);
|
||||
const input = JSON.stringify(officialInput(fixture, 'BeforeTool'));
|
||||
const result = await runGeminiHook(guard, input, fixture);
|
||||
assert.equal(result.code, 0, result.stderr);
|
||||
assert.deepEqual(JSON.parse(result.stdout), {});
|
||||
assert.equal(api.requests.filter((request) => request.method === 'GET').length, 1);
|
||||
} finally {
|
||||
await fixture.close();
|
||||
await api.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('Gemini guard propagates frozen and revoked states through exit code 2', 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 { guard } = await installedHandlers(fixture);
|
||||
const result = await runGeminiHook(
|
||||
guard,
|
||||
JSON.stringify(officialInput(fixture, 'BeforeTool')),
|
||||
fixture,
|
||||
);
|
||||
assert.equal(result.code, 2, result.stderr);
|
||||
assert.equal(result.stdout, '');
|
||||
assert.match(result.stderr, new RegExp(`is ${status}`, 'i'));
|
||||
} finally {
|
||||
await fixture.close();
|
||||
await api.close();
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
test('Gemini audit forwards the complete native AfterTool payload', async () => {
|
||||
const api = await startApiServer();
|
||||
const fixture = await createFixture({ baseUrl: api.baseUrl });
|
||||
try {
|
||||
assert.equal((await fixture.install()).code, 0);
|
||||
const { audit } = await installedHandlers(fixture);
|
||||
const payload = officialInput(fixture, 'AfterTool');
|
||||
payload.mcp_context = { server_name: 'filesystem', tool_name: 'write_file' };
|
||||
payload.original_request_name = 'write_file';
|
||||
payload.future_provider_field = { preserved: true };
|
||||
const source = JSON.stringify(payload);
|
||||
const result = await runGeminiHook(audit, source, fixture);
|
||||
assert.equal(result.code, 0, result.stderr);
|
||||
assert.deepEqual(JSON.parse(result.stdout), {});
|
||||
const request = api.requests.find((entry) => entry.method === 'POST');
|
||||
assert(request);
|
||||
assert.deepEqual(JSON.parse(request.raw).payload, payload);
|
||||
} finally {
|
||||
await fixture.close();
|
||||
await api.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('Gemini runtimes keep failures observable while preserving fail-open behavior', async () => {
|
||||
const fixture = await createFixture();
|
||||
try {
|
||||
assert.equal((await fixture.install()).code, 0);
|
||||
const { guard, audit } = await installedHandlers(fixture);
|
||||
const invalidGuard = await runGeminiHook(guard, '{ malformed', fixture);
|
||||
assert.equal(invalidGuard.code, 0, invalidGuard.stderr);
|
||||
assert.deepEqual(JSON.parse(invalidGuard.stdout), {});
|
||||
assert.match(invalidGuard.stderr, /invalid JSON/i);
|
||||
|
||||
const auditResult = await runGeminiHook(
|
||||
audit,
|
||||
JSON.stringify(officialInput(fixture, 'AfterTool')),
|
||||
fixture,
|
||||
);
|
||||
assert.equal(auditResult.code, 0, auditResult.stderr);
|
||||
assert.deepEqual(JSON.parse(auditResult.stdout), {});
|
||||
assert.match(
|
||||
await readFile(path.join(fixture.agentDir, 'error.log'), 'utf-8'),
|
||||
/Elydora audit|fetch failed|ECONNREFUSED/i,
|
||||
);
|
||||
} finally {
|
||||
await fixture.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('Gemini runtime artifacts use private modes on POSIX', {
|
||||
skip: process.platform === 'win32' ? 'POSIX mode bits are not authoritative on Windows' : false,
|
||||
}, async () => {
|
||||
const fixture = await createFixture();
|
||||
try {
|
||||
assert.equal((await fixture.install()).code, 0);
|
||||
for (const [filePath, expected] of [
|
||||
[path.join(fixture.agentDir, 'config.json'), 0o600],
|
||||
[path.join(fixture.agentDir, 'private.key'), 0o600],
|
||||
[fixture.guardScriptPath, 0o700],
|
||||
[fixture.hookScriptPath, 0o700],
|
||||
[fixture.settingsPath, 0o600],
|
||||
]) {
|
||||
assert.equal((await stat(filePath)).mode & 0o777, expected);
|
||||
}
|
||||
} finally {
|
||||
await fixture.close();
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,221 @@
|
||||
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,
|
||||
writeSettings,
|
||||
} from '../test-support/gemini-test-helpers.mjs';
|
||||
|
||||
const managedFileNames = ['guard.js', 'config.json', 'private.key', 'hook.js'];
|
||||
|
||||
async function assertMissing(filePath) {
|
||||
await assert.rejects(lstat(filePath), { code: 'ENOENT' });
|
||||
}
|
||||
|
||||
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(', '));
|
||||
}
|
||||
|
||||
function testEnvironment(fixture, overrides = {}) {
|
||||
return {
|
||||
HOME: fixture.homeDir,
|
||||
USERPROFILE: fixture.homeDir,
|
||||
GEMINI_CLI_HOME: fixture.geminiCliHome,
|
||||
ELYDORA_INSTALL_CONFIG: JSON.stringify(installConfig(fixture, overrides)),
|
||||
};
|
||||
}
|
||||
|
||||
test('Gemini 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 { readGeminiDocument } from ${JSON.stringify(ioModuleUrl)};
|
||||
import {
|
||||
commitGeminiInstallation,
|
||||
prepareGeminiInstallation,
|
||||
} from ${JSON.stringify(installationModuleUrl)};
|
||||
const config = JSON.parse(process.env.ELYDORA_INSTALL_CONFIG);
|
||||
const document = await readGeminiDocument();
|
||||
const prepared = await prepareGeminiInstallation(config, { document, changed: false });
|
||||
let calls = 0;
|
||||
await commitGeminiInstallation(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('Gemini detects concurrent settings changes before runtime commit', async () => {
|
||||
const fixture = await createFixture({ settings: { theme: 'GitHub' } });
|
||||
try {
|
||||
assert.equal((await fixture.install()).code, 0);
|
||||
const before = await snapshotInstallation(fixture);
|
||||
const concurrent = '{"theme":"Atom One","hooks":{"Notification":[]}}\n';
|
||||
const source = `
|
||||
import { writeFile } from 'node:fs/promises';
|
||||
import { readGeminiDocument } from ${JSON.stringify(ioModuleUrl)};
|
||||
import {
|
||||
commitGeminiInstallation,
|
||||
prepareGeminiInstallation,
|
||||
} from ${JSON.stringify(installationModuleUrl)};
|
||||
const document = await readGeminiDocument();
|
||||
const prepared = await prepareGeminiInstallation(
|
||||
JSON.parse(process.env.ELYDORA_INSTALL_CONFIG),
|
||||
{ document, changed: false },
|
||||
);
|
||||
await writeFile(document.filePath, process.env.ELYDORA_CONCURRENT, 'utf-8');
|
||||
await commitGeminiInstallation(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 Gemini CLI 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('Gemini 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 writeSettings(path.join(fixture.agentDir, 'config.json'), {
|
||||
agent_name: 'gemini',
|
||||
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();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
test('Gemini 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 = path.dirname(fixture.settingsPath);
|
||||
} else if (kind === 'runtime') {
|
||||
link = path.join(fixture.homeDir, '.elydora');
|
||||
} else {
|
||||
await mkdir(path.dirname(fixture.settingsPath), { recursive: true });
|
||||
const targetFile = path.join(target, 'settings.json');
|
||||
await writeFile(targetFile, '{}\n');
|
||||
link = fixture.settingsPath;
|
||||
linkType = 'file';
|
||||
await symlink(targetFile, link, linkType);
|
||||
}
|
||||
if (kind !== 'settings') await symlink(target, link, linkType);
|
||||
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('Gemini 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();
|
||||
}
|
||||
});
|
||||
Reference in new issue
Block a user