diff --git a/bin/gstack-session-kind b/bin/gstack-session-kind index 88959293f..5071ad0fb 100755 --- a/bin/gstack-session-kind +++ b/bin/gstack-session-kind @@ -10,7 +10,7 @@ # failure time: # spawned → orchestrator session (OpenClaw). Auto-choose recommended option # per the skill's SPAWNED_SESSION block. Never prose, never BLOCKED. -# headless → no human present (claude -p evals / CI). BLOCK on AUQ failure. +# headless → no human present (claude -p evals / CI / codex exec). BLOCK on AUQ failure. # interactive → a human is present. Prose-fallback on AUQ failure. # unattended → a parent agent drives this run and reads its artifacts, not # its prose (plan B1). Recommended options are auto-decided and @@ -66,11 +66,60 @@ if [ -n "${CONDUCTOR_WORKSPACE_PATH:-}" ] || [ -n "${CONDUCTOR_PORT:-}" ] || [ " exit 0 fi -# 4. CI / automation markers with no interactive host → headless. +# 4. Codex non-interactive run: `codex exec` (alias `e`) or `codex review`. Codex +# 0.170 gives every tool shell CODEX_THREAD_ID and CODEX_CI=1, and no TTY, in +# its interactive TUI and in exec alike, so the env cannot tell them apart. +# The process tree can: exec runs tool shells under its own `codex exec` +# process, while the TUI runs them under its `codex app-server` daemon. Walk +# up to the nearest codex process (argv[0], or argv[1] under node or a script +# interpreter) and read its subcommand. Linux's /proc keeps argv boundaries; +# elsewhere ps joins argv with spaces, so a TUI started with --no-daemon and a +# prompt whose first word is "exec" would read as exec there. Linux also reads +# parent pids from /proc, so a slim image without ps still works. Elsewhere +# any read failure (no ps, as in Git Bash) means no signal. +_codex_argv() { + if [ -r "/proc/$1/cmdline" ]; then tr '\0' '\n' < "/proc/$1/cmdline"; else ps -o args= -p "$1" 2>/dev/null | tr ' ' '\n'; fi +} +_codex_noninteractive_ancestor() { + local pid=$PPID depth=0 tok i found skip sub + while [ "$depth" -lt 12 ] && [ "${pid:-0}" -gt 1 ] 2>/dev/null; do + i=0 found=0 skip=0 sub="" + while IFS= read -r tok; do + i=$((i + 1)) + if [ "$found" -eq 0 ]; then + [ "$i" -le 2 ] || break + case "${tok##*/}" in codex|codex.js|codex.exe) found=1 ;; esac + continue + fi + if [ "$skip" -eq 1 ]; then skip=0; continue; fi + case "$tok" in + -c|--config|-m|--model|-p|--profile|-s|--sandbox|-a|--ask-for-approval|-C|--cd|-i|--image|--add-dir|--enable|--disable|--local-provider|--remote|--remote-auth-token-env) skip=1 ;; + -*|'') ;; + *) sub=$tok; break ;; + esac + done < <(_codex_argv "$pid") + if [ "$found" -eq 1 ]; then + case "$sub" in exec|e|review) return 0 ;; *) return 1 ;; esac + fi + if [ -r "/proc/$pid/status" ]; then + pid=$(while read -r tok sub; do [ "$tok" = "PPid:" ] && { echo "$sub"; break; }; done < "/proc/$pid/status") + else + pid=$(ps -o ppid= -p "$pid" 2>/dev/null | tr -d ' ') || return 1 + fi + depth=$((depth + 1)) + done + return 1 +} +if [ -n "${CODEX_THREAD_ID:-}" ] && _codex_noninteractive_ancestor; then + echo "headless" + exit 0 +fi + +# 5. CI / automation markers with no interactive host → headless. if [ -n "${CI:-}" ] || [ -n "${GITHUB_ACTIONS:-}" ]; then echo "headless" exit 0 fi -# 5. No positive headless signal → assume a human is present (degrade-safe default). +# 6. No positive headless signal → assume a human is present (degrade-safe default). echo "interactive" diff --git a/changelog.d/codex-unattended-runs-and-duplicate-skills.md b/changelog.d/codex-unattended-runs-and-duplicate-skills.md new file mode 100644 index 000000000..08cb67bf0 --- /dev/null +++ b/changelog.d/codex-unattended-runs-and-duplicate-skills.md @@ -0,0 +1,4 @@ +- **On Codex, office-hours, plan-design-review and gstack-upgrade work again when you name them.** `./setup --host codex` left a second copy of each of these three skills inside gstack's own folder, so Codex listed them twice and loaded nothing when you asked for one (`$office-hours` started without its instructions). On macOS and Linux, setup now links those files instead of copying them, so Codex lists each skill once; Windows setup still copies them, because it can't rely on symlinks there. Re-run `./setup --host codex`, or upgrade gstack, to fix an existing install. +- **gstack knows when Codex is running unattended.** A skill started under `codex exec` (or `codex review`) now reports `SESSION_KIND: headless` instead of `interactive`, the same as an unattended Claude Code run, so it stops with a clear BLOCKED line instead of asking a question nobody will answer. The Codex TUI, and Codex inside Conductor, still count as interactive. +- **Codex reviewers start with a clean context.** The design reviewers, /autoplan's review phases and /context-restore's summary helper now start their Codex subagents with `fork_turns: "none"`, so they no longer inherit the parent's whole conversation (GST-3091). +- **Docs no longer say Codex has no hook support.** Codex CLI 0.170 runs hooks; gstack's routing, contract and destructive-command hooks just aren't ported to it yet. diff --git a/docs/skill-routing-and-contracts.md b/docs/skill-routing-and-contracts.md index 7081c8343..e060c056d 100644 --- a/docs/skill-routing-and-contracts.md +++ b/docs/skill-routing-and-contracts.md @@ -32,7 +32,8 @@ 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, OpenCode, Cursor and other hosts | no | no | no | No hook support. `gstack-skill-contract check` still works on a Claude Code transcript | +| 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 | +| 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 diff --git a/docs/unattended.md b/docs/unattended.md index a5849f9cb..947b57735 100644 --- a/docs/unattended.md +++ b/docs/unattended.md @@ -7,13 +7,22 @@ kind changes, which files a run writes, how the parent decides whether the run finished, and how it reads the result without reading any markdown. The session kinds are: `interactive` (a human answers prompts), `headless` -(`GSTACK_HEADLESS`, `CI`, the eval harness; a question BLOCKs), `spawned` +(`GSTACK_HEADLESS`, `CI`, the eval harness, `codex exec`; a question BLOCKs), `spawned` (an orchestrator subagent; the recommended option is auto-chosen) and `unattended` (this page). `unattended` is honored only as the explicit `GSTACK_SESSION_KIND=unattended` override, which outranks `GSTACK_HEADLESS` so a parent can drive a run inside CI. Nothing in the test or eval harness sets it, so `headless` keeps its BLOCK semantics. +On Codex CLI, `gstack-session-kind` reports `headless` for a skill started +under `codex exec` (or its alias `codex e`, or `codex review`) and +`interactive` in the Codex TUI. Codex gives tool shells the same environment +(`CODEX_THREAD_ID`, `CODEX_CI=1`, no TTY) in both, so the helper reads the +subcommand of the nearest `codex` process instead: exec runs tool shells +itself, and the TUI runs them under its `codex app-server` daemon. Conductor's +markers still win, as they do for Claude Code. A Codex run that a parent agent +drives still sets `GSTACK_SESSION_KIND=unattended` itself. + ## What the session kind changes `gstack-skill-start` prints `SESSION_KIND: unattended`, diff --git a/hosts/codex.ts b/hosts/codex.ts index ce8f19270..fda22cd5b 100644 --- a/hosts/codex.ts +++ b/hosts/codex.ts @@ -8,7 +8,7 @@ import { defineHost, GBRAIN_RESOLVERS } from './define-host'; */ export const CODEX_SUBAGENT_DISPATCH = "Codex's `spawn_agent` (`fork_turns: \"none\"`), then `wait_agent` until a final status (a timeout is not one); its final message is the result. Without `spawn_agent`, the dispatch failed"; /** The same call where a step only names it inline. */ -export const CODEX_SUBAGENT_CALL = "Codex's `spawn_agent`, then `wait_agent` for its final message"; +export const CODEX_SUBAGENT_CALL = "`spawn_agent` with `fork_turns: \"none\"`, then `wait_agent`"; const codex = defineHost({ name: 'codex', @@ -64,9 +64,11 @@ const codex = defineHost({ 'using Agent, `subagent_type: "general-purpose"`\nand `run_in_background: false`': "using Codex's `spawn_agent`, then `wait_agent`", 'one read-only Agent (`subagent_type: "general-purpose"`,\n `run_in_background: false`)': "one read-only subagent (Codex's `spawn_agent`, then `wait_agent`)", 'with the Agent tool (never Skill),\n`subagent_type: "general-purpose"`.': "with Codex's `spawn_agent` (never Skill).", - 'Claude Code: set Agent `run_in_background: false` if its schema exposes it.\n A launch receipt means it went background: await its completion notice.\n Other hosts: foreground; await completion when supported.': 'Codex: `spawn_agent` sends the Agent prompt below; then `wait_agent` until its final status.', - '(via Agent tool):': "(via Codex's `spawn_agent`):", - 'through the Agent tool (a plain Read': "through Codex's `spawn_agent` and `wait_agent` (a plain Read", + 'Claude Code: set Agent `run_in_background: false` if its schema exposes it.\n A launch receipt means it went background: await its completion notice.\n Other hosts: foreground; await completion when supported.': '`spawn_agent` (`fork_turns: "none"`) sends the prompt below; `wait_agent` until its final status.', + '(via Agent tool):': '(via `spawn_agent`):', + 'verbatim as the Agent prompt:': 'verbatim as the prompt:', + 'not the Agent prompt.': 'not the prompt.', + 'through the Agent tool (a plain Read': "through Codex's `spawn_agent` (`fork_turns: \"none\"`) and `wait_agent` (a plain Read", }, transcripts: { diff --git a/setup b/setup index a2112cf28..227ba335d 100755 --- a/setup +++ b/setup @@ -855,6 +855,21 @@ _copy_runtime_skill_refs() { done } +# _link_codex_skill_refs RENDER_SKILLS ROOT — the Codex form of the two copies +# above plus gstack-upgrade's, which the preamble's upgrade flow reads. Codex +# lists every real SKILL.md under its skills directory, so a real copy here is a +# second entry beside gstack-/SKILL.md, and naming the skill then injects +# nothing (GEVA-555, Codex 0.170). Codex skips a symlinked SKILL.md, so these are +# links: each skill is listed once and the paths other skills read still resolve. +_link_codex_skill_refs() { + local s + for s in gstack-upgrade office-hours plan-design-review; do + [ -f "$1/gstack-${s#gstack-}/SKILL.md" ] || continue + mkdir -p "$2/$s" + _link_or_copy "$1/gstack-${s#gstack-}/SKILL.md" "$2/$s/SKILL.md" + done +} + # ─── Real-file SKILL.md copies in host runtime roots (C3, #333) ────────────── # Codex skips a symlinked SKILL.md file, so the router and the nested SKILL.md # files in every host runtime root are real copies, rewritten on every run. @@ -3179,10 +3194,7 @@ create_codex_runtime_root() { _link_or_copy "$gstack_dir/browse/bin" "$codex_gstack/browse/bin" fi _link_runtime_dists "$gstack_dir" "$codex_gstack" - if [ -f "$agents_dir/gstack-upgrade/SKILL.md" ]; then - _copy_skill_md "$agents_dir/gstack-upgrade/SKILL.md" "$codex_gstack/gstack-upgrade/SKILL.md" - fi - _copy_runtime_skill_refs "$agents_dir" "$codex_gstack" + _link_codex_skill_refs "$agents_dir" "$codex_gstack" # ETHOS.md — referenced by "Search Before Building" in all skill preambles if [ -f "$gstack_dir/ETHOS.md" ]; then _link_or_copy "$gstack_dir/ETHOS.md" "$codex_gstack/ETHOS.md" diff --git a/test/env-host-runtime-assets.test.ts b/test/env-host-runtime-assets.test.ts index 89f413a87..e68721e21 100644 --- a/test/env-host-runtime-assets.test.ts +++ b/test/env-host-runtime-assets.test.ts @@ -96,7 +96,7 @@ describe.skipIf(process.platform === 'win32')('Codex global install: the freeze const rootDir = path.join(codexHome, 'skills', 'gstack'); const project = path.join(sandbox, 'project', 'src'); fs.mkdirSync(project, { recursive: true }); - const functions = ['_link_or_copy', '_link_runtime_dists', '_copy_runtime_skill_refs', '_copy_skill_md', '_gstack_generated_header', 'create_codex_runtime_root'] + const functions = ['_link_or_copy', '_link_runtime_dists', '_copy_runtime_skill_refs', '_link_codex_skill_refs', '_copy_skill_md', '_gstack_generated_header', 'create_codex_runtime_root'] .filter(name => SETUP_SRC.includes(`\n${name}() {`)).map(extractFunction).join('\n'); const built = spawnSync('bash', ['-c', `IS_WINDOWS=0\n_CODEX_RENDER_ROOT="${renderDir}"\n${functions}\ncreate_codex_runtime_root "${ROOT}" "${rootDir}"`], { encoding: 'utf8', timeout: 30_000, env: { PATH: process.env.PATH ?? '/usr/bin:/bin', HOME: home } }); @@ -132,7 +132,7 @@ describe.skipIf(process.platform === 'win32')('Codex global install: the freeze try { const home = path.join(sandbox, 'home'); const rootDir = path.join(home, '.codex', 'skills', 'gstack'); - const functions = ['_link_or_copy', '_link_runtime_dists', '_copy_runtime_skill_refs', '_copy_skill_md', '_gstack_generated_header', 'create_codex_runtime_root'] + const functions = ['_link_or_copy', '_link_runtime_dists', '_copy_runtime_skill_refs', '_link_codex_skill_refs', '_copy_skill_md', '_gstack_generated_header', 'create_codex_runtime_root'] .filter(name => SETUP_SRC.includes(`\n${name}() {`)).map(extractFunction).join('\n'); const built = spawnSync('bash', ['-c', `IS_WINDOWS=1\n_CODEX_RENDER_ROOT="${renderDir}"\n${functions}\ncreate_codex_runtime_root "${ROOT}" "${rootDir}"`], { encoding: 'utf8', timeout: 60_000, env: { PATH: process.env.PATH ?? '/usr/bin:/bin', HOME: home } }); diff --git a/test/fixtures/skill-md-size-allowlist.json b/test/fixtures/skill-md-size-allowlist.json index 9d3dd4224..e0c5f3966 100644 --- a/test/fixtures/skill-md-size-allowlist.json +++ b/test/fixtures/skill-md-size-allowlist.json @@ -7,8 +7,8 @@ "agy/gstack-plan-devex-review": 114944, "agy/gstack-plan-eng-review": 143530, "agy/gstack-review": 104723, - "codex/gstack-autoplan": 107438, - "codex/gstack-plan-design-review": 110382, + "codex/gstack-autoplan": 107420, + "codex/gstack-plan-design-review": 110378, "codex/gstack-plan-devex-review": 114230, "codex/gstack-plan-eng-review": 142473, "codex/gstack-review": 104057, diff --git a/test/gen-skill-docs.test.ts b/test/gen-skill-docs.test.ts index bb3792e04..024605cc3 100644 --- a/test/gen-skill-docs.test.ts +++ b/test/gen-skill-docs.test.ts @@ -3853,7 +3853,10 @@ describe('setup script validation', () => { expect(fnBody).toContain('$codex_gstack/lib'); expect(fnBody).toContain('browse/dist'); expect(fnBody).toContain('browse/bin'); - expect(fnBody).toContain('gstack-upgrade/SKILL.md'); + expect(fnBody).toContain('_link_codex_skill_refs "$agents_dir" "$codex_gstack"'); + const refs = setupContent.slice(setupContent.indexOf('_link_codex_skill_refs() {'), setupContent.indexOf('\n}\n', setupContent.indexOf('_link_codex_skill_refs() {'))); + expect(refs).toContain('for s in gstack-upgrade office-hours plan-design-review; do'); + expect(refs).toContain('_link_or_copy'); expect(fnBody).toContain('_link_runtime_dists "$gstack_dir" "$codex_gstack"'); expect(fnBody).not.toContain('_link_or_copy "$gstack_dir" "$codex_gstack"'); // Review runtime assets: individual files from the shared helper, never diff --git a/test/gstack-session-kind.test.ts b/test/gstack-session-kind.test.ts index 9a7bee4a0..2ceeebdbd 100644 --- a/test/gstack-session-kind.test.ts +++ b/test/gstack-session-kind.test.ts @@ -11,9 +11,10 @@ * * Free, deterministic, gate-tier. */ -import { describe, test, expect } from 'bun:test'; +import { afterAll, describe, test, expect } from 'bun:test'; import { execFileSync } from 'child_process'; import * as fs from 'fs'; +import * as os from 'os'; import * as path from 'path'; const ROOT = path.resolve(__dirname, '..'); @@ -72,6 +73,60 @@ describe('gstack-session-kind', () => { }); }); +// Codex 0.170 gives every tool shell CODEX_THREAD_ID in its TUI and in exec +// alike; only the nearest codex process's subcommand tells them apart (exec +// runs tool shells itself, the TUI runs them under `codex app-server`). A fake +// `codex` script stands in for that process and runs the helper as its child. +describe.skipIf(process.platform === 'win32')('Codex sessions (GST-3161)', () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-codex-kind-')); + const fake = path.join(dir, 'codex'); + fs.writeFileSync(fake, `#!/usr/bin/env bash\nbash -c '"$SK_BIN"'\n`, { mode: 0o755 }); + afterAll(() => fs.rmSync(dir, { recursive: true, force: true })); + const underCodex = (args: string[], env: Record = {}) => execFileSync(fake, args, { + env: { PATH: process.env.PATH ?? '/usr/bin:/bin', SK_BIN: BIN, CODEX_THREAD_ID: 't-1', CODEX_CI: '1', ...env }, + encoding: 'utf-8', + timeout: 30_000, + }).trim(); + + test('codex exec (and its alias and global flags) → headless', () => { + expect(underCodex(['exec', '--json', 'fix the bug'])).toBe('headless'); + expect(underCodex(['e', 'fix the bug'])).toBe('headless'); + expect(underCodex(['-c', 'model="gpt-6.1-sol"', '--dangerously-bypass-approvals-and-sandbox', 'exec', '-'])).toBe('headless'); + expect(underCodex(['review', '--uncommitted'])).toBe('headless'); + }); + + test('interactive Codex (the TUI app-server, a resumed session, a prompt that says exec) → interactive', () => { + expect(underCodex(['app-server', '--listen', 'unix://', '--managed-daemon'])).toBe('interactive'); + expect(underCodex(['resume', '--last'])).toBe('interactive'); + // Linux reads argv from /proc; ps elsewhere joins argv, so this prompt reads as exec there. + if (process.platform === 'linux') expect(underCodex(['--no-daemon', 'exec the tests and fix them'])).toBe('interactive'); + expect(underCodex([])).toBe('interactive'); + }); + + test('negative controls: Conductor outranks codex exec; no CODEX_THREAD_ID means no Codex signal', () => { + expect(underCodex(['exec', 'x'], { CONDUCTOR_WORKSPACE_PATH: '/tmp/ws' })).toBe('interactive'); + expect(underCodex(['exec', 'x'], { CONDUCTOR_PORT: '55010' })).toBe('interactive'); + expect(underCodex(['exec', 'x'], { CODEX_THREAD_ID: '' })).toBe('interactive'); + expect(underCodex(['exec', 'x'], { GSTACK_SESSION_KIND: 'unattended' })).toBe('unattended'); + }); + + test.skipIf(process.platform !== 'linux')('a shell between codex exec and the helper, with no ps on PATH → headless (Linux reads parent pids from /proc)', () => { + const nested = path.join(dir, 'nested', 'codex'); + const noPs = path.join(dir, 'no-ps-bin'); + fs.mkdirSync(path.dirname(nested)); + fs.mkdirSync(noPs); + fs.writeFileSync(nested, `#!/usr/bin/env bash\nbash -c '"$SK_BIN"; true'\n`, { mode: 0o755 }); + for (const tool of ['bash', 'tr']) fs.symlinkSync(Bun.which(tool)!, path.join(noPs, tool)); + const run = (args: string[]) => execFileSync(nested, args, { + env: { PATH: noPs, SK_BIN: BIN, CODEX_THREAD_ID: 't-1', CODEX_CI: '1' }, + encoding: 'utf-8', + timeout: 30_000, + }).trim(); + expect(run(['exec', 'fix the bug'])).toBe('headless'); + expect(run(['app-server', '--listen', 'unix://'])).toBe('interactive'); + }); +}); + describe('GSTACK_SESSION_KIND explicit override (#2733)', () => { test('spawned wins over every ambient marker (step 0, explicit beats ambient)', () => { // Claude Code subagents inherit the parent env byte-for-byte, so the diff --git a/test/host-config.test.ts b/test/host-config.test.ts index ec5adf712..af671396d 100644 --- a/test/host-config.test.ts +++ b/test/host-config.test.ts @@ -26,6 +26,7 @@ import { agy, gemini, } from '../hosts/index'; +import { CODEX_SUBAGENT_DISPATCH } from '../hosts/codex'; import { HOST_PATHS } from '../scripts/resolvers/types'; import { RESOLVERS } from '../scripts/resolvers'; import { expectTokens } from './helpers/prompt-structure'; @@ -526,6 +527,36 @@ describe('golden-file regression', () => { expect(fs.readFileSync(path.join(ROOT, 'ship', 'sections', 'test-coverage.md'), 'utf-8')).toContain('`run_in_background: false`'); }); + test('every Codex subagent start passes fork_turns: "none", so reviewers start without the parent conversation (GST-3091)', () => { + // Codex 0.170's spawn_agent defaults fork_turns to "all": a start that omits + // it hands the child the whole parent conversation. A start is fine when its + // line or the next names fork_turns, or when it defers to a shared dispatch + // rule (CODEX_SUBAGENT_DISPATCH, which names it) stated in the same file. + const root = path.join(GOLDEN_OUT, '.agents', 'skills'); + const offenders: string[] = []; + const walk = (dir: string): void => { + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + const file = path.join(dir, entry.name); + if (entry.isDirectory()) { walk(file); continue; } + if (!entry.name.endsWith('.md')) continue; + const text = fs.readFileSync(file, 'utf-8'); + const sharedRule = text.includes(CODEX_SUBAGENT_DISPATCH); + const lines = text.split('\n'); + lines.forEach((line, i) => { + if (!line.includes('`spawn_agent`') || line.includes('Without `spawn_agent`')) return; + if ((line + lines[i + 1]).includes('fork_turns: "none"')) return; + if (sharedRule || /shared foreground-dispatch rule/.test(line)) return; + offenders.push(`${path.relative(root, file)}:${i + 1}: ${line.trim().slice(0, 120)}`); + }); + } + }; + walk(root); + expect(offenders).toEqual([]); + for (const skill of ['gstack-design-review/sections/outside-voices.md', 'gstack-plan-design-review/SKILL.md', 'gstack-autoplan/SKILL.md', 'gstack-context-restore/SKILL.md']) { + expect(fs.readFileSync(path.join(root, skill), 'utf-8'), skill).toContain('fork_turns: "none"'); + } + }); + test('Factory ship skill matches golden baseline', () => { const golden = fs.readFileSync(path.join(GOLDEN_DIR, 'factory-ship-SKILL.md'), 'utf-8'); const current = fs.readFileSync(path.join(GOLDEN_OUT, '.factory', 'skills', 'gstack-ship', 'SKILL.md'), 'utf-8'); diff --git a/test/host-conformance.test.ts b/test/host-conformance.test.ts index 8695a55d8..7a664ce03 100644 --- a/test/host-conformance.test.ts +++ b/test/host-conformance.test.ts @@ -63,6 +63,30 @@ function symlinkedSkillMds(dir: string): string[] { return found; } +/** Codex's runtime-root links to skills it already lists (setup's _link_codex_skill_refs). */ +const CODEX_SKILL_REFS = ['gstack-upgrade', 'office-hours', 'plan-design-review']; + +/** + * The SKILL.md files Codex 0.170 lists from dir, by its scan rule: it enters + * linked directories and nested ones, and skips a SKILL.md that is itself a + * symlink (verified with `codex debug prompt-input`, GST-3161). A skill listed + * twice injects nothing when named (GEVA-555). + */ +function codexListedSkillMds(dir: string, seen = new Set()): string[] { + const real = realpathSync(dir); + if (seen.has(real)) return []; + seen.add(real); + const found: string[] = []; + for (const name of readdirSync(dir)) { + const p = join(dir, name); + const st = lstatSync(p); + if (name === 'SKILL.md') { if (st.isFile()) found.push(p); continue; } + if (st.isDirectory() || (st.isSymbolicLink() && existsSync(p) && lstatSync(realpathSync(p)).isDirectory())) found.push(...codexListedSkillMds(p, seen)); + } + return found; +} +const listedNames = (mds: string[]) => mds.map(md => readFileSync(md, 'utf8').match(/^name:\s*(\S+)/m)?.[1] ?? md); + /** * Section pointers in installed SKILL.md files that do not resolve to a * readable file (INV-3, ENG-1). A pointer is "Read `/sections/.md`", @@ -145,7 +169,18 @@ describe.skipIf(process.platform === 'win32')('host conformance kit', () => { // INV-3 install-level checks (C2, C3, ENG-1, ENG-14). if (host !== 'claude') { const runtimeRoot = rows[0][4]; - expect(symlinkedSkillMds(dest), `${host}: symlinked SKILL.md files (Codex skips them)`).toEqual([]); + if (host === 'codex') { + // The runtime root's references to listed skills are links, so Codex lists each skill once. + expect(symlinkedSkillMds(dest).sort()).toEqual(CODEX_SKILL_REFS.map(s => join(runtimeRoot, s, 'SKILL.md')).filter(existsSync).sort()); + for (const s of CODEX_SKILL_REFS) { + const ref = join(runtimeRoot, s, 'SKILL.md'); + if (existsSync(ref)) expect(realpathSync(ref)).toBe(realpathSync(join(dest, `gstack-${s.replace(/^gstack-/, '')}`, 'SKILL.md'))); + } + const listed = listedNames(codexListedSkillMds(dest)); + expect(listed.filter((n, i) => listed.indexOf(n) !== i), 'skills Codex lists twice').toEqual([]); + } else { + expect(symlinkedSkillMds(dest), `${host}: symlinked SKILL.md files (Codex skips them)`).toEqual([]); + } for (const bin of ['design/dist/design', 'make-pdf/dist/pdf']) { expect(existsSync(join(runtimeRoot, bin)), `${host} runtime root ${bin}`).toBe(true); } @@ -262,7 +297,36 @@ describe.skipIf(process.platform === 'win32')('host conformance kit', () => { expect(saved![1]).toBe(router); expect(saved![2].startsWith(join(f.home, '.gstack/backups/skill-copies/'))).toBe(true); expect(readFileSync(saved![2], 'utf8')).toEndWith('\nmy local note\n'); - expect(upgrade.stdout).toContain(`refreshed SKILL.md copies in ${join(f.home, '.codex/skills/gstack')}: SKILL.md gstack-upgrade/SKILL.md office-hours/SKILL.md`); + expect(upgrade.stdout).toContain(`refreshed SKILL.md copies in ${join(f.home, '.codex/skills/gstack')}: SKILL.md\n`); + }, 90_000); + + test('an existing Codex install with real copies of three skills is upgraded to list each skill once (GST-3161)', () => { + const f = makeFixture(); + const src = makeSource(f, join(f.dir, 'gstack')); + expect(runSetup(f, join(src, 'setup'), ['--host', 'codex']).status).toBe(0); + const skills = join(f.home, '.codex/skills'); + const root = join(skills, 'gstack'); + // The layout setup wrote before GST-3161: real copies in the runtime root. + const refs = CODEX_SKILL_REFS.filter(s => existsSync(join(root, s, 'SKILL.md'))); + expect(refs).toContain('office-hours'); + for (const s of refs) { + const md = join(root, s, 'SKILL.md'); + const body = readFileSync(md, 'utf8'); + rmSync(md); + writeFileSync(md, body); + } + const before = listedNames(codexListedSkillMds(skills)); + expect(before.filter(n => n === 'office-hours')).toHaveLength(2); + + const upgrade = runSetup(f, join(src, 'setup'), ['--host', 'codex']); + expect(upgrade.status, upgrade.stdout + upgrade.stderr).toBe(0); + const after = listedNames(codexListedSkillMds(skills)); + expect(after.filter((n, i) => after.indexOf(n) !== i)).toEqual([]); + expect(before.filter(n => !after.includes(n))).toEqual([]); + for (const s of refs) { + expect(lstatSync(join(root, s, 'SKILL.md')).isSymbolicLink()).toBe(true); + expect(readFileSync(join(root, s, 'SKILL.md'), 'utf8')).toContain(`name: ${s}`); + } }, 90_000); test('a Codex namespace captured by a vendored project copy is reported, never repointed (#2879)', () => { diff --git a/test/qa-lazy-sections.test.ts b/test/qa-lazy-sections.test.ts index cc57bcfd2..efec9b877 100644 --- a/test/qa-lazy-sections.test.ts +++ b/test/qa-lazy-sections.test.ts @@ -529,7 +529,7 @@ describe('installed QA pointers', () => { '_gstack_generated_header', '_claude_entry_owned_strongly', '_claude_entry_is_ours', '_write_owned_marker', '_backup_skill_md', '_cleanup_weak_dir', '_gstack_dir_only_links', '_cleanup_linked_dir', '_owned_for_windows_refresh', '_sidecar_root_user_owned', '_prune_stale_generated', '_skill_source_exists', - '_link_runtime_dists', '_copy_runtime_skill_refs', '_copy_skill_md', '_skill_copy_hash', '_skill_copy_unmodified', '_preserve_skill_copy_edits', '_record_skill_copies', + '_link_runtime_dists', '_copy_runtime_skill_refs', '_link_codex_skill_refs', '_copy_skill_md', '_skill_copy_hash', '_skill_copy_unmodified', '_preserve_skill_copy_edits', '_record_skill_copies', ].map(setupFunction).join('\n') // Install-registry rows (setup's _setup_arm_* / _setup_row) are not under test here. + '\n_setup_arm_begin() { :; }\n_setup_arm_publish() { :; }\n_setup_row() { :; }'; diff --git a/test/runtime-root-assets.test.ts b/test/runtime-root-assets.test.ts index be5647d47..d855a7914 100644 --- a/test/runtime-root-assets.test.ts +++ b/test/runtime-root-assets.test.ts @@ -107,7 +107,7 @@ function makeSource(): void { function buildRoot(host: string, windows = false): { root: string; stderr: string; status: number | null } { const root = path.join(tmp, windows ? 'home-windows' : 'home', host, 'skills', 'gstack'); fs.mkdirSync(path.dirname(root), { recursive: true }); - const functions = ['_link_or_copy', '_link_runtime_dists', '_copy_runtime_skill_refs', '_copy_skill_md', + const functions = ['_link_or_copy', '_link_runtime_dists', '_copy_runtime_skill_refs', '_link_codex_skill_refs', '_copy_skill_md', '_sidecar_root_user_owned', '_gstack_generated_header', ROOT_BUILDERS[host]!] .filter(name => SETUP_SRC.includes(`\n${name}() {`)).map(extractFunction).join('\n'); const r = spawnSync('bash', ['-c', `set -e\nIS_WINDOWS=${windows ? 1 : 0}\n${functions}\n${ROOT_BUILDERS[host]} "${windows ? ROOT : src}" "${root}"`], @@ -224,7 +224,8 @@ describe.skipIf(process.platform === 'win32')('runtime roots carry every $GSTACK const { root } = buildRoot('codex'); for (const dir of ['plan-design-review', 'office-hours']) { expect(fs.readdirSync(path.join(root, dir))).toEqual(['SKILL.md']); - expect(fs.lstatSync(path.join(root, dir, 'SKILL.md')).isSymbolicLink()).toBe(false); + // A link on Codex, which skips a symlinked SKILL.md: a real copy would list the skill twice (GST-3161). + expect(fs.lstatSync(path.join(root, dir, 'SKILL.md')).isSymbolicLink()).toBe(true); expect(fs.readFileSync(path.join(root, dir, 'SKILL.md'), 'utf8')).toContain('$GSTACK_ROOT'); } expect(fs.existsSync(path.join(root, 'design-html', 'SKILL.md'))).toBe(false); diff --git a/test/setup-codex-design-pdf-runtime.test.ts b/test/setup-codex-design-pdf-runtime.test.ts index ea2e1f65e..162b62c09 100644 --- a/test/setup-codex-design-pdf-runtime.test.ts +++ b/test/setup-codex-design-pdf-runtime.test.ts @@ -97,7 +97,7 @@ const BUILDERS: Record Built> = { }, }; -const FUNCTIONS = ['_link_or_copy', '_link_runtime_dists', '_copy_runtime_skill_refs', '_copy_skill_md', '_sidecar_root_user_owned', '_gstack_generated_header', 'create_agents_sidecar', 'create_codex_runtime_root'] +const FUNCTIONS = ['_link_or_copy', '_link_runtime_dists', '_copy_runtime_skill_refs', '_link_codex_skill_refs', '_copy_skill_md', '_sidecar_root_user_owned', '_gstack_generated_header', 'create_agents_sidecar', 'create_codex_runtime_root'] .filter(name => SETUP_SRC.includes(`\n${name}() {`)) .map(extractFunction) .join('\n');