Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
135 changes: 118 additions & 17 deletions bin/gstack-settings-hook

Large diffs are not rendered by default.

10 changes: 8 additions & 2 deletions bin/gstack-uninstall
Original file line number Diff line number Diff line change
Expand Up @@ -618,9 +618,15 @@ fi
# that rm -rf this cleanup would silently skip. Only gstack's own matcher groups
# go (the KNOWN_HOOKS rows marked host codex); the user's groups stay as they are.
CODEX_HOOKS_FILE="${CODEX_HOME:-$HOME/.codex}/hooks.json"
# A gstack group that the user's own groups follow becomes an empty group, so
# their trust positions hold. When gstack-settings-hook still refuses (one of
# the user's handlers sits inside gstack's group), say so: its message names
# the exact handler to delete, and the hook would fail once this install is gone.
if [ -x "$SETTINGS_HOOK" ] && [ -f "$CODEX_HOOKS_FILE" ]; then
if GSTACK_HOOKS_FORMAT=codex GSTACK_SETTINGS_FILE="$CODEX_HOOKS_FILE" "$SETTINGS_HOOK" prune-stale --all | grep -q "removed [1-9]"; then
REMOVED+=("gstack's Codex hooks in $CODEX_HOOKS_FILE")
if _CODEX_PRUNE=$(GSTACK_HOOKS_FORMAT=codex GSTACK_SETTINGS_FILE="$CODEX_HOOKS_FILE" "$SETTINGS_HOOK" prune-stale --all 2>&1); then
case "$_CODEX_PRUNE" in *"removed "[1-9]*) REMOVED+=("gstack's Codex hooks in $CODEX_HOOKS_FILE") ;; esac
else
echo "WARNING: gstack's Codex hooks are still in $CODEX_HOOKS_FILE and will fail once gstack is removed. $(printf '%s\n' "$_CODEX_PRUNE" | sed -n 's/^gstack-settings-hook: //p' | head -1)" >&2
fi
fi

