Codex gets gstack's skill routing hint and destructive-command check (GST-3172) (#4512)

`./setup --host codex` now adds gstack's skill-routing hint and
destructive-command check to Codex's `~/.codex/hooks.json`, next to your
own hooks, so Codex users get the same guardrails Claude Code users
have.

Codex runs a hook only after you trust it, so nothing fires until you
accept gstack's hooks at Codex's startup prompt or in `/hooks`;
`gstack-doctor` shows whether you have.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
Review-Finding: p1/red-team#1 reader=red-team
This commit is contained in:
Garry Tanandcapy-ai[bot] authored and GitHub committed 2026-11-19 11:09:11 +00:00
1 parent 55aaa6c4a5
commit 944b41e24d
24 files changed
+1263 -39

No files matched your search

+45
View File
@@ -0,0 +1,45 @@
name: Codex hooks
# A real Codex CLI reads the hooks.json gstack writes (GST-3172). Codex 0.170
# skips the whole file when it holds a key it does not know, which would also
# switch off the user's own hooks, so the free check runs against the real
# binary: test/codex-hooks-real-codex.test.ts points Codex at a closed local
# port, so its hooks fire and no model is called. Secretless: no API key, and
# GSTACK_REQUIRE_CODEX=1 makes a missing codex fail instead of skipping.
on:
pull_request:
branches: [main]
paths:
- bin/gstack-settings-hook
- hosts/codex/hooks/**
- hosts/claude/hooks/skill-route-hook.ts
- hosts/claude/hooks/destructive-guard-hook.ts
- lib/skill-route.ts
- test/codex-hooks-real-codex.test.ts
- .github/workflows/codex-hooks.yml
workflow_dispatch:
permissions:
contents: read
jobs:
real-codex:
name: Real Codex reads gstack's hooks.json
runs-on: ubuntu-24.04
timeout-minutes: 10
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
with:
persist-credentials: false
- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2
with:
bun-version: 1.4.2
- name: Install dependencies
run: bun install --frozen-lockfile --ignore-scripts
- name: Install the Codex CLI the hooks are tested on
run: npm install -g @openai/codex@0.170.0 && codex --version
- name: Codex runs the merged hooks.json (no model call)
env:
GSTACK_REQUIRE_CODEX: "1"
run: bun test test/codex-hooks-real-codex.test.ts
+1 -1
View File
@@ -79,7 +79,7 @@ installs and passes the conformance tests but has no certification run yet;
| Agent | Tier | Install | First invocation | Safety skills | Outside review needs | Repair |
|-------|------|---------|------------------|---------------|----------------------|--------|
| Claude Code | full | `--host claude` (default) | `/office-hours` | enforced (hooks block) | Codex CLI, signed in | `./setup --host claude` |
| OpenAI Codex CLI | experimental | `--host codex` → `${CODEX_HOME:-~/.codex}/skills/gstack-*/` | ask for `gstack-office-hours` | advisory, not blocked | Claude Code CLI, signed in | `./setup --host codex` |
| OpenAI Codex CLI | experimental | `--host codex` → `${CODEX_HOME:-~/.codex}/skills/gstack-*/` | ask for `gstack-office-hours` | destructive commands blocked once you trust gstack's hooks ([Codex hooks](docs/skill-routing-and-contracts.md#codex)); the rest advisory | Claude Code CLI, signed in | `./setup --host codex` |
| OpenCode | experimental | `--host opencode` → `~/.config/opencode/skills/gstack-*/` + `/gstack-*` commands | `/gstack-office-hours` | advisory, not blocked | Codex CLI, signed in | `./setup --host opencode` |
| Cursor | experimental | `--host cursor` → `~/.cursor/skills/gstack-*/` | ask for `gstack-office-hours` | advisory, not blocked | Codex CLI, signed in | `./setup --host cursor` |
| Factory Droid | experimental | `--host factory` → `~/.factory/skills/gstack-*/` | ask for `gstack-office-hours` | advisory, not blocked | Codex CLI, signed in | `./setup --host factory` |
+30 -1
View File
@@ -14,7 +14,7 @@
# Rows and ids: bin/gstack-doctor-components.sh.
#
# Rows: install root, rescue refs, state root, bun, hooks, windows bash (on
# Windows only), codex, codex probe, artifacts sync, browse bundle, binaries,
# Windows only), codex, codex hooks (when hooks.json holds gstack's), codex probe, artifacts sync, browse bundle, binaries,
# cso, claude code, session journal, guard log, CLAUDE.md. Each row is
# `ok`, `warn`, `not configured` or `fail`; a row that is not ok carries a fix
# line, and every gstack helper in a fix line is an absolute path under this
@@ -206,6 +206,34 @@ check_hooks() {
# check_codex — CODEX_MODE from the free checks; sets CODEX_READY=1 when the
# probe row should follow.
# check_codex_hooks — gstack's hooks in Codex's hooks.json (GST-3172) and
# whether config.toml holds a trust entry for each. Codex skips a hook nobody
# trusted, silently. gstack-settings-hook trust-status never computes Codex's
# hash, so "trusted" means an entry exists, not that it matches today's hook.
# No hooks.json, or no gstack hook in it, prints no row.
check_codex_hooks() {
local file="${CODEX_HOME:-$HOME/.codex}/hooks.json" out line src st summary="" waiting=0
[ -f "$file" ] || return 0
if ! out=$(GSTACK_HOOKS_FORMAT=codex GSTACK_SETTINGS_FILE="$file" "$BIN/gstack-settings-hook" trust-status </dev/null 2>&1); then
row warn "codex hooks" "$(printf '%s\n' "$out" | head -1 | clamp ' -~' 200)" "fix the file named above, then cd $SRC && ./setup --host codex"
return 0
fi
[ -n "$out" ] || return 0
while IFS= read -r line; do
src=${line%% *}; st=${line##* }
[ "$st" = trusted ] || waiting=$((waiting + 1))
[ "$st" = untrusted ] && st="no trust entry"
summary="${summary:+$summary, }${src#gstack-} $st"
done <<EOF
$out
EOF
if [ "$waiting" -gt 0 ]; then
row warn "codex hooks" "$summary (Codex skips a hook until it is trusted)" "open Codex and trust them at its startup prompt or in /hooks"
else
row ok "codex hooks" "$summary (trust entry found; hash not checked)"
fi
}
check_codex() {
local reviews probe="$BIN/gstack-codex-probe" sel rc model src
CODEX_READY=0
@@ -630,6 +658,7 @@ check_bun
check_hooks
[ "$WINDOWS" -eq 1 ] && check_windows_bash
check_codex
check_codex_hooks
[ "$CODEX_READY" -eq 1 ] && check_codex_probe
check_sync
check_browse
+207 -8
View File
@@ -28,6 +28,17 @@
# gstack-settings-hook prune-stale --repoint <root> # re-point gstack items at <root>, prune still-dead
# gstack-settings-hook prune-stale --all # remove ALL gstack hook items (uninstall sweep)
#
# 4. Codex format (GSTACK_HOOKS_FORMAT=codex): the same verbs (but not the
# legacy add/remove) on ${CODEX_HOME:-~/.codex}/hooks.json, plus
# gstack-settings-hook trust-status # read-only: "<source>\t<event>\ttrusted|untrusted|disabled"
# Codex 0.170 skips the whole hooks.json when it holds a key it does not
# know, which would switch off the user's own hooks too. So this format
# never writes _gstack_source (identity is the KNOWN_HOOKS rows marked
# host codex), refuses a file that already fails the schema, re-reads the
# temp file against the schema before the rename, appends new groups after
# the user's (Codex keys trust by group index), and refuses ensure-event
# while config.toml declares a gstack hook under [hooks] (it would run twice).
#
# ensure-event is the update-in-place verb: same flags as add-event, but keyed
# on (event, source) — any entry carrying our source tag for the event is THE
# registration to compare/update, so a matcher change re-points in place
@@ -75,6 +86,16 @@ GSTACK_BUN_CONFIG=/dev/null; case "${OSTYPE:-}" in msys*|cygwin*) if command -v
ACTION="${1:-}"
SETTINGS_FILE="${GSTACK_SETTINGS_FILE:-${CLAUDE_CONFIG_DIR:-$HOME/.claude}/settings.json}"
if [ "${GSTACK_HOOKS_FORMAT:-}" = codex ]; then
SETTINGS_FILE="${GSTACK_SETTINGS_FILE:-${CODEX_HOME:-$HOME/.codex}/hooks.json}"
# Codex reads config.toml from CODEX_HOME, beside the hooks.json path it was
# given, so take its directory before the symlink-resolving step below.
GSTACK_CODEX_CONFIG="${GSTACK_CODEX_CONFIG:-$(dirname "$SETTINGS_FILE")/config.toml}"
export GSTACK_CODEX_CONFIG
case "$ACTION" in
add|remove) echo "gstack-settings-hook: $ACTION is the legacy settings.json verb; use ensure-event or remove-source with GSTACK_HOOKS_FORMAT=codex" >&2; exit 1 ;;
esac
fi
if [ -z "$ACTION" ]; then
cat <<EOF >&2
@@ -89,6 +110,7 @@ Usage:
gstack-settings-hook rollback
gstack-settings-hook list-sources
gstack-settings-hook list-items --event <name> [--owned-by <tag>] [--command-regex <js-re>]
GSTACK_HOOKS_FORMAT=codex gstack-settings-hook <verb> ... # Codex hooks.json; adds trust-status
EOF
exit 1
fi
@@ -140,8 +162,119 @@ var KNOWN_HOOKS = {
"ceo-review-gate-stop": { source: "gstack-ceo-review-gate", event: "Stop", matcher: "", relpath: "hosts/claude/hooks/ceo-review-gate-stop" },
"ceo-review-gate-subagent-stop": { source: "gstack-ceo-review-gate", event: "SubagentStop", matcher: "", relpath: "hosts/claude/hooks/ceo-review-gate-subagent-stop" },
"autoplan-stop-gate-stop": { source: "gstack-autoplan-gate", event: "Stop", matcher: "", relpath: "hosts/claude/hooks/autoplan-stop-gate-stop" },
"autoplan-stop-gate-publish": { source: "gstack-autoplan-gate", event: "PreToolUse", matcher: "Bash", relpath: "hosts/claude/hooks/autoplan-stop-gate-publish" }
"autoplan-stop-gate-publish": { source: "gstack-autoplan-gate", event: "PreToolUse", matcher: "Bash", relpath: "hosts/claude/hooks/autoplan-stop-gate-publish" },
"codex-skill-route-hook": { source: "gstack-skill-route", event: "UserPromptSubmit", matcher: "", relpath: "hosts/codex/hooks/codex-skill-route-hook", host: "codex" },
"codex-destructive-guard-hook": { source: "gstack-destructive-guard", event: "PreToolUse", matcher: "Bash", relpath: "hosts/codex/hooks/codex-destructive-guard-hook", host: "codex" }
};
// GSTACK_HOOKS_FORMAT=codex: the file is Codex hooks.json, and only rows with
// host codex identify gstack items in it; every other row belongs to
// settings.json. Codex skips the whole hooks.json when any key is unknown, so
// in this format nothing writes a _gstack_source tag and every write is
// checked against the Codex 0.170 schema (gsCodexProblem) before the rename.
var GS_CODEX = process.env.GSTACK_HOOKS_FORMAT === "codex";
var GS_CODEX_EVENTS = ["PreModelRequest", "PostModelRequest", "PreToolUse", "PermissionRequest", "PostToolUse", "PreCompact", "PostCompact", "SessionStart", "SessionEnd", "UserPromptSubmit", "SubagentStart", "SubagentStop", "Stop", "Interrupt"];
var GS_CODEX_HANDLER_KEYS = {
command: ["type", "command", "commandWindows", "command_windows", "timeout", "async", "statusMessage", "additionalContextLimit"],
mcp_tool: ["type", "server", "tool", "input", "timeout", "statusMessage"],
prompt: ["type"],
agent: ["type"]
};
function gsTag(entry, source) { if (!GS_CODEX) entry._gstack_source = source; }
function gsCodexProblem(doc) {
var isObj = function (v) { return v !== null && typeof v === "object" && !Array.isArray(v); };
var isCount = function (v) { return typeof v === "number" && Number.isInteger(v) && v >= 0; };
var extra = function (o, allowed, at) {
var k = Object.keys(o).find(function (x) { return allowed.indexOf(x) < 0; });
return k === undefined ? null : at + " has the key " + JSON.stringify(k) + ", which Codex does not know";
};
if (!isObj(doc)) return "the top level is not an object";
var bad = extra(doc, ["description", "hooks"], "the top level");
if (bad) return bad;
if (doc.description !== undefined && typeof doc.description !== "string") return "description is not a string";
if (doc.hooks === undefined) return null;
if (!isObj(doc.hooks)) return "hooks is not an object";
bad = extra(doc.hooks, GS_CODEX_EVENTS, "hooks");
if (bad) return bad;
for (var ev of Object.keys(doc.hooks)) {
var groups = doc.hooks[ev];
if (!Array.isArray(groups)) return "hooks." + ev + " is not an array";
for (var gi = 0; gi < groups.length; gi++) {
var g = groups[gi], at = "hooks." + ev + "[" + gi + "]";
if (!isObj(g)) return at + " is not an object";
bad = extra(g, ["matcher", "hooks"], at);
if (bad) return bad;
if (g.matcher !== undefined && g.matcher !== null && typeof g.matcher !== "string") return at + ".matcher is not a string";
if (g.hooks === undefined) continue;
if (!Array.isArray(g.hooks)) return at + ".hooks is not an array";
for (var hi = 0; hi < g.hooks.length; hi++) {
var h = g.hooks[hi], hat = at + ".hooks[" + hi + "]";
if (!isObj(h)) return hat + " is not an object";
var keys = Object.prototype.hasOwnProperty.call(GS_CODEX_HANDLER_KEYS, h.type) ? GS_CODEX_HANDLER_KEYS[h.type] : null;
if (!keys) return hat + ".type is " + JSON.stringify(h.type) + ", which Codex does not know";
bad = extra(h, keys, hat);
if (bad) return bad;
if (h.type === "command" && typeof h.command !== "string") return hat + ".command is not a string";
if (h.type === "mcp_tool" && (typeof h.server !== "string" || typeof h.tool !== "string")) return hat + " needs string server and tool";
if (h.type === "mcp_tool" && h.input !== undefined && !isObj(h.input)) return hat + ".input is not an object";
if (h.timeout !== undefined && !isCount(h.timeout)) return hat + ".timeout is not a whole number of seconds";
if (h.additionalContextLimit !== undefined && !isCount(h.additionalContextLimit)) return hat + ".additionalContextLimit is not a whole number";
if (h.async !== undefined && typeof h.async !== "boolean") return hat + ".async is not true or false";
for (var sk of ["statusMessage", "commandWindows", "command_windows"]) {
if (h[sk] !== undefined && typeof h[sk] !== "string") return hat + "." + sk + " is not a string";
}
}
}
}
return null;
}
function gsCodexConfigClash() {
// config.toml [hooks] tables load beside hooks.json in the same layer, so a
// gstack hook declared in both runs twice. Refuse instead of adding it.
var fs = require("fs");
var file = process.env.GSTACK_CODEX_CONFIG;
var raw;
try { raw = fs.readFileSync(file, "utf8"); }
catch (e) { if (e && e.code === "ENOENT") return; throw e; }
var cfg;
try { cfg = Bun.TOML.parse(raw); }
catch (e) {
throw Object.assign(new Error(file + " does not parse (" + e.message + "), so gstack cannot check it for hooks it already declares -- fix it and re-run ./setup"), { gstackUnreadableSettings: true });
}
var hooks = cfg && cfg.hooks;
if (!hooks || typeof hooks !== "object") return;
for (var ev of Object.keys(hooks)) {
if (ev === "state" || !Array.isArray(hooks[ev])) continue;
for (var g of hooks[ev]) {
for (var h of (g && Array.isArray(g.hooks) ? g.hooks : [])) {
var row = h && typeof h.command === "string" ? gsOwnedRow(h.command, ev, g.matcher || "") : null;
if (row) {
throw Object.assign(new Error(file + " already declares gstack hook " + row.source + " under [hooks." + ev + "], and Codex would run it twice -- remove it from config.toml (gstack keeps its hooks in hooks.json) and re-run ./setup"), { gstackUnreadableSettings: true });
}
}
}
}
}
function gsCodexRefuse(path, problem) {
throw Object.assign(new Error(path + " does not match the Codex hooks.json schema (" + problem + "); Codex skips that whole file, so gstack will not write it -- fix the file (or move it aside) and re-run ./setup"), { gstackUnreadableSettings: true });
}
function gsCodexMovedUserHooks(beforeText, settings) {
var before;
try { before = JSON.parse(beforeText); } catch (e) { return []; }
var bh = (before && before.hooks) || {};
var ah = (settings && settings.hooks) || {};
var moved = [];
Object.keys(bh).forEach(function (ev) {
(Array.isArray(bh[ev]) ? bh[ev] : []).forEach(function (g, gi) {
(g && Array.isArray(g.hooks) ? g.hooks : []).forEach(function (h, hi) {
if (h && h.type === "command" && gsOwnedRow(h.command, ev, g.matcher || "")) return;
var ag = (Array.isArray(ah[ev]) ? ah[ev] : [])[gi];
var same = ag && Array.isArray(ag.hooks) && JSON.stringify(ag.hooks[hi]) === JSON.stringify(h) && (ag.matcher || "") === (g.matcher || "");
if (!same && moved.indexOf(ev) < 0) moved.push(ev);
});
});
});
return moved;
}
function gsHadBashPrefix(c) { return String(c == null ? "" : c).trim().indexOf("bash ") === 0; }
function gsStripWrap(c) {
var s = String(c == null ? "" : c).trim();
@@ -169,6 +302,7 @@ function gsOwnedRow(cmd, event, matcher) {
if (p !== row.relpath && p.slice(-(row.relpath.length + 1)) !== "/" + row.relpath) return null;
if (row.event !== event) return null;
if (row.matcher && (matcher || "") !== row.matcher) return null;
if ((row.host || "claude") !== (GS_CODEX ? "codex" : "claude")) return null;
return row;
}
function gsWinPath(p) {
@@ -285,16 +419,28 @@ function gsLoadSettings(path) {
process.stderr.write("gstack-settings-hook: cannot read " + path + ": " + e.message + " -- refusing to mutate\n");
process.exit(3);
}
try { return { settings: JSON.parse(raw), existed: true }; }
var parsed;
try { parsed = JSON.parse(raw); }
catch (e) {
process.stderr.write("gstack-settings-hook: " + path + " is not valid JSON (" + e.message + ") -- refusing to mutate; fix or restore it (.bak files / rollback)\n");
process.exit(3);
}
if (GS_CODEX) {
var problem = gsCodexProblem(parsed);
if (problem) gsCodexRefuse(path, problem);
}
return { settings: parsed, existed: true };
}
function gsWriteIfChanged(path, beforeText, settings, existed) {
var fs = require("fs");
var afterText = JSON.stringify(settings, null, 2);
if (afterText === beforeText) return false;
if (GS_CODEX) {
var moved = gsCodexMovedUserHooks(beforeText, settings);
if (moved.length > 0) {
throw Object.assign(new Error("left " + path + " unchanged: this change would move your own " + moved.join(", ") + " hooks, which come after the gstack hook there, to new positions. Codex keys hook trust by position, so they would stop running until you trust them again, and codex exec would skip them without asking. To remove the gstack hook yourself, delete its group from " + path + " and re-trust your hooks in Codex with /hooks"), { gstackUnreadableSettings: true });
}
}
gsAssertSettingsUnchanged(path);
// Preserve the live file mode across the tmp+rename (settings.json can
// carry API keys in its env block -- a user-tightened 0600 must never be
@@ -307,9 +453,17 @@ function gsWriteIfChanged(path, beforeText, settings, existed) {
gsRotateBackups(path, 10);
}
var tmp = process.env.GSTACK_TMP_PATH;
if (GS_CODEX) {
var before = gsCodexProblem(settings);
if (before) gsCodexRefuse(path, "the new content: " + before);
}
fs.writeFileSync(tmp, afterText + "\n", { mode: mode, flag: "wx" });
try {
fs.chmodSync(tmp, mode);
if (GS_CODEX) {
var reread = gsCodexProblem(JSON.parse(fs.readFileSync(tmp, "utf8")));
if (reread) gsCodexRefuse(path, "the written copy: " + reread);
}
gsAssertSettingsUnchanged(path);
fs.renameSync(tmp, path);
} finally {
@@ -519,7 +673,7 @@ case "$ACTION" in
GSTACK_TIMEOUT="$TIMEOUT" \
GSTACK_DIFF_ONLY="$DIFF_ONLY" \
GSTACK_ENSURE="$ENSURE" \
bun --no-env-file --config="${GSTACK_BUN_CONFIG:-/dev/null}" -e "$_HOOK_JS_PRELUDE"'gsMain(function () {
bun --no-env-file --config="${GSTACK_BUN_CONFIG:-/dev/null}" -e "$_HOOK_JS_PRELUDE"'gsMain(function () {
const settingsPath = process.env.GSTACK_SETTINGS_PATH;
const event = process.env.GSTACK_EVENT;
const cmd = process.env.GSTACK_COMMAND;
@@ -532,6 +686,7 @@ case "$ACTION" in
const loaded = gsLoadSettings(settingsPath);
const settings = loaded.settings;
const before = JSON.stringify(settings, null, 2);
if (GS_CODEX) gsCodexConfigClash();
if (!settings.hooks) settings.hooks = {};
if (!settings.hooks[event]) settings.hooks[event] = [];
@@ -590,14 +745,14 @@ case "$ACTION" in
// entry-level ownership (remove-source deletes the whole tagged
// entry; add-event clobbers entry.hooks wholesale) -- a tag on a
// mixed entry hands them permission to destroy the user items in it.
if (primary.entry.hooks.length === 1) primary.entry._gstack_source = source;
if (primary.entry.hooks.length === 1) gsTag(primary.entry, source);
else delete primary.entry._gstack_source;
placed = true;
} else if (primary.entry.hooks.length === 1) {
// Tagged single-item entry under a stale matcher: the entry is
// exclusively ours, so re-point payload AND matcher in place.
primary.entry.hooks = [hookEntry];
primary.entry._gstack_source = source;
gsTag(primary.entry, source);
if (matcher) primary.entry.matcher = matcher;
else delete primary.entry.matcher;
placed = true;
@@ -621,8 +776,11 @@ case "$ACTION" in
!(Array.isArray(e.hooks) && e.hooks.length === 0 && cands.some(c => c.entry === e)));
}
if (!placed) {
const newEntry = { _gstack_source: source, hooks: [hookEntry] };
if (matcher) newEntry.matcher = matcher;
const newEntry = {};
gsTag(newEntry, source);
if (GS_CODEX && matcher) newEntry.matcher = matcher;
newEntry.hooks = [hookEntry];
if (!GS_CODEX && matcher) newEntry.matcher = matcher;
settings.hooks[event].push(newEntry);
}
@@ -836,7 +994,7 @@ case "$ACTION" in
// both would fire the hook twice per event, forever.
if (seenInEntry.has(newCmd)) { removed++; continue; }
seenInEntry.add(newCmd);
if (wasSingle) entry._gstack_source = row.source; // tag restore
if (wasSingle) gsTag(entry, row.source); // tag restore
remain.push(h);
continue;
}
@@ -994,6 +1152,47 @@ case "$ACTION" in
'
;;
trust-status)
# Read-only, Codex only: one line per gstack handler in hooks.json,
# "<source>\t<event>\t<state>", where state is trusted (config.toml holds a
# trusted_hash under [hooks.state."<hooks.json path>:<event>:<group>:<handler>"],
# the key Codex 0.170 builds in codex-rs/hooks/src/lib.rs hook_key),
# untrusted (no entry yet: Codex skips the hook until the user trusts it) or
# disabled (enabled = false). It never computes a hash, so a trusted line
# means an entry exists, not that it matches the current definition.
if [ "${GSTACK_HOOKS_FORMAT:-}" != codex ]; then
echo "trust-status needs GSTACK_HOOKS_FORMAT=codex" >&2
exit 1
fi
[ -f "$SETTINGS_FILE" ] || exit 0
GSTACK_SETTINGS_PATH="$SETTINGS_FILE" GSTACK_CODEX_HOOKS_INPUT="$GSTACK_SETTINGS_INPUT" \
bun --no-env-file --config="${GSTACK_BUN_CONFIG:-/dev/null}" -e "$_HOOK_JS_PRELUDE"'gsMain(function () {
const fs = require("fs");
const path = require("path");
const loaded = gsLoadSettings(process.env.GSTACK_SETTINGS_PATH);
let state = {};
try {
const cfg = Bun.TOML.parse(fs.readFileSync(process.env.GSTACK_CODEX_CONFIG, "utf8"));
state = (cfg && cfg.hooks && cfg.hooks.state) || {};
} catch (e) {
if (!e || e.code !== "ENOENT") throw Object.assign(new Error(process.env.GSTACK_CODEX_CONFIG + " does not parse (" + (e && e.message) + ")"), { gstackUnreadableSettings: true });
}
const label = (ev) => ev.replace(/([a-z])([A-Z])/g, "$1_$2").toLowerCase();
const files = Array.from(new Set([path.resolve(process.env.GSTACK_CODEX_HOOKS_INPUT), process.env.GSTACK_SETTINGS_PATH]));
const hooks = loaded.settings.hooks || {};
for (const ev of Object.keys(hooks)) {
hooks[ev].forEach((g, gi) => (g.hooks || []).forEach((h, hi) => {
const row = h && h.type === "command" ? gsOwnedRow(h.command, ev, g.matcher || "") : null;
if (!row) return;
const entry = files.map(f => state[f + ":" + label(ev) + ":" + gi + ":" + hi]).find(Boolean);
const st = entry && entry.enabled === false ? "disabled" : entry && typeof entry.trusted_hash === "string" ? "trusted" : "untrusted";
console.log(row.source + "\t" + ev + "\t" + st);
}));
}
});
'
;;
list-sources)
[ -f "$SETTINGS_FILE" ] || { echo "(no settings file)"; exit 0; }
GSTACK_SETTINGS_PATH="$SETTINGS_FILE" bun --no-env-file --config="${GSTACK_BUN_CONFIG:-/dev/null}" -e "$_HOOK_JS_PRELUDE"'gsMain(function () {
+13
View File
@@ -611,6 +611,19 @@ if [ -x "$SETTINGS_HOOK" ]; then
REMOVED+=("stray gstack hook entries")
fi
fi
# ─── Remove gstack hooks from Codex's hooks.json ────────────
# Before the Claude and Codex skills go: SETTINGS_HOOK lives in the install
# being removed (~/.claude/skills/gstack/bin on a global install), so after
# 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"
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")
fi
fi
# The Memorable consent key must never outlive the hook, kept state or not, and
# not only when the hook manager is present: gstack-config resolves its root
# through GSTACK_STATE_ROOT/GSTACK_HOME, which can be a different directory
@@ -0,0 +1,4 @@
---
bump: minor
---
- **On Codex, gstack now suggests the right skill for a prompt and stops destructive commands before they run.** `./setup --host codex` (Codex 0.170 or newer) adds two hooks to `~/.codex/hooks.json`: one adds a line naming the gstack skill a prompt fits (review, QA, verify), and one runs /careful's check before every shell command. Codex can't ask you about a single command, so in an interactive session a force-push, `git reset --hard`, `DROP TABLE` or the like is blocked, and the model is told to ask you first; if you want it, type `!` and the command to run it yourself. Under `codex exec` it's a warning instead, and deleting `/` or your home folder stays blocked everywhere. Codex runs new hooks only after you trust them, so pick "Trust all and continue" the next time Codex starts (setup prints a reminder, and `gstack-doctor` shows whether they're trusted). Your own hooks in that file are kept as they are, the same `gstack-config set skill_routing off` and `gstack-config set destructive_guard off` switches work on both hosts, and `gstack-uninstall` or `./setup --no-team` removes only gstack's entries. Setup also suggests `codex -c model_reasoning_effort=high` for gstack work and leaves your `config.toml` alone.
+8
View File
@@ -196,6 +196,14 @@ override applies to that run only; set `model` in your Codex `config.toml` to
make it stick across upgrades. After changing your Codex model, rerun
`./setup --host codex` to regenerate the skills.
**Reasoning effort and hooks.** gstack's workflows do best at high reasoning
effort; setup never changes it, so start Codex with
`codex -c model_reasoning_effort=high` when you run them. With Codex 0.170 or
newer, setup also adds gstack's routing hook and destructive-command check to
`${CODEX_HOME:-~/.codex}/hooks.json`, and Codex runs them once you trust them at
its startup prompt or in `/hooks`: see
[Codex hooks](skill-routing-and-contracts.md#codex).
**Plan-review and implementation tiers.** Plan workflows use an independent
`frontier` reviewer: Fable 5.1 from Codex, or GPT-6 Astra from Claude Code.
Implementation handoffs recommend the `smart` tier: Opus 5.5 or GPT-6.1 Sol.
+17 -2
View File
@@ -1,6 +1,6 @@
# Skill routing and skill contracts
Three Claude Code hooks that help a model actually run gstack's skills (GST-1088, GST-3110). All three are on by default. On Opus 5.5, unattended, a hook line naming a skill got it loaded in 58 of 60 bug-fix sessions, where the same skill relying on its description loaded in 0 of 60 (gstack-evals#369, and B1 before it on the same 60 tasks). With the contract hook, all 66 /review sessions ran its specialist reviewers, 42 of them after the hook's one block; in an earlier run without it, 0 of 66 did (gstack-evals board posts GEVA-271 and GEVA-105). Each has one default, `SWITCH_DEFAULT` in `lib/skill-route.ts`; `gstack-config defaults` prints it. With all three off nothing changes. The opt-in gates that hold one skill rule mid-run (the /plan-ceo-review and /autoplan gates) are in [skill-gates.md](skill-gates.md).
Three Claude Code hooks that help a model actually run gstack's skills (GST-1088, GST-3110); two of them also run on Codex ([Codex](#codex)). All three are on by default. On Opus 5.5, unattended, a hook line naming a skill got it loaded in 58 of 60 bug-fix sessions, where the same skill relying on its description loaded in 0 of 60 (gstack-evals#369, and B1 before it on the same 60 tasks). With the contract hook, all 66 /review sessions ran its specialist reviewers, 42 of them after the hook's one block; in an earlier run without it, 0 of 66 did (gstack-evals board posts GEVA-271 and GEVA-105). Each has one default, `SWITCH_DEFAULT` in `lib/skill-route.ts`; `gstack-config defaults` prints it. With all three off nothing changes. The opt-in gates that hold one skill rule mid-run (the /plan-ceo-review and /autoplan gates) are in [skill-gates.md](skill-gates.md).
- **Skill routing** (`skill_routing`, a UserPromptSubmit hook). When a prompt matches an installed skill's `triggers:`, the hook adds one line of context naming that skill, for example "this request fits /verify. Run /verify with the Skill tool before you start".
- **Skill contracts** (`skill_contracts`, a Stop hook). A skill can declare the outputs that must exist before it is done. When the model tries to stop without them, the hook blocks once and names what is missing.
@@ -32,7 +32,7 @@ The off switch is for people. The text the Stop hook shows the model never menti
| Host | Routing hook | Contract Stop hook | Destructive-command check | Notes |
|---|---|---|---|---|
| Claude Code | yes | yes | yes | Registered in `~/.claude/settings.json` by `./setup` |
| Codex | no | no | no | Not ported yet. Codex CLI 0.170 runs hooks (`SessionStart`, `UserPromptSubmit`, `PreToolUse`, `Stop` and more, from `$CODEX_HOME/hooks.json`), but `./setup --host codex` registers none of these three there |
| Codex | yes | not yet | yes, with a deny where Claude Code asks | Registered in `${CODEX_HOME:-~/.codex}/hooks.json` by `./setup --host codex` (Codex 0.170 or newer). Codex runs them only after you trust them: see [Codex](#codex) |
| OpenCode, Cursor and other hosts | no | no | no | gstack registers no hooks on these hosts. `gstack-skill-contract check` still works on a Claude Code transcript |
## Routing
@@ -80,6 +80,21 @@ In an Agent SDK program an ask with no permission callback is denied outright (c
The hook reads `destructive_guard` every time it runs, so `gstack-config set destructive_guard off` takes effect on the next command. With it off, /careful and /guard still load their own session hooks.
<a id="codex"></a>
## Codex
`./setup --host codex` (or `./setup --host auto` when `codex` is on your PATH) registers the routing 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 check on `PreToolUse` for `Bash` with a 10-second timeout. The contract Stop hook is not on Codex yet. 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.
**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 2 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`.
**Routing on Codex** scans `${CODEX_HOME:-~/.codex}/skills`, names gstack's skills the way Codex does (`gstack-review`), and takes their triggers from the same skill in gstack's checkout, because Codex's copies keep only a name and a description. The line reads "this request fits the gstack-review skill. Read and follow the gstack-review skill before you start". A prompt that starts with `$` (a Codex skill mention) or `/` is never routed.
**The destructive-command check on Codex** runs the same `check-careful.sh`, but Codex has no "ask": its hook parser rejects `permissionDecision: "ask"` and lets the command run. So in an interactive Codex session, every command the check would ask about is blocked instead, and the reason tells the model to stop and ask you. If you want it, run it yourself by typing `!` and the command in Codex (Codex runs `!` commands without hooks), or turn the check off. In `codex exec`, and any session `gstack-session-kind` reports as headless or unattended, it is a warning and the command runs, as on Claude Code. The two deny shapes stay a deny everywhere. Codex already refuses some `rm -rf` commands by itself, before any hook runs.
**Reasoning effort.** gstack's workflows do best at high reasoning effort. Setup leaves your `config.toml` alone and prints a reminder; start Codex with `codex -c model_reasoning_effort=high` when you run them.
## Contracts
### Schema (version 1)
+7 -1
View File
@@ -8,7 +8,7 @@ If gstack is installed on your machine:
~/.claude/skills/gstack/bin/gstack-uninstall
```
This handles skills, symlinks, harness registrations (the files `gstack-harness` wrote into OpenClaw, Hermes, a Dot or another harness, from their ledgers, plus the [start hook](hosts.md#start-hook), which it turns off through the harness's own CLI), global state (`~/.gstack/`), project-local state, browse daemons, and temp files. Use `--keep-state` to preserve config and analytics; it also keeps the repo's `.gstack/` and `.gstack-worktrees/`. Use `--force` to skip confirmation.
This handles skills, symlinks, harness registrations (the files `gstack-harness` wrote into OpenClaw, Hermes, a Dot or another harness, from their ledgers, plus the [start hook](hosts.md#start-hook), which it turns off through the harness's own CLI), gstack's entries in Codex's `${CODEX_HOME:-~/.codex}/hooks.json` (your own hooks there stay), global state (`~/.gstack/`), project-local state, browse daemons, and temp files. Use `--keep-state` to preserve config and analytics; it also keeps the repo's `.gstack/` and `.gstack-worktrees/`. Use `--force` to skip confirmation.
A plain uninstall keeps the git-tracked files under `.gstack/` (such as ship policy) and removes only the ones git ignores. It stops with exit 2, before removing anything, when a checkout under `.gstack-worktrees/` has uncommitted changes, has commits no branch or tag holds, or is not a worktree this repo registered. Pass `--force-worktrees` to delete those checkouts anyway. Every checkout is checked, including a worktree created inside another checkout under `.gstack-worktrees/`. A git submodule inside a clean checkout is deleted with it only when every commit it holds is on a remote-tracking branch; otherwise it stops the uninstall. A locked worktree (`git worktree lock`) always stops the uninstall, even with `--force-worktrees`; unlock it with `git worktree unlock <path>` if you want it gone. If `git worktree list` fails, the uninstall stops too, even with `--force-worktrees`, and so it does on git older than 2.36, which cannot list worktrees with `-z`. The check runs again after you confirm, before anything is removed, so a checkout you edit while the confirmation prompt waits is kept: uninstall exits 2 and removes nothing. Run from inside the gstack install itself, a `.gstack/` that holds its own git repository also stops the uninstall, because deleting the install would take it along. A `.gstack/` that is its own git repository is kept, with a message saying so, because its commits may exist nowhere else. When `.gstack-worktrees` is a symlink, uninstall removes only the link and never follows it, so the folder it points at and the worktrees there are kept.
@@ -131,6 +131,12 @@ the skill-routing UserPromptSubmit hook and the destructive-command PreToolUse h
/plan-ceo-review and /autoplan skill-gate hooks if you turned those on. Left in place, they error
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.
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
with `openclaw config unset plugins.entries.gstack-start` or `hermes plugins
+18 -6
View File
@@ -27,15 +27,27 @@ import { sessionKind } from './spawn-bin';
export const ASK_NOTE = "(gstack's destructive-command check, on in every session; off: gstack-config set destructive_guard off)";
const CHECK = path.join(import.meta.dir, '..', '..', '..', 'careful', 'bin', 'check-careful.sh');
function main(): void {
if (!readSkillSwitch('destructive_guard').on) return;
const r = runScriptSync(CHECK, [], { stdio: ['inherit', 'pipe', 'inherit'], encoding: 'utf8', timeout: 8000 }, {
export type CarefulDecision = { hookSpecificOutput?: { permissionDecision?: string; permissionDecisionReason?: string } };
/**
* check-careful.sh's answer to the hook payload (input, else this process's stdin): its JSON, its raw text when that is
* not JSON, or null when the switch is off or it printed nothing. Shared with the Codex wrapper (hosts/codex/hooks).
*/
export function carefulDecision(input?: string): { decision: CarefulDecision } | { raw: string } | null {
if (!readSkillSwitch('destructive_guard').on) return null;
const r = runScriptSync(CHECK, [], { stdio: [input === undefined ? 'inherit' : 'pipe', 'pipe', 'inherit'], input, encoding: 'utf8', timeout: 8000 }, {
resolve: () => resolveWindowsBashCached(path.join(resolveStateRoot(), 'cache', 'windows-bash.json')),
});
const out = (r.stdout ?? '').trim();
if (!out) return;
let decision: { hookSpecificOutput?: { permissionDecision?: string; permissionDecisionReason?: string } };
try { decision = JSON.parse(out); } catch { process.stdout.write(out + '\n'); return; }
if (!out) return null;
try { return { decision: JSON.parse(out) }; } catch { return { raw: out }; }
}
function main(): void {
const careful = carefulDecision();
if (!careful) return;
if ('raw' in careful) { process.stdout.write(careful.raw + '\n'); return; }
const decision = careful.decision;
const o = decision.hookSpecificOutput;
if (o?.permissionDecision === 'ask') {
const reason = `${o.permissionDecisionReason ?? ''} ${ASK_NOTE}`.trim();
+19 -13
View File
@@ -1,6 +1,6 @@
#!/usr/bin/env -S bun --no-env-file --config=/dev/null
/**
* skill-route-hook — UserPromptSubmit hook that names the skill a prompt fits,
* skill-route-hook — UserPromptSubmit hook (Claude Code, and Codex through hosts/codex/hooks) that names the skill a prompt fits,
* or the two that fit best (GST-1088, lane A; installed skills, GST-3123). On unless skill_routing is off (env
* GSTACK_SKILL_ROUTING, then config skill_routing, then SWITCH_DEFAULT).
*
@@ -20,8 +20,8 @@
*/
import * as fs from 'fs';
import {
appendHookTrace, firstStep, hintLine, hintVariant, installedSkillsDir, readSkillSwitch, readStdinBounded, routePrompt,
scanInstalledSkills, type RouteCandidate,
appendHookTrace, codexSkillsDir, firstStep, hintLine, hintVariant, hookHost, installedSkillsDir, readSkillSwitch, readStdinBounded,
routePrompt, scanCodexSkills, scanInstalledSkills, type HookHost, type RouteCandidate,
} from '../../../lib/skill-route';
import { itemSummary, parseContract } from '../../../lib/skill-contract';
@@ -52,7 +52,7 @@ function variantExtra(route: RouteCandidate, frontmatter: string): string {
return '';
}
async function main(): Promise<void> {
async function main(host: HookHost): Promise<void> {
setTimeout(() => { trace({ event: 'deadline', ms: DEADLINE_MS }, true); process.exit(0); }, DEADLINE_MS);
const sw = readSkillSwitch('skill_routing');
if (!sw.on) {
@@ -67,24 +67,30 @@ async function main(): Promise<void> {
const p = payload as Record<string, unknown>;
sessionId = typeof p.session_id === 'string' ? p.session_id : '';
if (typeof p.prompt !== 'string') return trace({ event: 'no-prompt' }, true);
const { skills, problems } = scanInstalledSkills(installedSkillsDir());
if (problems.length) trace({ event: 'skill-problems', problems: problems.join('; ') }, true);
const decision = routePrompt(p.prompt, skills);
const hostField: Record<string, string> = host === 'codex' ? { host } : {};
const { skills, problems } = host === 'codex' ? scanCodexSkills(codexSkillsDir()) : scanInstalledSkills(installedSkillsDir());
if (problems.length) trace({ event: 'skill-problems', problems: problems.join('; '), ...hostField }, true);
const decision = routePrompt(p.prompt, skills, undefined, host);
if (!decision.route) {
const top = decision.candidates[0];
return trace({ event: 'no-route', reason: decision.reason, chars: p.prompt.length, top: top ? `${top.skill}:${top.score}` : '-' });
return trace({ event: 'no-route', reason: decision.reason, chars: p.prompt.length, top: top ? `${top.skill}:${top.score}` : '-', ...hostField });
}
const route = decision.route;
const frontmatter = skills.find(s => s.file === route.file)?.frontmatter ?? '';
const also = decision.routes[1];
const out = JSON.stringify({ hookSpecificOutput: { hookEventName: 'UserPromptSubmit', additionalContext: hintLine(route, variantExtra(route, frontmatter), also) } });
const out = JSON.stringify({ hookSpecificOutput: { hookEventName: 'UserPromptSubmit', additionalContext: hintLine(route, variantExtra(route, frontmatter), also, host) } });
await new Promise<void>(resolve => process.stdout.write(out, () => resolve()));
trace({
event: 'routed', skill: route.skill, score: route.score, source: route.gstack ? 'gstack' : route.file, variant: hintVariant(),
...(also ? { also: also.skill, also_score: also.score, also_source: also.gstack ? 'gstack' : also.file } : {}),
...(also ? { also: also.skill, also_score: also.score, also_source: also.gstack ? 'gstack' : also.file } : {}), ...hostField,
});
}
main()
.catch(e => trace({ event: 'error', why: e instanceof Error ? e.message : String(e) }, true))
.finally(() => process.exit(0));
/** Runs the hook for one host and exits 0; the Codex wrapper (hosts/codex/hooks/codex-skill-route-hook.ts) passes codex. */
export function runSkillRouteHook(host: HookHost = hookHost()): void {
main(host)
.catch(e => trace({ event: 'error', why: e instanceof Error ? e.message : String(e) }, true))
.finally(() => process.exit(0));
}
if (import.meta.main) runSkillRouteHook();
+11
View File
@@ -0,0 +1,11 @@
#!/usr/bin/env bash
# Bash shim for Codex: Codex runs hook commands through a login shell, so this
# wrapper makes the TypeScript hook executable via bun. ${CODEX_HOME}/hooks.json
# references it through the Codex runtime root (${CODEX_HOME}/skills/gstack,
# whose hosts/codex/hooks links here), so pwd -P finds the checkout.
#
# FAIL-OPEN: every failure path — bun missing, script crash — still exits 0.
GSTACK_BUN_CONFIG=/dev/null; case "${OSTYPE:-}" in msys*|cygwin*) if command -v cygpath >/dev/null 2>&1; then GSTACK_BUN_CONFIG=NUL; fi ;; esac
HERE="$(cd "$(dirname "$0")" && pwd -P)" || exit 0
GSTACK_HOOK_HOST=codex bun --no-env-file --config="${GSTACK_BUN_CONFIG:-/dev/null}" "$HERE/codex-destructive-guard-hook.ts" || true
exit 0
+61
View File
@@ -0,0 +1,61 @@
#!/usr/bin/env -S bun --no-env-file --config=/dev/null
/**
* codex-destructive-guard-hook — /careful's destructive-command check as a Codex PreToolUse hook (matcher Bash),
* GST-3172. The decision is check-careful.sh's, through the Claude Code hook's carefulDecision, mapped onto what
* Codex accepts:
*
* deny -> deny, its reason unchanged.
* ask -> Codex 0.170 has no ask (its output parser rejects permissionDecision "ask" and runs the command), so:
* in a session gstack-session-kind calls interactive, a deny whose reason tells the model to stop and
* ask the user, who can run the command themselves with `!` (Codex runs `!` commands without hooks);
* in any other session (codex exec, CI, unattended), a systemMessage warning and no decision, the same
* as Claude Code with nobody to answer.
*
* Every ask category check-careful.sh has, or adds later, takes the same path: nothing here names one.
* Codex starts hooks without CODEX_THREAD_ID, which gstack-session-kind needs to find a `codex exec` parent, so the
* payload's session_id stands in for it. Always exits 0; with the switch off it prints nothing.
* Docs: docs/skill-routing-and-contracts.md#codex.
*/
import { ASK_NOTE, carefulDecision } from '../../claude/hooks/destructive-guard-hook.ts';
import { sessionKind } from '../../claude/hooks/spawn-bin';
export const CODEX_ASK_NOTE = 'Codex hooks cannot ask, so gstack blocked this command: stop and ask the user whether to run it. '
+ 'If they want it, they can run it themselves by typing ! followed by the command in Codex, '
+ 'or turn this check off with gstack-config set destructive_guard off.';
type CodexOutput = { hookSpecificOutput: { hookEventName: 'PreToolUse'; permissionDecision: 'deny'; permissionDecisionReason: string } } | { systemMessage: string };
/** What Codex gets for check-careful.sh's answer in a session of this kind; null prints nothing. */
export function codexDecision(careful: ReturnType<typeof carefulDecision>, kind: string): CodexOutput | null {
if (!careful || 'raw' in careful) return null;
const o = careful.decision.hookSpecificOutput;
const reason = (o?.permissionDecisionReason ?? '').trim();
const deny = (why: string): CodexOutput => ({ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: why } });
if (o?.permissionDecision === 'deny') return deny(reason || '[careful] Blocked a destructive command.');
if (o?.permissionDecision !== 'ask') return null;
if (kind && kind !== 'interactive') {
return { systemMessage: `${reason} ${ASK_NOTE} Allowed without asking: this ${kind} session has nobody to answer.`.trim() };
}
return deny(`${reason} ${CODEX_ASK_NOTE}`.trim());
}
async function main(): Promise<void> {
const chunks: Buffer[] = [];
for await (const chunk of process.stdin) chunks.push(chunk as Buffer);
const input = Buffer.concat(chunks).toString('utf8');
const careful = carefulDecision(input);
if (!careful || 'raw' in careful) return;
if (careful.decision.hookSpecificOutput?.permissionDecision === 'ask' && !process.env.CODEX_THREAD_ID) {
try {
const id = JSON.parse(input).session_id;
if (typeof id === 'string' && id) process.env.CODEX_THREAD_ID = id;
} catch { /* check-careful.sh already read the payload; no id means no exec signal */ }
}
const kind = careful.decision.hookSpecificOutput?.permissionDecision === 'ask' ? sessionKind(2000) : '';
const out = codexDecision(careful, kind);
if (out) process.stdout.write(JSON.stringify(out) + '\n');
}
if (import.meta.main) {
main().catch(() => {}).finally(() => process.exit(0));
}
+11
View File
@@ -0,0 +1,11 @@
#!/usr/bin/env bash
# Bash shim for Codex: Codex runs hook commands through a login shell, so this
# wrapper makes the TypeScript hook executable via bun. ${CODEX_HOME}/hooks.json
# references it through the Codex runtime root (${CODEX_HOME}/skills/gstack,
# whose hosts/codex/hooks links here), so pwd -P finds the checkout.
#
# FAIL-OPEN: every failure path — bun missing, script crash — still exits 0.
GSTACK_BUN_CONFIG=/dev/null; case "${OSTYPE:-}" in msys*|cygwin*) if command -v cygpath >/dev/null 2>&1; then GSTACK_BUN_CONFIG=NUL; fi ;; esac
HERE="$(cd "$(dirname "$0")" && pwd -P)" || exit 0
GSTACK_HOOK_HOST=codex bun --no-env-file --config="${GSTACK_BUN_CONFIG:-/dev/null}" "$HERE/codex-skill-route-hook.ts" || true
exit 0
+11
View File
@@ -0,0 +1,11 @@
#!/usr/bin/env -S bun --no-env-file --config=/dev/null
/**
* codex-skill-route-hook — the skill-routing hook on Codex (GST-3172). The same UserPromptSubmit hook as Claude
* Code's (hosts/claude/hooks/skill-route-hook.ts) with host codex: it scans ${CODEX_HOME:-~/.codex}/skills, names
* skills as Codex does (gstack-review), words the hint for Codex, and never routes a prompt that starts with `$`
* (a Codex skill mention) or `/`. Same switch (skill_routing), same deadline, same trace log.
* Docs: docs/skill-routing-and-contracts.md#codex.
*/
import { runSkillRouteHook } from '../../claude/hooks/skill-route-hook.ts';
runSkillRouteHook('codex');
+50 -3
View File
@@ -89,6 +89,16 @@ export function readSkillSwitch(name: SwitchName, env: NodeJS.ProcessEnv = proce
return v ? { on: v === 'on', source: `config ${name}` } : { on: fallback, source: `config ${name}`, invalid: cfg };
}
/** The host a skill hook runs under: codex when its Codex wrapper (hosts/codex/hooks) set GSTACK_HOOK_HOST, else Claude Code. */
export type HookHost = 'claude' | 'codex';
export const hookHost = (env: NodeJS.ProcessEnv = process.env): HookHost => (env.GSTACK_HOOK_HOST === 'codex' ? 'codex' : 'claude');
/** Where Codex reads skills: GSTACK_INSTALLED_SKILLS_DIR, else ${CODEX_HOME:-~/.codex}/skills. */
export function codexSkillsDir(env: NodeJS.ProcessEnv = process.env): string {
if (env.GSTACK_INSTALLED_SKILLS_DIR) return env.GSTACK_INSTALLED_SKILLS_DIR;
return path.join(env.CODEX_HOME || path.join(env.HOME || os.homedir(), '.codex'), 'skills');
}
/** Where Claude Code reads skills: GSTACK_INSTALLED_SKILLS_DIR, else ${CLAUDE_CONFIG_DIR:-~/.claude}/skills. */
export function installedSkillsDir(env: NodeJS.ProcessEnv = process.env): string {
if (env.GSTACK_INSTALLED_SKILLS_DIR) return env.GSTACK_INSTALLED_SKILLS_DIR;
@@ -192,6 +202,30 @@ export function scanInstalledSkills(dir: string): { skills: InstalledSkill[]; pr
return { skills, problems };
}
/**
* Codex's skills, as scanInstalledSkills reads them, with each gstack skill (a gstack-<name> directory) named by
* its directory, the name Codex mentions it by ($gstack-review). Codex renders keep only name and description, so
* a gstack skill without triggers takes them from the same skill's Claude render in this checkout.
*/
export function scanCodexSkills(dir: string): { skills: InstalledSkill[]; problems: string[] } {
const { skills, problems } = scanInstalledSkills(dir);
return {
problems,
skills: skills.map(s => {
const entry = path.basename(path.dirname(s.file));
if (!entry.startsWith('gstack-') || !isGstackSkill({ ...s, name: entry })) return s;
let triggers = s.triggers;
if (!triggers.length) {
try {
const fm = readFrontmatter(path.join(GSTACK_ROOT, entry.slice('gstack-'.length), 'SKILL.md'));
if (fm && /^triggers:/m.test(fm)) triggers = frontmatterList(`---\n${fm}\n---`, 'triggers');
} catch { /* no Claude render beside this file: the skill routes on nothing */ }
}
return { ...s, name: entry, triggers, gstack: true };
}),
};
}
const STOPWORDS = new Set(('a an the this that these those it its i me my we our us you your he she they them their ' +
'is are was were be been being am do does did done to of in on at by for from with as into onto about and or but ' +
'so if then than just please can could would should will shall may might must some any all here there now ' +
@@ -302,12 +336,14 @@ const isRouted = (s: InstalledSkill) => !isGstackSkill(s) || ROUTED_SKILLS.inclu
export type RouteDecision =
| { route: RouteCandidate; routes: RouteCandidate[]; candidates: RouteCandidate[] }
| { route: null; reason: 'slash-command' | 'empty' | 'below-threshold'; candidates: RouteCandidate[] };
| { route: null; reason: 'slash-command' | 'skill-mention' | 'empty' | 'below-threshold'; candidates: RouteCandidate[] };
export function routePrompt(prompt: string, skills: InstalledSkill[], threshold = ROUTE_THRESHOLD): RouteDecision {
/** A prompt that already names a command is never routed: `/` on both hosts, and Codex's `$skill` mention there. */
export function routePrompt(prompt: string, skills: InstalledSkill[], threshold = ROUTE_THRESHOLD, host: HookHost = 'claude'): RouteDecision {
const trimmed = prompt.trim();
if (!trimmed) return { route: null, reason: 'empty', candidates: [] };
if (trimmed.startsWith('/')) return { route: null, reason: 'slash-command', candidates: [] };
if (host === 'codex' && trimmed.startsWith('$')) return { route: null, reason: 'skill-mention', candidates: [] };
const candidates = scorePrompt(prompt, skills.filter(isRouted));
const routes = candidates.filter((c, i) => c.score >= threshold && candidates.findIndex(o => o.skill === c.skill) === i).slice(0, MAX_ROUTES);
return routes.length ? { route: routes[0], routes, candidates } : { route: null, reason: 'below-threshold', candidates };
@@ -324,7 +360,8 @@ export function hintVariant(env: NodeJS.ProcessEnv = process.env): HintVariant {
}
/** The one additionalContext line: its source, its off switch, the skill (or two), and the ask to say gstack routed it. */
export function hintLine(route: RouteCandidate, extra = '', also?: RouteCandidate): string {
export function hintLine(route: RouteCandidate, extra = '', also?: RouteCandidate, host: HookHost = 'claude'): string {
if (host === 'codex') return codexHintLine(route, extra, also);
const s = `/${route.skill}`;
const matched = (r: RouteCandidate) => `the installed /${r.skill} trigger "${r.trigger.replace(/["\s]+/g, ' ').trim()}"`;
const head = `gstack skill routing (UserPromptSubmit hook; matched ${matched(route)}${also ? ` and ${matched(also)}` : ''}; off: gstack-config set skill_routing off): `;
@@ -334,6 +371,16 @@ export function hintLine(route: RouteCandidate, extra = '', also?: RouteCandidat
return head + ask + (extra.trim() ? ` ${extra.replace(/\s+/g, ' ').trim()}` : '');
}
/** hintLine's Codex wording: skills by their Codex names (gstack-review), read and followed rather than run with the Skill tool. */
function codexHintLine(route: RouteCandidate, extra: string, also?: RouteCandidate): string {
const matched = (r: RouteCandidate) => `the installed ${r.skill} trigger "${r.trigger.replace(/["\s]+/g, ' ').trim()}"`;
const head = `gstack skill routing (UserPromptSubmit hook; matched ${matched(route)}${also ? ` and ${matched(also)}` : ''}; off: gstack-config set skill_routing off): `;
const ask = also
? `this request fits the ${route.skill} or ${also.skill} skill. Read and follow the one that fits better before you start (${route.skill} if both fit), and tell the user in one sentence which skill gstack routed this to.`
: `this request fits the ${route.skill} skill. Read and follow the ${route.skill} skill before you start, and tell the user in one sentence that gstack routed this to ${route.skill}.`;
return head + ask + (extra.trim() ? ` ${extra.replace(/\s+/g, ' ').trim()}` : '');
}
/** First sentence under a skill body's first "Step 1", "Phase 1" or "How to work" heading, plain text, at most 200 chars; '' without one. */
export function firstStep(skillMd: string): string {
const m = /^#{2,3}\s+(?:Step\s*0*1\b|Phase\s*0*1\b|How to work\b).*$/im.exec(skillMd);
@@ -1 +1 @@
{"blob":"6f9f93ff672653c72d9e0d97ff9499b6062890a3","since":6,"nonBehavioral":"adds crew/scripts/release-notes.ts to the free-only list beside release-cut.ts"}
{"blob":"5fa6f0beccfc08d49513c6cca9b1ae29a09265d8","since":6,"nonBehavioral":"Adds the new Codex hooks workflow to FREE_ONLY_PR_FILES; no paid case reads it, so no eval verdict can change"}
+1
View File
@@ -268,6 +268,7 @@ export const FREE_ONLY_PR_FILES = [
'.github/workflows/actionlint.yml',
'.github/workflows/arm-setup-smoke.yml',
'.github/workflows/ci-image.yml',
'.github/workflows/codex-hooks.yml', // Installs the pinned Codex CLI and runs the free test/codex-hooks-real-codex.test.ts; no paid case reads it.
'.github/workflows/cso-runtime-images.yml',
'.github/workflows/cso-runtime-promote.yml',
'.github/workflows/cso-runtime-qualification.yml',
+85 -3
View File
@@ -3187,6 +3187,11 @@ create_codex_runtime_root() {
if [ -d "$gstack_dir/lib" ]; then
_link_or_copy "$gstack_dir/lib" "$codex_gstack/lib"
fi
# Codex hook shims: ${CODEX_HOME}/hooks.json names this stable path (GST-3172).
if [ -d "$gstack_dir/hosts/codex/hooks" ]; then
mkdir -p "$codex_gstack/hosts/codex"
_link_or_copy "$gstack_dir/hosts/codex/hooks" "$codex_gstack/hosts/codex/hooks"
fi
if [ -d "$gstack_dir/browse/dist" ]; then
_link_or_copy "$gstack_dir/browse/dist" "$codex_gstack/browse/dist"
fi
@@ -3987,6 +3992,7 @@ if [ "$INSTALL_CODEX" -eq 1 ]; then
log " codex skills: $CODEX_SKILLS"
log " model profile: $CODEX_GENERATION_MODEL ($CODEX_GENERATION_MODEL_SOURCE)"
log " model changes: rerun ./setup --host codex"
log " reasoning effort: gstack's workflows do best at high; start Codex with codex -c model_reasoning_effort=high (setup leaves config.toml alone)"
if [ "$MODEL_OVERRIDE_SET" -eq 1 ]; then
log " note: --model applies to this run only. To persist across upgrades,"
log " set model = \"$MODEL_OVERRIDE\" in \${CODEX_HOME:-~/.codex}/config.toml."
@@ -4359,16 +4365,18 @@ CANONICAL_GSTACK_ROOT="$(gstack_canonical_claude_root)"
# Echo the canonical path for a hook (repo-relative arg); fails when the hook
# is not executable at the canonical install — callers must skip + log.
# A hook the parse gate below refused is never registered.
# A hook the parse gate below refused is never registered. A second argument
# names another stable root: the Codex runtime root for Codex's hooks.
_HOOK_REFUSED=""
_hook_refused() {
case " $_HOOK_REFUSED " in *" $1 "*) return 0 ;; esac
return 1
}
_hook_command_path() {
local root="${2:-$CANONICAL_GSTACK_ROOT}"
_hook_refused "$1" && return 1
if [ -x "$CANONICAL_GSTACK_ROOT/$1" ]; then
printf '%s\n' "$CANONICAL_GSTACK_ROOT/$1"
if [ -x "$root/$1" ]; then
printf '%s\n' "$root/$1"
return 0
fi
return 1
@@ -5014,6 +5022,7 @@ _skill_hook_gate() {
if [ -n "$mode" ] && [ "$unrecognized" -eq 0 ]; then
"$GSTACK_CONFIG" set "$key" "$decision" >/dev/null 2>&1 || true
fi
if [ -n "${CODEX_HOOKS_FILE:-}" ]; then _codex_hook_gate "$key" "$decision" "$src"; fi
[ -x "$SETTINGS_HOOK" ] || return 0
if [ "$decision" = "off" ] || [ "$NO_TEAM_MODE" -eq 1 ]; then
"$SETTINGS_HOOK" remove-source --source "$source" >/dev/null 2>&1 || true
@@ -5036,6 +5045,67 @@ _skill_hook_gate() {
fi
done
}
# ─── Codex hooks (GST-3172) ──────────────────────────────────────────────────
# The same switches register two Codex hooks in ${CODEX_HOME:-~/.codex}/hooks.json
# (docs/skill-routing-and-contracts.md#codex): skill_routing (UserPromptSubmit)
# and destructive_guard (PreToolUse on Bash), each in its own matcher group with
# an explicit timeout (Codex's default is 600 s). gstack-settings-hook writes the
# file in its Codex format: no tag keys (Codex skips a hooks.json with a key it
# does not know, the user's hooks included), the user's groups left as they are,
# a schema re-read before the rename, the usual lock, backup and rollback.
# Commands point at the Codex runtime root, never a version folder: Codex asks
# the user to trust a hook again whenever its command or timeout changes.
# Setup never writes trust; Codex skips the hooks until the user trusts them.
CODEX_HOOKS_FILE=""
CODEX_HOOKS_READY=0
CODEX_HOOKS_MIN="0.170.0"
CODEX_SETTINGS_HOOK="$SOURCE_GSTACK_DIR/bin/gstack-settings-hook"
_CODEX_HOOKS_CHANGED=0
if [ "$INSTALL_CODEX" -eq 1 ] && [ "$CODEX_REPO_LOCAL" -eq 0 ] && [ -x "$CODEX_SETTINGS_HOOK" ]; then
CODEX_HOOKS_FILE="$(dirname "$CODEX_SKILLS")/hooks.json"
_CODEX_VERSION="$(codex --version 2>/dev/null | sed -n 's/^codex-cli \([0-9][0-9.]*\).*/\1/p' | head -1 || true)"
if [ -z "$_CODEX_VERSION" ]; then
log " Codex hooks not registered: no codex on PATH to check (gstack's hooks need Codex $CODEX_HOOKS_MIN or newer). Install Codex, then re-run ./setup --host codex"
elif [ "$(printf '%s\n%s\n' "$CODEX_HOOKS_MIN" "$_CODEX_VERSION" | sort -t. -k1,1n -k2,2n -k3,3n | head -1)" != "$CODEX_HOOKS_MIN" ]; then
log " Codex hooks not registered: Codex $_CODEX_VERSION is older than $CODEX_HOOKS_MIN, the first version they are tested on. Upgrade (npm install -g @openai/codex), then re-run ./setup --host codex"
else
CODEX_HOOKS_READY=1
fi
fi
CODEX_ROUTE_HOOK="$(_hook_command_path hosts/codex/hooks/codex-skill-route-hook "$CODEX_GSTACK" || true)"
CODEX_GUARD_HOOK="$(_hook_command_path hosts/codex/hooks/codex-destructive-guard-hook "$CODEX_GSTACK" || true)"
# _codex_hook_gate KEY DECISION SOURCE_OF_DECISION — called from _skill_hook_gate
# with the decision it resolved, so both hosts follow one switch (D1).
_codex_hook_gate() {
local key="$1" decision="$2" src="$3" event cmd source timeout matcher out
case "$key" in
skill_routing) event=UserPromptSubmit; cmd="$CODEX_ROUTE_HOOK"; source=gstack-skill-route; timeout=5; matcher="" ;;
destructive_guard) event=PreToolUse; cmd="$CODEX_GUARD_HOOK"; source=gstack-destructive-guard; timeout=10; matcher=Bash ;;
*) return 0 ;;
esac
if [ "$decision" = "off" ] || [ "$NO_TEAM_MODE" -eq 1 ]; then
[ -f "$CODEX_HOOKS_FILE" ] || return 0
GSTACK_HOOKS_FORMAT=codex GSTACK_SETTINGS_FILE="$CODEX_HOOKS_FILE" "$CODEX_SETTINGS_HOOK" remove-source --source "$source" >/dev/null \
|| log " warning: could not remove gstack's Codex $event hook from $CODEX_HOOKS_FILE"
return 0
fi
[ "$CODEX_HOOKS_READY" -eq 1 ] || return 0
if [ -z "$cmd" ]; then
log " Codex $event hook not registered: $CODEX_GSTACK/hosts/codex/hooks is missing or does not parse"
return 0
fi
if out=$(GSTACK_HOOKS_FORMAT=codex GSTACK_SETTINGS_FILE="$CODEX_HOOKS_FILE" "$CODEX_SETTINGS_HOOK" ensure-event --event "$event" \
--command "$cmd" --source "$source" --timeout "$timeout" ${matcher:+--matcher "$matcher"} 2>&1); then
case "$out" in
*unchanged*) : ;;
*) _CODEX_HOOKS_CHANGED=1
log " registered Codex $event hook in $CODEX_HOOKS_FILE (on via $src; turn off: gstack-config set $key off, or ./setup --no-${key//_/-})" ;;
esac
else
log " warning: Codex hooks not registered: $(printf '%s\n' "$out" | head -1)"
fi
}
_HOOKS_ON_BY_DEFAULT=""
SKILL_ROUTE_BIN="$SOURCE_GSTACK_DIR/bin/gstack-skill-route"
SKILL_ROUTE_HOOK="$(_hook_command_path hosts/claude/hooks/skill-route-hook || true)"
@@ -5052,6 +5122,18 @@ DESTRUCTIVE_GUARD_HOOK="$(_hook_command_path hosts/claude/hooks/destructive-guar
_skill_hook_gate destructive_guard "$DESTRUCTIVE_GUARD_MODE" GSTACK_DESTRUCTIVE_GUARD PreToolUse \
"$DESTRUCTIVE_GUARD_HOOK" gstack-destructive-guard 10 \
"destructive commands (rm -rf, DROP TABLE, force-push) ask before they run" 'Bash|PowerShell'
# Codex skips a hook nobody trusted yet, silently, so say so once per run while
# any of gstack's Codex hooks waits for trust; setup never writes trust itself.
if [ "$CODEX_HOOKS_READY" -eq 1 ] && [ -f "$CODEX_HOOKS_FILE" ]; then
_CODEX_UNTRUSTED="$(GSTACK_HOOKS_FORMAT=codex GSTACK_SETTINGS_FILE="$CODEX_HOOKS_FILE" "$CODEX_SETTINGS_HOOK" trust-status 2>/dev/null | grep -c 'untrusted$' || true)"
if [ "${_CODEX_UNTRUSTED:-0}" -gt 0 ]; then
if [ "$_CODEX_HOOKS_CHANGED" -eq 1 ]; then
log "gstack added $_CODEX_UNTRUSTED Codex hook(s); trust them at Codex's startup prompt or in /hooks (Codex skips them until you do)."
else
log "gstack's $_CODEX_UNTRUSTED Codex hook(s) are not trusted yet; trust them at Codex's startup prompt or in /hooks (Codex skips them until you do)."
fi
fi
fi
# One notice, the first time a default turns these hooks on (an install that
# predates the default, or a new one). An off you set earlier is kept: the
# gate reads it before the default.
+99
View File
@@ -0,0 +1,99 @@
/**
* A real Codex reads the hooks.json gstack writes (GST-3172), with no model call: Codex 0.170 skips the whole file
* when it holds a key it does not know, the user's hooks included, so this is the check that matters most. Each
* run points Codex at a provider on a closed local port, so it runs SessionStart and UserPromptSubmit hooks and
* then retries the network until the test stops it. Skips without codex 0.170+ on PATH, unless
* GSTACK_REQUIRE_CODEX=1 (the codex-hooks CI job), where a missing codex fails instead.
*/
import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { spawn, spawnSync } from 'node:child_process';
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
const ROOT = path.resolve(import.meta.dir, '..');
const version = (() => {
const r = spawnSync('codex', ['--version'], { encoding: 'utf8', timeout: 30_000 });
return /^codex-cli (\d+)\.(\d+)\.(\d+)/m.exec(r.stdout ?? '');
})();
const usable = !!version && (Number(version[1]) > 0 || Number(version[2]) >= 170);
const required = process.env.GSTACK_REQUIRE_CODEX === '1';
let dir = '';
beforeEach(() => { dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-real-codex-')); });
afterEach(() => fs.rmSync(dir, { recursive: true, force: true }));
const home = () => path.join(dir, 'codex');
const marker = () => path.join(dir, 'user-session-start');
const routeLog = () => path.join(dir, 'state', 'hooks', 'skill-route.log');
/** The user's own SessionStart hook, then gstack's two groups through gstack-settings-hook's Codex format. */
function install(): void {
fs.mkdirSync(home(), { recursive: true });
fs.writeFileSync(path.join(home(), 'hooks.json'), JSON.stringify({
hooks: { SessionStart: [{ hooks: [{ type: 'command', command: 'touch ' + marker(), timeout: 5 }] }] },
}, null, 2));
const hook = (args: string[]) => {
const r = spawnSync('bash', [path.join(ROOT, 'bin', 'gstack-settings-hook'), ...args], {
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 shims = path.join(ROOT, 'hosts', 'codex', 'hooks');
hook(['ensure-event', '--event', 'UserPromptSubmit', '--command', path.join(shims, 'codex-skill-route-hook'), '--source', 'gstack-skill-route', '--timeout', '5']);
hook(['ensure-event', '--event', 'PreToolUse', '--command', path.join(shims, 'codex-destructive-guard-hook'), '--source', 'gstack-destructive-guard', '--matcher', 'Bash', '--timeout', '10']);
const skills = path.join(dir, 'skills', 'gstack-review');
fs.mkdirSync(skills, { recursive: true });
fs.writeFileSync(path.join(skills, 'SKILL.md'), '---\nname: review\ndescription: Review a diff before it lands.\n---\n');
}
/** Run codex exec until both hooks would have fired (or Codex reached the network), then stop it. */
async function codexExec(extra: string[]): Promise<string> {
const work = path.join(dir, 'work');
fs.mkdirSync(work, { recursive: true });
const child = spawn('codex', ['exec', '--skip-git-repo-check', ...extra, '-c', 'model_provider=gstack_null',
'-c', 'model_providers.gstack_null={name="null",base_url="http://127.0.0.1:9/v1",wire_api="responses"}', 'please review my changes'], {
cwd: work, stdio: ['ignore', 'pipe', 'pipe'],
env: {
PATH: process.env.PATH ?? '', HOME: dir, CODEX_HOME: home(), OPENAI_API_KEY: 'sk-not-a-real-key', SHELL: '/bin/bash',
GSTACK_STATE_ROOT: path.join(dir, 'state'), GSTACK_INSTALLED_SKILLS_DIR: path.join(dir, 'skills'),
},
});
let out = '';
child.stdout.on('data', d => { out += d; });
child.stderr.on('data', d => { out += d; });
const deadline = Date.now() + 45_000;
while (Date.now() < deadline && !/Reconnecting|stream error|error sending request/i.test(out)) await Bun.sleep(250);
await Bun.sleep(1000);
child.kill('SIGKILL');
return out;
}
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 /);
expect(usable).toBe(true);
});
test("Codex runs the user's hook and gstack's routing hook from the merged file", async () => {
install();
const out = await codexExec(['--dangerously-bypass-hook-trust']);
expect(fs.existsSync(marker())).toBe(true);
expect(fs.readFileSync(routeLog(), 'utf8')).toMatch(/event=routed skill=gstack-review .*host=codex/);
expect(out).not.toContain('failed to parse hooks config');
}, 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');
const good = fs.readFileSync(file, 'utf8');
fs.writeFileSync(file, good.replace('"hooks": {', '"_gstack_source": "x",\n "hooks": {'));
await codexExec(['--dangerously-bypass-hook-trust']);
expect(fs.existsSync(marker())).toBe(false);
expect(fs.existsSync(routeLog())).toBe(false);
fs.writeFileSync(file, good);
await codexExec([]);
expect(fs.existsSync(marker())).toBe(false);
expect(fs.existsSync(routeLog())).toBe(false);
}, 120_000);
});
+175
View File
@@ -0,0 +1,175 @@
/**
* setup, gstack-uninstall and gstack-doctor for gstack's Codex hooks (GST-3172). setup's _skill_hook_gate and
* _codex_hook_gate are lifted out and run against the real gstack-config and gstack-settings-hook with a temp state
* root, a temp hooks.json and no Claude install, so one switch drives both hosts (plan D1). The Codex version
* floor and the doctor row are lifted the same way; uninstall runs whole against a mock home.
*/
import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { spawnSync } from 'node:child_process';
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
const ROOT = path.resolve(import.meta.dir, '..');
const setupSrc = fs.readFileSync(path.join(ROOT, 'setup'), 'utf8');
const between = (from: string, to: string) => {
const a = setupSrc.indexOf(from);
const b = setupSrc.indexOf(to, a);
if (a < 0 || b < 0) throw new Error('setup no longer has ' + from + ' ... ' + to);
return setupSrc.slice(a, b);
};
const fnBody = (name: string) => {
const a = setupSrc.indexOf(name + '() {');
return setupSrc.slice(a, setupSrc.indexOf('\n}\n', a) + 3);
};
let dir = '';
beforeEach(() => { dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-codex-setup-')); });
afterEach(() => fs.rmSync(dir, { recursive: true, force: true }));
const hooksFile = () => path.join(dir, 'codex', 'hooks.json');
const hooks = () => (fs.existsSync(hooksFile()) ? JSON.parse(fs.readFileSync(hooksFile(), 'utf8')).hooks ?? {} : {});
const run = (script: string, env: Record<string, string> = {}) => {
const r = spawnSync('bash', ['-c', script], {
env: { PATH: process.env.PATH ?? '', HOME: dir, GSTACK_STATE_ROOT: path.join(dir, 'state'), ...env },
encoding: 'utf8', timeout: 60_000,
});
return { code: r.status, out: (r.stdout ?? '') + (r.stderr ?? '') };
};
describe('setup: Codex hook registration', () => {
test('both Codex hooks resolve through _hook_command_path against the Codex runtime root, which links hosts/codex/hooks', () => {
expect(setupSrc).toContain('CODEX_ROUTE_HOOK="$(_hook_command_path hosts/codex/hooks/codex-skill-route-hook "$CODEX_GSTACK" || true)"');
expect(setupSrc).toContain('CODEX_GUARD_HOOK="$(_hook_command_path hosts/codex/hooks/codex-destructive-guard-hook "$CODEX_GSTACK" || true)"');
expect(fnBody('create_codex_runtime_root')).toContain('_link_or_copy "$gstack_dir/hosts/codex/hooks" "$codex_gstack/hosts/codex/hooks"');
expect(fnBody('_skill_hook_gate')).toContain('if [ -n "${CODEX_HOOKS_FILE:-}" ]; then _codex_hook_gate "$key" "$decision" "$src"; fi');
for (const f of ['codex-skill-route-hook', 'codex-destructive-guard-hook']) {
expect(fs.statSync(path.join(ROOT, 'hosts', 'codex', 'hooks', f)).mode & 0o111).toBeTruthy();
}
});
/** 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');
const script = [
'set -e',
'log() { printf "%s\\n" "$*"; }',
'GSTACK_CONFIG="' + ROOT + '/bin/gstack-config"',
'SETTINGS_HOOK=""',
'SKILL_ROUTE_BIN="' + ROOT + '/bin/gstack-skill-route"',
'IS_WINDOWS=0; NO_TEAM_MODE=' + noTeam,
'CODEX_HOOKS_FILE="' + hooksFile() + '"; CODEX_HOOKS_READY=1; _CODEX_HOOKS_CHANGED=0',
'CODEX_SETTINGS_HOOK="' + ROOT + '/bin/gstack-settings-hook"; CODEX_GSTACK="' + runtimeRoot + '"',
'CODEX_ROUTE_HOOK="' + runtimeRoot + '/hosts/codex/hooks/codex-skill-route-hook"',
'CODEX_GUARD_HOOK="' + runtimeRoot + '/hosts/codex/hooks/codex-destructive-guard-hook"',
fnBody('_codex_hook_gate'),
fnBody('_skill_hook_gate'),
'_skill_hook_gate ' + key + ' "$1" GSTACK_X Event "" source 5 "what"',
].join('\n');
fs.mkdirSync(path.dirname(hooksFile()), { recursive: true });
const r = spawnSync('bash', ['-c', script, 'gate', mode], {
env: { PATH: process.env.PATH ?? '', HOME: dir, GSTACK_STATE_ROOT: path.join(dir, 'state'), ...env }, encoding: 'utf8', timeout: 60_000,
});
return { code: r.status, out: (r.stdout ?? '') + (r.stderr ?? '') };
}
test('on registers each hook in its own group with its timeout and says how to turn it off; a re-run is quiet', () => {
const routing = gate('skill_routing', 'on');
expect(routing.code).toBe(0);
expect(routing.out).toContain('registered Codex UserPromptSubmit hook in ' + hooksFile() + ' (on via flag; turn off: gstack-config set skill_routing off, or ./setup --no-skill-routing)');
expect(gate('destructive_guard', 'on').out).toContain('registered Codex PreToolUse hook');
expect(hooks().UserPromptSubmit).toEqual([{ hooks: [{ type: 'command', command: expect.stringMatching(/hosts\/codex\/hooks\/codex-skill-route-hook$/), timeout: 5 }] }]);
expect(hooks().PreToolUse).toEqual([{ matcher: 'Bash', hooks: [{ type: 'command', command: expect.stringMatching(/hosts\/codex\/hooks\/codex-destructive-guard-hook$/), timeout: 10 }] }]);
expect(gate('skill_routing', '')).toEqual({ code: 0, out: '' });
expect(gate('skill_contracts', 'on').out).not.toContain('Codex');
expect(Object.keys(hooks()).sort()).toEqual(['PreToolUse', 'UserPromptSubmit']);
});
test("off, a saved off and --no-team remove only gstack's Codex group", () => {
gate('skill_routing', 'on');
gate('destructive_guard', 'on');
gate('skill_routing', 'off');
expect(hooks().UserPromptSubmit).toBeUndefined();
expect(hooks().PreToolUse).toHaveLength(1);
gate('skill_routing', '');
expect(hooks().UserPromptSubmit).toBeUndefined();
gate('destructive_guard', '', {}, 1);
expect(hooks()).toEqual({});
});
test('the version floor: no codex, or one older than 0.170, registers nothing and says why', () => {
const block = between('CODEX_HOOKS_FILE=""\n', 'CODEX_ROUTE_HOOK=');
const bin = path.join(dir, 'bin');
fs.mkdirSync(bin);
const withCodex = (version: string | null) => {
fs.rmSync(path.join(bin, 'codex'), { force: true });
if (version) fs.writeFileSync(path.join(bin, 'codex'), '#!/bin/sh\necho "codex-cli ' + version + '"\n', { mode: 0o755 });
const script = ['log() { printf "%s\\n" "$*"; }', 'INSTALL_CODEX=1; CODEX_REPO_LOCAL=0', 'SOURCE_GSTACK_DIR="' + ROOT + '"',
'CODEX_SKILLS="' + path.join(dir, 'codex', 'skills') + '"', block, 'echo "READY=$CODEX_HOOKS_READY FILE=$CODEX_HOOKS_FILE"'].join('\n');
return run(script, { PATH: bin + ':' + path.dirname(process.execPath) + ':/usr/bin:/bin' }).out;
};
expect(withCodex(null)).toContain("Codex hooks not registered: no codex on PATH to check (gstack's hooks need Codex 0.170.0 or newer)");
expect(withCodex(null)).toContain('READY=0');
expect(withCodex('0.169.9')).toContain('Codex 0.169.9 is older than 0.170.0');
for (const v of ['0.170.0', '0.171.2', '0.1700.0', '1.0.0']) expect(withCodex(v)).toContain('READY=1 FILE=' + path.join(dir, 'codex', 'hooks.json'));
});
});
describe('gstack-uninstall and gstack-doctor with Codex hooks', () => {
function seed(): { user: unknown } {
const codex = path.join(dir, 'home', '.codex');
fs.mkdirSync(codex, { recursive: true });
const user = { matcher: 'Bash', hooks: [{ type: 'command', command: '/usr/local/bin/my-guard', timeout: 3 }] };
const ours = { matcher: 'Bash', hooks: [{ type: 'command', command: codex + '/skills/gstack/hosts/codex/hooks/codex-destructive-guard-hook', timeout: 10 }] };
const route = { hooks: [{ type: 'command', command: codex + '/skills/gstack/hosts/codex/hooks/codex-skill-route-hook', timeout: 5 }] };
fs.writeFileSync(path.join(codex, 'hooks.json'), JSON.stringify({ hooks: { PreToolUse: [user, ours], UserPromptSubmit: [route] } }, null, 2));
return { user };
}
test("uninstall removes gstack's Codex groups and keeps the user's", () => {
const { user } = seed();
const home = path.join(dir, 'home');
fs.mkdirSync(path.join(dir, 'repo'));
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,
});
expect(r.status).toBe(0);
expect(r.stdout).toContain("gstack's Codex hooks in " + path.join(home, '.codex', 'hooks.json'));
expect(JSON.parse(fs.readFileSync(path.join(home, '.codex', 'hooks.json'), 'utf8'))).toEqual({ hooks: { PreToolUse: [user] } });
});
test("uninstall run from a global install removes gstack's Codex groups before deleting its own helper", () => {
const { user } = seed();
const home = path.join(dir, 'home');
const bin = path.join(home, '.claude', 'skills', 'gstack', 'bin');
fs.mkdirSync(bin, { recursive: true });
for (const f of ['gstack-uninstall', 'gstack-settings-hook', 'gstack-lock.sh', 'gstack-state-root.sh', 'gstack-skill-name.sh']) fs.copyFileSync(path.join(ROOT, 'bin', f), path.join(bin, f));
fs.mkdirSync(path.join(dir, 'repo'));
const r = spawnSync('bash', [path.join(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,
});
expect(r.status).toBe(0);
expect(fs.existsSync(bin)).toBe(false);
expect(JSON.parse(fs.readFileSync(path.join(home, '.codex', 'hooks.json'), 'utf8'))).toEqual({ hooks: { PreToolUse: [user] } });
});
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');
const a = doctor.indexOf('check_codex_hooks() {');
const fn = doctor.slice(a, doctor.indexOf('\n}\n', a) + 3);
const script = [
'row() { printf "%s|%s|%s|%s\\n" "$1" "$2" "$3" "${4:-}"; }',
"clamp() { local LC_ALL=C line pat=\"[^$1]\"; IFS= read -r line; line=${line//$pat/}; printf '%s' \"${line:0:$2}\"; }",
'BIN="' + ROOT + '/bin"; SRC="' + ROOT + '"', fn, 'check_codex_hooks',
].join('\n');
const codexHome = path.join(dir, 'home', '.codex');
expect(run(script, { CODEX_HOME: codexHome }).out).toBe('warn|codex hooks|destructive-guard no trust entry, skill-route no trust entry (Codex skips a hook until it is trusted)|open Codex and trust them at its startup prompt or in /hooks\n');
const file = fs.realpathSync(path.join(codexHome, 'hooks.json'));
fs.writeFileSync(path.join(codexHome, 'config.toml'), '[hooks.state."' + file + ':pre_tool_use:1:0"]\ntrusted_hash = "sha256:a"\n[hooks.state."' + file + ':user_prompt_submit:0:0"]\ntrusted_hash = "sha256:b"\n');
expect(run(script, { CODEX_HOME: codexHome }).out).toBe('ok|codex hooks|destructive-guard trusted, skill-route trusted (trust entry found; hash not checked)|\n');
fs.writeFileSync(path.join(codexHome, 'hooks.json'), JSON.stringify({ hooks: {} }));
expect(run(script, { CODEX_HOME: codexHome }).out).toBe('');
});
});
+347
View File
@@ -0,0 +1,347 @@
/**
* gstack's hooks on Codex (GST-3172, plan GSTA-638 A1/B1/C1/D1): the Codex hooks.json format of
* bin/gstack-settings-hook, the routing and destructive-command hooks with host codex, and setup's and uninstall's
* wiring. Payloads come from codex-cli 0.170 probes (test/fixtures/codex-hooks). Claude Code's output is pinned
* unchanged here: the hint text, the routing of a "$" prompt, and the settings.json entries for the three hooks.
*/
import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { spawnSync } from 'node:child_process';
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import { codexDecision, CODEX_ASK_NOTE } from '../hosts/codex/hooks/codex-destructive-guard-hook.ts';
import { ASK_NOTE } from '../hosts/claude/hooks/destructive-guard-hook.ts';
import { hintLine, routePrompt, scanCodexSkills, type RouteCandidate } from '../lib/skill-route';
const ROOT = path.resolve(import.meta.dir, '..');
const HOOK_BIN = path.join(ROOT, 'bin', 'gstack-settings-hook');
const PAYLOADS = JSON.parse(fs.readFileSync(path.join(ROOT, 'test', 'fixtures', 'codex-hooks', 'codex-0.170-payloads.json'), 'utf8'));
let dir = '';
beforeEach(() => { dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-codex-hooks-')); });
afterEach(() => fs.rmSync(dir, { recursive: true, force: true }));
const hooksFile = () => path.join(dir, 'hooks.json');
const read = () => JSON.parse(fs.readFileSync(hooksFile(), 'utf8'));
const backups = () => fs.readdirSync(dir).filter(f => f.startsWith('hooks.json.bak.'));
function settingsHook(args: string[], env: Record<string, string> = {}) {
const r = spawnSync('bash', [HOOK_BIN, ...args], {
env: { PATH: process.env.PATH ?? '', HOME: dir, GSTACK_HOOKS_FORMAT: 'codex', GSTACK_SETTINGS_FILE: hooksFile(), ...env },
encoding: 'utf8', timeout: 30_000,
});
return { code: r.status, out: (r.stdout ?? '') + (r.stderr ?? '') };
}
const runtime = () => path.join(dir, 'skills', 'gstack');
const ROUTE_CMD = (root = runtime()) => path.join(root, 'hosts', 'codex', 'hooks', 'codex-skill-route-hook');
const GUARD_CMD = (root = runtime()) => path.join(root, 'hosts', 'codex', 'hooks', 'codex-destructive-guard-hook');
const ensureRoute = (root?: string) => settingsHook(['ensure-event', '--event', 'UserPromptSubmit', '--command', ROUTE_CMD(root), '--source', 'gstack-skill-route', '--timeout', '5']);
const ensureGuard = (root?: string) => settingsHook(['ensure-event', '--event', 'PreToolUse', '--command', GUARD_CMD(root), '--source', 'gstack-destructive-guard', '--matcher', 'Bash', '--timeout', '10']);
const USER_FILE = {
description: 'my hooks',
hooks: {
PreToolUse: [{ matcher: 'Bash', hooks: [{ type: 'command', command: '/usr/local/bin/my-guard', timeout: 3, statusMessage: 'checking' }] }],
UserPromptSubmit: [{ hooks: [{ type: 'command', command: '/usr/local/bin/my-prompt-log' }] }],
Stop: [{ hooks: [{ type: 'command', command: '/usr/local/bin/my-stop', async: false }] }],
},
};
const writeUser = (doc: unknown = USER_FILE) => fs.writeFileSync(hooksFile(), JSON.stringify(doc, null, 2) + '\n');
/** The keys Codex 0.170 accepts (codex-rs/config/src/hook_config.rs HooksFile, codex-rs/protocol/src/hooks.rs), written out independently. */
const CODEX_KEYS = {
top: ['description', 'hooks'],
group: ['matcher', 'hooks'],
command: ['type', 'command', 'commandWindows', 'command_windows', 'timeout', 'async', 'statusMessage', 'additionalContextLimit'],
};
function codexKeysOnly(doc: Record<string, any>): void {
for (const k of Object.keys(doc)) expect(CODEX_KEYS.top).toContain(k);
for (const groups of Object.values(doc.hooks ?? {}) as any[][]) {
for (const g of groups) {
for (const k of Object.keys(g)) expect(CODEX_KEYS.group).toContain(k);
for (const h of g.hooks) for (const k of Object.keys(h)) expect(CODEX_KEYS.command).toContain(k);
}
}
}
describe('gstack-settings-hook: Codex hooks.json format', () => {
test('merges after the user groups: theirs keep content and position, gstack adds one group per hook with explicit timeouts and no tag keys', () => {
writeUser();
expect(ensureRoute().out).toContain('OK: UserPromptSubmit hook registered (source: gstack-skill-route)');
expect(ensureGuard().out).toContain('OK: PreToolUse hook registered (source: gstack-destructive-guard)');
const doc = read();
expect(doc.description).toBe('my hooks');
expect(doc.hooks.Stop).toEqual(USER_FILE.hooks.Stop);
expect(doc.hooks.PreToolUse[0]).toEqual(USER_FILE.hooks.PreToolUse[0]);
expect(doc.hooks.UserPromptSubmit[0]).toEqual(USER_FILE.hooks.UserPromptSubmit[0]);
expect(doc.hooks.PreToolUse[1]).toEqual({ matcher: 'Bash', hooks: [{ type: 'command', command: GUARD_CMD(), timeout: 10 }] });
expect(doc.hooks.UserPromptSubmit[1]).toEqual({ hooks: [{ type: 'command', command: ROUTE_CMD(), timeout: 5 }] });
expect(JSON.stringify(doc)).not.toContain('_gstack_source');
codexKeysOnly(doc);
});
test('a re-run changes nothing: no write and no new backup; a moved runtime root re-points in place', () => {
writeUser();
ensureRoute(); ensureGuard();
const bytes = fs.readFileSync(hooksFile(), 'utf8');
const baks = backups().length;
expect(ensureRoute().out).toContain('unchanged');
expect(ensureGuard().out).toContain('unchanged');
expect(fs.readFileSync(hooksFile(), 'utf8')).toBe(bytes);
expect(backups().length).toBe(baks);
const moved = path.join(dir, 'other', 'gstack');
expect(ensureGuard(moved).out).toContain('re-pointed');
const doc = read();
expect(doc.hooks.PreToolUse).toHaveLength(2);
expect(doc.hooks.PreToolUse[1].hooks[0].command).toBe(GUARD_CMD(moved));
});
test('refuses a hooks.json that does not parse, or that Codex would skip, and leaves it byte-identical', () => {
const cases: Array<[string, string]> = [
['{ "hooks": ', 'is not valid JSON'],
[JSON.stringify({ hooks: { PreToolUse: [{ matcher: 'Bash', _gstack_source: 'x', hooks: [] }] } }), 'has the key "_gstack_source", which Codex does not know'],
[JSON.stringify({ hooks: { BeforeTool: [] } }), 'has the key "BeforeTool"'],
[JSON.stringify({ hooks: { Stop: [{ hooks: [{ type: 'command', command: 'x', retries: 2 }] }] } }), 'has the key "retries"'],
[JSON.stringify({ hooks: { Stop: [{ hooks: [{ type: 'shell', command: 'x' }] }] } }), '.type is "shell"'],
[JSON.stringify({ hooks: { Stop: [{ hooks: [{ type: 'command', command: 'x', timeout: 1.5 }] }] } }), 'timeout is not a whole number'],
[JSON.stringify({ version: 1, hooks: {} }), 'has the key "version"'],
];
for (const [text, why] of cases) {
fs.writeFileSync(hooksFile(), text);
const r = ensureRoute();
expect(r.code).toBe(3);
expect(r.out).toContain(why);
expect(r.out).toContain('refusing to mutate');
expect(fs.readFileSync(hooksFile(), 'utf8')).toBe(text);
}
expect(backups()).toEqual([]);
});
test('refuses while config.toml declares a gstack hook under [hooks] or does not parse; user hooks and trust state there are fine', () => {
writeUser();
const cfg = path.join(dir, 'config.toml');
fs.writeFileSync(cfg, '[[hooks.PreToolUse]]\nmatcher = "Bash"\n[[hooks.PreToolUse.hooks]]\ntype = "command"\ncommand = "' + GUARD_CMD() + '"\n');
let r = ensureRoute();
expect(r.code).toBe(3);
expect(r.out).toContain('already declares gstack hook gstack-destructive-guard under [hooks.PreToolUse], and Codex would run it twice');
fs.writeFileSync(cfg, 'model = [\n');
r = ensureRoute();
expect(r.code).toBe(3);
expect(r.out).toContain('does not parse');
expect(read()).toEqual(USER_FILE);
fs.writeFileSync(cfg, 'model = "gpt-6.1-sol"\n[[hooks.Stop]]\n[[hooks.Stop.hooks]]\ntype = "command"\ncommand = "/usr/local/bin/my-stop"\n[hooks.state."/x/hooks.json:stop:0:0"]\ntrusted_hash = "sha256:1"\n');
expect(ensureRoute().code).toBe(0);
});
test('remove-source takes only its hook, prune-stale --all returns the user file exactly, and rollback undoes the last write', () => {
writeUser();
ensureRoute(); ensureGuard();
expect(settingsHook(['remove-source', '--source', 'gstack-skill-route']).out).toContain('removed 1');
expect(read().hooks.UserPromptSubmit).toEqual(USER_FILE.hooks.UserPromptSubmit);
expect(read().hooks.PreToolUse).toHaveLength(2);
const beforeSweep = fs.readFileSync(hooksFile(), 'utf8');
expect(settingsHook(['prune-stale', '--all']).out).toContain('removed 1 gstack hook entries');
expect(read()).toEqual(USER_FILE);
expect(settingsHook(['rollback']).code).toBe(0);
expect(fs.readFileSync(hooksFile(), 'utf8')).toBe(beforeSweep);
});
test('the legacy settings.json verbs are refused in the Codex format', () => {
for (const verb of ['add', 'remove']) {
const r = settingsHook([verb, '/x/bin/gstack-session-update']);
expect(r.code).toBe(1);
expect(r.out).toContain('legacy settings.json verb');
}
expect(fs.existsSync(hooksFile())).toBe(false);
});
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([
'gstack-destructive-guard\tPreToolUse\tuntrusted', 'gstack-skill-route\tUserPromptSubmit\tuntrusted',
]);
const file = fs.realpathSync(hooksFile());
fs.writeFileSync(path.join(dir, 'config.toml'), [
'[hooks.state]', '',
'[hooks.state."' + file + ':pre_tool_use:0:0"]', 'trusted_hash = "sha256:aa"', '',
'[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([
'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', () => {
writeUser();
ensureRoute(); ensureGuard();
const doc = read();
doc.hooks.PreToolUse.push({ matcher: 'Bash', hooks: [{ type: 'command', command: '/usr/local/bin/my-late-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(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', () => {
const home = path.join(dir, 'codex');
const dotfiles = path.join(dir, 'dotfiles');
fs.mkdirSync(home); fs.mkdirSync(dotfiles);
fs.writeFileSync(path.join(dotfiles, 'hooks.json'), JSON.stringify(USER_FILE, null, 2) + '\n');
fs.symlinkSync(path.join(dotfiles, 'hooks.json'), path.join(home, 'hooks.json'));
const linked = { GSTACK_SETTINGS_FILE: path.join(home, 'hooks.json') };
const cfg = path.join(home, 'config.toml');
fs.writeFileSync(cfg, '[[hooks.UserPromptSubmit]]\n[[hooks.UserPromptSubmit.hooks]]\ntype = "command"\ncommand = "' + ROUTE_CMD() + '"\n');
const route = ['ensure-event', '--event', 'UserPromptSubmit', '--command', ROUTE_CMD(), '--source', 'gstack-skill-route', '--timeout', '5'];
const r = settingsHook(route, linked);
expect(r.code).toBe(3);
expect(r.out).toContain(cfg + ' already declares gstack hook gstack-skill-route');
fs.writeFileSync(cfg, '[hooks.state."' + path.join(home, 'hooks.json') + ':user_prompt_submit:1:0"]\ntrusted_hash = "sha256:aa"\n');
expect(settingsHook(route, linked).code).toBe(0);
expect(settingsHook(['trust-status'], linked).out.trim()).toBe('gstack-skill-route\tUserPromptSubmit\ttrusted');
});
test('the formats stay apart: Codex rows never claim settings.json items, Claude rows never claim hooks.json items', () => {
const claudeShaped = { hooks: { PreToolUse: [{ matcher: 'Bash|PowerShell', hooks: [{ type: 'command', command: '/x/.claude/skills/gstack/hosts/claude/hooks/destructive-guard-hook', timeout: 10 }] }] } };
writeUser(claudeShaped);
expect(settingsHook(['prune-stale', '--all']).out).toContain('removed 0');
expect(read()).toEqual(claudeShaped);
const settings = path.join(dir, 'settings.json');
const codexShaped = { hooks: { PreToolUse: [{ matcher: 'Bash', hooks: [{ type: 'command', command: GUARD_CMD() }] }] } };
fs.writeFileSync(settings, JSON.stringify(codexShaped));
expect(settingsHook(['prune-stale', '--all'], { GSTACK_HOOKS_FORMAT: '', GSTACK_SETTINGS_FILE: settings }).out).toContain('removed 0');
expect(JSON.parse(fs.readFileSync(settings, 'utf8'))).toEqual(codexShaped);
});
test("Claude Code's settings.json entries for the three hooks are unchanged", () => {
const settings = path.join(dir, 'settings.json');
const claude = (args: string[]) => settingsHook(args, { GSTACK_HOOKS_FORMAT: '', GSTACK_SETTINGS_FILE: settings });
const root = '/home/you/.claude/skills/gstack/hosts/claude/hooks';
claude(['ensure-event', '--event', 'UserPromptSubmit', '--command', root + '/skill-route-hook', '--source', 'gstack-skill-route', '--timeout', '5']);
claude(['ensure-event', '--event', 'Stop', '--command', root + '/skill-contract-stop-hook', '--source', 'gstack-skill-contract', '--timeout', '10']);
claude(['ensure-event', '--event', 'PreToolUse', '--command', root + '/destructive-guard-hook', '--source', 'gstack-destructive-guard', '--timeout', '10', '--matcher', 'Bash|PowerShell']);
expect(fs.readFileSync(settings, 'utf8')).toBe(JSON.stringify({
hooks: {
UserPromptSubmit: [{ _gstack_source: 'gstack-skill-route', hooks: [{ type: 'command', command: root + '/skill-route-hook', timeout: 5 }] }],
Stop: [{ _gstack_source: 'gstack-skill-contract', hooks: [{ type: 'command', command: root + '/skill-contract-stop-hook', timeout: 10 }] }],
PreToolUse: [{ _gstack_source: 'gstack-destructive-guard', hooks: [{ type: 'command', command: root + '/destructive-guard-hook', timeout: 10 }], matcher: 'Bash|PowerShell' }],
},
}, null, 2) + '\n');
});
});
const route = (skill: string, trigger: string): RouteCandidate => ({ skill, score: 1, matched: 3, trigger, file: '/x/SKILL.md', gstack: true });
describe('skill routing on Codex', () => {
function codexSkills(): string {
const skills = path.join(dir, 'codex-skills');
for (const [entry, name] of [['gstack-review', 'review'], ['gstack-ship', 'ship'], ['gstack-qa', 'qa']]) {
fs.mkdirSync(path.join(skills, entry), { recursive: true });
fs.writeFileSync(path.join(skills, entry, 'SKILL.md'), '---\nname: ' + name + '\ndescription: |\n A Codex render keeps only name and description.\n---\nbody\n');
}
fs.mkdirSync(path.join(skills, 'my-notes'), { recursive: true });
fs.writeFileSync(path.join(skills, 'my-notes', 'SKILL.md'), '---\nname: my-notes\ndescription: notes\n---\n');
return skills;
}
test("gstack's Codex skills take Codex's names and the triggers of the same skill in this checkout", () => {
const { skills } = scanCodexSkills(codexSkills());
const review = skills.find(s => s.name === 'gstack-review');
expect(review?.gstack).toBe(true);
expect(review?.triggers).toContain('review my changes');
expect(skills.find(s => s.name === 'my-notes')?.triggers).toEqual([]);
const decision = routePrompt(PAYLOADS.UserPromptSubmit.prompt, skills, undefined, 'codex');
expect(decision.route?.skill).toBe('gstack-review');
});
test('a $ skill mention or a / command is never routed on Codex; on Claude Code a $ prompt still routes as before', () => {
const { skills } = scanCodexSkills(codexSkills());
expect(routePrompt('$gstack-review review my changes', skills, undefined, 'codex')).toMatchObject({ route: null, reason: 'skill-mention' });
expect(routePrompt('/review review my changes', skills, undefined, 'codex')).toMatchObject({ route: null, reason: 'slash-command' });
expect(routePrompt(' $ review my changes', skills).route?.skill).toBe('gstack-review');
});
test("the Codex line names Codex's skill; Claude Code's line is unchanged", () => {
expect(hintLine(route('review', 'review my changes'))).toBe('gstack skill routing (UserPromptSubmit hook; matched the installed /review trigger "review my changes"; off: gstack-config set skill_routing off): this request fits /review. Run /review with the Skill tool before you start, and tell the user in one sentence that gstack routed this to /review.');
expect(hintLine(route('review', 'review my changes'), '', route('qa', 'test the site'))).toBe('gstack skill routing (UserPromptSubmit hook; matched the installed /review trigger "review my changes" and the installed /qa trigger "test the site"; off: gstack-config set skill_routing off): this request fits /review or /qa. Run the one that fits better with the Skill tool before you start (/review if both fit), and tell the user in one sentence which skill gstack routed this to.');
expect(hintLine(route('gstack-review', 'review my changes'), '', undefined, 'codex')).toBe('gstack skill routing (UserPromptSubmit hook; matched the installed gstack-review trigger "review my changes"; off: gstack-config set skill_routing off): this request fits the gstack-review skill. Read and follow the gstack-review skill before you start, and tell the user in one sentence that gstack routed this to gstack-review.');
expect(hintLine(route('gstack-review', 'review my changes'), '', route('gstack-qa', 'test the site'), 'codex')).toContain('fits the gstack-review or gstack-qa skill. Read and follow the one that fits better before you start (gstack-review if both fit)');
});
test('the Codex shim answers a Codex payload with the Codex line, and prints nothing with skill_routing off', () => {
const skills = codexSkills();
const run = (env: Record<string, string> = {}) => spawnSync('bash', [path.join(ROOT, 'hosts', 'codex', 'hooks', 'codex-skill-route-hook')], {
input: JSON.stringify(PAYLOADS.UserPromptSubmit),
env: { PATH: process.env.PATH ?? '', HOME: dir, GSTACK_STATE_ROOT: path.join(dir, 'state'), GSTACK_INSTALLED_SKILLS_DIR: skills, ...env },
encoding: 'utf8', timeout: 30_000,
});
const r = run();
expect(r.status).toBe(0);
const out = JSON.parse(r.stdout).hookSpecificOutput;
expect(out.hookEventName).toBe('UserPromptSubmit');
expect(out.additionalContext).toContain('this request fits the gstack-review skill. Read and follow the gstack-review skill');
expect(fs.readFileSync(path.join(dir, 'state', 'hooks', 'skill-route.log'), 'utf8')).toMatch(/event=routed skill=gstack-review .*host=codex/);
expect(run({ GSTACK_SKILL_ROUTING: 'off' }).stdout).toBe('');
});
});
describe('the destructive-command check on Codex', () => {
const ask = (reason: string) => ({ decision: { hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'ask', permissionDecisionReason: reason } } });
test('Codex has no ask: interactive sessions get a deny that tells the model to ask the user, others a warning; a deny stays a deny', () => {
expect(codexDecision(ask('[careful] Destructive: git reset --hard discards all uncommitted changes.'), 'interactive')).toEqual({
hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: '[careful] Destructive: git reset --hard discards all uncommitted changes. ' + CODEX_ASK_NOTE },
});
expect(CODEX_ASK_NOTE).toContain('stop and ask the user');
expect(CODEX_ASK_NOTE).toContain('typing ! followed by the command');
expect(CODEX_ASK_NOTE).toContain('gstack-config set destructive_guard off');
expect(codexDecision(ask('[careful] x.'), 'headless')).toEqual({ systemMessage: '[careful] x. ' + ASK_NOTE + ' Allowed without asking: this headless session has nobody to answer.' });
expect(codexDecision(ask('[careful] x.'), 'unattended')).toHaveProperty('systemMessage');
const deny = { decision: { hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: '[careful][HIGH] no.' } } };
for (const kind of ['interactive', 'headless']) {
expect(codexDecision(deny, kind)).toEqual({ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: '[careful][HIGH] no.' } });
}
});
test('any ask category, including ones check-careful.sh adds later, takes the same path; everything else prints nothing', () => {
const later = codexDecision(ask('[careful] Destructive: a category added after this hook.'), 'interactive') as any;
expect(later.hookSpecificOutput.permissionDecision).toBe('deny');
expect(later.hookSpecificOutput.permissionDecisionReason).toStartWith('[careful] Destructive: a category added after this hook. Codex hooks cannot ask');
expect(codexDecision(null, 'interactive')).toBeNull();
expect(codexDecision({ raw: 'not json' }, 'interactive')).toBeNull();
expect(codexDecision({ decision: {} }, 'interactive')).toBeNull();
});
const guard = (payload: unknown, env: Record<string, string> = {}) => {
const r = spawnSync('bash', [path.join(ROOT, 'hosts', 'codex', 'hooks', 'codex-destructive-guard-hook')], {
input: JSON.stringify(payload),
env: { PATH: process.env.PATH ?? '', HOME: dir, GSTACK_STATE_ROOT: path.join(dir, 'state'), ...env },
encoding: 'utf8', timeout: 30_000,
});
expect(r.status).toBe(0);
return r.stdout.trim() ? JSON.parse(r.stdout) : null;
};
const withCommand = (command: string) => ({ ...PAYLOADS.PreToolUse, tool_input: { command } });
test('end to end on Codex payloads: ask maps by session kind, root deletes stay denied, only Codex output keys, off prints nothing', () => {
const interactive = guard(PAYLOADS.PreToolUse);
expect(interactive.hookSpecificOutput.permissionDecision).toBe('deny');
expect(interactive.hookSpecificOutput.permissionDecisionReason).toContain(CODEX_ASK_NOTE);
expect(Object.keys(interactive)).toEqual(['hookSpecificOutput']);
expect(Object.keys(interactive.hookSpecificOutput).sort()).toEqual(['hookEventName', 'permissionDecision', 'permissionDecisionReason']);
expect(guard(PAYLOADS.PreToolUse, { CI: '1' })).toEqual({ systemMessage: expect.stringContaining('Allowed without asking: this headless session') });
expect(guard(withCommand('rm -rf /'), { CI: '1' }).hookSpecificOutput.permissionDecision).toBe('deny');
expect(guard(PAYLOADS.PreToolUseTui)).toBeNull();
expect(guard(PAYLOADS.PreToolUse, { GSTACK_DESTRUCTIVE_GUARD: 'off' })).toBeNull();
});
});
+41
View File
@@ -0,0 +1,41 @@
{
"_source": "UserPromptSubmit and PreToolUse: captured from codex-cli 0.170.0 under codex exec on 2026-11-19 by a hook that wrote its stdin, with paths shortened to /home/you. PreToolUseTui: the interactive TUI probe logged the same keys with permission_mode \"default\" and only the key list was kept, so it is the exec payload with that field and the TUI probe's command.",
"UserPromptSubmit": {
"session_id": "01a1f28a-7419-7eb3-934b-cd3b11888e17",
"turn_id": "01a1f28a-7536-70c3-ac51-cd5e3c3f5fe6",
"transcript_path": "/home/you/.codex/sessions/2026/11/19/rollout-2026-11-19T06-42-02-01a1f28a-7419-7eb3-934b-cd3b11888e17.jsonl",
"cwd": "/home/you/repo",
"hook_event_name": "UserPromptSubmit",
"model": "gpt-5.4-mini",
"permission_mode": "bypassPermissions",
"prompt": "Please review my changes. Start by running the shell command: git reset --hard --dry-run-not-real-flag"
},
"PreToolUse": {
"session_id": "01a1f28a-7419-7eb3-934b-cd3b11888e17",
"turn_id": "01a1f28a-7536-70c3-ac51-cd5e3c3f5fe6",
"transcript_path": "/home/you/.codex/sessions/2026/11/19/rollout-2026-11-19T06-42-02-01a1f28a-7419-7eb3-934b-cd3b11888e17.jsonl",
"cwd": "/home/you/repo",
"hook_event_name": "PreToolUse",
"model": "gpt-5.4-mini",
"permission_mode": "bypassPermissions",
"tool_name": "Bash",
"tool_input": {
"command": "git reset --hard --dry-run-not-real-flag"
},
"tool_use_id": "call_jnsEUlxnBr5cuaqZaMTRvMEz"
},
"PreToolUseTui": {
"session_id": "01a1f28a-7419-7eb3-934b-cd3b11888e17",
"turn_id": "01a1f28a-7536-70c3-ac51-cd5e3c3f5fe6",
"transcript_path": "/home/you/.codex/sessions/2026/11/19/rollout-2026-11-19T06-42-02-01a1f28a-7419-7eb3-934b-cd3b11888e17.jsonl",
"cwd": "/home/you/repo",
"hook_event_name": "PreToolUse",
"model": "gpt-5.4-mini",
"permission_mode": "default",
"tool_name": "Bash",
"tool_input": {
"command": "echo tui-probe"
},
"tool_use_id": "call_jnsEUlxnBr5cuaqZaMTRvMEz"
}
}
+1
View File
@@ -33,6 +33,7 @@ export const FREE_FIXTURES: Readonly<Record<string, readonly string[]>> = {
'test/fixtures/careful/geva-560-synthetic.jsonl': ['test/careful-replay.test.ts'],
'test/fixtures/ceo-completion-handoff-m-call.json': ['test/plan-count-completion.test.ts'],
'test/fixtures/claude-usage-2.1.292.json': ['test/claude-usage.test.ts'],
'test/fixtures/codex-hooks/codex-0.170-payloads.json': ['test/codex-hooks.test.ts'],
'test/fixtures/context-restore-transcript.jsonl': ['test/context-restore-transcripts.test.ts'],
'test/fixtures/ceo-completion-handoff-o-call.json': ['test/plan-count-completion.test.ts'],
'test/fixtures/ceo-completion-handoff-q-call.json': ['test/plan-count-completion.test.ts'],