mirror of
https://github.com/garrytan/gstack.git
synced 2026-11-22 08:01:32 +01:00
gstack's Codex hooks keep working with unusual folder paths and after uninstall (GST-3197) (#4528)
gstack's Codex hooks no longer block every prompt when your Codex folder's path has a `(` or `&`, and uninstall keeps your own Codex hooks trusted. Why: both broke Codex sessions; setup also now matches Codex's hook rules, and the /review checklist on Codex reads shell commands more carefully. Nothing to do: plain paths keep the exact hook command they had, so Codex asks for no new trust. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> Review-Finding: p1/specialist-batched#1 reader=red-team Review-Finding: lib/codex-rollout.ts:217:functional-contract reader=qa
This commit is contained in:
1 parent
bd449234aa
commit
9610ba43db
11 files changed
+557
-50
No files matched your search
+118
-17
@@ -184,6 +184,16 @@ 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; };
|
||||
// Codex 0.170 deserialize_mcp_tool_input: no null and no u64 past i64::MAX at
|
||||
// any depth. JSON.parse cannot tell 2^63-1 from 2^63 or 1e19 from an integer,
|
||||
// so integers from 2^63-1 up are refused too: refusing only leaves the file alone.
|
||||
var tomlSafe = function (v) {
|
||||
if (v === null) return false;
|
||||
if (typeof v === "number") return !(Number.isInteger(v) && v >= 9223372036854775807);
|
||||
if (Array.isArray(v)) return v.every(tomlSafe);
|
||||
if (typeof v === "object") return Object.keys(v).every(function (k) { return tomlSafe(v[k]); });
|
||||
return true;
|
||||
};
|
||||
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";
|
||||
@@ -191,7 +201,7 @@ function gsCodexProblem(doc) {
|
||||
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.description !== undefined && doc.description !== null && 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");
|
||||
@@ -217,6 +227,7 @@ function gsCodexProblem(doc) {
|
||||
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.type === "mcp_tool" && h.input !== undefined && !tomlSafe(h.input)) return hat + ".input holds a null or an integer too large for TOML, which Codex rejects (MCP hook input must be representable as TOML)";
|
||||
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";
|
||||
@@ -247,7 +258,7 @@ function gsCodexConfigClash() {
|
||||
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;
|
||||
var row = h && typeof h.command === "string" ? gsOwnedRow(h.command, ev, g.matcher || "") || gsCodexClashRow(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 });
|
||||
}
|
||||
@@ -255,6 +266,36 @@ function gsCodexConfigClash() {
|
||||
}
|
||||
}
|
||||
}
|
||||
// A gstack command declared under another matcher still runs twice when that
|
||||
// matcher selects a tool the row names: Codex 0.170 matcher.rs treats empty
|
||||
// or "*" as every tool, [A-Za-z0-9_|] as exact names and anything else as an
|
||||
// unanchored regex (Rust syntax: a leading (?i), (?m) or (?s) group and \A / \z
|
||||
// are translated). A matcher JS still cannot compile counts as a clash
|
||||
// (refusal is the safe side). Bash, the only tool a Codex row names, has no matcher aliases.
|
||||
function gsCodexClashRow(cmd, event, matcher) {
|
||||
var b = gsBaseOf(cmd);
|
||||
var row = Object.prototype.hasOwnProperty.call(KNOWN_HOOKS, b) ? KNOWN_HOOKS[b] : null;
|
||||
if (!row || !gsOwnedRow(cmd, event, row.matcher)) return null;
|
||||
if (!row.matcher || matcher === undefined || matcher === null || matcher === "" || matcher === "*") return row;
|
||||
var tools = row.matcher.split("|");
|
||||
if (/^[A-Za-z0-9_|]+$/.test(matcher)) {
|
||||
var names = matcher.split("|");
|
||||
return tools.some(function (t) { return names.indexOf(t) >= 0; }) ? row : null;
|
||||
}
|
||||
var src = matcher, flags = "";
|
||||
var lead = /^\(\?([a-zA-Z]+)\)/.exec(src);
|
||||
if (lead) {
|
||||
if (/[^ims]/.test(lead[1])) return row;
|
||||
flags = lead[1];
|
||||
src = src.slice(lead[0].length);
|
||||
}
|
||||
src = src.replace(/(^|[^\\])((?:\\\\)*)\\A/g, "$1$2^").replace(/(^|[^\\])((?:\\\\)*)\\z/g, "$1$2$$");
|
||||
var re;
|
||||
try { re = new RegExp(src, flags); } catch (e) {
|
||||
try { re = new RegExp(src, flags + "u"); } catch (e2) { return row; }
|
||||
}
|
||||
return tools.some(function (t) { return re.test(t); }) ? row : null;
|
||||
}
|
||||
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 });
|
||||
}
|
||||
@@ -276,6 +317,43 @@ function gsCodexMovedUserHooks(beforeText, settings) {
|
||||
});
|
||||
return moved;
|
||||
}
|
||||
// The gstack handlers in beforeText that this change removes or moves, named by
|
||||
// position and command: the refusal below tells the user to delete only these,
|
||||
// never the group around them (a group can hold their own handlers too).
|
||||
function gsCodexGstackHandlers(beforeText, settings) {
|
||||
var before;
|
||||
try { before = JSON.parse(beforeText); } catch (e) { return []; }
|
||||
var bh = (before && before.hooks) || {};
|
||||
var ah = (settings && settings.hooks) || {};
|
||||
var out = [];
|
||||
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];
|
||||
if (ag && Array.isArray(ag.hooks) && JSON.stringify(ag.hooks[hi]) === JSON.stringify(h)) return;
|
||||
out.push("hooks." + ev + "[" + gi + "].hooks[" + hi + "] (command " + JSON.stringify(h.command) + ")");
|
||||
});
|
||||
});
|
||||
});
|
||||
return out;
|
||||
}
|
||||
// Removing a Codex group shifts every later group of that event down one
|
||||
// index, and Codex keys trust by index. A group gstack empties therefore stays
|
||||
// as {"hooks": []} while any group follows it: Codex 0.170 enumerates empty
|
||||
// groups when it numbers them (discovery.rs append_matcher_groups), loads one
|
||||
// with no warning, and hashes only event, matcher and handler, so every later
|
||||
// key and hash stays the same. Slots gstack makes at the end are dropped; the
|
||||
// marker is not enumerable, so it never reaches the file.
|
||||
function gsCodexSlot() {
|
||||
var slot = { hooks: [] };
|
||||
Object.defineProperty(slot, "gsSlot", { value: true });
|
||||
return slot;
|
||||
}
|
||||
function gsCodexTrimSlots(groups) {
|
||||
while (groups.length > 0 && groups[groups.length - 1] && groups[groups.length - 1].gsSlot === true) groups.pop();
|
||||
return groups;
|
||||
}
|
||||
function gsHadBashPrefix(c) { return String(c == null ? "" : c).trim().indexOf("bash ") === 0; }
|
||||
function gsStripWrap(c) {
|
||||
var s = String(c == null ? "" : c).trim();
|
||||
@@ -377,11 +455,13 @@ function gsIsAlive(cmd) {
|
||||
}
|
||||
}
|
||||
function gsQuoteCmd(target, hadBash) {
|
||||
// Shell-metacharacter hardening: the command string is executed by a shell
|
||||
// when Claude Code fires the hook, so a path containing $, backtick (x60 --
|
||||
// written as an escape so the prelude itself stays backtick-free), or a
|
||||
// quote must be neutralized, not just space-wrapped.
|
||||
var needsQuote = /[\s$\x60"\\]/.test(target);
|
||||
// Shell-metacharacter hardening: Claude Code and Codex both run the command
|
||||
// string through a shell, so any path character outside the plain set
|
||||
// (letters, digits, non-ASCII, and _ @ % + = : , . / -) is wrapped in double
|
||||
// quotes, with $, backtick (x60 -- written as an escape so the prelude itself
|
||||
// stays backtick-free), quote and backslash escaped. A bare ( or & is a
|
||||
// syntax error, exit 2, which Codex reads as a block on every event.
|
||||
var needsQuote = /[^A-Za-z0-9_@%+=:,.\/\x2d\u0080-\uffff]/.test(target);
|
||||
var quoted = needsQuote
|
||||
? "\"" + target.replace(/[\\"$\x60]/g, function (ch) { return "\\" + ch; }) + "\""
|
||||
: target;
|
||||
@@ -439,7 +519,8 @@ function gsWriteIfChanged(path, beforeText, settings, existed) {
|
||||
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 });
|
||||
var ours = gsCodexGstackHandlers(beforeText, settings);
|
||||
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 only the gstack handler" + (ours.length === 1 ? " " : "s ") + ours.join(", ") + " from " + path + ", keeping your own handlers and groups as they are, then re-trust your hooks in Codex with /hooks"), { gstackUnreadableSettings: true });
|
||||
}
|
||||
}
|
||||
gsAssertSettingsUnchanged(path);
|
||||
@@ -773,8 +854,10 @@ case "$ACTION" in
|
||||
}
|
||||
// Drop only entries WE emptied; started-empty foreign entries are
|
||||
// never candidates, so they are preserved verbatim.
|
||||
settings.hooks[event] = settings.hooks[event].filter(e =>
|
||||
!(Array.isArray(e.hooks) && e.hooks.length === 0 && cands.some(c => c.entry === e)));
|
||||
const emptied = e => Array.isArray(e.hooks) && e.hooks.length === 0 && cands.some(c => c.entry === e);
|
||||
settings.hooks[event] = GS_CODEX
|
||||
? gsCodexTrimSlots(settings.hooks[event].map(e => (emptied(e) ? gsCodexSlot() : e)))
|
||||
: settings.hooks[event].filter(e => !emptied(e));
|
||||
}
|
||||
if (!placed) {
|
||||
const newEntry = {};
|
||||
@@ -879,12 +962,12 @@ case "$ACTION" in
|
||||
return true;
|
||||
});
|
||||
if (touched === 0) { kept.push(entry); continue; }
|
||||
if (remain.length === 0) continue;
|
||||
if (remain.length === 0) { if (GS_CODEX) kept.push(gsCodexSlot()); continue; }
|
||||
entry.hooks = remain;
|
||||
if (tagged) delete entry._gstack_source;
|
||||
kept.push(entry);
|
||||
}
|
||||
settings.hooks[event] = kept;
|
||||
settings.hooks[event] = GS_CODEX ? gsCodexTrimSlots(kept) : kept;
|
||||
if (settings.hooks[event].length === 0) delete settings.hooks[event];
|
||||
}
|
||||
if (Object.keys(settings.hooks).length === 0) delete settings.hooks;
|
||||
@@ -1003,7 +1086,7 @@ case "$ACTION" in
|
||||
// No re-point target (or plan-tune opt-out): keep live, prune dead.
|
||||
if (gsIsAlive(cmdRaw)) remain.push(h); else { removed++; }
|
||||
}
|
||||
if (remain.length === 0) continue; // entry emptied → dropped
|
||||
if (remain.length === 0) { if (GS_CODEX) rebuilt.push(gsCodexSlot()); continue; } // entry emptied → dropped (Codex: a slot)
|
||||
entry.hooks = remain;
|
||||
// Tag hygiene: a tag must never sit on an entry containing foreign
|
||||
// items (old gstack versions in sibling worktrees treat tags as
|
||||
@@ -1030,10 +1113,11 @@ case "$ACTION" in
|
||||
if (at === undefined) { seen.set(key, out.length); out.push(entry); }
|
||||
else {
|
||||
if (!out[at]._gstack_source && entry._gstack_source) out[at] = entry;
|
||||
if (GS_CODEX) out.push(gsCodexSlot());
|
||||
removed++;
|
||||
}
|
||||
}
|
||||
settings.hooks[event] = out;
|
||||
settings.hooks[event] = GS_CODEX ? gsCodexTrimSlots(out) : out;
|
||||
if (out.length === 0) delete settings.hooks[event];
|
||||
}
|
||||
if (settings.hooks && Object.keys(settings.hooks).length === 0) delete settings.hooks;
|
||||
@@ -1082,6 +1166,17 @@ case "$ACTION" in
|
||||
var tmp = process.env.GSTACK_TMP_PATH;
|
||||
gsAssertSettingsTarget(target);
|
||||
gsLoadedIdentity = gsSettingsIdentity(target);
|
||||
if (GS_CODEX) {
|
||||
// Restoring a backup Codex would skip switches off every hook in the
|
||||
// file, the user ones too, so the backup passes the same schema check
|
||||
// as any write before it replaces the live file.
|
||||
var problem;
|
||||
try { problem = gsCodexProblem(JSON.parse(fs.readFileSync(backup, "utf8"))); }
|
||||
catch (e) { problem = "it is not valid JSON (" + e.message + ")"; }
|
||||
if (problem) {
|
||||
throw Object.assign(new Error("left " + target + " unchanged: the backup " + backup + " does not match the Codex hooks.json schema (" + problem + "), and Codex would skip that whole file"), { gstackUnreadableSettings: true });
|
||||
}
|
||||
}
|
||||
try {
|
||||
fs.copyFileSync(backup, tmp, fs.constants.COPYFILE_EXCL);
|
||||
gsAssertSettingsUnchanged(target);
|
||||
@@ -1157,7 +1252,8 @@ case "$ACTION" in
|
||||
# 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),
|
||||
# the key Codex 0.170 builds in codex-rs/hooks/src/lib.rs hook_key, from the
|
||||
# canonical CODEX_HOME when that is set, else $HOME/.codex as written),
|
||||
# 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.
|
||||
@@ -1179,13 +1275,18 @@ case "$ACTION" in
|
||||
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]));
|
||||
// Codex 0.170 keys trust by the hooks.json path inside its home, never by
|
||||
// where a symlinked hooks.json points: a CODEX_HOME that is set is
|
||||
// canonicalized (utils/home-dir find_codex_home), the default
|
||||
// $HOME/.codex is used as written.
|
||||
const input = path.resolve(process.env.GSTACK_CODEX_HOOKS_INPUT);
|
||||
const keyFile = process.env.CODEX_HOME ? path.join(fs.realpathSync(path.dirname(input)), path.basename(input)) : input;
|
||||
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 entry = state[keyFile + ":" + label(ev) + ":" + gi + ":" + hi];
|
||||
const st = entry && entry.enabled === false ? "disabled" : entry && typeof entry.trusted_hash === "string" ? "trusted" : "untrusted";
|
||||
console.log(row.source + "\t" + ev + "\t" + st);
|
||||
}));
|
||||
|
||||
@@ -618,9 +618,15 @@ fi
|
||||
# that rm -rf this cleanup would silently skip. Only gstack's own matcher groups
|
||||
# go (the KNOWN_HOOKS rows marked host codex); the user's groups stay as they are.
|
||||
CODEX_HOOKS_FILE="${CODEX_HOME:-$HOME/.codex}/hooks.json"
|
||||
# A gstack group that the user's own groups follow becomes an empty group, so
|
||||
# their trust positions hold. When gstack-settings-hook still refuses (one of
|
||||
# the user's handlers sits inside gstack's group), say so: its message names
|
||||
# the exact handler to delete, and the hook would fail once this install is gone.
|
||||
if [ -x "$SETTINGS_HOOK" ] && [ -f "$CODEX_HOOKS_FILE" ]; then
|
||||
if GSTACK_HOOKS_FORMAT=codex GSTACK_SETTINGS_FILE="$CODEX_HOOKS_FILE" "$SETTINGS_HOOK" prune-stale --all | grep -q "removed [1-9]"; then
|
||||
REMOVED+=("gstack's Codex hooks in $CODEX_HOOKS_FILE")
|
||||
if _CODEX_PRUNE=$(GSTACK_HOOKS_FORMAT=codex GSTACK_SETTINGS_FILE="$CODEX_HOOKS_FILE" "$SETTINGS_HOOK" prune-stale --all 2>&1); then
|
||||
case "$_CODEX_PRUNE" in *"removed "[1-9]*) REMOVED+=("gstack's Codex hooks in $CODEX_HOOKS_FILE") ;; esac
|
||||
else
|
||||
echo "WARNING: gstack's Codex hooks are still in $CODEX_HOOKS_FILE and will fail once gstack is removed. $(printf '%s\n' "$_CODEX_PRUNE" | sed -n 's/^gstack-settings-hook: //p' | head -1)" >&2
|
||||
fi
|
||||
fi
|
||||
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
- **gstack's Codex hooks work when your Codex folder's path has a `(`, `&` or other shell character in it.** An unquoted `(` made the hook command a shell syntax error, which Codex reads as "block", so every prompt and Bash call was blocked once you trusted the hooks; an `&` split the command in two. Both Claude Code and Codex hook commands now quote those paths. A path made only of letters, digits and `_ @ % + = : , . / -` keeps the command it had; any other path is quoted once, so Codex asks you to trust those hooks again.
|
||||
- **Uninstalling gstack keeps your own Codex hooks trusted.** When your hook groups come after gstack's in `hooks.json`, uninstall (and turning a hook off) now leaves an empty group where gstack's was, so your hooks keep the positions Codex trusts them by. If your handler sits inside gstack's group, gstack leaves the file alone and names the one handler to delete.
|
||||
- **Codex hook setup matches Codex more closely.** `description: null` is accepted, MCP hook input with a null is refused, `rollback` won't restore a backup Codex would skip, a gstack hook already declared in `config.toml` under any matcher that covers Bash is caught (Rust's `(?i)`, `\A` and `\z` included), and `gstack-doctor` reads hook trust from the same key Codex uses when `CODEX_HOME` is a symlink.
|
||||
- **On Windows, setup copies the Claude Code hook code that gstack's Codex hooks import** into Codex's gstack folder, so the hook scripts are complete. Native Windows Codex still starts hooks through `cmd.exe`, which can't run these Bash scripts, so the hooks don't run there yet.
|
||||
- **/review's checklist on Codex reads shell commands more carefully.** A `;` inside quotes no longer splits a command, a read that never ran or failed isn't counted, a read error that names another file no longer drops a good read, PowerShell's "Cannot find path" counts as an error, and a message with only an image starts a new turn.
|
||||
@@ -83,11 +83,11 @@ The hook reads `destructive_guard` every time it runs, so `gstack-config set des
|
||||
<a id="codex"></a>
|
||||
## Codex
|
||||
|
||||
`./setup --host codex` (or `./setup --host auto` when `codex` is on your PATH) registers the routing hook, the contract Stop hook and the destructive-command check in `${CODEX_HOME:-~/.codex}/hooks.json`, each in its own matcher group: routing on `UserPromptSubmit` with a 5-second timeout, the contract hook on `Stop` with a 10-second timeout (as on Claude Code), the check on `PreToolUse` for `Bash` with a 10-second timeout. The same three switches, in the same order, turn them on and off on both hosts; Codex adds its own two, a hook's toggle in `/hooks` and `[features] hooks = false` in `config.toml` for every hook at once.
|
||||
`./setup --host codex` (or `./setup --host auto` when `codex` is on your PATH) registers the routing hook, the contract Stop hook and the destructive-command check in `${CODEX_HOME:-~/.codex}/hooks.json`, each in its own matcher group: routing on `UserPromptSubmit` with a 5-second timeout, the contract hook on `Stop` with a 10-second timeout (as on Claude Code), the check on `PreToolUse` for `Bash` with a 10-second timeout. The same three switches, in the same order, turn them on and off on both hosts; Codex adds its own two, a hook's toggle in `/hooks` and `[features] hooks = false` in `config.toml` for every hook at once. On native Windows, Codex starts hooks through `cmd.exe`, which can't run these Bash scripts, so gstack's Codex hooks don't run there yet.
|
||||
|
||||
**You trust them once.** Codex runs a hook only after you trust it, and skips an untrusted one without saying so. Setup never writes that trust. It prints one line, "gstack added 3 Codex hook(s); trust them at Codex's startup prompt or in /hooks", and the next time you start Codex it shows "Hooks need review": pick "Trust all and continue", or review them one by one in `/hooks`. `gstack-doctor` has a `codex hooks` row saying whether `config.toml` holds a trust entry for each of gstack's hooks. It only checks that an entry exists; it never computes Codex's hash. Codex asks again when a hook's command or timeout changes, so the commands point at the stable runtime root (`${CODEX_HOME:-~/.codex}/skills/gstack/hosts/codex/hooks/`), and an upgrade that only changes the scripts behind them asks nothing. Codex also keys trust by a group's position in the file, so setup adds gstack's groups after yours and never reorders them. Evals and CI that run `codex exec` pass `--dangerously-bypass-hook-trust`.
|
||||
|
||||
**Your own hooks stay as they are.** Codex 0.170 skips the whole `hooks.json` when it holds a key it does not know, your hooks included. So gstack adds no marker keys (it recognizes its groups by their command path), checks the new file against Codex's schema before moving it into place, and keeps the lock, the `hooks.json.bak.<ts>` backup and `gstack-settings-hook rollback` that `settings.json` has (`GSTACK_HOOKS_FORMAT=codex gstack-settings-hook rollback`). Setup leaves the file alone, prints why and carries on when the file does not parse or already fails Codex's schema, when `config.toml` does not parse, or when `config.toml` already declares one of gstack's hooks under `[hooks]` (Codex would run it twice). It also skips the hooks, saying why, when `codex` is missing or older than 0.170. `./setup --host codex --no-team` (plain `./setup --no-team` installs for Claude Code only, so it leaves the Codex hooks alone; `--host auto` with `codex` on your PATH also reaches them) and `gstack-uninstall` remove gstack's groups and nothing else. If one of your own hooks comes after gstack's group in the same event, removing gstack's group would shift yours to a new position and Codex would stop trusting it (`codex exec` skips an untrusted hook without asking). So gstack leaves the file unchanged and says so; delete gstack's group by hand and re-trust your hooks in `/hooks`.
|
||||
**Your own hooks stay as they are.** Codex 0.170 skips the whole `hooks.json` when it holds a key it does not know, your hooks included. So gstack adds no marker keys (it recognizes its groups by their command path), checks the new file against Codex's schema before moving it into place, and keeps the lock, the `hooks.json.bak.<ts>` backup and `gstack-settings-hook rollback` that `settings.json` has (`GSTACK_HOOKS_FORMAT=codex gstack-settings-hook rollback`). Setup leaves the file alone, prints why and carries on when the file does not parse or already fails Codex's schema, when `config.toml` does not parse, or when `config.toml` already declares one of gstack's hooks under `[hooks]` (Codex would run it twice). It also skips the hooks, saying why, when `codex` is missing or older than 0.170. `./setup --host codex --no-team` (plain `./setup --no-team` installs for Claude Code only, so it leaves the Codex hooks alone; `--host auto` with `codex` on your PATH also reaches them) and `gstack-uninstall` remove gstack's groups and nothing else. Codex keys trust by position, so removing a group that your own groups come after would shift yours and Codex would stop trusting them (`codex exec` skips an untrusted hook without asking). So gstack leaves an empty group, `{ "hooks": [] }`, where its own was, and your hooks keep their positions; an emptied group at the end of an event is dropped. If one of your own handlers comes after gstack's inside the same group, gstack leaves the file unchanged and names the gstack handler to delete by hand; then re-trust your hooks in `/hooks`.
|
||||
|
||||
**Routing on Codex** scans `${CODEX_HOME:-~/.codex}/skills`, names each of gstack's skills by the `name:` in its installed `SKILL.md`, which is the name Codex lists and you mention with `$` (the `gstack-review` folder holds `name: review`, so `$review`), and takes their triggers from the same skill in gstack's checkout, because Codex's copies keep only a name and a description. A skill whose `name:` is missing or unreadable is named by its folder. The line reads "this request fits the review skill. Read and follow the review skill before you start". A prompt that starts with `$` (a Codex skill mention) or `/` is never routed.
|
||||
|
||||
|
||||
+17
-4
@@ -132,10 +132,23 @@ the skill-routing UserPromptSubmit hook and the destructive-command PreToolUse h
|
||||
on every matching event once the install directory is gone.
|
||||
|
||||
On Codex, manual removal also leaves gstack's hooks in
|
||||
`${CODEX_HOME:-~/.codex}/hooks.json`. Delete each matcher group whose command
|
||||
path points into `skills/gstack/hosts/codex/hooks/` (the skill-routing
|
||||
`UserPromptSubmit` hook and the destructive-command `PreToolUse` hook), and keep
|
||||
the rest of the file as it is.
|
||||
`${CODEX_HOME:-~/.codex}/hooks.json`: the skill-routing `UserPromptSubmit`
|
||||
hook, the destructive-command `PreToolUse` hook and the skill-contract `Stop`
|
||||
hook. Delete only gstack's handlers, the entries in a group's `hooks` list
|
||||
whose `command` points into `skills/gstack/hosts/codex/hooks/`, and keep your
|
||||
own handlers and the rest of the file as they are. Codex remembers which hooks
|
||||
you trusted by their position, so:
|
||||
|
||||
- If gstack's handler is the only one in its group and your own groups come
|
||||
after it in the same event, leave the group in place as `{ "hooks": [] }`.
|
||||
Your hooks keep their positions and stay trusted. (The uninstall script does
|
||||
this for you.)
|
||||
- If gstack's group is the last one in that event and holds only gstack's
|
||||
handlers, delete the whole group. If it also holds one of yours, delete only
|
||||
gstack's handler.
|
||||
- If one of your handlers comes after gstack's inside the same group, deleting
|
||||
gstack's handler moves yours up one place, so trust it again in Codex with
|
||||
`/hooks`.
|
||||
|
||||
If the OpenClaw or Hermes [start hook](hosts.md#start-hook) is on (the default for a new registration),
|
||||
manual removal also leaves its `gstack-start` plugin turned on. Turn it off
|
||||
|
||||
+86
-15
@@ -11,10 +11,15 @@
|
||||
* - assistant message: text.
|
||||
* - exec_command / shell call: a Bash tool_use whose command is the shell
|
||||
* line; a command in it that reads a gstack-* SKILL.md under a skills/
|
||||
* directory (cat, sed, head and the like) is also a skill load, unless
|
||||
* the output says that read failed. Reading the same skill again with no
|
||||
* user prompt or other skill load in between (a long SKILL.md read in
|
||||
* chunks) continues the run, so it is not a new load.
|
||||
* directory (cat, sed, head and the like) is also a skill load. The line
|
||||
* splits into commands on &&, ||, ;, | and newlines outside quotes. A read
|
||||
* does not count when an output line reports a read error for that path
|
||||
* (matched up to the folder before skills/ when it is written out, and
|
||||
* never as the prefix of a longer name), or when the read is the line's
|
||||
* last simple command, names one file, and the call exited non-zero: that
|
||||
* exit status is the read's own, so it failed or never ran. Reading the same skill again
|
||||
* with no user turn (text or image) or other skill load in between (a long
|
||||
* SKILL.md read in chunks) continues the run, so it is not a new load.
|
||||
* - Codex's own spawn_agent call that started an agent: an Agent dispatch
|
||||
* whose prompt is its message. Codex 0.170 answers a started agent with
|
||||
* {"agent_id": ...} from its multi_agent_v1 namespace, or {"task_name":
|
||||
@@ -38,8 +43,7 @@ const SKILL_INJECTION = /^\s*<skill>\s*<name>[^<]*<\/name>\s*<path>([^<]+)<\/pat
|
||||
const GSTACK_SKILL_FILE = /(?:^|[\\/])skills[\\/](gstack-[A-Za-z0-9][A-Za-z0-9_-]*)[\\/]SKILL\.md$/;
|
||||
const SHELL_SKILL_READ = /(?:^|[\\/\s'"=])skills[\\/](gstack-[A-Za-z0-9][A-Za-z0-9_-]*)[\\/]SKILL\.md(?=$|[\s'"`;|&)<>])/g;
|
||||
const READ_PROGRAM = /(?:^|[\s;|&(`'"])(?:cat|sed|head|tail|nl|less|more|bat|awk|Get-Content)(?=\s)/;
|
||||
const READ_FAILURE = /No such file|cannot open|can't read|cannot access|Permission denied|Is a directory/i;
|
||||
const SHELL_SEPARATOR = /&&|\|\||[;|\n]/;
|
||||
const READ_FAILURE = /No such file|cannot open|can't read|cannot access|Permission denied|Is a directory|Cannot find path/i;
|
||||
const SHELL_TOOLS = new Set(['exec_command', 'shell', 'shell_command', 'local_shell']);
|
||||
const EXIT_CODE = /(?:^|\n)Process exited with code (\d+)/;
|
||||
|
||||
@@ -76,13 +80,76 @@ function shellLine(input: Record<string, any>): string | null {
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The gstack-* skills a shell line's read commands read, in order of appearance. */
|
||||
function shellSkillReads(line: string): string[] {
|
||||
return line.split(SHELL_SEPARATOR).filter(cmd => READ_PROGRAM.test(cmd)).flatMap(cmd => [...cmd.matchAll(SHELL_SKILL_READ)].map(m => m[1]));
|
||||
/** A shell line's commands: split on &&, ||, ;, | and newlines that sit outside quotes and backslash escapes. */
|
||||
function shellCommands(line: string): string[] {
|
||||
const out: string[] = [];
|
||||
let cur = '';
|
||||
let quote = '';
|
||||
for (let i = 0; i < line.length; i++) {
|
||||
const c = line[i];
|
||||
if (c === '\\' && quote !== "'" && i + 1 < line.length) { cur += c + line[++i]; continue; }
|
||||
if (quote) { if (c === quote) quote = ''; cur += c; continue; }
|
||||
if (c === "'" || c === '"') { quote = c; cur += c; continue; }
|
||||
if ((c === '&' || c === '|') && line[i + 1] === c) { out.push(cur); cur = ''; i++; continue; }
|
||||
if (c === ';' || c === '|' || c === '\n') { out.push(cur); cur = ''; continue; }
|
||||
cur += c;
|
||||
}
|
||||
out.push(cur);
|
||||
return out;
|
||||
}
|
||||
|
||||
const readFailed = (output: string | undefined, skill: string) =>
|
||||
(output ?? '').split('\n').some(l => READ_FAILURE.test(l) && new RegExp(`skills[\\\\/]${skill}[\\\\/]SKILL\\.md`).test(l));
|
||||
interface ShellRead { skill: string; tail: string; last: boolean }
|
||||
|
||||
const READ_WORD = /^(?:.*[\\/])?(cat|sed|head|tail|nl|less|more|bat|awk|Get-Content)$/;
|
||||
|
||||
/** Whether a read command names one file: the words after its program, less options, numbers, redirections and a sed or awk script. */
|
||||
function namesOneFile(cmd: string): boolean {
|
||||
const words = cmd.match(/(?:[^\s'"]+|'[^']*'|"(?:\\.|[^"\\])*")+/g) ?? [];
|
||||
const at = words.findIndex(w => READ_WORD.test(w));
|
||||
let script = at >= 0 && /^(?:sed|awk)$/.test(READ_WORD.exec(words[at])![1]);
|
||||
let files = 0;
|
||||
for (let i = at + 1; i < words.length; i++) {
|
||||
const w = words[i];
|
||||
if (/^\d*[<>]/.test(w)) { if (/^\d*[<>]+&?$/.test(w)) i++; continue; }
|
||||
if (/^-(?:[ef]|-expression|-file)$/.test(w)) { script = false; i++; continue; }
|
||||
if (w.startsWith('-') || /^\+?\d+$/.test(w)) continue;
|
||||
if (script) { script = false; continue; }
|
||||
files++;
|
||||
}
|
||||
return files === 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* The gstack-* skill reads in a shell line, in order. tail is the path an error line must name: from the folder
|
||||
* before skills/ when that is written out literally, else from skills/. last: the read is the line's final command,
|
||||
* a simple one (no grouping or substitution) that names one file, so the call's exit status is the read's own.
|
||||
*/
|
||||
function shellSkillReads(line: string): ShellRead[] {
|
||||
const cmds = shellCommands(line);
|
||||
let lastIdx = cmds.length - 1;
|
||||
while (lastIdx > 0 && !cmds[lastIdx].trim()) lastIdx--;
|
||||
return cmds.flatMap((cmd, i) => (READ_PROGRAM.test(cmd) ? [...cmd.matchAll(SHELL_SKILL_READ)] : []).map(m => {
|
||||
const at = m.index + m[0].indexOf('skills');
|
||||
const parent = /(?:^|[\s'"=\\/])([A-Za-z0-9._-]+)[\\/]$/.exec(cmd.slice(0, at))?.[1];
|
||||
return { skill: m[1], tail: `${parent ? `${parent}/` : ''}skills/${m[1]}/SKILL.md`, last: i === lastIdx && !/[(){}`]/.test(cmd) && namesOneFile(cmd) };
|
||||
}));
|
||||
}
|
||||
|
||||
const tailPattern = (tail: string) =>
|
||||
new RegExp(`(?:^|[\\s'"\`:=\\\\/])${tail.split('/').map(p => p.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('[\\\\/]')}(?![\\w.-])`);
|
||||
|
||||
/**
|
||||
* Whether an output line reports a read error for this read. Every error line counts, except one that provably
|
||||
* names another file: another read's written-out path (cat A || cat B, with A failing; the longer path wins when
|
||||
* both match), or a path that is no SKILL.md at all (cat SKILL.md /tmp/x).
|
||||
*/
|
||||
const readFailed = (output: string | undefined, read: ShellRead, reads: ShellRead[]) =>
|
||||
(output ?? '').split('\n').some(l => {
|
||||
if (!READ_FAILURE.test(l)) return false;
|
||||
const own = tailPattern(read.tail).test(l);
|
||||
if (reads.some(o => o !== read && o.tail !== read.tail && tailPattern(o.tail).test(l) && (!own || o.tail.length > read.tail.length))) return false;
|
||||
return own || !/[\\/]/.test(l) || /SKILL\.md(?![\w.-])/i.test(l);
|
||||
});
|
||||
|
||||
const exitedNonZero = (output: string | undefined) => {
|
||||
const code = output === undefined ? null : EXIT_CODE.exec(output);
|
||||
@@ -146,6 +213,8 @@ export function parseCodexRollout(text: string): Transcript {
|
||||
const body = contentText(p.content);
|
||||
if (p.role === 'assistant') {
|
||||
if (body) events.push({ kind: 'text', line, text: body });
|
||||
} else if (p.role === 'user' && !body && !fromHarness(p) && p.content.some((c: unknown) => isObject(c) && c.type === 'input_image')) {
|
||||
lastLoad = null;
|
||||
} else if (p.role === 'user' && body) {
|
||||
const injected = SKILL_INJECTION.exec(body);
|
||||
const skill = injected ? GSTACK_SKILL_FILE.exec(injected[1].trim())?.[1] : undefined;
|
||||
@@ -161,10 +230,12 @@ export function parseCodexRollout(text: string): Transcript {
|
||||
const command = SHELL_TOOLS.has(p.name) ? shellLine(input) : null;
|
||||
if (command !== null) {
|
||||
events.push({ kind: 'tool_use', line, id, name: 'Bash', input: { command } });
|
||||
for (const skill of shellSkillReads(command)) {
|
||||
if (skill === lastLoad || readFailed(outputs.get(id), skill)) continue;
|
||||
events.push({ kind: 'load', line, skill, via: 'read' });
|
||||
lastLoad = skill;
|
||||
const reads = shellSkillReads(command);
|
||||
const out = outputs.get(id);
|
||||
for (const read of reads) {
|
||||
if (read.skill === lastLoad || readFailed(out, read, reads) || (read.last && exitedNonZero(out))) continue;
|
||||
events.push({ kind: 'load', line, skill: read.skill, via: 'read' });
|
||||
lastLoad = read.skill;
|
||||
}
|
||||
} else if (p.name === 'spawn_agent' && startedAgent(outputs.get(id), p.namespace ?? undefined)) {
|
||||
const prompt = [input.message, ...(Array.isArray(input.items) ? input.items.map((i: unknown) => (isObject(i) ? i.text : undefined)) : [])]
|
||||
|
||||
@@ -3188,9 +3188,13 @@ create_codex_runtime_root() {
|
||||
_link_or_copy "$gstack_dir/lib" "$codex_gstack/lib"
|
||||
fi
|
||||
# Codex hook shims: ${CODEX_HOME}/hooks.json names this stable path (GST-3172).
|
||||
# They import the Claude Code hooks beside them (../../claude/hooks), which
|
||||
# a symlink reaches through the checkout but a Windows copy does not, so the
|
||||
# Claude hooks come along too; without them all three shims fail open there.
|
||||
if [ -d "$gstack_dir/hosts/codex/hooks" ]; then
|
||||
mkdir -p "$codex_gstack/hosts/codex"
|
||||
mkdir -p "$codex_gstack/hosts/codex" "$codex_gstack/hosts/claude"
|
||||
_link_or_copy "$gstack_dir/hosts/codex/hooks" "$codex_gstack/hosts/codex/hooks"
|
||||
_link_or_copy "$gstack_dir/hosts/claude/hooks" "$codex_gstack/hosts/claude/hooks"
|
||||
fi
|
||||
if [ -d "$gstack_dir/browse/dist" ]; then
|
||||
_link_or_copy "$gstack_dir/browse/dist" "$codex_gstack/browse/dist"
|
||||
|
||||
@@ -105,6 +105,30 @@ async function codexAgainstStub(prompt: string): Promise<string[]> {
|
||||
return bodies;
|
||||
}
|
||||
|
||||
/** Codex's own view of its hooks: app-server's hooks/list gives each handler's trust key, current hash and status. */
|
||||
async function listHooks(): Promise<{ hooks: { key: string; command?: string; currentHash: string; trustStatus: string }[]; warnings: string[]; errors: unknown[] }> {
|
||||
const child = spawn('codex', ['app-server'], {
|
||||
cwd: dir, stdio: ['pipe', 'pipe', 'ignore'],
|
||||
env: { PATH: process.env.PATH ?? '', HOME: dir, CODEX_HOME: home(), OPENAI_API_KEY: 'sk-not-a-real-key' },
|
||||
});
|
||||
let out = '';
|
||||
child.stdout.on('data', d => { out += d; });
|
||||
for (const msg of [
|
||||
{ jsonrpc: '2.0', id: 1, method: 'initialize', params: { clientInfo: { name: 'gstack-test', version: '1' } } },
|
||||
{ jsonrpc: '2.0', method: 'initialized' },
|
||||
{ jsonrpc: '2.0', id: 2, method: 'hooks/list', params: { cwds: [dir] } },
|
||||
]) child.stdin.write(JSON.stringify(msg) + '\n');
|
||||
const deadline = Date.now() + 30_000;
|
||||
let reply: any;
|
||||
while (Date.now() < deadline && !reply) {
|
||||
reply = out.split('\n').filter(Boolean).map(l => { try { return JSON.parse(l); } catch { return null; } }).find(m => m?.id === 2);
|
||||
if (!reply) await Bun.sleep(100);
|
||||
}
|
||||
child.kill('SIGKILL');
|
||||
if (!reply?.result) throw new Error('codex app-server gave no hooks/list reply: ' + out.slice(-500));
|
||||
return reply.result.data[0];
|
||||
}
|
||||
|
||||
describe.skipIf(!usable && !required)('real codex reads the hooks.json gstack writes', () => {
|
||||
test('codex 0.170 or newer is on PATH', () => {
|
||||
expect(version?.[0] ?? 'no codex on PATH').toMatch(/^codex-cli /);
|
||||
@@ -132,6 +156,43 @@ describe.skipIf(!usable && !required)('real codex reads the hooks.json gstack wr
|
||||
expect((await codexAgainstStub('$gstack-review look at this')).join('\n')).not.toContain('REAL_CODEX_SKILL_BODY');
|
||||
}, 200_000);
|
||||
|
||||
test("removing gstack's group before yours leaves an empty group, and Codex still trusts your hook at the same key", async () => {
|
||||
fs.mkdirSync(home(), { recursive: true });
|
||||
const file = path.join(home(), 'hooks.json');
|
||||
const gstackGuard = path.join(home(), 'skills', 'gstack', 'hosts', 'codex', 'hooks', 'codex-destructive-guard-hook');
|
||||
const mine = { matcher: 'Bash', hooks: [{ type: 'command', command: '/usr/local/bin/my-guard', timeout: 3 }] };
|
||||
fs.writeFileSync(file, JSON.stringify({ hooks: { PreToolUse: [{ matcher: 'Bash', hooks: [{ type: 'command', command: gstackGuard, timeout: 10 }] }, mine] } }, null, 2));
|
||||
const before = (await listHooks()).hooks.find(h => h.command === '/usr/local/bin/my-guard')!;
|
||||
expect(before.key).toBe(fs.realpathSync(file) + ':pre_tool_use:1:0');
|
||||
fs.writeFileSync(path.join(home(), 'config.toml'), '[hooks.state."' + before.key + '"]\ntrusted_hash = "' + before.currentHash + '"\n');
|
||||
expect((await listHooks()).hooks.find(h => h.key === before.key)?.trustStatus).toBe('trusted');
|
||||
const r = spawnSync('bash', [path.join(ROOT, 'bin', 'gstack-settings-hook'), 'prune-stale', '--all'], {
|
||||
env: { PATH: process.env.PATH ?? '', HOME: dir, GSTACK_HOOKS_FORMAT: 'codex', CODEX_HOME: home() }, encoding: 'utf8', timeout: 30_000,
|
||||
});
|
||||
expect(r.status).toBe(0);
|
||||
expect(JSON.parse(fs.readFileSync(file, 'utf8')).hooks.PreToolUse).toEqual([{ hooks: [] }, mine]);
|
||||
const after = await listHooks();
|
||||
expect(after.warnings).toEqual([]);
|
||||
expect(after.errors).toEqual([]);
|
||||
expect(after.hooks.map(h => [h.key, h.trustStatus])).toEqual([[before.key, 'trusted']]);
|
||||
fs.writeFileSync(file, JSON.stringify({ hooks: { PreToolUse: [mine] } }, null, 2));
|
||||
expect((await listHooks()).hooks.map(h => [h.key.split(':').slice(-2).join(':'), h.trustStatus])).toEqual([['0:0', 'untrusted']]);
|
||||
}, 120_000);
|
||||
|
||||
test('a hook path with ( in it runs under Codex instead of exiting 2, which Codex reads as a block on every prompt', async () => {
|
||||
install();
|
||||
const odd = path.join(dir, 'hooks(2)');
|
||||
fs.symlinkSync(path.join(ROOT, 'hosts', 'codex', 'hooks'), odd);
|
||||
const r = spawnSync('bash', [path.join(ROOT, 'bin', 'gstack-settings-hook'), 'ensure-event', '--event', 'UserPromptSubmit', '--command', path.join(odd, 'codex-skill-route-hook'), '--source', 'gstack-skill-route', '--timeout', '5'], {
|
||||
env: { PATH: process.env.PATH ?? '', HOME: dir, GSTACK_HOOKS_FORMAT: 'codex', CODEX_HOME: home() }, encoding: 'utf8', timeout: 30_000,
|
||||
});
|
||||
expect(r.status).toBe(0);
|
||||
const out = await codexExec(['--dangerously-bypass-hook-trust']);
|
||||
expect(fs.existsSync(marker())).toBe(true);
|
||||
expect(fs.readFileSync(routeLog(), 'utf8')).toMatch(/event=routed skill=review .*host=codex/);
|
||||
expect(out).not.toMatch(/blocked|exit code 2|syntax error/i);
|
||||
}, 90_000);
|
||||
|
||||
test('negative controls: an unknown key makes Codex skip the whole file, and untrusted hooks never run', async () => {
|
||||
install();
|
||||
const file = path.join(home(), 'hooks.json');
|
||||
|
||||
@@ -48,6 +48,27 @@ describe('setup: Codex hook registration', () => {
|
||||
}
|
||||
});
|
||||
|
||||
test('a Windows install copies the Claude hooks the Codex shims import, so the copied shims run under bash instead of failing open', () => {
|
||||
const root = path.join(dir, 'codex', 'skills', 'gstack');
|
||||
const script = ['set -e', 'IS_WINDOWS=1', '_CODEX_RENDER_ROOT="' + ROOT + '"', ...['_link_or_copy', '_copy_skill_md', '_link_runtime_dists', '_link_codex_skill_refs', 'create_codex_runtime_root'].map(fnBody),
|
||||
'create_codex_runtime_root "' + ROOT + '" "' + root + '"'].join('\n');
|
||||
const made = run(script);
|
||||
expect(made.code).toBe(0);
|
||||
expect(fs.lstatSync(path.join(root, 'hosts', 'claude', 'hooks')).isSymbolicLink()).toBe(false);
|
||||
const payloads = JSON.parse(fs.readFileSync(path.join(ROOT, 'test', 'fixtures', 'codex-hooks', 'codex-0.170-payloads.json'), 'utf8'));
|
||||
const shim = (name: string, payload: unknown) => spawnSync('bash', [path.join(root, 'hosts', 'codex', 'hooks', name)], {
|
||||
input: JSON.stringify(payload), encoding: 'utf8', timeout: 30_000,
|
||||
env: { PATH: process.env.PATH ?? '', HOME: dir, GSTACK_STATE_ROOT: path.join(dir, 'state') },
|
||||
});
|
||||
const guard = shim('codex-destructive-guard-hook', payloads.PreToolUse);
|
||||
expect(guard.status).toBe(0);
|
||||
expect(JSON.parse(guard.stdout).hookSpecificOutput.permissionDecision).toBe('deny');
|
||||
for (const [name, payload] of [['codex-skill-route-hook', payloads.UserPromptSubmit], ['codex-skill-contract-stop-hook', { hook_event_name: 'Stop', stop_hook_active: false }]] as const) {
|
||||
const r = shim(name, payload);
|
||||
expect({ name, status: r.status, stderr: r.stderr }).toEqual({ name, status: 0, stderr: expect.not.stringMatching(/Cannot find|ResolveMessage|error:/i) });
|
||||
}
|
||||
});
|
||||
|
||||
/** One gate run with Codex selected and Claude not: SETTINGS_HOOK is empty, as setup leaves it for --host codex. */
|
||||
function gate(key: 'skill_routing' | 'destructive_guard' | 'skill_contracts', mode: string, env: Record<string, string> = {}, noTeam = 0) {
|
||||
const runtimeRoot = path.join(dir, 'codex', 'skills', 'gstack');
|
||||
@@ -161,6 +182,43 @@ describe('gstack-uninstall and gstack-doctor with Codex hooks', () => {
|
||||
expect(JSON.parse(fs.readFileSync(path.join(home, '.codex', 'hooks.json'), 'utf8'))).toEqual({ hooks: { PreToolUse: [user] } });
|
||||
});
|
||||
|
||||
const uninstall = () => {
|
||||
const home = path.join(dir, 'home');
|
||||
fs.mkdirSync(path.join(dir, 'repo'), { recursive: true });
|
||||
const r = spawnSync('bash', [path.join(ROOT, 'bin', 'gstack-uninstall'), '--force', '--keep-state'], {
|
||||
env: { PATH: process.env.PATH ?? '', HOME: home, CODEX_HOME: path.join(home, '.codex'), GSTACK_STATE_DIR: path.join(home, '.gstack') },
|
||||
cwd: path.join(dir, 'repo'), encoding: 'utf8', timeout: 60_000,
|
||||
});
|
||||
return { ...r, file: path.join(home, '.codex', 'hooks.json') };
|
||||
};
|
||||
|
||||
test("uninstall with your own group after gstack's removes gstack's handler and leaves an empty group, so your hook keeps its trust position", () => {
|
||||
const { user } = seed();
|
||||
const file = path.join(dir, 'home', '.codex', 'hooks.json');
|
||||
const doc = JSON.parse(fs.readFileSync(file, 'utf8'));
|
||||
doc.hooks.PreToolUse.reverse();
|
||||
fs.writeFileSync(file, JSON.stringify(doc, null, 2));
|
||||
const r = uninstall();
|
||||
expect(r.status).toBe(0);
|
||||
expect(r.stdout).toContain("gstack's Codex hooks in " + r.file);
|
||||
expect(r.stderr).not.toContain('WARNING');
|
||||
expect(JSON.parse(fs.readFileSync(r.file, 'utf8'))).toEqual({ hooks: { PreToolUse: [{ hooks: [] }, user] } });
|
||||
});
|
||||
|
||||
test("uninstall says so, naming the one handler to delete, when your handler sits inside gstack's group", () => {
|
||||
seed();
|
||||
const file = path.join(dir, 'home', '.codex', 'hooks.json');
|
||||
const doc = JSON.parse(fs.readFileSync(file, 'utf8'));
|
||||
doc.hooks.PreToolUse[1].hooks.push({ type: 'command', command: '/usr/local/bin/my-inner-guard' });
|
||||
fs.writeFileSync(file, JSON.stringify(doc, null, 2));
|
||||
const r = uninstall();
|
||||
expect(r.status).toBe(0);
|
||||
expect(r.stderr).toContain("WARNING: gstack's Codex hooks are still in " + r.file + ' and will fail once gstack is removed.');
|
||||
expect(r.stderr).toContain('delete only the gstack handlers hooks.PreToolUse[1].hooks[0] (command ');
|
||||
expect(r.stderr).not.toContain('delete its group');
|
||||
expect(JSON.parse(fs.readFileSync(r.file, 'utf8'))).toEqual(doc);
|
||||
});
|
||||
|
||||
test('the doctor row says whether each hook has a trust entry, and prints nothing without gstack hooks', () => {
|
||||
seed();
|
||||
const doctor = fs.readFileSync(path.join(ROOT, 'bin', 'gstack-doctor'), 'utf8');
|
||||
|
||||
+136
-9
@@ -157,7 +157,7 @@ describe('gstack-settings-hook: Codex hooks.json format', () => {
|
||||
test('trust-status reads the key Codex writes (<hooks.json>:<event>:<group>:<handler>) and never computes a hash', () => {
|
||||
writeUser();
|
||||
ensureRoute(); ensureGuard();
|
||||
expect(settingsHook(['trust-status']).out.trim().split('\n').sort()).toEqual([
|
||||
expect(settingsHook(['trust-status'], { CODEX_HOME: dir }).out.trim().split('\n').sort()).toEqual([
|
||||
'gstack-destructive-guard\tPreToolUse\tuntrusted', 'gstack-skill-route\tUserPromptSubmit\tuntrusted',
|
||||
]);
|
||||
const file = fs.realpathSync(hooksFile());
|
||||
@@ -167,30 +167,48 @@ describe('gstack-settings-hook: Codex hooks.json format', () => {
|
||||
'[hooks.state."' + file + ':pre_tool_use:1:0"]', 'trusted_hash = "sha256:bb"', '',
|
||||
'[hooks.state."' + file + ':user_prompt_submit:1:0"]', 'enabled = false', 'trusted_hash = "sha256:cc"', '',
|
||||
].join('\n'));
|
||||
expect(settingsHook(['trust-status']).out.trim().split('\n').sort()).toEqual([
|
||||
expect(settingsHook(['trust-status'], { CODEX_HOME: dir }).out.trim().split('\n').sort()).toEqual([
|
||||
'gstack-destructive-guard\tPreToolUse\ttrusted', 'gstack-skill-route\tUserPromptSubmit\tdisabled',
|
||||
]);
|
||||
expect(settingsHook(['trust-status'], { GSTACK_HOOKS_FORMAT: '' }).code).toBe(1);
|
||||
});
|
||||
|
||||
test('removing a gstack group that one of your hooks follows in the same event refuses and leaves the file as it was, so Codex keeps trusting your hook', () => {
|
||||
test('removing a gstack group that one of your groups follows leaves an empty group in its place, so your hooks keep their trust positions', () => {
|
||||
writeUser();
|
||||
ensureRoute(); ensureGuard();
|
||||
const doc = read();
|
||||
doc.hooks.PreToolUse.push({ matcher: 'Bash', hooks: [{ type: 'command', command: '/usr/local/bin/my-late-guard' }] });
|
||||
const late = { matcher: 'Bash', hooks: [{ type: 'command', command: '/usr/local/bin/my-late-guard' }] };
|
||||
doc.hooks.PreToolUse.push(late);
|
||||
writeUser(doc);
|
||||
for (const args of [['remove-source', '--source', 'gstack-destructive-guard'], ['prune-stale', '--all']]) {
|
||||
writeUser(doc);
|
||||
const r = settingsHook(args);
|
||||
expect(r.code).toBe(0);
|
||||
expect(read().hooks.PreToolUse).toEqual([USER_FILE.hooks.PreToolUse[0], { hooks: [] }, late]);
|
||||
codexKeysOnly(read());
|
||||
}
|
||||
expect(read().hooks.UserPromptSubmit).toEqual(USER_FILE.hooks.UserPromptSubmit);
|
||||
expect(read().hooks.Stop).toEqual(USER_FILE.hooks.Stop);
|
||||
expect(ensureGuard().out).toContain('registered');
|
||||
expect(read().hooks.PreToolUse.slice(0, 3)).toEqual([USER_FILE.hooks.PreToolUse[0], { hooks: [] }, late]);
|
||||
});
|
||||
|
||||
test('when one of your handlers follows the gstack handler inside its group, removal refuses and names only the gstack handler to delete', () => {
|
||||
writeUser();
|
||||
ensureGuard();
|
||||
const doc = read();
|
||||
doc.hooks.PreToolUse[1].hooks.push({ type: 'command', command: '/usr/local/bin/my-inner-guard' });
|
||||
writeUser(doc);
|
||||
const text = fs.readFileSync(hooksFile(), 'utf8');
|
||||
for (const args of [['remove-source', '--source', 'gstack-destructive-guard'], ['prune-stale', '--all']]) {
|
||||
const r = settingsHook(args);
|
||||
expect(r.code).toBe(3);
|
||||
expect(r.out).toContain('would move your own PreToolUse hooks');
|
||||
expect(r.out).toContain('re-trust your hooks in Codex with /hooks');
|
||||
expect(r.out).toContain('delete only the gstack handler hooks.PreToolUse[1].hooks[0] (command ' + JSON.stringify(GUARD_CMD()) + ')');
|
||||
expect(r.out).toContain('keeping your own handlers and groups as they are, then re-trust your hooks in Codex with /hooks');
|
||||
expect(r.out).not.toContain('delete its group');
|
||||
expect(fs.readFileSync(hooksFile(), 'utf8')).toBe(text);
|
||||
}
|
||||
expect(ensureGuard().out).toContain('unchanged');
|
||||
expect(settingsHook(['remove-source', '--source', 'gstack-skill-route']).code).toBe(0);
|
||||
expect(read().hooks.UserPromptSubmit).toEqual(USER_FILE.hooks.UserPromptSubmit);
|
||||
expect(read().hooks.PreToolUse).toEqual(doc.hooks.PreToolUse);
|
||||
});
|
||||
|
||||
test('a symlinked hooks.json still reads config.toml from the Codex home, not from beside the link target', () => {
|
||||
@@ -240,6 +258,115 @@ describe('gstack-settings-hook: Codex hooks.json format', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('gstack-settings-hook: hardening after #4512 and #4522 (GST-3197)', () => {
|
||||
const runUnder = (shell: string[], command: string) => spawnSync(shell[0], [...shell.slice(1), command], { input: '{}', encoding: 'utf8', timeout: 30_000, env: { PATH: process.env.PATH ?? '', HOME: dir } });
|
||||
const fakeHook = (file: string) => {
|
||||
fs.mkdirSync(path.dirname(file), { recursive: true });
|
||||
fs.writeFileSync(file, '#!/bin/sh\necho RAN_HOOK\n', { mode: 0o755 });
|
||||
};
|
||||
|
||||
test('a home path with ( or & gives commands both hosts run: no exit 2, which Codex would read as a block on every prompt and Bash call', () => {
|
||||
const root = path.join(dir, 'codex(old)&co', 'skills', 'gstack');
|
||||
fakeHook(ROUTE_CMD(root));
|
||||
expect(ensureRoute(root).out).toContain('registered');
|
||||
const codexCmd = read().hooks.UserPromptSubmit[0].hooks[0].command;
|
||||
const settings = path.join(dir, 'settings.json');
|
||||
const claudeHook = path.join(root, 'hosts', 'claude', 'hooks', 'skill-route-hook');
|
||||
fakeHook(claudeHook);
|
||||
expect(settingsHook(['ensure-event', '--event', 'UserPromptSubmit', '--command', claudeHook, '--source', 'gstack-skill-route', '--timeout', '5'], { GSTACK_HOOKS_FORMAT: '', GSTACK_SETTINGS_FILE: settings }).code).toBe(0);
|
||||
const claudeCmd = JSON.parse(fs.readFileSync(settings, 'utf8')).hooks.UserPromptSubmit[0].hooks[0].command;
|
||||
for (const cmd of [codexCmd, claudeCmd]) {
|
||||
for (const shell of [['bash', '-lc'], ['sh', '-c']]) {
|
||||
const r = runUnder(shell, cmd);
|
||||
expect({ shell: shell[0], status: r.status, out: r.stdout.trim() }).toEqual({ shell: shell[0], status: 0, out: 'RAN_HOOK' });
|
||||
}
|
||||
}
|
||||
expect(ensureRoute(root).out).toContain('unchanged');
|
||||
});
|
||||
|
||||
test('plain paths keep their unquoted commands, so no install is asked to re-trust its hooks', () => {
|
||||
expect(ensureRoute().code).toBe(0);
|
||||
expect(read().hooks.UserPromptSubmit[0].hooks[0].command).toBe(ROUTE_CMD());
|
||||
const accented = path.join(dir, 'Jos\u00e9', 'skills', 'gstack');
|
||||
expect(ensureRoute(accented).out).toContain('re-pointed');
|
||||
expect(read().hooks.UserPromptSubmit[0].hooks[0].command).toBe(ROUTE_CMD(accented));
|
||||
});
|
||||
|
||||
test('schema parity with Codex 0.170: description null is accepted; a null anywhere in MCP hook input is refused', () => {
|
||||
writeUser({ description: null, hooks: {} });
|
||||
expect(ensureRoute().code).toBe(0);
|
||||
expect(read().description).toBeNull();
|
||||
const mcp = (input: unknown) => ({ hooks: { Stop: [{ hooks: [{ type: 'mcp_tool', server: 's', tool: 't', input }] }] } });
|
||||
for (const input of [{ optional: null }, { metadata: { optional: null } }, { values: [null] }, { big: 18446744073709551615 }]) {
|
||||
const text = JSON.stringify(mcp(input));
|
||||
fs.writeFileSync(hooksFile(), text);
|
||||
const r = ensureRoute();
|
||||
expect(r.code).toBe(3);
|
||||
expect(r.out).toContain('input holds a null or an integer too large for TOML, which Codex rejects');
|
||||
expect(fs.readFileSync(hooksFile(), 'utf8')).toBe(text);
|
||||
}
|
||||
writeUser(mcp({ metadata: { depth: 1, tags: ['a', true, -2.5] } }));
|
||||
expect(ensureRoute().code).toBe(0);
|
||||
});
|
||||
|
||||
test('rollback refuses a backup Codex would skip and leaves the live file as it is', () => {
|
||||
writeUser();
|
||||
ensureRoute();
|
||||
const live = fs.readFileSync(hooksFile(), 'utf8');
|
||||
const backup = fs.readFileSync(path.join(dir, 'hooks.json.bak-latest'), 'utf8').trim();
|
||||
for (const bad of [JSON.stringify({ hooks: {}, _gstack_source: 'x' }), '{ "hooks": ']) {
|
||||
fs.writeFileSync(backup, bad);
|
||||
const r = settingsHook(['rollback']);
|
||||
expect(r.code).toBe(3);
|
||||
expect(r.out).toContain('does not match the Codex hooks.json schema');
|
||||
expect(fs.readFileSync(hooksFile(), 'utf8')).toBe(live);
|
||||
}
|
||||
fs.writeFileSync(backup, JSON.stringify(USER_FILE, null, 2) + '\n');
|
||||
expect(settingsHook(['rollback']).code).toBe(0);
|
||||
expect(read()).toEqual(USER_FILE);
|
||||
});
|
||||
|
||||
test('config.toml declaring the gstack guard under any matcher that selects Bash is a clash; matchers that never select Bash are not', () => {
|
||||
writeUser();
|
||||
const cfg = path.join(dir, 'config.toml');
|
||||
const declare = (matcher: string | null) => fs.writeFileSync(cfg, '[[hooks.PreToolUse]]\n' + (matcher === null ? '' : 'matcher = ' + JSON.stringify(matcher) + '\n') + '[[hooks.PreToolUse.hooks]]\ntype = "command"\ncommand = "' + GUARD_CMD() + '"\n');
|
||||
for (const matcher of ['^Bash$', 'Bash|PowerShell', '*', '', null, 'B.sh', '(unclosed']) {
|
||||
declare(matcher);
|
||||
const r = ensureGuard();
|
||||
expect({ matcher, code: r.code }).toEqual({ matcher, code: 3 });
|
||||
expect(r.out).toContain('already declares gstack hook gstack-destructive-guard under [hooks.PreToolUse], and Codex would run it twice');
|
||||
}
|
||||
expect(read()).toEqual(USER_FILE);
|
||||
for (const matcher of ['\\ABash\\z', '(?i)^bash$']) {
|
||||
declare(matcher);
|
||||
expect({ matcher, code: ensureGuard().code }).toEqual({ matcher, code: 3 });
|
||||
}
|
||||
for (const matcher of ['PowerShell', '^Edit$', 'apply_patch|Write', '(?i)^Edit$', '\\AEdit\\z']) {
|
||||
declare(matcher);
|
||||
expect({ matcher, code: ensureGuard().code }).toEqual({ matcher, code: 0 });
|
||||
}
|
||||
});
|
||||
|
||||
test('trust-status keys on the hooks.json in the canonical CODEX_HOME, the way Codex does, even when hooks.json itself is a link', () => {
|
||||
const real = path.join(dir, 'real-codex');
|
||||
const link = path.join(dir, 'codex-link');
|
||||
const dotfiles = path.join(dir, 'dotfiles');
|
||||
fs.mkdirSync(real); fs.mkdirSync(dotfiles);
|
||||
fs.symlinkSync(real, link);
|
||||
fs.writeFileSync(path.join(dotfiles, 'hooks.json'), JSON.stringify(USER_FILE, null, 2) + '\n');
|
||||
fs.symlinkSync(path.join(dotfiles, 'hooks.json'), path.join(real, 'hooks.json'));
|
||||
const env = { CODEX_HOME: link, GSTACK_SETTINGS_FILE: '' };
|
||||
expect(settingsHook(['ensure-event', '--event', 'UserPromptSubmit', '--command', ROUTE_CMD(), '--source', 'gstack-skill-route', '--timeout', '5'], env).code).toBe(0);
|
||||
const trust = (keyFile: string) => {
|
||||
fs.writeFileSync(path.join(real, 'config.toml'), '[hooks.state."' + keyFile + ':user_prompt_submit:1:0"]\ntrusted_hash = "sha256:aa"\n');
|
||||
return settingsHook(['trust-status'], env).out.trim();
|
||||
};
|
||||
expect(trust(path.join(fs.realpathSync(real), 'hooks.json'))).toBe('gstack-skill-route\tUserPromptSubmit\ttrusted');
|
||||
expect(trust(path.join(link, 'hooks.json'))).toBe('gstack-skill-route\tUserPromptSubmit\tuntrusted');
|
||||
expect(trust(fs.realpathSync(path.join(dotfiles, 'hooks.json')))).toBe('gstack-skill-route\tUserPromptSubmit\tuntrusted');
|
||||
});
|
||||
});
|
||||
|
||||
const route = (skill: string, trigger: string): RouteCandidate => ({ skill, score: 1, matched: 3, trigger, file: '/x/SKILL.md', gstack: true });
|
||||
|
||||
describe('skill routing on Codex', () => {
|
||||
|
||||
@@ -104,6 +104,67 @@ describe('loads: Codex reading or injecting a gstack-* SKILL.md', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('reads: shell edge cases from the #4522 notes (GST-3197)', () => {
|
||||
const meta = lines('exec-read-met.jsonl')[0];
|
||||
const record = (payload: Record<string, unknown>) => JSON.stringify({ type: 'response_item', payload });
|
||||
const user = record({ type: 'message', role: 'user', content: [{ type: 'input_text', text: 'review this' }] });
|
||||
const call = (cmd: string, id = 'c1') => record({ type: 'function_call', name: 'exec_command', arguments: JSON.stringify({ cmd }), call_id: id });
|
||||
const result = (output: string, id = 'c1') => record({ type: 'function_call_output', call_id: id, output });
|
||||
const loads = (cmd: string, output?: string) => skillLoads(parseTranscript([meta, user, call(cmd), ...(output === undefined ? [] : [result(output)])].join('\n'))).map(l => l.skill);
|
||||
const READ = 'cat ~/.codex/skills/gstack-review/SKILL.md';
|
||||
|
||||
test('A: a read that an earlier && command kept from running is not a load; a read before a later failure still is', () => {
|
||||
expect(loads('cd /nope && ' + READ, 'Process exited with code 1\nOutput:\nbash: line 1: cd: /nope: No such file or directory')).toEqual([]);
|
||||
expect(loads('cd /repo && ' + READ, 'Process exited with code 0\nOutput:\n---\nname: review')).toEqual(['gstack-review']);
|
||||
expect(loads('cd /repo && ' + READ + ' && git diff missing-ref', "Process exited with code 128\nOutput:\n---\nfatal: bad revision 'missing-ref'")).toEqual(['gstack-review']);
|
||||
expect(loads('cd /nope && ' + READ)).toEqual(['gstack-review']);
|
||||
expect(loads('cd /nope && { ' + READ + '; }', 'Process exited with code 1\nOutput:\n')).toEqual(['gstack-review']);
|
||||
});
|
||||
|
||||
test("B: ; inside quotes does not split a command, so sed -n '1,200p;201q' is a read", () => {
|
||||
expect(loads("sed -n '1,200p;201q' ~/.codex/skills/gstack-review/SKILL.md", 'Process exited with code 0\nOutput:\n---')).toEqual(['gstack-review']);
|
||||
expect(loads('sed -n "1,200p;201q" ~/.codex/skills/gstack-review/SKILL.md')).toEqual(['gstack-review']);
|
||||
expect(loads('echo x; ' + READ)).toEqual(['gstack-review']);
|
||||
});
|
||||
|
||||
test('C: a user turn holding only an image ends the run, so the next read of the same skill is a new load', () => {
|
||||
const image = record({ type: 'message', role: 'user', content: [{ type: 'input_image', image_url: 'data:image/png;base64,AAAA' }] });
|
||||
const t = (between: string[]) => parseTranscript([meta, user, call(READ, 'a'), result('Process exited with code 0\nOutput:\n---', 'a'), ...between, call(READ, 'b'), result('Process exited with code 0\nOutput:\n---', 'b')].join('\n'));
|
||||
expect(skillLoads(t([image]))).toHaveLength(2);
|
||||
expect(skillLoads(t([]))).toHaveLength(1);
|
||||
});
|
||||
|
||||
test('a || fallback whose first read fails loads from the second; the error names only the first path', () => {
|
||||
expect(loads(READ + ' || cat ~/.agents/skills/gstack-review/SKILL.md', 'Process exited with code 0\nOutput:\ncat: /home/u/.codex/skills/gstack-review/SKILL.md: No such file or directory\n---\nname: review')).toEqual(['gstack-review']);
|
||||
expect(loads(READ + ' || cat ~/.agents/skills/gstack-review/SKILL.md', 'Process exited with code 1\nOutput:\ncat: /home/u/.codex/skills/gstack-review/SKILL.md: No such file or directory\ncat: /home/u/.agents/skills/gstack-review/SKILL.md: No such file or directory')).toEqual([]);
|
||||
});
|
||||
|
||||
test('a read error must name the path itself: SKILL.md.bak or another skill folder does not drop a good read', () => {
|
||||
expect(loads(READ + '; ls ~/.codex/skills/gstack-review/SKILL.md.bak', "Process exited with code 2\nOutput:\n---\nls: cannot access '/home/u/.codex/skills/gstack-review/SKILL.md.bak': No such file or directory")).toEqual(['gstack-review']);
|
||||
expect(loads(READ, "Process exited with code 1\nOutput:\ncat: /home/u/.codex/skills/gstack-review/SKILL.md: Permission denied")).toEqual([]);
|
||||
});
|
||||
|
||||
test('an error line that does not provably name another file still drops the read', () => {
|
||||
expect(loads('cat "$(realpath -m ~/.codex/skills/gstack-review/SKILL.md)"', 'Process exited with code 1\nOutput:\ncat: /home/u/dotfiles/skills/gstack-review/SKILL.md: No such file or directory')).toEqual([]);
|
||||
expect(loads('cd ~/.codex/skills/gstack-review && cat SKILL.md', 'Process exited with code 1\nOutput:\ncat: SKILL.md: No such file or directory')).toEqual([]);
|
||||
expect(loads(READ + '; cat /tmp/notes.txt', 'Process exited with code 1\nOutput:\n---\nname: review\ncat: /tmp/notes.txt: No such file or directory')).toEqual(['gstack-review']);
|
||||
});
|
||||
|
||||
test('a multi-file read whose other file fails still loads', () => {
|
||||
expect(loads(READ + ' /tmp/x', 'Process exited with code 1\nOutput:\n---\nname: review\ncat: /tmp/x: No such file or directory')).toEqual(['gstack-review']);
|
||||
});
|
||||
|
||||
test('a one-file read that exits non-zero with no error text is not a load', () => {
|
||||
expect(loads(READ, 'Process exited with code 1\nOutput:\n')).toEqual([]);
|
||||
expect(loads("sed -n '1,200p' ~/.codex/skills/gstack-review/SKILL.md", 'Process exited with code 1\nOutput:\n')).toEqual([]);
|
||||
});
|
||||
|
||||
test("PowerShell's Cannot find path is a read error", () => {
|
||||
expect(loads('Get-Content C:\\Users\\u\\.codex\\skills\\gstack-review\\SKILL.md', "Get-Content: Cannot find path 'C:\\Users\\u\\.codex\\skills\\gstack-review\\SKILL.md' because it does not exist.")).toEqual([]);
|
||||
expect(loads('Get-Content C:\\Users\\u\\.codex\\skills\\gstack-review\\SKILL.md', '---\nname: review')).toEqual(['gstack-review']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('chunked reads: reading the same SKILL.md again continues the run', () => {
|
||||
const met = lines('exec-read-met.jsonl');
|
||||
const spawnAt = met.findIndex(l => l.includes('"function_call"') && l.includes('spawn_agent') && met.some(o => o.includes('function_call_output') && o.includes(JSON.parse(l).payload.call_id) && o.includes('agent_id')));
|
||||
|
||||
Reference in new issue
Block a user