mirror of
https://github.com/garrytan/gstack.git
synced 2026-11-23 00:21:14 +01:00
gstack's Codex hooks keep working with unusual folder paths and after uninstall (GST-3197) (#4528)
gstack's Codex hooks no longer block every prompt when your Codex folder's path has a `(` or `&`, and uninstall keeps your own Codex hooks trusted. Why: both broke Codex sessions; setup also now matches Codex's hook rules, and the /review checklist on Codex reads shell commands more carefully. Nothing to do: plain paths keep the exact hook command they had, so Codex asks for no new trust. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> Review-Finding: p1/specialist-batched#1 reader=red-team Review-Finding: lib/codex-rollout.ts:217:functional-contract reader=qa
This commit is contained in:
1 parent
bd449234aa
commit
9610ba43db
11 files changed
+557
-50
No files matched your search
@@ -105,6 +105,30 @@ async function codexAgainstStub(prompt: string): Promise<string[]> {
|
||||
return bodies;
|
||||
}
|
||||
|
||||
/** Codex's own view of its hooks: app-server's hooks/list gives each handler's trust key, current hash and status. */
|
||||
async function listHooks(): Promise<{ hooks: { key: string; command?: string; currentHash: string; trustStatus: string }[]; warnings: string[]; errors: unknown[] }> {
|
||||
const child = spawn('codex', ['app-server'], {
|
||||
cwd: dir, stdio: ['pipe', 'pipe', 'ignore'],
|
||||
env: { PATH: process.env.PATH ?? '', HOME: dir, CODEX_HOME: home(), OPENAI_API_KEY: 'sk-not-a-real-key' },
|
||||
});
|
||||
let out = '';
|
||||
child.stdout.on('data', d => { out += d; });
|
||||
for (const msg of [
|
||||
{ jsonrpc: '2.0', id: 1, method: 'initialize', params: { clientInfo: { name: 'gstack-test', version: '1' } } },
|
||||
{ jsonrpc: '2.0', method: 'initialized' },
|
||||
{ jsonrpc: '2.0', id: 2, method: 'hooks/list', params: { cwds: [dir] } },
|
||||
]) child.stdin.write(JSON.stringify(msg) + '\n');
|
||||
const deadline = Date.now() + 30_000;
|
||||
let reply: any;
|
||||
while (Date.now() < deadline && !reply) {
|
||||
reply = out.split('\n').filter(Boolean).map(l => { try { return JSON.parse(l); } catch { return null; } }).find(m => m?.id === 2);
|
||||
if (!reply) await Bun.sleep(100);
|
||||
}
|
||||
child.kill('SIGKILL');
|
||||
if (!reply?.result) throw new Error('codex app-server gave no hooks/list reply: ' + out.slice(-500));
|
||||
return reply.result.data[0];
|
||||
}
|
||||
|
||||
describe.skipIf(!usable && !required)('real codex reads the hooks.json gstack writes', () => {
|
||||
test('codex 0.170 or newer is on PATH', () => {
|
||||
expect(version?.[0] ?? 'no codex on PATH').toMatch(/^codex-cli /);
|
||||
@@ -132,6 +156,43 @@ describe.skipIf(!usable && !required)('real codex reads the hooks.json gstack wr
|
||||
expect((await codexAgainstStub('$gstack-review look at this')).join('\n')).not.toContain('REAL_CODEX_SKILL_BODY');
|
||||
}, 200_000);
|
||||
|
||||
test("removing gstack's group before yours leaves an empty group, and Codex still trusts your hook at the same key", async () => {
|
||||
fs.mkdirSync(home(), { recursive: true });
|
||||
const file = path.join(home(), 'hooks.json');
|
||||
const gstackGuard = path.join(home(), 'skills', 'gstack', 'hosts', 'codex', 'hooks', 'codex-destructive-guard-hook');
|
||||
const mine = { matcher: 'Bash', hooks: [{ type: 'command', command: '/usr/local/bin/my-guard', timeout: 3 }] };
|
||||
fs.writeFileSync(file, JSON.stringify({ hooks: { PreToolUse: [{ matcher: 'Bash', hooks: [{ type: 'command', command: gstackGuard, timeout: 10 }] }, mine] } }, null, 2));
|
||||
const before = (await listHooks()).hooks.find(h => h.command === '/usr/local/bin/my-guard')!;
|
||||
expect(before.key).toBe(fs.realpathSync(file) + ':pre_tool_use:1:0');
|
||||
fs.writeFileSync(path.join(home(), 'config.toml'), '[hooks.state."' + before.key + '"]\ntrusted_hash = "' + before.currentHash + '"\n');
|
||||
expect((await listHooks()).hooks.find(h => h.key === before.key)?.trustStatus).toBe('trusted');
|
||||
const r = spawnSync('bash', [path.join(ROOT, 'bin', 'gstack-settings-hook'), 'prune-stale', '--all'], {
|
||||
env: { PATH: process.env.PATH ?? '', HOME: dir, GSTACK_HOOKS_FORMAT: 'codex', CODEX_HOME: home() }, encoding: 'utf8', timeout: 30_000,
|
||||
});
|
||||
expect(r.status).toBe(0);
|
||||
expect(JSON.parse(fs.readFileSync(file, 'utf8')).hooks.PreToolUse).toEqual([{ hooks: [] }, mine]);
|
||||
const after = await listHooks();
|
||||
expect(after.warnings).toEqual([]);
|
||||
expect(after.errors).toEqual([]);
|
||||
expect(after.hooks.map(h => [h.key, h.trustStatus])).toEqual([[before.key, 'trusted']]);
|
||||
fs.writeFileSync(file, JSON.stringify({ hooks: { PreToolUse: [mine] } }, null, 2));
|
||||
expect((await listHooks()).hooks.map(h => [h.key.split(':').slice(-2).join(':'), h.trustStatus])).toEqual([['0:0', 'untrusted']]);
|
||||
}, 120_000);
|
||||
|
||||
test('a hook path with ( in it runs under Codex instead of exiting 2, which Codex reads as a block on every prompt', async () => {
|
||||
install();
|
||||
const odd = path.join(dir, 'hooks(2)');
|
||||
fs.symlinkSync(path.join(ROOT, 'hosts', 'codex', 'hooks'), odd);
|
||||
const r = spawnSync('bash', [path.join(ROOT, 'bin', 'gstack-settings-hook'), 'ensure-event', '--event', 'UserPromptSubmit', '--command', path.join(odd, 'codex-skill-route-hook'), '--source', 'gstack-skill-route', '--timeout', '5'], {
|
||||
env: { PATH: process.env.PATH ?? '', HOME: dir, GSTACK_HOOKS_FORMAT: 'codex', CODEX_HOME: home() }, encoding: 'utf8', timeout: 30_000,
|
||||
});
|
||||
expect(r.status).toBe(0);
|
||||
const out = await codexExec(['--dangerously-bypass-hook-trust']);
|
||||
expect(fs.existsSync(marker())).toBe(true);
|
||||
expect(fs.readFileSync(routeLog(), 'utf8')).toMatch(/event=routed skill=review .*host=codex/);
|
||||
expect(out).not.toMatch(/blocked|exit code 2|syntax error/i);
|
||||
}, 90_000);
|
||||
|
||||
test('negative controls: an unknown key makes Codex skip the whole file, and untrusted hooks never run', async () => {
|
||||
install();
|
||||
const file = path.join(home(), 'hooks.json');
|
||||
|
||||
@@ -48,6 +48,27 @@ describe('setup: Codex hook registration', () => {
|
||||
}
|
||||
});
|
||||
|
||||
test('a Windows install copies the Claude hooks the Codex shims import, so the copied shims run under bash instead of failing open', () => {
|
||||
const root = path.join(dir, 'codex', 'skills', 'gstack');
|
||||
const script = ['set -e', 'IS_WINDOWS=1', '_CODEX_RENDER_ROOT="' + ROOT + '"', ...['_link_or_copy', '_copy_skill_md', '_link_runtime_dists', '_link_codex_skill_refs', 'create_codex_runtime_root'].map(fnBody),
|
||||
'create_codex_runtime_root "' + ROOT + '" "' + root + '"'].join('\n');
|
||||
const made = run(script);
|
||||
expect(made.code).toBe(0);
|
||||
expect(fs.lstatSync(path.join(root, 'hosts', 'claude', 'hooks')).isSymbolicLink()).toBe(false);
|
||||
const payloads = JSON.parse(fs.readFileSync(path.join(ROOT, 'test', 'fixtures', 'codex-hooks', 'codex-0.170-payloads.json'), 'utf8'));
|
||||
const shim = (name: string, payload: unknown) => spawnSync('bash', [path.join(root, 'hosts', 'codex', 'hooks', name)], {
|
||||
input: JSON.stringify(payload), encoding: 'utf8', timeout: 30_000,
|
||||
env: { PATH: process.env.PATH ?? '', HOME: dir, GSTACK_STATE_ROOT: path.join(dir, 'state') },
|
||||
});
|
||||
const guard = shim('codex-destructive-guard-hook', payloads.PreToolUse);
|
||||
expect(guard.status).toBe(0);
|
||||
expect(JSON.parse(guard.stdout).hookSpecificOutput.permissionDecision).toBe('deny');
|
||||
for (const [name, payload] of [['codex-skill-route-hook', payloads.UserPromptSubmit], ['codex-skill-contract-stop-hook', { hook_event_name: 'Stop', stop_hook_active: false }]] as const) {
|
||||
const r = shim(name, payload);
|
||||
expect({ name, status: r.status, stderr: r.stderr }).toEqual({ name, status: 0, stderr: expect.not.stringMatching(/Cannot find|ResolveMessage|error:/i) });
|
||||
}
|
||||
});
|
||||
|
||||
/** One gate run with Codex selected and Claude not: SETTINGS_HOOK is empty, as setup leaves it for --host codex. */
|
||||
function gate(key: 'skill_routing' | 'destructive_guard' | 'skill_contracts', mode: string, env: Record<string, string> = {}, noTeam = 0) {
|
||||
const runtimeRoot = path.join(dir, 'codex', 'skills', 'gstack');
|
||||
@@ -161,6 +182,43 @@ describe('gstack-uninstall and gstack-doctor with Codex hooks', () => {
|
||||
expect(JSON.parse(fs.readFileSync(path.join(home, '.codex', 'hooks.json'), 'utf8'))).toEqual({ hooks: { PreToolUse: [user] } });
|
||||
});
|
||||
|
||||
const uninstall = () => {
|
||||
const home = path.join(dir, 'home');
|
||||
fs.mkdirSync(path.join(dir, 'repo'), { recursive: true });
|
||||
const r = spawnSync('bash', [path.join(ROOT, 'bin', 'gstack-uninstall'), '--force', '--keep-state'], {
|
||||
env: { PATH: process.env.PATH ?? '', HOME: home, CODEX_HOME: path.join(home, '.codex'), GSTACK_STATE_DIR: path.join(home, '.gstack') },
|
||||
cwd: path.join(dir, 'repo'), encoding: 'utf8', timeout: 60_000,
|
||||
});
|
||||
return { ...r, file: path.join(home, '.codex', 'hooks.json') };
|
||||
};
|
||||
|
||||
test("uninstall with your own group after gstack's removes gstack's handler and leaves an empty group, so your hook keeps its trust position", () => {
|
||||
const { user } = seed();
|
||||
const file = path.join(dir, 'home', '.codex', 'hooks.json');
|
||||
const doc = JSON.parse(fs.readFileSync(file, 'utf8'));
|
||||
doc.hooks.PreToolUse.reverse();
|
||||
fs.writeFileSync(file, JSON.stringify(doc, null, 2));
|
||||
const r = uninstall();
|
||||
expect(r.status).toBe(0);
|
||||
expect(r.stdout).toContain("gstack's Codex hooks in " + r.file);
|
||||
expect(r.stderr).not.toContain('WARNING');
|
||||
expect(JSON.parse(fs.readFileSync(r.file, 'utf8'))).toEqual({ hooks: { PreToolUse: [{ hooks: [] }, user] } });
|
||||
});
|
||||
|
||||
test("uninstall says so, naming the one handler to delete, when your handler sits inside gstack's group", () => {
|
||||
seed();
|
||||
const file = path.join(dir, 'home', '.codex', 'hooks.json');
|
||||
const doc = JSON.parse(fs.readFileSync(file, 'utf8'));
|
||||
doc.hooks.PreToolUse[1].hooks.push({ type: 'command', command: '/usr/local/bin/my-inner-guard' });
|
||||
fs.writeFileSync(file, JSON.stringify(doc, null, 2));
|
||||
const r = uninstall();
|
||||
expect(r.status).toBe(0);
|
||||
expect(r.stderr).toContain("WARNING: gstack's Codex hooks are still in " + r.file + ' and will fail once gstack is removed.');
|
||||
expect(r.stderr).toContain('delete only the gstack handlers hooks.PreToolUse[1].hooks[0] (command ');
|
||||
expect(r.stderr).not.toContain('delete its group');
|
||||
expect(JSON.parse(fs.readFileSync(r.file, 'utf8'))).toEqual(doc);
|
||||
});
|
||||
|
||||
test('the doctor row says whether each hook has a trust entry, and prints nothing without gstack hooks', () => {
|
||||
seed();
|
||||
const doctor = fs.readFileSync(path.join(ROOT, 'bin', 'gstack-doctor'), 'utf8');
|
||||
|
||||
+136
-9
@@ -157,7 +157,7 @@ describe('gstack-settings-hook: Codex hooks.json format', () => {
|
||||
test('trust-status reads the key Codex writes (<hooks.json>:<event>:<group>:<handler>) and never computes a hash', () => {
|
||||
writeUser();
|
||||
ensureRoute(); ensureGuard();
|
||||
expect(settingsHook(['trust-status']).out.trim().split('\n').sort()).toEqual([
|
||||
expect(settingsHook(['trust-status'], { CODEX_HOME: dir }).out.trim().split('\n').sort()).toEqual([
|
||||
'gstack-destructive-guard\tPreToolUse\tuntrusted', 'gstack-skill-route\tUserPromptSubmit\tuntrusted',
|
||||
]);
|
||||
const file = fs.realpathSync(hooksFile());
|
||||
@@ -167,30 +167,48 @@ describe('gstack-settings-hook: Codex hooks.json format', () => {
|
||||
'[hooks.state."' + file + ':pre_tool_use:1:0"]', 'trusted_hash = "sha256:bb"', '',
|
||||
'[hooks.state."' + file + ':user_prompt_submit:1:0"]', 'enabled = false', 'trusted_hash = "sha256:cc"', '',
|
||||
].join('\n'));
|
||||
expect(settingsHook(['trust-status']).out.trim().split('\n').sort()).toEqual([
|
||||
expect(settingsHook(['trust-status'], { CODEX_HOME: dir }).out.trim().split('\n').sort()).toEqual([
|
||||
'gstack-destructive-guard\tPreToolUse\ttrusted', 'gstack-skill-route\tUserPromptSubmit\tdisabled',
|
||||
]);
|
||||
expect(settingsHook(['trust-status'], { GSTACK_HOOKS_FORMAT: '' }).code).toBe(1);
|
||||
});
|
||||
|
||||
test('removing a gstack group that one of your hooks follows in the same event refuses and leaves the file as it was, so Codex keeps trusting your hook', () => {
|
||||
test('removing a gstack group that one of your groups follows leaves an empty group in its place, so your hooks keep their trust positions', () => {
|
||||
writeUser();
|
||||
ensureRoute(); ensureGuard();
|
||||
const doc = read();
|
||||
doc.hooks.PreToolUse.push({ matcher: 'Bash', hooks: [{ type: 'command', command: '/usr/local/bin/my-late-guard' }] });
|
||||
const late = { matcher: 'Bash', hooks: [{ type: 'command', command: '/usr/local/bin/my-late-guard' }] };
|
||||
doc.hooks.PreToolUse.push(late);
|
||||
writeUser(doc);
|
||||
for (const args of [['remove-source', '--source', 'gstack-destructive-guard'], ['prune-stale', '--all']]) {
|
||||
writeUser(doc);
|
||||
const r = settingsHook(args);
|
||||
expect(r.code).toBe(0);
|
||||
expect(read().hooks.PreToolUse).toEqual([USER_FILE.hooks.PreToolUse[0], { hooks: [] }, late]);
|
||||
codexKeysOnly(read());
|
||||
}
|
||||
expect(read().hooks.UserPromptSubmit).toEqual(USER_FILE.hooks.UserPromptSubmit);
|
||||
expect(read().hooks.Stop).toEqual(USER_FILE.hooks.Stop);
|
||||
expect(ensureGuard().out).toContain('registered');
|
||||
expect(read().hooks.PreToolUse.slice(0, 3)).toEqual([USER_FILE.hooks.PreToolUse[0], { hooks: [] }, late]);
|
||||
});
|
||||
|
||||
test('when one of your handlers follows the gstack handler inside its group, removal refuses and names only the gstack handler to delete', () => {
|
||||
writeUser();
|
||||
ensureGuard();
|
||||
const doc = read();
|
||||
doc.hooks.PreToolUse[1].hooks.push({ type: 'command', command: '/usr/local/bin/my-inner-guard' });
|
||||
writeUser(doc);
|
||||
const text = fs.readFileSync(hooksFile(), 'utf8');
|
||||
for (const args of [['remove-source', '--source', 'gstack-destructive-guard'], ['prune-stale', '--all']]) {
|
||||
const r = settingsHook(args);
|
||||
expect(r.code).toBe(3);
|
||||
expect(r.out).toContain('would move your own PreToolUse hooks');
|
||||
expect(r.out).toContain('re-trust your hooks in Codex with /hooks');
|
||||
expect(r.out).toContain('delete only the gstack handler hooks.PreToolUse[1].hooks[0] (command ' + JSON.stringify(GUARD_CMD()) + ')');
|
||||
expect(r.out).toContain('keeping your own handlers and groups as they are, then re-trust your hooks in Codex with /hooks');
|
||||
expect(r.out).not.toContain('delete its group');
|
||||
expect(fs.readFileSync(hooksFile(), 'utf8')).toBe(text);
|
||||
}
|
||||
expect(ensureGuard().out).toContain('unchanged');
|
||||
expect(settingsHook(['remove-source', '--source', 'gstack-skill-route']).code).toBe(0);
|
||||
expect(read().hooks.UserPromptSubmit).toEqual(USER_FILE.hooks.UserPromptSubmit);
|
||||
expect(read().hooks.PreToolUse).toEqual(doc.hooks.PreToolUse);
|
||||
});
|
||||
|
||||
test('a symlinked hooks.json still reads config.toml from the Codex home, not from beside the link target', () => {
|
||||
@@ -240,6 +258,115 @@ describe('gstack-settings-hook: Codex hooks.json format', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('gstack-settings-hook: hardening after #4512 and #4522 (GST-3197)', () => {
|
||||
const runUnder = (shell: string[], command: string) => spawnSync(shell[0], [...shell.slice(1), command], { input: '{}', encoding: 'utf8', timeout: 30_000, env: { PATH: process.env.PATH ?? '', HOME: dir } });
|
||||
const fakeHook = (file: string) => {
|
||||
fs.mkdirSync(path.dirname(file), { recursive: true });
|
||||
fs.writeFileSync(file, '#!/bin/sh\necho RAN_HOOK\n', { mode: 0o755 });
|
||||
};
|
||||
|
||||
test('a home path with ( or & gives commands both hosts run: no exit 2, which Codex would read as a block on every prompt and Bash call', () => {
|
||||
const root = path.join(dir, 'codex(old)&co', 'skills', 'gstack');
|
||||
fakeHook(ROUTE_CMD(root));
|
||||
expect(ensureRoute(root).out).toContain('registered');
|
||||
const codexCmd = read().hooks.UserPromptSubmit[0].hooks[0].command;
|
||||
const settings = path.join(dir, 'settings.json');
|
||||
const claudeHook = path.join(root, 'hosts', 'claude', 'hooks', 'skill-route-hook');
|
||||
fakeHook(claudeHook);
|
||||
expect(settingsHook(['ensure-event', '--event', 'UserPromptSubmit', '--command', claudeHook, '--source', 'gstack-skill-route', '--timeout', '5'], { GSTACK_HOOKS_FORMAT: '', GSTACK_SETTINGS_FILE: settings }).code).toBe(0);
|
||||
const claudeCmd = JSON.parse(fs.readFileSync(settings, 'utf8')).hooks.UserPromptSubmit[0].hooks[0].command;
|
||||
for (const cmd of [codexCmd, claudeCmd]) {
|
||||
for (const shell of [['bash', '-lc'], ['sh', '-c']]) {
|
||||
const r = runUnder(shell, cmd);
|
||||
expect({ shell: shell[0], status: r.status, out: r.stdout.trim() }).toEqual({ shell: shell[0], status: 0, out: 'RAN_HOOK' });
|
||||
}
|
||||
}
|
||||
expect(ensureRoute(root).out).toContain('unchanged');
|
||||
});
|
||||
|
||||
test('plain paths keep their unquoted commands, so no install is asked to re-trust its hooks', () => {
|
||||
expect(ensureRoute().code).toBe(0);
|
||||
expect(read().hooks.UserPromptSubmit[0].hooks[0].command).toBe(ROUTE_CMD());
|
||||
const accented = path.join(dir, 'Jos\u00e9', 'skills', 'gstack');
|
||||
expect(ensureRoute(accented).out).toContain('re-pointed');
|
||||
expect(read().hooks.UserPromptSubmit[0].hooks[0].command).toBe(ROUTE_CMD(accented));
|
||||
});
|
||||
|
||||
test('schema parity with Codex 0.170: description null is accepted; a null anywhere in MCP hook input is refused', () => {
|
||||
writeUser({ description: null, hooks: {} });
|
||||
expect(ensureRoute().code).toBe(0);
|
||||
expect(read().description).toBeNull();
|
||||
const mcp = (input: unknown) => ({ hooks: { Stop: [{ hooks: [{ type: 'mcp_tool', server: 's', tool: 't', input }] }] } });
|
||||
for (const input of [{ optional: null }, { metadata: { optional: null } }, { values: [null] }, { big: 18446744073709551615 }]) {
|
||||
const text = JSON.stringify(mcp(input));
|
||||
fs.writeFileSync(hooksFile(), text);
|
||||
const r = ensureRoute();
|
||||
expect(r.code).toBe(3);
|
||||
expect(r.out).toContain('input holds a null or an integer too large for TOML, which Codex rejects');
|
||||
expect(fs.readFileSync(hooksFile(), 'utf8')).toBe(text);
|
||||
}
|
||||
writeUser(mcp({ metadata: { depth: 1, tags: ['a', true, -2.5] } }));
|
||||
expect(ensureRoute().code).toBe(0);
|
||||
});
|
||||
|
||||
test('rollback refuses a backup Codex would skip and leaves the live file as it is', () => {
|
||||
writeUser();
|
||||
ensureRoute();
|
||||
const live = fs.readFileSync(hooksFile(), 'utf8');
|
||||
const backup = fs.readFileSync(path.join(dir, 'hooks.json.bak-latest'), 'utf8').trim();
|
||||
for (const bad of [JSON.stringify({ hooks: {}, _gstack_source: 'x' }), '{ "hooks": ']) {
|
||||
fs.writeFileSync(backup, bad);
|
||||
const r = settingsHook(['rollback']);
|
||||
expect(r.code).toBe(3);
|
||||
expect(r.out).toContain('does not match the Codex hooks.json schema');
|
||||
expect(fs.readFileSync(hooksFile(), 'utf8')).toBe(live);
|
||||
}
|
||||
fs.writeFileSync(backup, JSON.stringify(USER_FILE, null, 2) + '\n');
|
||||
expect(settingsHook(['rollback']).code).toBe(0);
|
||||
expect(read()).toEqual(USER_FILE);
|
||||
});
|
||||
|
||||
test('config.toml declaring the gstack guard under any matcher that selects Bash is a clash; matchers that never select Bash are not', () => {
|
||||
writeUser();
|
||||
const cfg = path.join(dir, 'config.toml');
|
||||
const declare = (matcher: string | null) => fs.writeFileSync(cfg, '[[hooks.PreToolUse]]\n' + (matcher === null ? '' : 'matcher = ' + JSON.stringify(matcher) + '\n') + '[[hooks.PreToolUse.hooks]]\ntype = "command"\ncommand = "' + GUARD_CMD() + '"\n');
|
||||
for (const matcher of ['^Bash$', 'Bash|PowerShell', '*', '', null, 'B.sh', '(unclosed']) {
|
||||
declare(matcher);
|
||||
const r = ensureGuard();
|
||||
expect({ matcher, code: r.code }).toEqual({ matcher, code: 3 });
|
||||
expect(r.out).toContain('already declares gstack hook gstack-destructive-guard under [hooks.PreToolUse], and Codex would run it twice');
|
||||
}
|
||||
expect(read()).toEqual(USER_FILE);
|
||||
for (const matcher of ['\\ABash\\z', '(?i)^bash$']) {
|
||||
declare(matcher);
|
||||
expect({ matcher, code: ensureGuard().code }).toEqual({ matcher, code: 3 });
|
||||
}
|
||||
for (const matcher of ['PowerShell', '^Edit$', 'apply_patch|Write', '(?i)^Edit$', '\\AEdit\\z']) {
|
||||
declare(matcher);
|
||||
expect({ matcher, code: ensureGuard().code }).toEqual({ matcher, code: 0 });
|
||||
}
|
||||
});
|
||||
|
||||
test('trust-status keys on the hooks.json in the canonical CODEX_HOME, the way Codex does, even when hooks.json itself is a link', () => {
|
||||
const real = path.join(dir, 'real-codex');
|
||||
const link = path.join(dir, 'codex-link');
|
||||
const dotfiles = path.join(dir, 'dotfiles');
|
||||
fs.mkdirSync(real); fs.mkdirSync(dotfiles);
|
||||
fs.symlinkSync(real, link);
|
||||
fs.writeFileSync(path.join(dotfiles, 'hooks.json'), JSON.stringify(USER_FILE, null, 2) + '\n');
|
||||
fs.symlinkSync(path.join(dotfiles, 'hooks.json'), path.join(real, 'hooks.json'));
|
||||
const env = { CODEX_HOME: link, GSTACK_SETTINGS_FILE: '' };
|
||||
expect(settingsHook(['ensure-event', '--event', 'UserPromptSubmit', '--command', ROUTE_CMD(), '--source', 'gstack-skill-route', '--timeout', '5'], env).code).toBe(0);
|
||||
const trust = (keyFile: string) => {
|
||||
fs.writeFileSync(path.join(real, 'config.toml'), '[hooks.state."' + keyFile + ':user_prompt_submit:1:0"]\ntrusted_hash = "sha256:aa"\n');
|
||||
return settingsHook(['trust-status'], env).out.trim();
|
||||
};
|
||||
expect(trust(path.join(fs.realpathSync(real), 'hooks.json'))).toBe('gstack-skill-route\tUserPromptSubmit\ttrusted');
|
||||
expect(trust(path.join(link, 'hooks.json'))).toBe('gstack-skill-route\tUserPromptSubmit\tuntrusted');
|
||||
expect(trust(fs.realpathSync(path.join(dotfiles, 'hooks.json')))).toBe('gstack-skill-route\tUserPromptSubmit\tuntrusted');
|
||||
});
|
||||
});
|
||||
|
||||
const route = (skill: string, trigger: string): RouteCandidate => ({ skill, score: 1, matched: 3, trigger, file: '/x/SKILL.md', gstack: true });
|
||||
|
||||
describe('skill routing on Codex', () => {
|
||||
|
||||
@@ -104,6 +104,67 @@ describe('loads: Codex reading or injecting a gstack-* SKILL.md', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('reads: shell edge cases from the #4522 notes (GST-3197)', () => {
|
||||
const meta = lines('exec-read-met.jsonl')[0];
|
||||
const record = (payload: Record<string, unknown>) => JSON.stringify({ type: 'response_item', payload });
|
||||
const user = record({ type: 'message', role: 'user', content: [{ type: 'input_text', text: 'review this' }] });
|
||||
const call = (cmd: string, id = 'c1') => record({ type: 'function_call', name: 'exec_command', arguments: JSON.stringify({ cmd }), call_id: id });
|
||||
const result = (output: string, id = 'c1') => record({ type: 'function_call_output', call_id: id, output });
|
||||
const loads = (cmd: string, output?: string) => skillLoads(parseTranscript([meta, user, call(cmd), ...(output === undefined ? [] : [result(output)])].join('\n'))).map(l => l.skill);
|
||||
const READ = 'cat ~/.codex/skills/gstack-review/SKILL.md';
|
||||
|
||||
test('A: a read that an earlier && command kept from running is not a load; a read before a later failure still is', () => {
|
||||
expect(loads('cd /nope && ' + READ, 'Process exited with code 1\nOutput:\nbash: line 1: cd: /nope: No such file or directory')).toEqual([]);
|
||||
expect(loads('cd /repo && ' + READ, 'Process exited with code 0\nOutput:\n---\nname: review')).toEqual(['gstack-review']);
|
||||
expect(loads('cd /repo && ' + READ + ' && git diff missing-ref', "Process exited with code 128\nOutput:\n---\nfatal: bad revision 'missing-ref'")).toEqual(['gstack-review']);
|
||||
expect(loads('cd /nope && ' + READ)).toEqual(['gstack-review']);
|
||||
expect(loads('cd /nope && { ' + READ + '; }', 'Process exited with code 1\nOutput:\n')).toEqual(['gstack-review']);
|
||||
});
|
||||
|
||||
test("B: ; inside quotes does not split a command, so sed -n '1,200p;201q' is a read", () => {
|
||||
expect(loads("sed -n '1,200p;201q' ~/.codex/skills/gstack-review/SKILL.md", 'Process exited with code 0\nOutput:\n---')).toEqual(['gstack-review']);
|
||||
expect(loads('sed -n "1,200p;201q" ~/.codex/skills/gstack-review/SKILL.md')).toEqual(['gstack-review']);
|
||||
expect(loads('echo x; ' + READ)).toEqual(['gstack-review']);
|
||||
});
|
||||
|
||||
test('C: a user turn holding only an image ends the run, so the next read of the same skill is a new load', () => {
|
||||
const image = record({ type: 'message', role: 'user', content: [{ type: 'input_image', image_url: 'data:image/png;base64,AAAA' }] });
|
||||
const t = (between: string[]) => parseTranscript([meta, user, call(READ, 'a'), result('Process exited with code 0\nOutput:\n---', 'a'), ...between, call(READ, 'b'), result('Process exited with code 0\nOutput:\n---', 'b')].join('\n'));
|
||||
expect(skillLoads(t([image]))).toHaveLength(2);
|
||||
expect(skillLoads(t([]))).toHaveLength(1);
|
||||
});
|
||||
|
||||
test('a || fallback whose first read fails loads from the second; the error names only the first path', () => {
|
||||
expect(loads(READ + ' || cat ~/.agents/skills/gstack-review/SKILL.md', 'Process exited with code 0\nOutput:\ncat: /home/u/.codex/skills/gstack-review/SKILL.md: No such file or directory\n---\nname: review')).toEqual(['gstack-review']);
|
||||
expect(loads(READ + ' || cat ~/.agents/skills/gstack-review/SKILL.md', 'Process exited with code 1\nOutput:\ncat: /home/u/.codex/skills/gstack-review/SKILL.md: No such file or directory\ncat: /home/u/.agents/skills/gstack-review/SKILL.md: No such file or directory')).toEqual([]);
|
||||
});
|
||||
|
||||
test('a read error must name the path itself: SKILL.md.bak or another skill folder does not drop a good read', () => {
|
||||
expect(loads(READ + '; ls ~/.codex/skills/gstack-review/SKILL.md.bak', "Process exited with code 2\nOutput:\n---\nls: cannot access '/home/u/.codex/skills/gstack-review/SKILL.md.bak': No such file or directory")).toEqual(['gstack-review']);
|
||||
expect(loads(READ, "Process exited with code 1\nOutput:\ncat: /home/u/.codex/skills/gstack-review/SKILL.md: Permission denied")).toEqual([]);
|
||||
});
|
||||
|
||||
test('an error line that does not provably name another file still drops the read', () => {
|
||||
expect(loads('cat "$(realpath -m ~/.codex/skills/gstack-review/SKILL.md)"', 'Process exited with code 1\nOutput:\ncat: /home/u/dotfiles/skills/gstack-review/SKILL.md: No such file or directory')).toEqual([]);
|
||||
expect(loads('cd ~/.codex/skills/gstack-review && cat SKILL.md', 'Process exited with code 1\nOutput:\ncat: SKILL.md: No such file or directory')).toEqual([]);
|
||||
expect(loads(READ + '; cat /tmp/notes.txt', 'Process exited with code 1\nOutput:\n---\nname: review\ncat: /tmp/notes.txt: No such file or directory')).toEqual(['gstack-review']);
|
||||
});
|
||||
|
||||
test('a multi-file read whose other file fails still loads', () => {
|
||||
expect(loads(READ + ' /tmp/x', 'Process exited with code 1\nOutput:\n---\nname: review\ncat: /tmp/x: No such file or directory')).toEqual(['gstack-review']);
|
||||
});
|
||||
|
||||
test('a one-file read that exits non-zero with no error text is not a load', () => {
|
||||
expect(loads(READ, 'Process exited with code 1\nOutput:\n')).toEqual([]);
|
||||
expect(loads("sed -n '1,200p' ~/.codex/skills/gstack-review/SKILL.md", 'Process exited with code 1\nOutput:\n')).toEqual([]);
|
||||
});
|
||||
|
||||
test("PowerShell's Cannot find path is a read error", () => {
|
||||
expect(loads('Get-Content C:\\Users\\u\\.codex\\skills\\gstack-review\\SKILL.md', "Get-Content: Cannot find path 'C:\\Users\\u\\.codex\\skills\\gstack-review\\SKILL.md' because it does not exist.")).toEqual([]);
|
||||
expect(loads('Get-Content C:\\Users\\u\\.codex\\skills\\gstack-review\\SKILL.md', '---\nname: review')).toEqual(['gstack-review']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('chunked reads: reading the same SKILL.md again continues the run', () => {
|
||||
const met = lines('exec-read-met.jsonl');
|
||||
const spawnAt = met.findIndex(l => l.includes('"function_call"') && l.includes('spawn_agent') && met.some(o => o.includes('function_call_output') && o.includes(JSON.parse(l).payload.call_id) && o.includes('agent_id')));
|
||||
|
||||
Reference in new issue
Block a user