fix(node): mirror official Grok hooks

This commit is contained in:
ZacharyZhang-NY committed 2026-07-20 05:20:44 -04:00
1 parent 3ddce86c37
commit d84580e5a7
17 files changed
+1648 -843

No files matched your search

+201 -405
View File
@@ -1,146 +1,33 @@
import assert from 'node:assert/strict';
import { spawn } from 'node:child_process';
import { mkdtemp, mkdir, readFile, readdir, rm, writeFile } from 'node:fs/promises';
import os from 'node:os';
import { lstat, mkdir, readFile, readdir, writeFile } from 'node:fs/promises';
import path from 'node:path';
import test from 'node:test';
import { pathToFileURL } from 'node:url';
import {
assertManagedHandler,
cliPath,
createFixture,
legacyCommand,
managedHandler,
readGrokConfig,
registryModuleUrl,
runNode,
runPlugin,
} from '../test-support/grok-test-helpers.mjs';
const pluginModuleUrl = pathToFileURL(path.resolve('dist/plugins/grok.js')).href;
const registryModuleUrl = pathToFileURL(path.resolve('dist/plugins/registry.js')).href;
const cliPath = path.resolve('dist/cli.js');
function runNode(args, env, input = '', unset = [], cwd) {
return new Promise((resolve, reject) => {
const childEnv = { ...process.env, ...env };
for (const key of unset) delete childEnv[key];
const child = spawn(process.execPath, args, {
cwd,
env: childEnv,
stdio: ['pipe', 'pipe', 'pipe'],
});
let stdout = '';
let stderr = '';
child.stdout.on('data', (chunk) => { stdout += chunk; });
child.stderr.on('data', (chunk) => { stderr += chunk; });
child.once('error', reject);
child.once('close', (code) => resolve({ code, stdout, stderr }));
child.stdin.end(input);
});
async function assertMissing(filePath) {
await assert.rejects(lstat(filePath), { code: 'ENOENT' });
}
function runCommand(command, input = '') {
return new Promise((resolve, reject) => {
const child = spawn(command, { shell: true, stdio: ['pipe', 'pipe', 'pipe'] });
let stdout = '';
let stderr = '';
child.stdout.on('data', (chunk) => { stdout += chunk; });
child.stderr.on('data', (chunk) => { stderr += chunk; });
child.once('error', reject);
child.once('close', (code) => resolve({ code, stdout, stderr }));
child.stdin.end(input);
});
}
function quotePosix(value) {
return `'${value.replaceAll("'", `'"'"'`)}'`;
}
function quoteWindows(value) {
return `"${value.replaceAll('"', '\\"')}"`;
}
function buildCommand(scriptPath) {
const quote = process.platform === 'win32' ? quoteWindows : quotePosix;
return `${quote(process.execPath)} ${quote(scriptPath)}`;
}
async function runPlugin(fixture, method, argument) {
const script = `
import { grokPlugin } from ${JSON.stringify(pluginModuleUrl)};
const argument = JSON.parse(process.env.ELYDORA_TEST_ARGUMENT);
const result = await grokPlugin[process.env.ELYDORA_TEST_METHOD](argument);
if (result !== undefined) console.log(JSON.stringify(result));
`;
const env = {
HOME: fixture.homeDir,
USERPROFILE: fixture.homeDir,
ELYDORA_TEST_ARGUMENT: JSON.stringify(argument),
ELYDORA_TEST_METHOD: method,
};
if (fixture.explicitGrokHome) env.GROK_HOME = fixture.grokHome;
return runNode(
['--input-type=module', '--eval', script],
env,
'',
fixture.explicitGrokHome ? [] : ['GROK_HOME'],
fixture.homeDir,
function assertManagedTriple(config) {
assertManagedHandler(managedHandler(config, 'PreToolUse'));
assertManagedHandler(managedHandler(config, 'PostToolUse'));
assertManagedHandler(managedHandler(config, 'PostToolUseFailure'));
assert.equal(
managedHandler(config, 'PostToolUse').command,
managedHandler(config, 'PostToolUseFailure').command,
);
}
async function createFixture({
config,
explicitGrokHome = true,
guardSource,
hookSource,
} = {}) {
const homeDir = await mkdtemp(path.join(os.tmpdir(), 'elydora-grok-'));
const grokHome = explicitGrokHome ? path.join(homeDir, 'custom-grok') : path.join(homeDir, '.grok');
const configPath = path.join(grokHome, 'hooks', 'elydora-audit.json');
const agentDir = path.join(homeDir, '.elydora', 'agent-1');
const guardScriptPath = path.join(agentDir, 'guard.js');
const hookScriptPath = path.join(agentDir, 'hook.js');
await mkdir(agentDir, { recursive: true });
await writeFile(
guardScriptPath,
guardSource ?? "process.stderr.write('Agent is frozen by Elydora.'); process.exit(2);\n",
);
await writeFile(hookScriptPath, hookSource ?? 'process.exit(0);\n');
await writeFile(path.join(agentDir, 'config.json'), JSON.stringify({
agent_id: 'agent-1',
agent_name: 'grok',
}));
if (config !== undefined) {
await mkdir(path.dirname(configPath), { recursive: true });
await writeFile(configPath, typeof config === 'string' ? config : JSON.stringify(config, null, 2));
}
const fixture = {
agentDir,
configPath,
explicitGrokHome,
grokHome,
guardScriptPath,
homeDir,
hookScriptPath,
async close() {
await rm(homeDir, { recursive: true, force: true });
},
};
fixture.installResult = await runPlugin(fixture, 'install', {
agentName: 'grok',
agentId: 'agent-1',
baseUrl: 'https://api.elydora.com',
guardScriptPath,
hookScriptPath,
});
return fixture;
}
function managedHandler(config, event, scriptName) {
for (const group of config.hooks?.[event] ?? []) {
if (Object.hasOwn(group, 'matcher')) continue;
const handler = group.hooks.find((candidate) => candidate.command?.includes(scriptName));
if (handler) return handler;
}
return undefined;
}
function assertStrictHandler(handler) {
assert.deepEqual(Object.keys(handler).sort(), ['command', 'timeout', 'type']);
assert.equal(handler.type, 'command');
assert.equal(handler.timeout, 10);
}
test('Grok Build is registered in the SDK and CLI', async () => {
const { SUPPORTED_AGENTS } = await import(registryModuleUrl);
assert.deepEqual(SUPPORTED_AGENTS.get('grok'), {
@@ -148,71 +35,63 @@ test('Grok Build is registered in the SDK and CLI', async () => {
configDir: '~/.grok/hooks',
configFile: 'elydora-audit.json',
});
const homeDir = await mkdtemp(path.join(os.tmpdir(), 'elydora-grok-cli-'));
const fixture = await createFixture();
try {
const result = await runNode(['--no-warnings', cliPath, 'status'], {
HOME: homeDir,
USERPROFILE: homeDir,
GROK_HOME: path.join(homeDir, 'custom-grok'),
}, '', [], homeDir);
HOME: fixture.homeDir,
USERPROFILE: fixture.homeDir,
GROK_HOME: fixture.grokHome,
}, fixture.projectDir);
assert.equal(result.code, 0, result.stderr);
assert.match(result.stdout, /Grok Build \(grok\)/);
} finally {
await rm(homeDir, { recursive: true, force: true });
}
});
test('Grok install preserves native user config and is idempotent', async () => {
const existing = {
schemaVersion: 1,
hooks: {
SessionStart: [{
matcher: 'startup',
hooks: [{ type: 'http', url: 'https://example.test/hook', timeout: 5, headers: { x: 'keep' } }],
label: 'keep group metadata',
}],
PreToolUse: [{
matcher: 'Bash',
hooks: [{ type: 'command', command: 'existing-command', timeout: 5 }],
}],
},
};
const fixture = await createFixture({ config: existing });
try {
assert.equal(fixture.installResult.code, 0, fixture.installResult.stderr);
assert.match(fixture.installResult.stdout, /global PreToolUse and PostToolUse hooks installed/i);
const second = await runPlugin(fixture, 'install', {
agentName: 'grok',
agentId: 'agent-1',
guardScriptPath: fixture.guardScriptPath,
hookScriptPath: fixture.hookScriptPath,
});
assert.equal(second.code, 0, second.stderr);
const config = JSON.parse(await readFile(fixture.configPath, 'utf-8'));
assert.equal(config.schemaVersion, 1);
assert.deepEqual(config.hooks.SessionStart, existing.hooks.SessionStart);
assert.deepEqual(config.hooks.PreToolUse[0], existing.hooks.PreToolUse[0]);
assert.equal(config.hooks.PreToolUse.length, 2);
assert.equal(config.hooks.PostToolUse.length, 1);
assert.deepEqual(Object.keys(config.hooks.PreToolUse[1]), ['hooks']);
assertStrictHandler(managedHandler(config, 'PreToolUse', 'guard.js'));
assertStrictHandler(managedHandler(config, 'PostToolUse', 'hook.js'));
await assert.rejects(readFile(path.join(fixture.homeDir, '.grok', 'hooks', 'elydora-audit.json')), {
code: 'ENOENT',
});
await assert.rejects(readFile(path.join(fixture.homeDir, '.claude', 'settings.json')), { code: 'ENOENT' });
await assert.rejects(readFile(path.join(fixture.homeDir, '.cursor', 'hooks.json')), { code: 'ENOENT' });
} finally {
await fixture.close();
}
});
test('Grok treats an empty home override as the official default', async () => {
test('Grok installs an exact managed triple and preserves valid user hooks', async () => {
const existing = {
schemaVersion: 1,
hooks: {
SessionStart: [{
hooks: [{ type: 'http', url: 'https://example.test/hook', timeout: 0 }],
label: 'keep group metadata',
}],
PreToolUse: [{
matcher: 'Bash|run_terminal_command',
hooks: [{ type: 'command', command: 'existing-command', timeout: 5 }],
}],
},
};
const source = `${JSON.stringify(existing, null, 2)}\n`;
const fixture = await createFixture({ config: source });
try {
const first = await fixture.install();
assert.equal(first.code, 0, first.stderr);
assert.match(first.stdout, /PostToolUseFailure hooks installed/i);
const firstDocument = await readGrokConfig(fixture.configPath);
assert.equal(firstDocument.config.schemaVersion, 1);
assert.deepEqual(firstDocument.config.hooks.SessionStart, existing.hooks.SessionStart);
assert.deepEqual(firstDocument.config.hooks.PreToolUse[0], existing.hooks.PreToolUse[0]);
assert.equal(firstDocument.config.hooks.PreToolUse.length, 2);
assertManagedTriple(firstDocument.config);
const second = await fixture.install();
assert.equal(second.code, 0, second.stderr);
assert.equal(await readFile(fixture.configPath, 'utf-8'), firstDocument.raw);
await assertMissing(path.join(fixture.homeDir, '.grok', 'hooks', 'elydora-audit.json'));
await assertMissing(path.join(fixture.homeDir, '.claude', 'settings.json'));
await assertMissing(path.join(fixture.homeDir, '.cursor', 'hooks.json'));
} finally {
await fixture.close();
}
});
test('empty GROK_HOME resolves to the documented default', async () => {
const fixture = await createFixture({ explicitGrokHome: false });
try {
assert.equal(fixture.installResult.code, 0, fixture.installResult.stderr);
fixture.explicitGrokHome = true;
fixture.grokHome = '';
assert.equal((await fixture.install()).code, 0);
fixture.grokHomeOverride = '';
const status = await runPlugin(fixture, 'status', null);
assert.equal(status.code, 0, status.stderr);
assert.equal(JSON.parse(status.stdout).installed, true);
@@ -221,240 +100,157 @@ test('Grok treats an empty home override as the official default', async () => {
}
});
test('Grok commands block freezes and forward the official payload byte-for-byte', async () => {
const capturePath = path.join(os.tmpdir(), `elydora-grok-event-${process.pid}-${Date.now()}.json`);
const hookSource = `
const fs = require('node:fs');
const chunks = [];
process.stdin.on('data', (chunk) => chunks.push(chunk));
process.stdin.on('end', () => fs.writeFileSync(${JSON.stringify(capturePath)}, Buffer.concat(chunks)));
`;
const fixture = await createFixture({ hookSource });
try {
assert.equal(fixture.installResult.code, 0, fixture.installResult.stderr);
const config = JSON.parse(await readFile(fixture.configPath, 'utf-8'));
const guard = managedHandler(config, 'PreToolUse', 'guard.js');
const audit = managedHandler(config, 'PostToolUse', 'hook.js');
const prePayload = JSON.stringify({
hookEventName: 'PreToolUse',
sessionId: 'session-1',
cwd: fixture.homeDir,
workspaceRoot: fixture.homeDir,
toolName: 'Bash',
toolInput: { command: 'echo test' },
});
const guardResult = await runCommand(guard.command, prePayload);
assert.equal(guardResult.code, 2);
assert.match(guardResult.stderr, /Agent is frozen by Elydora/);
const postPayload = JSON.stringify({
hookEventName: 'PostToolUse',
sessionId: 'session-1',
cwd: fixture.homeDir,
workspaceRoot: fixture.homeDir,
toolName: 'Bash',
toolInput: { command: 'echo test' },
toolResult: { output: 'test' },
});
const auditResult = await runCommand(audit.command, postPayload);
assert.equal(auditResult.code, 0, auditResult.stderr);
assert.equal(await readFile(capturePath, 'utf-8'), postPayload);
} finally {
await fixture.close();
await rm(capturePath, { force: true });
}
});
test('Grok status requires a complete hook pair and both runtime files', async () => {
const fixture = await createFixture();
try {
assert.equal(fixture.installResult.code, 0, fixture.installResult.stderr);
let status = await runPlugin(fixture, 'status', null);
assert.equal(JSON.parse(status.stdout).installed, true);
const config = JSON.parse(await readFile(fixture.configPath, 'utf-8'));
delete config.hooks.PostToolUse;
await writeFile(fixture.configPath, JSON.stringify(config, null, 2));
status = await runPlugin(fixture, 'status', null);
assert.equal(JSON.parse(status.stdout).hookConfigured, false);
await runPlugin(fixture, 'install', {
agentName: 'grok',
agentId: 'agent-1',
guardScriptPath: fixture.guardScriptPath,
hookScriptPath: fixture.hookScriptPath,
});
await rm(fixture.guardScriptPath);
status = await runPlugin(fixture, 'status', null);
assert.equal(JSON.parse(status.stdout).installed, false);
} finally {
await fixture.close();
}
});
test('Grok uninstall removes exact ownership and preserves mixed user handlers', async () => {
const fixture = await createFixture({ config: { owner: 'user', hooks: { Notification: [] } } });
try {
assert.equal(fixture.installResult.code, 0, fixture.installResult.stderr);
const config = JSON.parse(await readFile(fixture.configPath, 'utf-8'));
config.hooks.PreToolUse.at(-1).hooks.push({ type: 'command', command: 'user-command', timeout: 10 });
config.hooks.PreToolUse.push({ hooks: [{
type: 'command',
command: buildCommand(path.join(fixture.agentDir, 'guard.js.backup')),
timeout: 10,
}] });
config.hooks.PreToolUse.push({ hooks: [{
type: 'command',
command: buildCommand(path.join(fixture.homeDir, '.elydora', 'agent-10', 'guard.js')),
timeout: 10,
}] });
await writeFile(fixture.configPath, JSON.stringify(config, null, 2));
const uninstallId = process.platform === 'win32' ? 'AGENT-1' : 'agent-1';
const result = await runPlugin(fixture, 'uninstall', uninstallId);
assert.equal(result.code, 0, result.stderr);
const remaining = JSON.parse(await readFile(fixture.configPath, 'utf-8'));
assert.equal(remaining.owner, 'user');
assert.equal(remaining.hooks.PreToolUse.length, 3);
assert.equal(remaining.hooks.PreToolUse[0].hooks[0].command, 'user-command');
assert(remaining.hooks.PreToolUse.some((group) => group.hooks[0].command.includes('guard.js.backup')));
assert(remaining.hooks.PreToolUse.some((group) => group.hooks[0].command.includes('agent-10')));
assert.equal(remaining.hooks.PostToolUse, undefined);
assert.deepEqual(remaining.hooks.Notification, []);
} finally {
await fixture.close();
}
});
test('Grok install replaces stale Elydora handlers for every agent', async () => {
const fixture = await createFixture();
try {
assert.equal(fixture.installResult.code, 0, fixture.installResult.stderr);
const config = JSON.parse(await readFile(fixture.configPath, 'utf-8'));
for (const [event, scriptName] of [['PreToolUse', 'guard.js'], ['PostToolUse', 'hook.js']]) {
config.hooks[event].push({ hooks: [{
type: 'command',
command: buildCommand(path.join(fixture.homeDir, '.elydora', 'agent-old', scriptName)),
timeout: 10,
}] });
}
await writeFile(fixture.configPath, JSON.stringify(config, null, 2));
const result = await runPlugin(fixture, 'install', {
agentName: 'grok',
agentId: 'agent-1',
guardScriptPath: fixture.guardScriptPath,
hookScriptPath: fixture.hookScriptPath,
});
assert.equal(result.code, 0, result.stderr);
const current = await readFile(fixture.configPath, 'utf-8');
assert.doesNotMatch(current, /agent-old/);
assert.equal(JSON.parse(current).hooks.PreToolUse.length, 1);
assert.equal(JSON.parse(current).hooks.PostToolUse.length, 1);
} finally {
await fixture.close();
}
});
test('Grok uninstall preserves an untouched empty native group', async () => {
const fixture = await createFixture({ config: { owner: 'user' } });
try {
assert.equal(fixture.installResult.code, 0, fixture.installResult.stderr);
const config = JSON.parse(await readFile(fixture.configPath, 'utf-8'));
config.hooks.PreToolUse.unshift({ hooks: [], label: 'keep empty group' });
await writeFile(fixture.configPath, JSON.stringify(config, null, 2));
const result = await runPlugin(fixture, 'uninstall', 'agent-1');
assert.equal(result.code, 0, result.stderr);
const remaining = JSON.parse(await readFile(fixture.configPath, 'utf-8'));
assert.deepEqual(remaining.hooks.PreToolUse, [{ hooks: [], label: 'keep empty group' }]);
assert.equal(remaining.hooks.PostToolUse, undefined);
} finally {
await fixture.close();
}
});
test('Grok uninstall removes a config owned entirely by Elydora', async () => {
const fixture = await createFixture();
try {
assert.equal(fixture.installResult.code, 0, fixture.installResult.stderr);
const result = await runPlugin(fixture, 'uninstall', 'agent-1');
assert.equal(result.code, 0, result.stderr);
await assert.rejects(readFile(fixture.configPath), { code: 'ENOENT' });
} finally {
await fixture.close();
}
});
test('Grok preserves malformed JSON for recovery', async () => {
test('Grok parses the hook file before creating runtime files', async () => {
const fixture = await createFixture({ config: '{ malformed' });
try {
assert.equal(fixture.installResult.code, 1);
assert.match(fixture.installResult.stderr, /parse Grok hooks config/i);
assert.equal(await readFile(fixture.configPath, 'utf-8'), '{ malformed');
} finally {
await fixture.close();
}
});
test('Grok rejects invalid native hook shapes before writing', async () => {
const cases = [
{ hooks: null },
{ hooks: { PreToolUse: null } },
{ hooks: { PreToolUse: [null] } },
{ hooks: { PreToolUse: [{ matcher: 1, hooks: [] }] } },
{ hooks: { PreToolUse: [{ hooks: null }] } },
{ hooks: { PreToolUse: [{ hooks: [{ type: 'command', command: '' }] }] } },
{ hooks: { PreToolUse: [{ hooks: [{ type: 'file', command: 'x' }] }] } },
{ hooks: { PreToolUse: [{ hooks: [{ type: 'http', url: '' }] }] } },
{ hooks: { PreToolUse: [{ hooks: [{ type: 'command', command: 'x', timeout: 0 }] }] } },
];
for (const existing of cases) {
const fixture = await createFixture({ config: existing });
try {
assert.equal(fixture.installResult.code, 1);
assert.deepEqual(JSON.parse(await readFile(fixture.configPath, 'utf-8')), existing);
} finally {
await fixture.close();
}
}
});
test('Grok install rejects missing runtimes before creating config', async () => {
const homeDir = await mkdtemp(path.join(os.tmpdir(), 'elydora-grok-missing-runtime-'));
const fixture = {
explicitGrokHome: true,
grokHome: path.join(homeDir, 'custom-grok'),
homeDir,
};
const configPath = path.join(fixture.grokHome, 'hooks', 'elydora-audit.json');
try {
const result = await runPlugin(fixture, 'install', {
agentName: 'grok',
agentId: 'agent-1',
guardScriptPath: path.join(homeDir, '.elydora', 'agent-1', 'guard.js'),
hookScriptPath: path.join(homeDir, '.elydora', 'agent-1', 'hook.js'),
});
const result = await fixture.install();
assert.equal(result.code, 1);
assert.match(result.stderr, /runtime is missing/i);
await assert.rejects(readFile(configPath), { code: 'ENOENT' });
assert.match(result.stderr, /parse Grok user hooks/i);
assert.equal(await readFile(fixture.configPath, 'utf-8'), '{ malformed');
await assertMissing(fixture.agentDir);
} finally {
await rm(homeDir, { recursive: true, force: true });
await fixture.close();
}
});
test('Grok status surfaces malformed referenced runtime metadata', async () => {
test('Grok rejects inactive native hook shapes before writes', async (t) => {
const cases = [
['duplicate field', '{"hooks":{},"hooks":{}}', /duplicate field "hooks"/i],
['hooks shape', JSON.stringify({ hooks: null }), /field "hooks" must be an object/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],
['matcher shape', JSON.stringify({ hooks: { PreToolUse: [{ matcher: 1, hooks: [] }] } }), /matcher must be a string/i],
['lifecycle matcher', JSON.stringify({ hooks: { SessionStart: [{ matcher: 'x', hooks: [] }] } }), /cannot declare a matcher/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],
['command value', JSON.stringify({ hooks: { PreToolUse: [{ hooks: [{ type: 'command', command: '' }] }] } }), /non-empty command/i],
['http value', JSON.stringify({ hooks: { PostToolUse: [{ hooks: [{ type: 'http', url: '' }] }] } }), /non-empty url/i],
['negative timeout', JSON.stringify({ hooks: { PreToolUse: [{ hooks: [{ type: 'command', command: 'x', timeout: -1 }] }] } }), /non-negative integer/i],
['fraction timeout', JSON.stringify({ hooks: { PreToolUse: [{ hooks: [{ type: 'command', command: 'x', timeout: 1.5 }] }] } }), /non-negative integer/i],
['environment shape', JSON.stringify({ hooks: { PreToolUse: [{ hooks: [{ type: 'command', command: 'x', env: { A: 1 } }] }] } }), /env must map names to strings/i],
];
for (const [name, config, pattern] of cases) {
await t.test(name, async () => {
const fixture = await createFixture({ config });
try {
const result = await fixture.install();
assert.equal(result.code, 1);
assert.match(result.stderr, pattern);
assert.equal(await readFile(fixture.configPath, 'utf-8'), config);
await assertMissing(fixture.agentDir);
} finally {
await fixture.close();
}
});
}
});
test('Grok migrates exact legacy commands and preserves ownership lookalikes', async () => {
const fixture = await createFixture();
const lookalike = `${legacyCommand(fixture.guardScriptPath)} --inspect`;
const legacy = {
hooks: {
PreToolUse: [
{ hooks: [{ type: 'command', command: legacyCommand(fixture.guardScriptPath), timeout: 10 }] },
{ hooks: [{ type: 'command', command: lookalike, timeout: 10 }] },
],
PostToolUse: [{ hooks: [{
type: 'command',
command: legacyCommand(fixture.hookScriptPath),
timeout: 10,
}] }],
},
};
try {
await mkdir(path.dirname(fixture.configPath), { recursive: true });
await writeFile(fixture.configPath, JSON.stringify(legacy, null, 2));
const install = await fixture.install();
assert.equal(install.code, 0, install.stderr);
let { config } = await readGrokConfig(fixture.configPath);
assertManagedTriple(config);
assert(config.hooks.PreToolUse.some((group) => group.hooks[0].command === lookalike));
const managedGroup = config.hooks.PreToolUse.at(-1);
managedGroup.hooks.push({ type: 'command', command: 'user-command', timeout: 10 });
await writeFile(fixture.configPath, JSON.stringify(config, null, 2));
const uninstall = await runPlugin(fixture, 'uninstall', 'agent-1');
assert.equal(uninstall.code, 0, uninstall.stderr);
config = (await readGrokConfig(fixture.configPath)).config;
assert.deepEqual(config.hooks.PreToolUse.flatMap((group) => group.hooks), [
{ type: 'command', command: lookalike, timeout: 10 },
{ type: 'command', command: 'user-command', timeout: 10 },
]);
assert.equal(config.hooks.PostToolUse, undefined);
assert.equal(config.hooks.PostToolUseFailure, undefined);
} finally {
await fixture.close();
}
});
test('Grok uninstall preserves user config and removes a fully managed file', async () => {
const userSource = `${JSON.stringify({ owner: 'user', hooks: { Notification: [] } }, null, 2)}\n`;
const userFixture = await createFixture({ config: userSource });
try {
assert.equal((await userFixture.install()).code, 0);
const result = await runPlugin(userFixture, 'uninstall', 'agent-1');
assert.equal(result.code, 0, result.stderr);
assert.deepEqual((await readGrokConfig(userFixture.configPath)).config, {
owner: 'user',
hooks: { Notification: [] },
});
} finally {
await userFixture.close();
}
const managedFixture = await createFixture();
try {
assert.equal((await managedFixture.install()).code, 0);
const result = await runPlugin(managedFixture, 'uninstall', 'agent-1');
assert.equal(result.code, 0, result.stderr);
await assertMissing(managedFixture.configPath);
} finally {
await managedFixture.close();
}
});
test('Grok status requires one complete triple, exact identity, and private key', async () => {
const fixture = await createFixture();
try {
assert.equal(fixture.installResult.code, 0, fixture.installResult.stderr);
await writeFile(path.join(fixture.agentDir, 'config.json'), '{ malformed');
const status = await runPlugin(fixture, 'status', null);
assert.equal((await fixture.install()).code, 0);
let status = await runPlugin(fixture, 'status', null);
assert.equal(JSON.parse(status.stdout).installed, true);
let { config } = await readGrokConfig(fixture.configPath);
delete config.hooks.PostToolUseFailure;
await writeFile(fixture.configPath, JSON.stringify(config, null, 2));
status = await runPlugin(fixture, 'status', null);
assert.equal(JSON.parse(status.stdout).installed, false);
assert.equal((await fixture.install()).code, 0);
config = (await readGrokConfig(fixture.configPath)).config;
config.hooks.PostToolUseFailure.push(config.hooks.PostToolUseFailure.at(-1));
await writeFile(fixture.configPath, JSON.stringify(config, null, 2));
status = await runPlugin(fixture, 'status', null);
assert.equal(JSON.parse(status.stdout).installed, false);
assert.equal((await fixture.install()).code, 0);
await writeFile(path.join(fixture.agentDir, 'private.key'), 'invalid');
status = await runPlugin(fixture, 'status', null);
assert.equal(status.code, 1);
assert.match(status.stderr, /parse Elydora runtime config/i);
assert.match(status.stderr, /private key is invalid/i);
} finally {
await fixture.close();
}
});
test('Grok atomic writes leave no temporary files', async () => {
test('Grok installation leaves no transaction files', async () => {
const fixture = await createFixture();
try {
assert.equal(fixture.installResult.code, 0, fixture.installResult.stderr);
assert.equal((await readdir(path.dirname(fixture.configPath))).some((name) => name.endsWith('.tmp')), false);
assert.equal((await fixture.install()).code, 0);
for (const directory of [fixture.agentDir, path.dirname(fixture.configPath)]) {
const names = await readdir(directory);
assert.equal(names.some((name) => /\.(tmp|rollback)$/.test(name)), false, names.join(', '));
}
} finally {
await fixture.close();
}
+139
View File
@@ -0,0 +1,139 @@
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,
readGrokConfig,
runGrokHook,
startApiServer,
} from '../test-support/grok-test-helpers.mjs';
const prePayload = {
hookEventName: 'pre_tool_use',
sessionId: 'session-1',
cwd: 'C:/project',
workspaceRoot: 'C:/project',
toolName: 'run_terminal_command',
toolInput: { command: 'npm test' },
toolUseId: 'tool-use-1',
toolInputTruncated: false,
timestamp: '2026-07-19T12:00:00Z',
};
test('Grok runtimes enforce active state and preserve success and failure payloads', async () => {
const api = await startApiServer();
const fixture = await createFixture({ baseUrl: api.baseUrl });
try {
const install = await fixture.install();
assert.equal(install.code, 0, install.stderr);
const { config } = await readGrokConfig(fixture.configPath);
const guard = managedHandler(config, 'PreToolUse');
const successAudit = managedHandler(config, 'PostToolUse');
const failureAudit = managedHandler(config, 'PostToolUseFailure');
const guardResult = await runGrokHook(
guard.command,
JSON.stringify(prePayload),
fixture,
{ GROK_HOOK_EVENT: 'injected-command-fragment' },
);
assert.equal(guardResult.code, 0, guardResult.stderr);
assert.equal(guardResult.stdout, '');
const successPayload = {
...prePayload,
hookEventName: 'post_tool_use',
toolResult: { output: 'tests passed' },
toolResultTruncated: false,
durationMs: 125,
};
const success = await runGrokHook(
successAudit.command,
JSON.stringify(successPayload),
fixture,
);
assert.equal(success.code, 0, success.stderr);
const failurePayload = {
...prePayload,
hookEventName: 'post_tool_use_failure',
toolResult: { error: 'command failed', exitCode: 1 },
toolResultTruncated: false,
durationMs: 40,
};
const failure = await runGrokHook(
failureAudit.command,
JSON.stringify(failurePayload),
fixture,
);
assert.equal(failure.code, 0, failure.stderr);
const operations = api.requests
.filter((request) => request.method === 'POST')
.map((request) => JSON.parse(request.raw));
assert.equal(operations.length, 2);
assert.deepEqual(operations[0].payload, successPayload);
assert.deepEqual(operations[1].payload, failurePayload);
assert.equal(operations[0].subject.session_id, 'session-1');
assert.equal(operations[1].action.tool, 'run_terminal_command');
} finally {
await fixture.close();
await api.close();
}
});
test('Grok guard emits official deny JSON and 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 { config } = await readGrokConfig(fixture.configPath);
const result = await runGrokHook(
managedHandler(config, 'PreToolUse').command,
JSON.stringify(prePayload),
fixture,
);
assert.equal(result.code, 2);
assert.match(result.stderr, new RegExp(status, 'i'));
const decision = JSON.parse(result.stdout);
assert.deepEqual(Object.keys(decision).sort(), ['decision', 'reason']);
assert.equal(decision.decision, 'deny');
assert.match(decision.reason, new RegExp(status, 'i'));
} finally {
await fixture.close();
await api.close();
}
});
}
});
test('Grok audit runtime records malformed input and API failures', async () => {
const api = await startApiServer({ operationStatus: 503 });
const fixture = await createFixture({ baseUrl: api.baseUrl });
try {
assert.equal((await fixture.install()).code, 0);
const { config } = await readGrokConfig(fixture.configPath);
const command = managedHandler(config, 'PostToolUse').command;
const malformed = await runGrokHook(command, '{ malformed', fixture);
assert.equal(malformed.code, 0);
assert.equal(malformed.stderr, '');
const upstream = await runGrokHook(command, JSON.stringify({
...prePayload,
hookEventName: 'post_tool_use',
toolResult: { output: 'test' },
}), fixture);
assert.equal(upstream.code, 0);
assert.equal(upstream.stderr, '');
const log = await readFile(path.join(fixture.agentDir, 'error.log'), 'utf-8');
assert.match(log, /invalid JSON/i);
assert.match(log, /HTTP 503/i);
} finally {
await fixture.close();
await api.close();
}
});
+168
View File
@@ -0,0 +1,168 @@
import assert from 'node:assert/strict';
import {
lstat,
mkdir,
readFile,
readdir,
rm,
symlink,
writeFile,
} from 'node:fs/promises';
import path from 'node:path';
import test from 'node:test';
import {
createFixture,
installConfig,
runPlugin,
} from '../test-support/grok-test-helpers.mjs';
async function createLink(t, target, linkPath, type) {
try {
await symlink(target, linkPath, type);
return true;
} catch (error) {
if (error?.code === 'EPERM') {
t.skip(`symbolic links unavailable: ${error.message}`);
return false;
}
throw error;
}
}
async function assertMissing(filePath) {
await assert.rejects(lstat(filePath), { code: 'ENOENT' });
}
test('Grok rejects linked hook files before creating runtimes', async (t) => {
const fixture = await createFixture();
try {
const target = path.join(fixture.rootDir, 'hooks-target.json');
const source = '{"owner":"protected"}\n';
await mkdir(path.dirname(fixture.configPath), { recursive: true });
await writeFile(target, source, 'utf-8');
if (!await createLink(t, target, fixture.configPath, 'file')) return;
const result = await fixture.install();
assert.equal(result.code, 1);
assert.match(result.stderr, /not a physical file/i);
assert.equal(await readFile(target, 'utf-8'), source);
await assertMissing(fixture.agentDir);
} finally {
await fixture.close();
}
});
test('Grok rejects linked home, hooks, and runtime directories before writes', async (t) => {
for (const kind of ['home', 'hooks', 'runtime']) {
await t.test(kind, async (subtest) => {
const fixture = await createFixture();
try {
const target = path.join(fixture.rootDir, `${kind}-target`);
await mkdir(target, { recursive: true });
let linkPath;
if (kind === 'home') {
linkPath = fixture.grokHome;
await mkdir(path.join(target, 'hooks'), { recursive: true });
await mkdir(path.dirname(linkPath), { recursive: true });
} else if (kind === 'hooks') {
linkPath = path.dirname(fixture.configPath);
await mkdir(fixture.grokHome, { recursive: true });
} else {
linkPath = path.join(fixture.homeDir, '.elydora');
await mkdir(path.dirname(linkPath), { recursive: true });
}
if (!await createLink(subtest, target, linkPath, 'junction')) return;
const result = await fixture.install();
assert.equal(result.code, 1);
assert.match(result.stderr, /physical directory/i);
const untouched = kind === 'runtime' ? fixture.configPath : fixture.agentDir;
await assertMissing(untouched);
} finally {
await fixture.close();
}
});
}
});
test('Grok status rejects a linked private key', async (t) => {
const fixture = await createFixture();
try {
assert.equal((await fixture.install()).code, 0);
const keyPath = path.join(fixture.agentDir, 'private.key');
const target = path.join(fixture.rootDir, 'private-key-target');
const source = await readFile(keyPath, 'utf-8');
await writeFile(target, source, 'utf-8');
await rm(keyPath);
if (!await createLink(t, target, keyPath, 'file')) return;
const status = await runPlugin(fixture, 'status', null);
assert.equal(status.code, 1);
assert.match(status.stderr, /not a physical file/i);
assert.equal(await readFile(target, 'utf-8'), source);
} finally {
await fixture.close();
}
});
test('Grok rejects orphaned and mismatched runtime identity before hook writes', async () => {
for (const kind of ['orphaned', 'mismatched']) {
const fixture = await createFixture();
try {
await mkdir(fixture.agentDir, { recursive: true });
if (kind === 'orphaned') {
await writeFile(fixture.guardScriptPath, 'orphaned guard\n');
} else {
await writeFile(path.join(fixture.agentDir, 'config.json'), JSON.stringify({
agent_name: 'grok',
agent_id: 'another-agent',
}));
}
const result = await fixture.install();
assert.equal(result.code, 1);
assert.match(
result.stderr,
kind === 'orphaned' ? /identity cannot be verified/i : /identity does not match/i,
);
await assertMissing(fixture.configPath);
} finally {
await fixture.close();
}
}
});
test('Grok validates managed runtime inputs before creating hook files', async (t) => {
const fixture = await createFixture();
try {
for (const [name, overrides, pattern] of [
['agent name', { agentName: 'codex' }, /requires agentName grok/i],
['private key', { privateKey: 'invalid' }, /canonical 32-byte/i],
['API origin', { baseUrl: 'https://api.elydora.com/path?token=secret' }, /query parameters/i],
[
'runtime path',
{ guardScriptPath: path.join(fixture.homeDir, 'outside', 'guard.js') },
/managed agent directory/i,
],
]) {
await t.test(name, async () => {
const result = await runPlugin(fixture, 'install', installConfig(fixture, overrides));
assert.equal(result.code, 1);
assert.match(result.stderr, pattern);
await assertMissing(fixture.configPath);
await assertMissing(fixture.agentDir);
});
}
} finally {
await fixture.close();
}
});
test('Grok status surfaces malformed referenced runtime metadata', async () => {
const fixture = await createFixture();
try {
assert.equal((await fixture.install()).code, 0);
await writeFile(path.join(fixture.agentDir, 'config.json'), '{ malformed');
const status = await runPlugin(fixture, 'status', null);
assert.equal(status.code, 1);
assert.match(status.stderr, /parse Elydora runtime config/i);
} finally {
await fixture.close();
}
});
+175
View File
@@ -0,0 +1,175 @@
import assert from 'node:assert/strict';
import { readFile, readdir } from 'node:fs/promises';
import path from 'node:path';
import test from 'node:test';
import {
contractModuleUrl,
createFixture,
installationModuleUrl,
installConfig,
ioModuleUrl,
runNode,
} from '../test-support/grok-test-helpers.mjs';
const runtimeNames = ['guard.js', 'config.json', 'private.key', 'hook.js'];
async function snapshotFixture(fixture) {
const paths = [
...runtimeNames.map((name) => path.join(fixture.agentDir, name)),
fixture.configPath,
];
return new Map(await Promise.all(paths.map(async (filePath) => [
filePath,
await readFile(filePath, 'utf-8'),
])));
}
async function assertSnapshot(snapshot) {
for (const [filePath, contents] of snapshot) {
assert.equal(await readFile(filePath, 'utf-8'), contents, filePath);
}
}
async function assertNoTransactionFiles(fixture) {
for (const directory of [fixture.agentDir, path.dirname(fixture.configPath)]) {
const names = await readdir(directory);
assert.equal(names.some((name) => /\.(tmp|rollback)$/.test(name)), false, names.join(', '));
}
}
function runFixtureSource(fixture, source, environment = {}) {
return runNode(
['--input-type=module', '--eval', source],
{
HOME: fixture.homeDir,
USERPROFILE: fixture.homeDir,
GROK_HOME: fixture.grokHome,
...environment,
},
fixture.projectDir,
);
}
const prepareInstallSource = `
import {
buildGrokGroup,
removeManagedGrokHooks,
renderGrokDocument,
} from ${JSON.stringify(contractModuleUrl)};
import { readGrokDocument } from ${JSON.stringify(ioModuleUrl)};
import {
preflightGrokInstallation,
prepareGrokInstallation,
} from ${JSON.stringify(installationModuleUrl)};
const config = JSON.parse(process.env.ELYDORA_INSTALL_CONFIG);
const document = await readGrokDocument();
const paths = await preflightGrokInstallation(config, document.filePath);
const cleaned = removeManagedGrokHooks(document.hooks);
const hooks = {
...cleaned,
PreToolUse: [...(cleaned.PreToolUse ?? []), buildGrokGroup(paths.guardPath)],
PostToolUse: [...(cleaned.PostToolUse ?? []), buildGrokGroup(paths.auditPath)],
PostToolUseFailure: [
...(cleaned.PostToolUseFailure ?? []),
buildGrokGroup(paths.auditPath),
],
};
const prepared = await prepareGrokInstallation(
config,
renderGrokDocument(document, hooks),
);
`;
test('Grok restores its hook config and four runtime files after the final commit fails', async () => {
const fixture = await createFixture();
try {
assert.equal((await fixture.install()).code, 0);
const before = await snapshotFixture(fixture);
const source = `${prepareInstallSource}
import { rename } from 'node:fs/promises';
import { commitGrokInstallation } from ${JSON.stringify(installationModuleUrl)};
let calls = 0;
await commitGrokInstallation(prepared, async (from, to) => {
calls += 1;
if (calls === 5) throw new Error('injected Grok config failure');
await rename(from, to);
});
`;
const result = await runFixtureSource(fixture, source, {
ELYDORA_INSTALL_CONFIG: JSON.stringify(installConfig(fixture, {
orgId: 'org-updated',
token: 'token-updated',
})),
});
assert.equal(result.code, 1);
assert.match(result.stderr, /injected Grok config failure/i);
await assertSnapshot(before);
await assertNoTransactionFiles(fixture);
} finally {
await fixture.close();
}
});
test('Grok rejects concurrent config changes before committing runtime updates', async () => {
const fixture = await createFixture();
try {
assert.equal((await fixture.install()).code, 0);
const before = await snapshotFixture(fixture);
const concurrent = '{"owner":"concurrent"}\n';
const source = `${prepareInstallSource}
import { writeFile } from 'node:fs/promises';
import { commitGrokInstallation } from ${JSON.stringify(installationModuleUrl)};
await writeFile(document.filePath, process.env.ELYDORA_CONCURRENT, 'utf-8');
await commitGrokInstallation(prepared);
`;
const result = await runFixtureSource(fixture, source, {
ELYDORA_CONCURRENT: concurrent,
ELYDORA_INSTALL_CONFIG: JSON.stringify(installConfig(fixture, { orgId: 'updated' })),
});
assert.equal(result.code, 1);
assert.match(result.stderr, /changed during Grok Build installation/i);
for (const [filePath, contents] of before) {
if (filePath !== fixture.configPath) {
assert.equal(await readFile(filePath, 'utf-8'), contents, filePath);
}
}
assert.equal(await readFile(fixture.configPath, 'utf-8'), concurrent);
await assertNoTransactionFiles(fixture);
} finally {
await fixture.close();
}
});
test('Grok uninstall keeps the original hook config when commit fails', async () => {
const fixture = await createFixture({ config: '{"owner":"user"}\n' });
try {
assert.equal((await fixture.install()).code, 0);
const before = await readFile(fixture.configPath, 'utf-8');
const source = `
import {
removeManagedGrokHooks,
renderGrokDocument,
} from ${JSON.stringify(contractModuleUrl)};
import { readGrokDocument } from ${JSON.stringify(ioModuleUrl)};
import {
commitGrokUninstall,
prepareGrokUninstall,
} from ${JSON.stringify(installationModuleUrl)};
const document = await readGrokDocument();
const prepared = await prepareGrokUninstall(renderGrokDocument(
document,
removeManagedGrokHooks(document.hooks, 'agent-1'),
));
await commitGrokUninstall(prepared, async () => {
throw new Error('injected Grok uninstall failure');
});
`;
const result = await runFixtureSource(fixture, source);
assert.equal(result.code, 1);
assert.match(result.stderr, /injected Grok uninstall failure/i);
assert.equal(await readFile(fixture.configPath, 'utf-8'), before);
await assertNoTransactionFiles(fixture);
} finally {
await fixture.close();
}
});