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
62 changes: 62 additions & 0 deletions .codex/hooks.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,12 @@
"command": "rtk pnpm exec node \"$(git rev-parse --show-toplevel)/scripts/check-codex-agents.mjs\" --hook-pretool",
"timeout": 30,
"statusMessage": "Checking LOOP_PROTOCOL Bash guardrail"
},
{
"type": "command",
"command": "rtk pnpm exec node \"$(git rev-parse --show-toplevel)/.codex/hooks/session-recording-composite.mjs\" --event PreToolUse",
"timeout": 30,
"statusMessage": "Checking Codex session-recording PreToolUse guard"
}
]
},
Expand All @@ -33,6 +39,62 @@
"command": "rtk pnpm exec node \"$(git rev-parse --show-toplevel)/scripts/check-codex-agents.mjs\" --hook-pretool",
"timeout": 30,
"statusMessage": "Checking LOOP_PROTOCOL patch guardrail"
},
{
"type": "command",
"command": "rtk pnpm exec node \"$(git rev-parse --show-toplevel)/.codex/hooks/session-recording-composite.mjs\" --event PreToolUse",
"timeout": 30,
"statusMessage": "Checking Codex session-recording patch guard"
}
]
}
],
"PermissionRequest": [
{
"matcher": "^Bash$",
"hooks": [
{
"type": "command",
"command": "rtk pnpm exec node \"$(git rev-parse --show-toplevel)/.codex/hooks/session-recording-composite.mjs\" --event PermissionRequest",
"timeout": 30,
"statusMessage": "Checking Codex session-recording PermissionRequest guard"
}
]
},
{
"matcher": "^(apply_patch|Edit|Write)$",
"hooks": [
{
"type": "command",
"command": "rtk pnpm exec node \"$(git rev-parse --show-toplevel)/.codex/hooks/session-recording-composite.mjs\" --event PermissionRequest",
"timeout": 30,
"statusMessage": "Checking Codex session-recording PermissionRequest guard"
}
]
}
],
"Stop": [
{
"matcher": ".*",
"hooks": [
{
"type": "command",
"command": "rtk pnpm exec node \"$(git rev-parse --show-toplevel)/.codex/hooks/session-recording-composite.mjs\" --event Stop",
"timeout": 30,
"statusMessage": "Writing Codex session-recording Stop manifest"
}
]
}
],
"SubagentStop": [
{
"matcher": ".*",
"hooks": [
{
"type": "command",
"command": "rtk pnpm exec node \"$(git rev-parse --show-toplevel)/.codex/hooks/session-recording-composite.mjs\" --event SubagentStop",
"timeout": 30,
"statusMessage": "Writing Codex session-recording SubagentStop manifest"
}
]
}
Expand Down
3 changes: 3 additions & 0 deletions .codex/hooks/session-recording-composite.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
#!/usr/bin/env node

import '../../scripts/session-recording/codex-hook-adapter.mjs'
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ tmp/nlm/
# Project-local tmp working files (issue backups / intermediate body / reviewer feedback など)
# `tmp/` 自体は create-issue / edit-issue / post-merge-cleanup の作業領域として使うが、
# 中身(バックアップ・中間ファイル)はコミットしない
tmp/session-manifests/codex/
tmp/codex-pilot-metrics.json
tmp/issue_*_backup_*.md
tmp/issue_*_new_*.md
tmp/reviewer_feedback.md
Expand Down
7 changes: 7 additions & 0 deletions docs/dev/onboarding/session-recording-tool.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,13 @@ created: "2026-05-24"
導入作業のうち権限・secret・外部契約が必要な部分を明確に分離し、
AI が実行できる準備作業と人間が判断しなければならない操作を区別する。

## Codex CLI Hook Trust 補足

- Codex repo-local hook の canonical config key は `[features].hooks`。旧 `codex_hooks` alias が残っていても、それを唯一の正本として説明しない。
- `.codex/hooks.json` を validator が pass しても、runtime active hook state と trust state は別途 `/hooks` 等で確認する必要がある。
- trusted project でない `.codex/` layer の hook は load されない。pilot で `--dangerously-bypass-hook-trust` を既定運用に組み込まない。
- Codex session-recording manifest は `tmp/session-manifests/codex/**` の private/local artifact に閉じ、public comment や public checkpoint branch に転載しない。

---

## Pilot 開始可否
Expand Down
8 changes: 8 additions & 0 deletions docs/dev/session-recording-policy.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,14 @@ created: "2026-05-24"
本文書は `session_recording_policy/v1` YAML と Kill Switch 手順の唯一の正本(SSOT)である。
`secrets_mode` が `none` 以外に遷移した場合の session 記録制御と、Kill Switch の実行手順を定める。

## Codex CLI Hook Boundary

- `.codex/hooks.json` の structural validation は repo-local wiring の確認に限られ、runtime active hook state や trust state の証跡にはならない。
- Codex CLI では `[features].hooks` を canonical key とし、`codex_hooks` は deprecated alias としてのみ扱う。
- project `.codex/` layer は trust 済みでなければ load されない。`--dangerously-bypass-hook-trust` は one-off automation 向けの非既定 escape hatch であり、pilot の通常運用では使わない。
- `PreToolUse` / `PermissionRequest` は予防層であり security boundary ではない。canonical final gate は post-run verifier と private artifact validation に置く。
- Codex hook command は `rtk pnpm exec node ...` を明示 dependency とし、runtime では `node` と repo script のみで deterministic に再実行できるようにする。

---

## 機械可読メタデータ (session_recording_policy/v1)
Expand Down
1 change: 1 addition & 0 deletions docs/dev/smoke/session-recording-pilot.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ status: in-progress
## Evidence Storage Boundary

- `artifacts/session-recording-pilot/` は local-only / private artifact 用であり、raw transcript、local absolute path、API key、`.env`、agent-local settings を GitHub に投稿・commit・push してはならない。
- Codex CLI adapter で追加される `tmp/session-manifests/codex/**` と `tmp/codex-pilot-metrics.json` も private/local artifact とし、runtime active hook / trust state の public evidence に流用しない。
- public GitHub comment に置けるのは `agent_session_manifest/v1` の metadata のみ(`source_kind: public_github_comment`)。
- `entire/checkpoints/v1` または同等の checkpoint branch が public remote に存在しないことを Kill Switch 検証で確認する。
- raw transcript は `public_github_comment` surface への出力禁止(#242 policy)。
Expand Down
241 changes: 241 additions & 0 deletions scripts/session-recording/codex-hook-adapter.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,241 @@
#!/usr/bin/env node

import { execFileSync } from 'node:child_process'
import { dirname, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'

import { buildCodexManifestFileName, writeCodexSessionManifest } from './write-codex-session-manifest.mjs'
import { scanObjectForSyntheticCanary, scanTextForSyntheticCanary } from './codex-metadata-scan.mjs'
import { verifyCodexPostRun } from './codex-postrun-verifier.mjs'

const __dirname = dirname(fileURLToPath(import.meta.url))
const repoRoot = resolve(__dirname, '..', '..')
const defaultProducerScript = resolve(repoRoot, 'scripts', 'generate-session-manifest.mjs')
const configuredProducerScript = process.env.CODEX_SESSION_RECORDING_PRODUCER
? resolve(process.env.CODEX_SESSION_RECORDING_PRODUCER)
: defaultProducerScript
const producerScript = configuredProducerScript.startsWith(repoRoot)
? configuredProducerScript
: defaultProducerScript

function parseArgs(argv) {
const args = { event: null }
for (let index = 2; index < argv.length; index += 1) {
const token = argv[index]
if (token === '--event') {
args.event = argv[index + 1]
index += 1
continue
}
throw new Error(`Unknown option: ${token}`)
}
if (!args.event) {
throw new Error('--event is required')
}
return args
}

function emitJson(payload) {
process.stdout.write(JSON.stringify(payload))
}

function stopEventOutput(reason) {
return {
continue: false,
stopReason: reason,
}
}

function denyPreToolUse(reason) {
return {
hookSpecificOutput: {
hookEventName: 'PreToolUse',
permissionDecision: 'deny',
permissionDecisionReason: reason,
},
}
}

function denyPermissionRequest(reason) {
return {
hookSpecificOutput: {
hookEventName: 'PermissionRequest',
decision: {
behavior: 'deny',
message: reason,
},
},
}
}

async function readJsonFromStdin() {
let text = ''
process.stdin.setEncoding('utf8')
for await (const chunk of process.stdin) {
text += chunk
}
if (!text.trim()) {
throw new Error('empty stdin')
}
return JSON.parse(text)
}

function getCommand(payload) {
return String(payload?.tool_input?.command ?? payload?.tool_input?.description ?? '')
}

function sanitizeStopReason(eventName) {
return `${eventName}: Codex session recording failed; see private local log.`
}

function matchesForbiddenPath(command) {
return /(^|[^A-Za-z0-9_./-])((assets|LICENSES)\/|(?:[^\s'"]*\/)?\.env(?:\.[^\s'"]+)*)/.test(command)
}

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

if (payload?.public_checkpoint_enabled === true) {
return `${eventName}: public checkpoint is forbidden`
}
if (payload?.unknown_visibility_mapping === true) {
return `${eventName}: unknown visibility mapping must fail closed`
}
if (payload?.secrets_mode && payload.secrets_mode !== 'none') {
return `${eventName}: secrets_mode must remain none`
}
if (payload?.forbidden_path_touched === true || matchesForbiddenPath(command)) {
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`
}
return null
}

function buildProducerArgs(eventName, evidenceSourceRef) {
return [
producerScript,
'--repository', 'squne121/loop-protocol',
'--phase-main-loop', 'impl',
'--phase-ledger-phase', 'post_commit_verification',
'--phase-instance-id', 'issue-768:impl:001',
'--actor-type', 'ai_agent',
'--actor-name', `codex-${eventName.toLowerCase()}-hook`,
'--evidence-source-kind', 'artifact',
'--evidence-source-ref', evidenceSourceRef,
'--evidence-visibility', 'private_artifact',
'--format', 'json',
'--validate',
]
}

function produceManifest(eventName, payload, evidenceSourceRef) {
const stdout = execFileSync(process.execPath, buildProducerArgs(eventName, evidenceSourceRef), {
cwd: repoRoot,
encoding: 'utf8',
stdio: ['pipe', 'pipe', 'pipe'],
})
const manifest = JSON.parse(stdout)
manifest.secret_policy.runtime_boundary = {
attested: true,
evidence_ref: evidenceSourceRef,
}
manifest.token_usage = {
availability: 'unavailable',
source: 'none',
prompt: null,
completion: null,
total: null,
}
return manifest
}

function runManifestFlow(eventName, payload) {
const metadataFindings = scanObjectForSyntheticCanary(payload)
const fileName = buildCodexManifestFileName()
const evidenceSourceRef = `tmp/session-manifests/codex/${eventName.toLowerCase()}/${fileName}`
const manifest = produceManifest(eventName, payload, evidenceSourceRef)
const stdoutFindings = scanTextForSyntheticCanary(JSON.stringify(manifest))
const stderrFindings = []

if (metadataFindings.length > 0 || stdoutFindings.length > 0 || stderrFindings.length > 0) {
throw new Error(`${eventName}: synthetic canary leaked into public surface`)
}

writeCodexSessionManifest({
manifest,
repoRoot,
eventName,
fileName,
})

const verification = verifyCodexPostRun(payload, { repoRoot })
if (!verification.ok) {
return stopEventOutput(`${eventName}: ${verification.failures.join(', ')}`)
}
return { continue: true }
}

async function main() {
const { event } = parseArgs(process.argv)
let payload
try {
payload = await readJsonFromStdin()
} catch {
if (event === 'PreToolUse') {
emitJson(denyPreToolUse(`Malformed ${event} payload blocked by hook.`))
return
}
if (event === 'PermissionRequest') {
emitJson(denyPermissionRequest(`Malformed ${event} payload blocked by hook.`))
return
}
emitJson(stopEventOutput(`Malformed ${event} payload blocked by hook.`))
return
}

const reason = evaluateGuard(payload, event)
if (reason) {
if (event === 'PreToolUse') {
emitJson(denyPreToolUse(reason))
return
}
if (event === 'PermissionRequest') {
emitJson(denyPermissionRequest(reason))
return
}
emitJson(stopEventOutput(reason))
return
}

if (event === 'Stop' || event === 'SubagentStop') {
emitJson(runManifestFlow(event, payload))
return
}

if (event === 'PreToolUse' || event === 'PermissionRequest') {
return
}

throw new Error(`Unsupported event: ${event}`)
}

main().catch(() => {
const eventIndex = process.argv.indexOf('--event')
const eventName = eventIndex >= 0 ? process.argv[eventIndex + 1] : null
if (eventName === 'Stop' || eventName === 'SubagentStop') {
emitJson(stopEventOutput(sanitizeStopReason(eventName)))
process.exit(0)
}
if (eventName === 'PreToolUse') {
emitJson(denyPreToolUse(`Malformed ${eventName} payload blocked by hook.`))
process.exit(0)
}
if (eventName === 'PermissionRequest') {
emitJson(denyPermissionRequest(`Malformed ${eventName} payload blocked by hook.`))
process.exit(0)
}
process.stderr.write('Codex session recording hook failed.\n')
process.exit(1)
})
Loading
Loading