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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 69 additions & 0 deletions docs/dev/session-recording-policy.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,75 @@ created: "2026-05-24"

---

## active PreToolUse handlers(#783 追加)

`.codex/hooks.json` に登録されている active PreToolUse handlers とその責務境界。

| matcher | handler | 責務 |
|---|---|---|
| `^Bash$` | `scripts/check-codex-agents.mjs --hook-pretool` | rtk bypass guard / Allowed Paths enforcement |
| `^Bash$` | `.codex/hooks/session-recording-composite.mjs --event PreToolUse` | session recording guard(reason_code taxonomy) |
| `^(apply_patch\|Edit\|Write)$` | `scripts/check-codex-agents.mjs --hook-pretool` | Allowed Paths enforcement(write tool) |
| `^(apply_patch\|Edit\|Write)$` | `.codex/hooks/session-recording-composite.mjs --event PreToolUse` | session recording guard(patch/write) |

Codex CLI は同一 event に matching する複数の command hooks を **concurrently launched** する(公式仕様)。
実行順序・short-circuit・handler 間依存は保証されない。
各 handler は独立して fail-closed な判定を返す必要があり、他の handler が先に deny することに依存してはならない。

### reason_code taxonomy(#783)

`session-recording-composite.mjs` が返す deny reason の分類。

| reason_code | command_kind | 対象コマンド例 | 意味 |
|---|---|---|---|
| `secret_boundary_violation` | `gh_secret` | `gh secret list` | gh secret コマンドによる Secret 参照 |
| `secret_boundary_violation` | `gh_api_actions_secrets` | `gh api .../secrets` | gh api 経由の GitHub Actions Secret 参照 |
| `secret_boundary_violation` | `printenv` | `printenv` | 環境変数全ダンプ |
| `secret_boundary_violation` | `env_dump` | `env`(standalone) | 環境変数全ダンプ(bare env) |
| `secret_boundary_violation` | `python_os_environ` | `python3 -c '...os.environ...'` | Python 経由の環境変数アクセス |
| `remote_write_requires_approval` | `git_push` | `git push origin main` | remote への git push |
| `readonly_investigation_allowed` | — | `env FOO=bar cmd` | variable prefix 付き read-only 調査(通過) |

`env FOO=bar <cmd>` パターン(変数代入プレフィックス)は secret dump ではなく read-only investigation として通過する(AC2)。

### #360 / #639 との境界

- **#360(destination guard policy)**: remote write の許可 policy 自体の見直しは #360 が担当する。本 #783 は deny reason の分類整理のみ。`remote_write_requires_approval` を自動許可に変更する設計は #360 スコープ。
- **#639(PR body mutation enforcement)**: PR body の mutation 強制実装は #639 が担当する。本 #783 は hook output shape の整形のみ。

---

## codex exec live smoke(diagnostic-only、#783 追加)

`codex exec` を使った live smoke test は **diagnostic-only 手順**とする。CI required gate には含めない。

### 背景

2026-06-10 時点で upstream issue [`openai/codex#26452`](https://github.com/openai/codex/issues/26452) が OPEN であり、
`codex exec` の hook dispatch 動作が不安定なことが確認されている。
live smoke の成功/失敗はこの Issue の merge gate に含めない(`decision: not_applicable`)。

### diagnostic 手順(人間が手動確認する場合)

```bash
# codex exec が利用可能か確認(binary チェック)
which codex || echo "codex not found"
codex --version 2>/dev/null || echo "codex version unavailable"

# PreToolUse hook が発火するか確認(diagnostic-only — 成功は保証しない)
# upstream openai/codex#26452 が open のため hook dispatch が不安定
codex exec --dangerously-bypass-hook-trust false -- bash -c 'echo test' 2>&1 || true

# hook output を手動確認する場合
echo '{"tool_name":"Bash","tool_input":{"command":"git push origin main"}}' \
| node .codex/hooks/session-recording-composite.mjs --event PreToolUse
# 期待: {"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"..."}}
```

上記は **diagnostic-only**。CI ゲートや merge 条件には含めない。

---

## 機械可読メタデータ (session_recording_policy/v1)

```yaml
Expand Down
63 changes: 53 additions & 10 deletions scripts/check-codex-agents.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -281,17 +281,30 @@ function validateHooksJson(hooksPath, failures) {
continue;
}
const hooks = entry?.hooks ?? [];
assert(hooks.length === 1, `hooks.json: matcher ${matcher} must have exactly one hook`, failures);
// PreToolUse matchers must have exactly 2 hooks (active handler inventory, #783):
// 1. scripts/check-codex-agents.mjs --hook-pretool (rtk bypass guard / Allowed Paths enforcement)
// 2. .codex/hooks/session-recording-composite.mjs --event PreToolUse (session recording guard)
assert(hooks.length >= 2, `hooks.json: matcher ${matcher} must have at least 2 hooks (check-codex-agents + session-recording-composite)`, failures);
const pretoolHook = hooks.find((h) => h?.command?.includes('--hook-pretool'));
assert(
hooks[0]?.command?.includes('--hook-pretool'),
`hooks.json: matcher ${matcher} command must include --hook-pretool`,
Boolean(pretoolHook),
`hooks.json: matcher ${matcher} must have a hook command including --hook-pretool`,
failures,
);
assert(
hooks[0]?.statusMessage === expectedStatusMessage,
pretoolHook?.statusMessage === expectedStatusMessage,
`hooks.json: matcher ${matcher} statusMessage must be ${expectedStatusMessage}`,
failures,
);
// Verify session-recording-composite.mjs --event PreToolUse is an active handler (#783)
const sessionRecordingHook = hooks.find(
(h) => h?.command?.includes('session-recording-composite.mjs') && h?.command?.includes('--event PreToolUse'),
);
assert(
Boolean(sessionRecordingHook),
`hooks.json: matcher ${matcher} must have session-recording-composite.mjs --event PreToolUse as an active handler (Fix 4 #783)`,
failures,
);
}

