> For the complete documentation index, see [llms.txt](https://faction-os.gitbook.io/faction-os-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://faction-os.gitbook.io/faction-os-docs/.spec_system/archive/sessions/phase09-session03-codex-hook-map-and-codex-specific-handlers/spec.md).

# Session Specification

**Session ID**: `phase09-session03-codex-hook-map-and-codex-specific-handlers` **Phase**: 09 - Codex Provider-Neutral Foundation **Status**: Not Started **Created**: 2026-05-31 **Package**: apps/hooks **Package Stack**: JavaScript hook maps, Node hook handlers, Vitest node tests, Biome checks

***

## 1. Session Overview

This session adds the first Codex-specific hook map and the minimal handler coverage needed to turn Phase 09 provider-neutral protocol and runtime normalization into a concrete Codex hook surface. Session 01 added shared protocol vocabulary, and Session 02 normalized hook input fields so Claude-shaped and Codex-shaped payloads can share safe posting, logging, and spool behavior. Session 03 now uses that foundation to define Codex event wiring without changing the existing Claude hook map behavior.

The work stays package-scoped to `apps/hooks`. It creates source-controlled Codex hook-map assets, adds handler coverage for Codex-only event shapes such as `SubagentStart` and `PostToolUse`, adapts file observability for `apply_patch`, and preserves the existing `hooks.json` Claude compatibility path. CLI installation, user-level Codex writes under `~/.codex`, server ingest expansion, and web product labeling remain later sessions.

Privacy and trust boundaries are first-class requirements. Official Codex hook docs confirm that non-managed command hooks must be reviewed and trusted, matching hooks can run concurrently, `PostToolUse` cannot undo side effects, and `apply_patch` and MCP inputs can carry sensitive bodies. This session must emit only bounded observability payloads, keep normal handler stdout/stderr quiet, and avoid raw patch bodies, command output, transcript contents, MCP argument bodies, token-like values, provider credentials, and broad absolute paths in logs, spool files, or docs.

***

## 2. Objectives

1. Add a provider-specific Codex hook map while keeping the Claude compatibility map unchanged.
2. Add Codex-specific handler coverage for `SubagentStart` and compact `PostToolUse` result events.
3. Adapt existing file, permission, and subagent handlers for Codex `apply_patch`, MCP, and agent field shapes.
4. Add static and runtime tests proving map wiring, privacy redaction, and Claude no-regression behavior.

***

## 3. Prerequisites

### Required Sessions

* [x] `phase09-session01-contracts-and-naming-baseline` - provides `codex-cli`, provider-neutral hook event names, Codex lifecycle names, and optional-safe ingest metadata.
* [x] `phase09-session02-hook-runtime-normalization` - provides shared helpers for provider field normalization, Codex-sensitive sanitization, and Codex-shaped fixture coverage.
* [x] `phase03-session06-cli-diagnostics-and-recovery-controls` - provides current hook/listener diagnostic and recovery posture.
* [x] `phase01-session02-hook-runtime-safety` - provides silent, timeout-bound hook process behavior.

### Required Tools/Knowledge

* Node 20+ and npm workspace dependencies.
* Current `apps/hooks/hooks.json`, handler scripts, and hook tests.
* Official OpenAI Codex hook docs reviewed on 2026-05-31:
  * `https://developers.openai.com/codex/hooks`
  * `https://developers.openai.com/codex/config-reference#configtoml`
  * `https://developers.openai.com/codex/cli/slash-commands#built-in-slash-commands`
* Existing Phase 09 PRD constraints for Codex trust, matcher behavior, `apply_patch`, MCP tools, and no custom slash-command claims.

### Environment Requirements

* No Codex, Claude, OpenAI, Anthropic, Cloudflare, hosted, or provider credentials are required.
* Tests must use isolated temporary FactionOS homes for runtime handlers.
* Normal hook process tests must keep stdout and stderr empty except intentional restricted git-guard denial behavior.

***

## 4. Scope

### In Scope (MVP)

* Hook maintainers can inspect a Codex hook map - create `apps/hooks/hooks.codex.json` with required lifecycle, Bash, `apply_patch`, MCP, permission, post-tool, and subagent event groups.
* Claude users keep existing behavior - keep `apps/hooks/hooks.json` unchanged and add map tests that prove Claude command strings remain stable.
* Provider map ownership is explicit - add `apps/hooks/hooks.claude.json` as the provider-specific Claude map source while retaining `hooks.json` as the compatibility alias.
* Codex command hooks identify the provider - Codex commands include `FACTIONOS_CLI=codex-cli`, bounded timeouts, and status messages without assuming installer-managed absolute paths yet.
* Codex `apply_patch` is observable safely - adapt file observability to summarize touched paths and line counts from patch command headers without storing raw diff bodies.
* Codex `PostToolUse` is result-only - add compact result handling for Bash, `apply_patch`, and selected MCP tool calls without implying side-effect rollback.
* Codex subagent start events produce bounded lineage - add `SubagentStart` handler coverage using normalized `agent_id` and `agent_type`.
* Permission requests stay decision-free - preserve FactionOS as an observability surface and do not auto-approve or deny Codex approvals.
* Tests prove privacy and no regression - add static map tests, process fixtures, and redaction assertions for patch, transcript, terminal output, MCP, and agent fields.

### Out of Scope (Deferred)

* User-level Codex hook installation into `~/.codex/hooks.json` or config files - *Reason: Phase 10 owns installer, uninstall, status, and doctor flows.*
* Project-local `.codex/` generation or trust automation - *Reason: Phase 10 and Phase 11 own install scope and real/fixture validation.*
* Bypassing Codex hook trust with `--dangerously-bypass-hook-trust` - *Reason: users must review hooks with `/hooks`; bypass is not the product default.*
* Server ingest changes for `SubagentStart`, `PreCompact`, or `PostCompact` event names - *Reason: Phase 10 owns server lifecycle ingest beyond current tolerant behavior.*
* Web labels, filters, or UI changes for Codex heroes - *Reason: Phase 10 owns product integration surfaces.*
* Full transcript reconstruction, raw patch parsing, terminal output persistence, MCP argument body storage, or provider credential handling - *Reason: this phase only emits compact observability metadata.*
* Compact lifecycle hooks for `PreCompact` and `PostCompact` - *Reason: optional diagnostics can be added later after map and privacy tests prove the core events.*

***

## 5. Technical Approach

### Architecture

Add provider-specific hook map assets in `apps/hooks` and treat `hooks.json` as the Claude compatibility alias for one release cycle. `hooks.codex.json` should be a source-controlled template for the installer to resolve later, not a claim that Codex installation is complete today. Codex command entries should include `FACTIONOS_CLI=codex-cli`, use existing shared handlers where behavior already matches, and route Codex-only shapes to narrow adapter handlers.

Handler updates should stay dependency-light and reuse the Session 02 normalization layer in `apps/hooks/src/_lib.js`. `factionos-file-access.js` should recognize Codex `apply_patch` inputs and derive bounded path and line metadata without persisting patch bodies. A new `factionos-tool-result.js` should turn `PostToolUse` payloads into compact result events with tool name, tool use id, success status, and short preview only. A new `factionos-subagent-start.js` should emit `subagent_spawn` from Codex `agent_id` and `agent_type` while preserving degraded-state behavior.

Tests should split static map correctness from process behavior. Static tests should assert the Codex map events, matchers, timeouts, provider env, and unchanged Claude commands. Runtime fixtures should execute the relevant handlers with Codex-shaped JSON and isolated homes, then inspect posted or spooled payloads for bounded fields and redaction. Documentation should describe the map and handler readiness without claiming installer support, trusted hook state, hosted validation, custom slash commands, or end-to-end Codex runtime proof.

### Design Patterns

* Provider-specific maps with compatibility alias: keep `hooks.json` stable while adding `hooks.claude.json` and `hooks.codex.json`.
* Adapter handlers: add small Codex-specific wrappers only where event shape differs from Claude.
* Bounded observability: summarize tool inputs and results instead of storing raw patches, outputs, transcripts, or MCP arguments.
* Negative privacy tests: assert sensitive Codex fields do not appear in logs, spool files, or docs.
* Source-backed docs: reference current Codex hook/trust behavior without making installer or live-runtime claims.

### Technology Stack

* JavaScript ES modules in `apps/hooks`.
* JSON hook maps.
* Node process fixtures for handler behavior.
* Vitest node tests through the root `vitest.config.ts`.
* Biome formatting and linting.

***

## 6. Deliverables

### Files to Create

| File                                         | Purpose                                                                                       | Est. Lines |
| -------------------------------------------- | --------------------------------------------------------------------------------------------- | ---------- |
| `apps/hooks/hooks.claude.json`               | Provider-specific Claude map copied from current compatibility map                            | \~120      |
| `apps/hooks/hooks.codex.json`                | Initial Codex hook map template with lifecycle, tool, permission, result, and subagent groups | \~180      |
| `apps/hooks/src/factionos-subagent-start.js` | Codex `SubagentStart` adapter that emits bounded `subagent_spawn` payloads                    | \~80       |
| `apps/hooks/src/factionos-tool-result.js`    | Codex `PostToolUse` result adapter for Bash, `apply_patch`, and MCP summaries                 | \~110      |
| `apps/hooks/tests/codexHookMap.test.js`      | Static map tests for Codex wiring and Claude compatibility                                    | \~220      |

### Files to Modify

| File                                                | Changes                                                                                            | Est. Lines |
| --------------------------------------------------- | -------------------------------------------------------------------------------------------------- | ---------- |
| `apps/hooks/src/factionos-file-access.js`           | Summarize Codex `apply_patch` file edits without raw patch storage                                 | \~90       |
| `apps/hooks/src/factionos-permission-request.js`    | Improve Codex tool-description handling while staying decision-free                                | \~40       |
| `apps/hooks/src/factionos-subagent-complete.js`     | Cover Codex agent stop summaries and agent transcript redaction                                    | \~45       |
| `apps/hooks/tests/hookPayloads.test.js`             | Add static assertions for new handlers and no raw field promotion                                  | \~80       |
| `apps/hooks/tests/hookRuntime.test.js`              | Add Codex map-driven fixtures for lifecycle, `apply_patch`, permission, result, and subagent paths | \~220      |
| `apps/hooks/tests/orchestrationDiagnostics.test.js` | Add redaction coverage for Codex patch, transcript, terminal, MCP, and agent result fields         | \~90       |
| `apps/hooks/README_hooks.md`                        | Document Codex map support, hook trust, remaining install gap, and privacy boundaries              | \~90       |

***

## 7. Success Criteria

### Functional Requirements

* [ ] `apps/hooks/hooks.codex.json` includes `SessionStart`, `UserPromptSubmit`, `Stop`, `PreToolUse`, `PermissionRequest`, `PostToolUse`, `SubagentStart`, and `SubagentStop`.
* [ ] Codex `SessionStart` matches `startup|resume|clear|compact` and uses the existing session start handler with `FACTIONOS_CLI=codex-cli`.
* [ ] Codex `PreToolUse` covers Bash, `apply_patch|Edit|Write`, and selected MCP matcher patterns.
* [ ] Codex `PostToolUse` covers Bash, `apply_patch|Edit|Write`, and selected MCP matcher patterns with compact result payloads only.
* [ ] Codex `PermissionRequest` surfaces first-class permission requests without returning allow or deny decisions.
* [ ] Codex `SubagentStart` emits bounded `subagent_spawn` payloads from `agent_id` and `agent_type`.
* [ ] Codex `SubagentStop` continues emitting bounded `subagent_complete` payloads and does not store `agent_transcript_path`.
* [ ] `apps/hooks/hooks.json` remains byte-for-byte compatible for existing Claude installation behavior.
* [ ] `apps/hooks/hooks.claude.json` mirrors the current Claude provider map or is tested as equivalent.
* [ ] `apply_patch` handling emits bounded file-edit metadata and never stores raw patch bodies.
* [ ] Normal handler execution remains silent on stdout and stderr.

### Testing Requirements

* [ ] Static Codex map tests verify events, matchers, commands, timeouts, status messages, and provider env.
* [ ] Static Claude map tests verify no existing Claude command strings changed.
* [ ] Runtime fixtures cover Codex `SessionStart`, `UserPromptSubmit`, `apply_patch`, Bash result, MCP result, `PermissionRequest`, `SubagentStart`, and `SubagentStop`.
* [ ] Redaction tests prove raw patch bodies, terminal output, transcript paths, agent transcript paths, MCP argument bodies, token-like values, and broad local paths do not leak into logs or spool output.
* [ ] Focused hooks tests pass.
* [ ] Focused Biome check passes for touched hook files.

### Non-Functional Requirements

* [ ] Hook handlers remain dependency-light and timeout-bound.
* [ ] No Codex installer, uninstall, status, doctor, hosted transfer, custom slash command, or production-hosted claim is introduced.
* [ ] Hook docs explicitly tell users that Codex hook trust and installation are later workflow surfaces.
* [ ] Logs and spool entries remain local, bounded, and sanitized.

### Quality Gates

* [ ] All files ASCII-encoded.
* [ ] Unix LF line endings.
* [ ] Code follows project conventions.
* [ ] `git diff --check` passes.

***

## 8. Implementation Notes

### Key Considerations

* Keep `hooks.json` stable. Any Claude map restructuring must be proven equivalent before changing installer-facing behavior.
* Treat `hooks.codex.json` as source map readiness, not user install readiness. Phase 10 owns resolving absolute install roots and writing `~/.codex` files.
* Use Codex matchers according to official docs: matchers apply to tool name, start source, compact trigger, or subagent type depending on event; `UserPromptSubmit` and `Stop` ignore matchers.
* Do not return Codex approval decisions from FactionOS permission hooks in this session. The handler observes and reports; it does not enforce policy.
* `PostToolUse` is after the tool already ran. Result handling can annotate or mark completion, but it cannot undo Bash, `apply_patch`, or MCP side effects.
* Codex `apply_patch` inputs can carry patch bodies in `tool_input.command`; parse only headers or summarize counts, and redact the body from logs and spool.

### Potential Challenges

* Codex hook command templates need installer resolution later: mitigate by testing template consistency and documenting the Phase 10 handoff.
* `apply_patch` parsing can accidentally expose diff content: mitigate with path-only extraction, size limits, and redaction tests.
* Server ingest does not yet treat `SubagentStart` as first-class when `eventName` is preserved: mitigate by recording this as a Phase 10 server ingest dependency and limiting this session to hook payload readiness.
* MCP tool arguments vary widely and may include secrets: mitigate by summarizing tool names, key counts, and safe labels only.
* Multiple matching Codex command hooks run concurrently: keep handler state atomic and avoid relying on one hook preventing another from starting.

### Relevant Considerations

* \[P03-apps/cli+apps/hooks] **Lifecycle state is local and file-based**: session aliases, listener PID files, spool, and logs must keep crash recovery and stale-state behavior stable.
* \[P07] **Redaction is boundary-specific**: patch, transcript, MCP, permission, and result payloads need explicit minimization at the hook boundary.
* \[P03] **Stable docs are the current contract**: use current README and docs/api behavior as source truth, not historical examples.
* \[P08] **Release-candidate evidence is claim-scoped**: Codex hook-map readiness is not installer support, production validation, trusted erasure, or full live Codex proof.
* \[Security] **P06-S07-ERASURE**: local spool/log cleanup remains operational hygiene only and must not be described as trusted erasure.

### Behavioral Quality Focus

Checklist active: Yes

Top behavioral risks for this session:

* Hook maps could imply Codex support before install, trust, server, or web flows exist.
* `apply_patch`, MCP, transcript, terminal output, and agent result payloads could leak raw local data if handlers forward nested bodies.
* `PermissionRequest` or `PostToolUse` behavior could imply enforcement or rollback that FactionOS does not provide.
* Codex hook matchers could be too broad or too narrow, missing core events or firing on unsupported tool shapes.

***

## 9. Testing Strategy

### Unit Tests

* Test `hooks.codex.json` event groups, matchers, command strings, timeouts, and status messages.
* Test `hooks.claude.json` and `hooks.json` equivalence or byte-stable command behavior.
* Test `apply_patch` path and line summary helpers with small, malformed, multi-file, and oversized patch commands.
* Test new result and subagent handlers with Codex-shaped provider fields.

### Integration Tests

* Run focused hook tests:
  * `npx vitest run apps/hooks/tests/codexHookMap.test.js apps/hooks/tests/hookPayloads.test.js apps/hooks/tests/hookRuntime.test.js apps/hooks/tests/orchestrationDiagnostics.test.js apps/hooks/tests/listenerRuntime.test.js`
* Run focused Biome check for touched hook source, tests, maps, and README paths.
* Run `git diff --check`.

### Manual Testing

* Review `apps/hooks/hooks.codex.json` against official Codex event and matcher docs.
* Review generated spool entries from process fixtures for bounded event payloads and no raw Codex-sensitive fields.
* Review `apps/hooks/README_hooks.md` for no claims about Codex installation, hook trust bypass, custom slash commands, hosted transfer, server ingest completion, web UI readiness, or production validation.

### Edge Cases

* Missing `session_id` with saved TTY fallback.
* `FACTIONOS_CLI=codex-cli` with Claude-shaped event fields.
* `apply_patch` command with no file headers, multiple files, binary-looking content, or oversized diff body.
* MCP tool names with nested argument objects or token-like values.
* `PermissionRequest` with no `tool_input.description`.
* `PostToolUse` with no `tool_use_id`, failed tool response, huge output, or malformed response object.
* `SubagentStart` with missing or malformed `agent_id` and `agent_type`.
* `SubagentStop` with `agent_transcript_path` and `last_assistant_message` present.
* Server unavailable, malformed server URL, full spool directory, and log write failures.

***

## 10. Dependencies

### External Libraries

* None expected. Use existing Node, Vitest, npm workspace, and Biome tooling.

### Other Sessions

* **Depends on**: `phase09-session01-contracts-and-naming-baseline`, `phase09-session02-hook-runtime-normalization`
* **Depended by**: `phase10-session02-codex-hook-install-uninstall-and-diagnostics`, `phase10-session03-server-ingest-codex-lifecycle`, `phase10-session04-web-codex-awareness`, `phase11-session02-test-fixture-hardening`

***

## Next Steps

Run the implement workflow step to begin AI-led implementation.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://faction-os.gitbook.io/faction-os-docs/.spec_system/archive/sessions/phase09-session03-codex-hook-map-and-codex-specific-handlers/spec.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