Expand Down
5 changes: 5 additions & 0 deletions changelog.d/codex-hooks-hardening.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
- **gstack's Codex hooks work when your Codex folder's path has a `(`, `&` or other shell character in it.** An unquoted `(` made the hook command a shell syntax error, which Codex reads as "block", so every prompt and Bash call was blocked once you trusted the hooks; an `&` split the command in two. Both Claude Code and Codex hook commands now quote those paths. A path made only of letters, digits and `_ @ % + = : , . / -` keeps the command it had; any other path is quoted once, so Codex asks you to trust those hooks again.
- **Uninstalling gstack keeps your own Codex hooks trusted.** When your hook groups come after gstack's in `hooks.json`, uninstall (and turning a hook off) now leaves an empty group where gstack's was, so your hooks keep the positions Codex trusts them by. If your handler sits inside gstack's group, gstack leaves the file alone and names the one handler to delete.
- **Codex hook setup matches Codex more closely.** `description: null` is accepted, MCP hook input with a null is refused, `rollback` won't restore a backup Codex would skip, a gstack hook already declared in `config.toml` under any matcher that covers Bash is caught (Rust's `(?i)`, `\A` and `\z` included), and `gstack-doctor` reads hook trust from the same key Codex uses when `CODEX_HOME` is a symlink.
- **On Windows, setup copies the Claude Code hook code that gstack's Codex hooks import** into Codex's gstack folder, so the hook scripts are complete. Native Windows Codex still starts hooks through `cmd.exe`, which can't run these Bash scripts, so the hooks don't run there yet.
- **/review's checklist on Codex reads shell commands more carefully.** A `;` inside quotes no longer splits a command, a read that never ran or failed isn't counted, a read error that names another file no longer drops a good read, PowerShell's "Cannot find path" counts as an error, and a message with only an image starts a new turn.
4 changes: 2 additions & 2 deletions docs/skill-routing-and-contracts.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,11 +83,11 @@ The hook reads `destructive_guard` every time it runs, so `gstack-config set des
<a id="codex"></a>
## Codex

`./setup --host codex` (or `./setup --host auto` when `codex` is on your PATH) registers the routing hook, the contract Stop hook and the destructive-command check in `${CODEX_HOME:-~/.codex}/hooks.json`, each in its own matcher group: routing on `UserPromptSubmit` with a 5-second timeout, the contract hook on `Stop` with a 10-second timeout (as on Claude Code), the check on `PreToolUse` for `Bash` with a 10-second timeout. The same three switches, in the same order, turn them on and off on both hosts; Codex adds its own two, a hook's toggle in `/hooks` and `[features] hooks = false` in `config.toml` for every hook at once.
`./setup --host codex` (or `./setup --host auto` when `codex` is on your PATH) registers the routing hook, the contract Stop hook and the destructive-command check in `${CODEX_HOME:-~/.codex}/hooks.json`, each in its own matcher group: routing on `UserPromptSubmit` with a 5-second timeout, the contract hook on `Stop` with a 10-second timeout (as on Claude Code), the check on `PreToolUse` for `Bash` with a 10-second timeout. The same three switches, in the same order, turn them on and off on both hosts; Codex adds its own two, a hook's toggle in `/hooks` and `[features] hooks = false` in `config.toml` for every hook at once. On native Windows, Codex starts hooks through `cmd.exe`, which can't run these Bash scripts, so gstack's Codex hooks don't run there yet.

**You trust them once.** Codex runs a hook only after you trust it, and skips an untrusted one without saying so. Setup never writes that trust. It prints one line, "gstack added 3 Codex hook(s); trust them at Codex's startup prompt or in /hooks", and the next time you start Codex it shows "Hooks need review": pick "Trust all and continue", or review them one by one in `/hooks`. `gstack-doctor` has a `codex hooks` row saying whether `config.toml` holds a trust entry for each of gstack's hooks. It only checks that an entry exists; it never computes Codex's hash. Codex asks again when a hook's command or timeout changes, so the commands point at the stable runtime root (`${CODEX_HOME:-~/.codex}/skills/gstack/hosts/codex/hooks/`), and an upgrade that only changes the scripts behind them asks nothing. Codex also keys trust by a group's position in the file, so setup adds gstack's groups after yours and never reorders them. Evals and CI that run `codex exec` pass `--dangerously-bypass-hook-trust`.

**Your own hooks stay as they are.** Codex 0.170 skips the whole `hooks.json` when it holds a key it does not know, your hooks included. So gstack adds no marker keys (it recognizes its groups by their command path), checks the new file against Codex's schema before moving it into place, and keeps the lock, the `hooks.json.bak.<ts>` backup and `gstack-settings-hook rollback` that `settings.json` has (`GSTACK_HOOKS_FORMAT=codex gstack-settings-hook rollback`). Setup leaves the file alone, prints why and carries on when the file does not parse or already fails Codex's schema, when `config.toml` does not parse, or when `config.toml` already declares one of gstack's hooks under `[hooks]` (Codex would run it twice). It also skips the hooks, saying why, when `codex` is missing or older than 0.170. `./setup --host codex --no-team` (plain `./setup --no-team` installs for Claude Code only, so it leaves the Codex hooks alone; `--host auto` with `codex` on your PATH also reaches them) and `gstack-uninstall` remove gstack's groups and nothing else. If one of your own hooks comes after gstack's group in the same event, removing gstack's group would shift yours to a new position and Codex would stop trusting it (`codex exec` skips an untrusted hook without asking). So gstack leaves the file unchanged and says so; delete gstack's group by hand and re-trust your hooks in `/hooks`.
**Your own hooks stay as they are.** Codex 0.170 skips the whole `hooks.json` when it holds a key it does not know, your hooks included. So gstack adds no marker keys (it recognizes its groups by their command path), checks the new file against Codex's schema before moving it into place, and keeps the lock, the `hooks.json.bak.<ts>` backup and `gstack-settings-hook rollback` that `settings.json` has (`GSTACK_HOOKS_FORMAT=codex gstack-settings-hook rollback`). Setup leaves the file alone, prints why and carries on when the file does not parse or already fails Codex's schema, when `config.toml` does not parse, or when `config.toml` already declares one of gstack's hooks under `[hooks]` (Codex would run it twice). It also skips the hooks, saying why, when `codex` is missing or older than 0.170. `./setup --host codex --no-team` (plain `./setup --no-team` installs for Claude Code only, so it leaves the Codex hooks alone; `--host auto` with `codex` on your PATH also reaches them) and `gstack-uninstall` remove gstack's groups and nothing else. Codex keys trust by position, so removing a group that your own groups come after would shift yours and Codex would stop trusting them (`codex exec` skips an untrusted hook without asking). So gstack leaves an empty group, `{ "hooks": [] }`, where its own was, and your hooks keep their positions; an emptied group at the end of an event is dropped. If one of your own handlers comes after gstack's inside the same group, gstack leaves the file unchanged and names the gstack handler to delete by hand; then re-trust your hooks in `/hooks`.

**Routing on Codex** scans `${CODEX_HOME:-~/.codex}/skills`, names each of gstack's skills by the `name:` in its installed `SKILL.md`, which is the name Codex lists and you mention with `$` (the `gstack-review` folder holds `name: review`, so `$review`), and takes their triggers from the same skill in gstack's checkout, because Codex's copies keep only a name and a description. A skill whose `name:` is missing or unreadable is named by its folder. The line reads "this request fits the review skill. Read and follow the review skill before you start". A prompt that starts with `$` (a Codex skill mention) or `/` is never routed.

Expand Down
21 changes: 17 additions & 4 deletions docs/uninstall.md
Original file line number Diff line number Diff line change
Expand Up @@ -132,10 +132,23 @@ the skill-routing UserPromptSubmit hook and the destructive-command PreToolUse h
on every matching event once the install directory is gone.

On Codex, manual removal also leaves gstack's hooks in
`${CODEX_HOME:-~/.codex}/hooks.json`. Delete each matcher group whose command
path points into `skills/gstack/hosts/codex/hooks/` (the skill-routing
`UserPromptSubmit` hook and the destructive-command `PreToolUse` hook), and keep
the rest of the file as it is.
`${CODEX_HOME:-~/.codex}/hooks.json`: the skill-routing `UserPromptSubmit`
hook, the destructive-command `PreToolUse` hook and the skill-contract `Stop`
hook. Delete only gstack's handlers, the entries in a group's `hooks` list
whose `command` points into `skills/gstack/hosts/codex/hooks/`, and keep your
own handlers and the rest of the file as they are. Codex remembers which hooks
you trusted by their position, so:

- If gstack's handler is the only one in its group and your own groups come
after it in the same event, leave the group in place as `{ "hooks": [] }`.
Your hooks keep their positions and stay trusted. (The uninstall script does
this for you.)
- If gstack's group is the last one in that event and holds only gstack's
handlers, delete the whole group. If it also holds one of yours, delete only
gstack's handler.
- If one of your handlers comes after gstack's inside the same group, deleting
gstack's handler moves yours up one place, so trust it again in Codex with
`/hooks`.

If the OpenClaw or Hermes [start hook](hosts.md#start-hook) is on (the default for a new registration),
manual removal also leaves its `gstack-start` plugin turned on. Turn it off
Expand Down
101 changes: 86 additions & 15 deletions lib/codex-rollout.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,15 @@
* - assistant message: text.
* - exec_command / shell call: a Bash tool_use whose command is the shell
* line; a command in it that reads a gstack-* SKILL.md under a skills/
* directory (cat, sed, head and the like) is also a skill load, unless
* the output says that read failed. Reading the same skill again with no
* user prompt or other skill load in between (a long SKILL.md read in
* chunks) continues the run, so it is not a new load.
* directory (cat, sed, head and the like) is also a skill load. The line
* splits into commands on &&, ||, ;, | and newlines outside quotes. A read
* does not count when an output line reports a read error for that path
* (matched up to the folder before skills/ when it is written out, and
* never as the prefix of a longer name), or when the read is the line's
* last simple command, names one file, and the call exited non-zero: that
* exit status is the read's own, so it failed or never ran. Reading the same skill again
* with no user turn (text or image) or other skill load in between (a long
* SKILL.md read in chunks) continues the run, so it is not a new load.
* - Codex's own spawn_agent call that started an agent: an Agent dispatch
* whose prompt is its message. Codex 0.170 answers a started agent with
* {"agent_id": ...} from its multi_agent_v1 namespace, or {"task_name":
Expand All @@ -38,8 +43,7 @@ const SKILL_INJECTION = /^\s*<skill>\s*<name>[^<]*<\/name>\s*<path>([^<]+)<\/pat
const GSTACK_SKILL_FILE = /(?:^|[\\/])skills[\\/](gstack-[A-Za-z0-9][A-Za-z0-9_-]*)[\\/]SKILL\.md$/;
const SHELL_SKILL_READ = /(?:^|[\\/\s'"=])skills[\\/](gstack-[A-Za-z0-9][A-Za-z0-9_-]*)[\\/]SKILL\.md(?=$|[\s'"`;|&)<>])/g;
const READ_PROGRAM = /(?:^|[\s;|&(`'"])(?:cat|sed|head|tail|nl|less|more|bat|awk|Get-Content)(?=\s)/;
const READ_FAILURE = /No such file|cannot open|can't read|cannot access|Permission denied|Is a directory/i;
const SHELL_SEPARATOR = /&&|\|\||[;|\n]/;
const READ_FAILURE = /No such file|cannot open|can't read|cannot access|Permission denied|Is a directory|Cannot find path/i;
const SHELL_TOOLS = new Set(['exec_command', 'shell', 'shell_command', 'local_shell']);
const EXIT_CODE = /(?:^|\n)Process exited with code (\d+)/;

Expand Down Expand Up @@ -76,13 +80,76 @@ function shellLine(input: Record<string, any>): string | null {
return null;
}

/** The gstack-* skills a shell line's read commands read, in order of appearance. */
function shellSkillReads(line: string): string[] {
return line.split(SHELL_SEPARATOR).filter(cmd => READ_PROGRAM.test(cmd)).flatMap(cmd => [...cmd.matchAll(SHELL_SKILL_READ)].map(m => m[1]));
/** A shell line's commands: split on &&, ||, ;, | and newlines that sit outside quotes and backslash escapes. */
function shellCommands(line: string): string[] {
const out: string[] = [];
let cur = '';
let quote = '';
for (let i = 0; i < line.length; i++) {
const c = line[i];
if (c === '\\' && quote !== "'" && i + 1 < line.length) { cur += c + line[++i]; continue; }
if (quote) { if (c === quote) quote = ''; cur += c; continue; }
if (c === "'" || c === '"') { quote = c; cur += c; continue; }
if ((c === '&' || c === '|') && line[i + 1] === c) { out.push(cur); cur = ''; i++; continue; }
if (c === ';' || c === '|' || c === '\n') { out.push(cur); cur = ''; continue; }
cur += c;
}
out.push(cur);
return out;
}

const readFailed = (output: string | undefined, skill: string) =>
(output ?? '').split('\n').some(l => READ_FAILURE.test(l) && new RegExp(`skills[\\\\/]${skill}[\\\\/]SKILL\\.md`).test(l));
interface ShellRead { skill: string; tail: string; last: boolean }

const READ_WORD = /^(?:.*[\\/])?(cat|sed|head|tail|nl|less|more|bat|awk|Get-Content)$/;

/** Whether a read command names one file: the words after its program, less options, numbers, redirections and a sed or awk script. */
function namesOneFile(cmd: string): boolean {
const words = cmd.match(/(?:[^\s'"]+|'[^']*'|"(?:\\.|[^"\\])*")+/g) ?? [];
const at = words.findIndex(w => READ_WORD.test(w));
let script = at >= 0 && /^(?:sed|awk)$/.test(READ_WORD.exec(words[at])![1]);
let files = 0;
for (let i = at + 1; i < words.length; i++) {
const w = words[i];
if (/^\d*[<>]/.test(w)) { if (/^\d*[<>]+&?$/.test(w)) i++; continue; }
if (/^-(?:[ef]|-expression|-file)$/.test(w)) { script = false; i++; continue; }
if (w.startsWith('-') || /^\+?\d+$/.test(w)) continue;
if (script) { script = false; continue; }
files++;
}
return files === 1;
}

/**
* The gstack-* skill reads in a shell line, in order. tail is the path an error line must name: from the folder
* before skills/ when that is written out literally, else from skills/. last: the read is the line's final command,
* a simple one (no grouping or substitution) that names one file, so the call's exit status is the read's own.
*/
function shellSkillReads(line: string): ShellRead[] {
const cmds = shellCommands(line);
let lastIdx = cmds.length - 1;
while (lastIdx > 0 && !cmds[lastIdx].trim()) lastIdx--;
return cmds.flatMap((cmd, i) => (READ_PROGRAM.test(cmd) ? [...cmd.matchAll(SHELL_SKILL_READ)] : []).map(m => {
const at = m.index + m[0].indexOf('skills');
const parent = /(?:^|[\s'"=\\/])([A-Za-z0-9._-]+)[\\/]$/.exec(cmd.slice(0, at))?.[1];
return { skill: m[1], tail: `${parent ? `${parent}/` : ''}skills/${m[1]}/SKILL.md`, last: i === lastIdx && !/[(){}`]/.test(cmd) && namesOneFile(cmd) };
}));
}