const allHookCommands = [];
Expand Down Expand Up @@ -680,11 +693,16 @@ function isDirectBypass(command) {
}

function denyForBash(command) {
if (/^rtk\b/.test(command) || !command) {
if (!command) {
return null;
}
// rtk-prefixed commands pass through (read-only investigation allowed)
if (/^rtk\b/.test(command)) {
return null; // readonly_investigation_allowed: rtk commands pass through
}
if (isDirectBypass(command)) {
return 'Use repo-documented rtk wrappers instead of direct pnpm / gh / mutating git commands.';
// direct_bypass_requires_rtk: non-rtk direct invocation of pnpm / gh / mutating git
return 'direct_bypass_requires_rtk: Use repo-documented rtk wrappers instead of direct pnpm / gh / mutating git commands.';
}
return null;
}
Expand Down Expand Up @@ -757,7 +775,8 @@ function denyForWriteTool(toolName, toolInput, allowedPaths) {
// Strict mode: check against Allowed Paths
for (const filePath of touchedPaths) {
if (!isPathAllowed(filePath, allowedPaths)) {
return `Allowed Paths enforcement: "${filePath}" is outside the declared Allowed Paths set. (CODEX_ALLOWED_PATHS enforcement)`;
// AC5: allowed_paths_violation — path is outside declared Allowed Paths
return `allowed_paths_violation: "${filePath}" is outside the declared Allowed Paths set. (CODEX_ALLOWED_PATHS enforcement)`;
}
}
} else if (legacyMode) {
Expand All @@ -768,7 +787,8 @@ function denyForWriteTool(toolName, toolInput, allowedPaths) {
} else {
// Fail-closed default: CODEX_ALLOWED_PATHS must be declared
if (touchedPaths.length > 0) {
return 'CODEX_ALLOWED_PATHS is not set. Declare allowed paths per Issue contract or set CODEX_LEGACY_ALLOW_WRITES=1 to opt out.';
// AC5: allowed_paths_missing — CODEX_ALLOWED_PATHS not declared
return 'allowed_paths_missing: CODEX_ALLOWED_PATHS is not set. Declare allowed paths per Issue contract or set CODEX_LEGACY_ALLOW_WRITES=1 to opt out.';
}
}
return null;
Expand All @@ -783,7 +803,8 @@ function denyForWriteTool(toolName, toolInput, allowedPaths) {
if (allowedPaths !== null) {
// Strict mode
if (!isPathAllowed(filePath, allowedPaths)) {
return `Allowed Paths enforcement: "${filePath}" is outside the declared Allowed Paths set. (CODEX_ALLOWED_PATHS enforcement)`;
// AC5: allowed_paths_violation — path is outside declared Allowed Paths
return `allowed_paths_violation: "${filePath}" is outside the declared Allowed Paths set. (CODEX_ALLOWED_PATHS enforcement)`;
}
} else if (legacyMode) {
// Legacy opt-in: only block assets/LICENSES
Expand All @@ -792,7 +813,8 @@ function denyForWriteTool(toolName, toolInput, allowedPaths) {
}
} else {
// Fail-closed default: CODEX_ALLOWED_PATHS must be declared
return 'CODEX_ALLOWED_PATHS is not set. Declare allowed paths per Issue contract or set CODEX_LEGACY_ALLOW_WRITES=1 to opt out.';
// AC5: allowed_paths_missing — CODEX_ALLOWED_PATHS not declared
return 'allowed_paths_missing: CODEX_ALLOWED_PATHS is not set. Declare allowed paths per Issue contract or set CODEX_LEGACY_ALLOW_WRITES=1 to opt out.';
}
return null;
}
Expand Down Expand Up @@ -1026,6 +1048,27 @@ function runSelfTest() {
selfAssert(result !== null, 'Bash hook: git push is denied');
}

// Test: direct gh is denied with direct_bypass_requires_rtk reason
{
const result = denyForBash('gh pr merge 1');
selfAssert(result !== null && result.includes('direct_bypass_requires_rtk'), 'Bash hook: direct gh denied with direct_bypass_requires_rtk reason');
}

// Test: Edit denied with allowed_paths_missing when CODEX_ALLOWED_PATHS not set
{
delete process.env.CODEX_ALLOWED_PATHS;
delete process.env.CODEX_LEGACY_ALLOW_WRITES;
const result = denyForWriteTool('Edit', { file_path: 'src/main.ts' }, null);
selfAssert(result !== null && result.includes('allowed_paths_missing'), 'Write tool: denied with allowed_paths_missing when no CODEX_ALLOWED_PATHS');
}

// Test: Write denied with allowed_paths_violation when path is outside Allowed Paths
{
const allowed = ['scripts'];
const result = denyForWriteTool('Write', { file_path: 'src/main.ts' }, allowed);
selfAssert(result !== null && result.includes('allowed_paths_violation'), 'Write tool: denied with allowed_paths_violation when path outside allowed set');
}

process.stdout.write('\n');
if (selfTestFailures.length > 0) {
for (const f of selfTestFailures) {
Expand Down
132 changes: 128 additions & 4 deletions scripts/session-recording/codex-hook-adapter.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -92,8 +92,107 @@ function matchesForbiddenPath(command) {
return /(^|[^A-Za-z0-9_./-])((assets|LICENSES)\/|(?:[^\s'"]*\/)?\.env(?:\.[^\s'"]+)*)/.test(command)
}

// ---------------------------------------------------------------------------
// Command classification helpers (AC2-AC5, #783)
// Each classifier returns a structured denial descriptor or null.
// Priority: forbidden_path > secret_boundary > remote_write > read_only pass-through
// ---------------------------------------------------------------------------

/** AC3: secret-revealing commands - gh secrets / printenv / env dump */
function classifySecretBoundary(command) {
// gh secret list/set/get or gh api .../secrets
if (/\bgh\s+(?:secret\b|api\b[^\n]*\bsecrets\b)/.test(command)) {
return {
reason_code: 'secret_boundary_violation',
command_kind: /\bgh\s+api\b/.test(command) ? 'gh_api_actions_secrets' : 'gh_secret',
}
}
// printenv - dumps all env vars including secrets
if (/\bprintenv\b/.test(command)) {
return { reason_code: 'secret_boundary_violation', command_kind: 'printenv' }
}
// bare env invocation as a standalone dump command (not env FOO=bar cmd prefix)
if (/(?:^|[;&|]\s*|\n\s*)env\s*$/.test(command)) {
return { reason_code: 'secret_boundary_violation', command_kind: 'env_dump' }
}
// python -c with sensitive env variable access patterns
if (/\bpython[23]?\s+-c\s+['"][^'"]*os\.environ/.test(command)) {
return { reason_code: 'secret_boundary_violation', command_kind: 'python_os_environ' }
}
return null
}

/** AC4: remote write commands - git push variants */
function classifyRemoteWrite(command) {
if (/\bgit(?:\s+-C\s+\S+)?\s+push\b/.test(command)) {
return { reason_code: 'remote_write_requires_approval', command_kind: 'git_push' }
}
return null
}

/** AC2: read-only investigation commands that must NOT be blocked.
* This function is called only AFTER secret/remote classifiers have been
* applied to the stripped command (env prefix already removed by stripEnvPrefix).
* Returns true for commands that are safe read-only investigations. */
function isReadonlyInvestigation(_command) {
// Placeholder — all env-prefix handling is now done via stripEnvPrefix.
// This function remains for future read-only pass-through extensions.
return false
}

/** Strip `env VAR=val ...` prefix from a command string.
* Returns { stripped: string, isEnvDump: boolean }.
*
* Cases:
* "env" → isEnvDump: true
* "env -0" → isEnvDump: true
* "env --ignore-environment" → isEnvDump: true
* "env VAR=val cmd arg" → stripped: "cmd arg", isEnvDump: false
* anything else starting with env → stripped: original, isEnvDump: false
*/
function stripEnvPrefix(command) {
const trimmed = command.trim()
// bare "env" with no args (possibly trailing whitespace) → env dump
if (/^env\s*$/.test(trimmed)) {
return { stripped: trimmed, isEnvDump: true }
}
// "env" followed by a flag that means dump all vars
if (/^env\s+(-0|--ignore-environment|-i)(\s|$)/.test(trimmed)) {
return { stripped: trimmed, isEnvDump: true }
}
// "env VAR=val ... cmd ..." — strip all leading VAR=val tokens
const envPrefixMatch = /^env\s+((?:[A-Za-z_][A-Za-z0-9_]*=[^\s]*\s+)+)(.+)$/.exec(trimmed)
if (envPrefixMatch) {
return { stripped: envPrefixMatch[2], isEnvDump: false }
}
// "env" followed by something that is not VAR=val assignments → treat as env dump
if (/^env\s+/.test(trimmed)) {
return { stripped: trimmed, isEnvDump: true }
}
return { stripped: trimmed, isEnvDump: false }
}

/** Produce a redacted preview of a command for deny reason strings (AC7). */
function redactCommandPreview(command) {
// Redact secret-like tokens before truncation
let redacted = command
.replace(/\bsk-[A-Za-z0-9_-]{10,}/g, 'sk-[REDACTED]')
.replace(/\bghp_[A-Za-z0-9_]{10,}/g, 'ghp_[REDACTED]')
.replace(/\bgithub_pat_[A-Za-z0-9_]{10,}/g, 'github_pat_[REDACTED]')
.replace(/Authorization:\s*Bearer\s+[^\s"']+/gi, 'Authorization: Bearer [REDACTED]')
.replace(/\b[A-Z_]*(TOKEN|SECRET|PASSWORD|KEY)=[^\s"']+/g, (match, keyword) => `${keyword}=[REDACTED]`)
.replace(/--token\s+[^\s"']+/g, '--token [REDACTED]')
.replace(/-H\s+"Authorization:[^"]+/g, '-H "Authorization: [REDACTED]')
.replace(/-H\s+'Authorization:[^']+/g, "-H 'Authorization: [REDACTED]")

const truncated = redacted.length > 80
? `${redacted.slice(0, 80).replace(/\s+/g, ' ')}...`
: redacted.replace(/\s+/g, ' ')
return truncated
}

function evaluateGuard(payload, eventName) {
const command = getCommand(payload)
const rawCommand = getCommand(payload)

if (payload?.public_checkpoint_enabled === true) {
return `${eventName}: public checkpoint is forbidden`
Expand All @@ -104,12 +203,37 @@ function evaluateGuard(payload, eventName) {
if (payload?.secrets_mode && payload.secrets_mode !== 'none') {
return `${eventName}: secrets_mode must remain none`
}
if (payload?.forbidden_path_touched === true || matchesForbiddenPath(command)) {
if (payload?.forbidden_path_touched === true || matchesForbiddenPath(rawCommand)) {
return `${eventName}: forbidden path access blocked`
}
if (/\bgit(?:\s+-C\s+\S+)?\s+push\b|\bgh\s+(?:secret|api\b[^\n]*secrets)\b|\bprintenv\b|\benv\b|python\s+-c\s+['"][^'"]*os\./.test(command)) {
return `${eventName}: destructive or secret-revealing command blocked`

// Normalize env VAR=val prefix before classification.
// env dump variants (bare "env", "env -0", etc.) are denied immediately.
const { stripped: command, isEnvDump } = stripEnvPrefix(rawCommand)
if (isEnvDump) {
const preview = redactCommandPreview(rawCommand)
return `${eventName}: secret_boundary_violation [command_kind=env_dump] blocked_command_preview="${preview}"`
}

// AC3: secret boundary - highest priority deny among command classifiers
const secretDenial = classifySecretBoundary(command)
if (secretDenial) {
const preview = redactCommandPreview(rawCommand)
return `${eventName}: secret_boundary_violation [command_kind=${secretDenial.command_kind}] blocked_command_preview="${preview}"`
}

// AC4: remote write - deny with remote-write-specific reason (not secret)
const remoteWriteDenial = classifyRemoteWrite(command)
if (remoteWriteDenial) {
const preview = redactCommandPreview(rawCommand)
return `${eventName}: remote_write_requires_approval [command_kind=${remoteWriteDenial.command_kind}] blocked_command_preview="${preview}"`
}

// AC2: read-only investigation passes through (no deny)
if (isReadonlyInvestigation(command)) {
return null
}

return null
}

Expand Down
Loading
Loading