const tailPattern = (tail: string) =>
new RegExp(`(?:^|[\\s'"\`:=\\\\/])${tail.split('/').map(p => p.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('[\\\\/]')}(?![\\w.-])`);

/**
* Whether an output line reports a read error for this read. Every error line counts, except one that provably
* names another file: another read's written-out path (cat A || cat B, with A failing; the longer path wins when
* both match), or a path that is no SKILL.md at all (cat SKILL.md /tmp/x).
*/
const readFailed = (output: string | undefined, read: ShellRead, reads: ShellRead[]) =>
(output ?? '').split('\n').some(l => {
if (!READ_FAILURE.test(l)) return false;
const own = tailPattern(read.tail).test(l);
if (reads.some(o => o !== read && o.tail !== read.tail && tailPattern(o.tail).test(l) && (!own || o.tail.length > read.tail.length))) return false;
return own || !/[\\/]/.test(l) || /SKILL\.md(?![\w.-])/i.test(l);
});

const exitedNonZero = (output: string | undefined) => {
const code = output === undefined ? null : EXIT_CODE.exec(output);
Expand Down Expand Up @@ -146,6 +213,8 @@ export function parseCodexRollout(text: string): Transcript {
const body = contentText(p.content);
if (p.role === 'assistant') {
if (body) events.push({ kind: 'text', line, text: body });
} else if (p.role === 'user' && !body && !fromHarness(p) && p.content.some((c: unknown) => isObject(c) && c.type === 'input_image')) {
lastLoad = null;
} else if (p.role === 'user' && body) {
const injected = SKILL_INJECTION.exec(body);
const skill = injected ? GSTACK_SKILL_FILE.exec(injected[1].trim())?.[1] : undefined;
Expand All @@ -161,10 +230,12 @@ export function parseCodexRollout(text: string): Transcript {
const command = SHELL_TOOLS.has(p.name) ? shellLine(input) : null;
if (command !== null) {
events.push({ kind: 'tool_use', line, id, name: 'Bash', input: { command } });
for (const skill of shellSkillReads(command)) {
if (skill === lastLoad || readFailed(outputs.get(id), skill)) continue;
events.push({ kind: 'load', line, skill, via: 'read' });
lastLoad = skill;
const reads = shellSkillReads(command);
const out = outputs.get(id);
for (const read of reads) {
if (read.skill === lastLoad || readFailed(out, read, reads) || (read.last && exitedNonZero(out))) continue;
events.push({ kind: 'load', line, skill: read.skill, via: 'read' });
lastLoad = read.skill;
}
} else if (p.name === 'spawn_agent' && startedAgent(outputs.get(id), p.namespace ?? undefined)) {
const prompt = [input.message, ...(Array.isArray(input.items) ? input.items.map((i: unknown) => (isObject(i) ? i.text : undefined)) : [])]
Expand Down
6 changes: 5 additions & 1 deletion setup
Original file line number Diff line number Diff line change
Expand Up @@ -3188,9 +3188,13 @@ create_codex_runtime_root() {
_link_or_copy "$gstack_dir/lib" "$codex_gstack/lib"
fi
# Codex hook shims: ${CODEX_HOME}/hooks.json names this stable path (GST-3172).
# They import the Claude Code hooks beside them (../../claude/hooks), which
# a symlink reaches through the checkout but a Windows copy does not, so the
# Claude hooks come along too; without them all three shims fail open there.
if [ -d "$gstack_dir/hosts/codex/hooks" ]; then
mkdir -p "$codex_gstack/hosts/codex"
mkdir -p "$codex_gstack/hosts/codex" "$codex_gstack/hosts/claude"
_link_or_copy "$gstack_dir/hosts/codex/hooks" "$codex_gstack/hosts/codex/hooks"
_link_or_copy "$gstack_dir/hosts/claude/hooks" "$codex_gstack/hosts/claude/hooks"
fi
if [ -d "$gstack_dir/browse/dist" ]; then
_link_or_copy "$gstack_dir/browse/dist" "$codex_gstack/browse/dist"
Expand Down
Loading
Loading