> 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/phase10-session02-codex-hook-install-uninstall-and-diagnostics/spec.md).

# Session Specification

**Session ID**: `phase10-session02-codex-hook-install-uninstall-and-diagnostics` **Phase**: 10 - Codex Product Integration **Status**: Not Started **Created**: 2026-05-31 **Package**: apps/cli, apps/hooks **Package Stack**: JavaScript CLI commands, Codex hook map template, provider diagnostics, Vitest node tests, Biome checks

***

## 1. Session Overview

This session replaces the Phase 10 Session 01 deferred Codex routing boundary with real, user-level Codex hook installation, uninstall, status, and doctor diagnostics. Phase 09 supplied the provider-neutral hook vocabulary and `apps/hooks/hooks.codex.json`; Phase 10 Session 01 added provider-aware CLI routing while explicitly avoiding Codex file mutation. Session 02 now wires those pieces into safe `~/.codex/hooks.json` management.

The work spans `apps/cli` and `apps/hooks`. In `apps/cli`, the Codex installer must create the local FactionOS state directories, optionally merge local FactionOS settings, read the source-controlled Codex hook template, back up existing Codex hook state, merge only managed FactionOS hook commands, uninstall only FactionOS-managed entries, and report compact posture through `status` and `doctor`. In `apps/hooks`, the source template remains the contract used by the installer and must stay documented as a hook map plus user trust-review handoff, not a bypass of Codex `/hooks`.

The session must preserve the local-first privacy posture. It may read and write the Codex user-level hooks file under `CODEX_HOME` or `~/.codex`, but it must not mutate Codex auth, provider, telemetry, model, profile, API key, OpenAI account, or trusted-project state. CLI output should expose labels, validity, counts, backup state, and next-step guidance only.

***

## 2. Objectives

1. Implement safe, idempotent `factionos init --cli codex` hook installation for user-level Codex configuration.
2. Implement `factionos uninstall --cli codex` backup restore and surgical managed-hook removal while preserving user-owned hooks.
3. Add compact Codex posture to `doctor` and `status`, including hook file presence, JSON validity, managed-hook counts, backup state, and optional `features.hooks = false` detection.
4. Cover malformed hooks, missing Codex directory, reinstall, `--cli all`, uninstall, backup restore, and privacy-safe diagnostics with focused tests and docs.

***

## 3. Prerequisites

### Required Sessions

* [x] `phase10-session01-cli-provider-selection-and-installer-split` - provides provider-aware CLI routing, deferred Codex installer hooks, and provider posture helpers.
* [x] `phase09-session03-codex-hook-map-and-codex-specific-handlers` - provides `apps/hooks/hooks.codex.json` and Codex-specific handler coverage.
* [x] `phase09-session02-hook-runtime-normalization` - provides provider-aware runtime normalization for Codex-shaped payloads.
* [x] `phase03-session06-cli-diagnostics-and-recovery-controls` - provides compact doctor/status diagnostics and local recovery boundaries.
* [x] `phase01-session03-cli-lifecycle-parity` - provides local CLI lifecycle command conventions and install/uninstall behavior.

### Required Tools/Knowledge

* Node 20+ and npm workspace dependencies.
* Current `apps/cli/src/installers/codex.js`, `apps/cli/src/installers/claude.js`, and provider posture helper behavior.
* Current `apps/hooks/hooks.codex.json` command template and placeholder format.
* Codex hook trust-review boundary: users review installed hooks with `/hooks`; FactionOS does not bypass trust prompts.
* Existing local file helpers for atomic writes, home directory resolution, and JSON parsing.

### Environment Requirements

* Tests must use isolated temporary homes and must not read or mutate the real user `~/.codex` or `CODEX_HOME`.
* No OpenAI, Codex, Claude, Anthropic, hosted, Cloudflare, or provider credentials are required.
* Diagnostics must not print raw hook command bodies, auth tokens, env values, full local paths, settings JSON, prompts, payloads, or terminal output.

***

## 4. Scope

### In Scope (MVP)

* CLI users can install Codex hooks safely - implement `factionos init --cli codex` and `factionos install --cli codex` using the source-controlled Codex hook map with backup-first, atomic writes.
* CLI users can select all providers - make `factionos init --cli all` run Claude installation and Codex installation deterministically without duplicate managed hook entries.
* CLI users can uninstall Codex hooks safely - restore the FactionOS-created Codex hooks backup when present, otherwise remove only FactionOS-managed command hooks.
* Existing Codex users keep their hooks - preserve user-owned hook events, entries, matchers, and non-FactionOS command hooks during install, reinstall, and uninstall.
* Malformed Codex hook files are handled predictably - back up raw malformed content, write a fresh hooks object during install, and refuse uninstall overwrite unless a backup restore is available.
* Local FactionOS state is prepared - ensure `~/.factionos/`, `sessions/`, and `spool/` exist, and write `cli: "codex-cli"` only when Codex is the selected default local agent CLI.
* Provider diagnostics are first-class - `status` and `doctor` report Codex hooks file presence, JSON validity, managed counts, backup state, hook-disable posture, and `/hooks` guidance without raw command bodies.
* `CODEX_HOME` is respected - user-level Codex state resolves from `CODEX_HOME` when set, otherwise from `~/.codex`.
* Documentation is updated - CLI and hooks package READMEs describe install, uninstall, diagnostics, trust review, and excluded Codex settings.

### Out of Scope (Deferred)

* Project-local `.codex/` generation or default install path - *Reason: Phase 10 only owns user-level Codex hook support for this session.*
* Automatic approval or bypass of Codex hook trust prompts - *Reason: users must review loaded hooks with `/hooks`.*
* Codex auth, provider, telemetry, model, profile, OpenAI API key, or account settings mutation - *Reason: explicitly excluded by the Phase 10 safety boundary.*
* Server ingest Codex lifecycle persistence - *Reason: Phase 10 Session 03 owns server lifecycle ingest.*
* Web Codex labels, filters, replay, export, or UI treatment - *Reason: Phase 10 Session 04 owns web product integration.*
* Plugin packaging or Codex plugin marketplace behavior - *Reason: Phase 12 owns packaging and release readiness.*
* Trusted erasure, production-hosted validation, or hosted identity claims - *Reason: unrelated no-claim areas remain tracked in security posture.*

***

## 5. Technical Approach

### Architecture

Use `apps/cli/src/installers/codex.js` as the Codex provider implementation behind the routing added in Session 01. The module should resolve the Codex directory from `CODEX_HOME` or `~/.codex`, resolve the hook package root through the existing hook root resolver, read `apps/hooks/hooks.codex.json`, replace the Codex `${PLUGIN_ROOT}` placeholder with the absolute hook package root, normalize managed commands, and merge into a top-level `hooks` object matching the source template.

Keep install and uninstall operations backup-first and atomic. Install should create `hooks.backup.factionos.json` from the first raw `hooks.json` when no FactionOS backup exists. If the existing file is valid JSON, merge after removing only FactionOS-managed command hooks. If malformed, preserve the raw backup and write a fresh `{ "hooks": ... }` object. Uninstall should restore the backup when present, or surgically remove managed commands from a valid hooks file. If the hooks file is malformed and no backup exists, it should report `malformed` and leave the file untouched.

Provider posture should move from deferred text to compact facts. `inspectCodexProviderPosture()` should return labels for directory/file presence, JSON validity, backup presence, managed hook count, unmanaged hook count, and optional `features.hooks = false` posture from `config.toml` using safe text inspection only. Formatting in `status` and `doctor` should show counts and guidance, never command bodies or raw config content. Command summaries should print next steps to start FactionOS, launch Codex, and run `/hooks`.

### Design Patterns

* Backup-first local mutation: preserve the first raw Codex hooks file before managed writes.
* Managed-command filtering: identify FactionOS-owned command hooks by hook package root, `FACTIONOS_CLI=codex-cli`, and known FactionOS hook script names.
* Idempotent merge: remove old managed Codex hooks before adding the current source template.
* Atomic writes: use temp-file-plus-rename for Codex hooks and FactionOS settings.
* Compact diagnostics: expose status labels, booleans, and counts only.
* Negative ownership: never write Codex auth, provider, telemetry, model, profile, API key, account, trust, or project-local config.

### Technology Stack

* JavaScript ES modules in `apps/cli` and `apps/hooks`.
* Node filesystem helpers for isolated local state, backups, and atomic writes.
* Vitest node tests for installer, runtime routing, provider posture, and CLI output.
* Biome formatting and linting.

***

## 6. Deliverables

### Files to Create

| File                                    | Purpose                                                                                                          | Est. Lines |
| --------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | ---------- |
| `apps/cli/tests/codexInstaller.test.js` | Focused Codex install, reinstall, malformed, backup restore, surgical uninstall, `CODEX_HOME`, and posture tests | \~260      |

### Files to Modify

| File                                    | Changes                                                                                                       | Est. Lines |
| --------------------------------------- | ------------------------------------------------------------------------------------------------------------- | ---------- |
| `apps/cli/src/installers/codex.js`      | Implement Codex hooks backup, merge, install, uninstall, posture, and safe config inspection                  | \~280      |
| `apps/cli/src/installers/claude.js`     | Reuse or export managed-command helpers where safe without changing Claude behavior                           | \~30       |
| `apps/cli/src/lib/localFiles.js`        | Add Codex directory helper if needed for `CODEX_HOME` and user home resolution                                | \~20       |
| `apps/cli/src/lib/providerPosture.js`   | Format real Codex posture with counts, validity, backup, disabled-hook, and trust-review guidance             | \~80       |
| `apps/cli/src/commands/init.js`         | Replace deferred Codex summary with installed/partial/error-safe Codex next steps                             | \~70       |
| `apps/cli/src/commands/uninstall.js`    | Print Codex uninstall restore, removal, absent, malformed, and not-found outcomes                             | \~60       |
| `apps/cli/src/commands/doctor.js`       | Check Codex hooks file validity, managed count, disabled hooks, and `/hooks` guidance                         | \~70       |
| `apps/cli/src/commands/status.js`       | Show compact Codex posture without command bodies                                                             | \~30       |
| `apps/cli/tests/cliProvider.test.js`    | Replace deferred no-mutation assertions with real Codex installer expectations                                | \~80       |
| `apps/cli/tests/cliRuntime.test.js`     | Update runtime coverage for Codex install, `all`, uninstall, status, and doctor output                        | \~140      |
| `apps/hooks/tests/codexHookMap.test.js` | Assert the source template remains installable with `${PLUGIN_ROOT}` placeholders and FactionOS command hooks | \~60       |
| `apps/cli/README_cli.md`                | Document Codex install, uninstall, diagnostics, trust review, and excluded settings                           | \~100      |
| `apps/hooks/README_hooks.md`            | Update Codex map readiness wording now that user-level install is supported                                   | \~70       |

***

## 7. Success Criteria

### Functional Requirements

* [ ] `factionos init --cli codex` creates FactionOS local state directories and writes user-level Codex hooks atomically.
* [ ] `factionos install --cli codex` behaves as the same provider-aware install path.
* [ ] `factionos init --cli all` installs Claude and Codex provider hooks without duplicating managed hooks.
* [ ] `factionos uninstall --cli codex` restores the FactionOS-created backup when present.
* [ ] `factionos uninstall --cli codex` removes only FactionOS-managed Codex command hooks when no backup is present.
* [ ] User-owned Codex hook entries survive install, reinstall, and uninstall.
* [ ] Malformed existing `hooks.json` is backed up during install and replaced with a fresh managed hooks object.
* [ ] Malformed `hooks.json` is not overwritten during uninstall unless backup restore is available.
* [ ] `CODEX_HOME` overrides the default `~/.codex` path in install, uninstall, and diagnostics.
* [ ] `doctor` and `status` report Codex hook posture with compact counts, backup state, JSON validity, disabled-hook posture, and `/hooks` trust guidance.

### Testing Requirements

* [ ] Focused Codex installer tests cover missing directory, existing hooks, malformed hooks, reinstall, backup restore, surgical uninstall, `CODEX_HOME`, env interpolation, and posture inspection.
* [ ] CLI runtime tests cover `init --cli codex`, `init --cli all`, `install --cli codex`, `uninstall --cli codex`, `doctor --cli codex`, and `status --cli codex`.
* [ ] Hook map tests prove `hooks.codex.json` remains a valid source template for installer interpolation.
* [ ] Focused CLI and hook tests pass.
* [ ] Focused Biome check passes for touched files.

### Non-Functional Requirements

* [ ] No Codex auth, provider, telemetry, model, profile, OpenAI API key, account settings, trusted-project state, or project-local config is written.
* [ ] CLI diagnostics remain local-first, compact, and credential-free.
* [ ] Raw hook command bodies, full paths, tokens, prompts, payloads, terminal output, and settings JSON are not printed.
* [ ] Install and uninstall behavior is idempotent and reversible where backup evidence exists.
* [ ] Existing Claude provider behavior remains unchanged.

### Quality Gates

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

***

## 8. Implementation Notes

### Key Considerations

* Treat `hooks.backup.factionos.json` as the FactionOS-managed Codex backup name; do not collide with user-created backups.
* Keep `hooks.codex.json` as source truth and replace `${PLUGIN_ROOT}` only during install.
* Preserve user-owned entries even when they share events or matchers with FactionOS-managed hooks.
* Do not use a broad restore or cleanup command as trusted erasure. Uninstall removes provider hooks only and leaves FactionOS sessions, spool, logs, archive, and browser state alone.
* `features.hooks = false` detection should be a read-only, best-effort text check. Do not implement TOML rewriting in this session.
* `factionos codex init` aliases remain out of scope until the flag path is stable.

### Potential Challenges

* Codex hook JSON may contain unknown but valid shapes: mitigate by preserving unknown object fields and only filtering command hooks under recognized hook arrays.
* Managed-command detection could remove user hooks accidentally: mitigate by requiring FactionOS script/root/CLI markers and testing user-owned commands on matching events.
* Malformed hooks need different install and uninstall handling: mitigate with explicit tests for backup-first install and no-overwrite uninstall.
* `--cli all` can leave partial provider results: mitigate with deterministic result reporting and no duplicate managed hooks on rerun.
* Diagnostics can over-disclose local state: mitigate by formatting only status labels and counts.

### Relevant Considerations

* \[P03-apps/cli+apps/hooks] **Lifecycle state is local and file-based**: install, backup, restore, and diagnostics must remain recoverable and tested with isolated local files.
* \[P07] **Redaction is boundary-specific**: status, doctor, installer summaries, and logs must expose labels and counts only.
* \[P03] **Stable docs are the current contract**: update package READMEs to reflect the new supported Codex install boundary without overclaiming trust or plugin packaging.
* \[P08] **Release-candidate evidence is claim-scoped**: this is local user-level Codex hook support, not production-hosted validation or trusted erasure.
* \[P09-apps/hooks] **Provider-specific map files make boundaries explicit**: keep the source template and compatibility map aligned while preserving Claude aliases.
* \[P09-apps/hooks] **Do not forward raw Codex payloads**: installer output and diagnostics must not reveal patch bodies, terminal output, transcript paths, token-like values, or MCP arguments.
* \[Security] **P06-S07-ERASURE**: uninstall must not be described as broad deletion or trusted unified erasure.

### Behavioral Quality Focus

Checklist active: Yes

Top behavioral risks for this session:

* Installer writes could corrupt or overwrite user-owned Codex hooks.
* Reinstall or `--cli all` could duplicate managed hooks or produce unclear partial results.
* Uninstall could remove non-FactionOS hooks or overwrite malformed user files.
* Status and doctor could leak command bodies, env values, paths, tokens, or config contents.
* Trust-review messaging could imply FactionOS bypasses Codex `/hooks` approval.

***

## 9. Testing Strategy

### Unit Tests

* Test Codex directory resolution with default home and `CODEX_HOME`.
* Test install with missing `~/.codex`, valid existing hooks, user-owned hooks on same events, malformed hooks, and existing FactionOS backup.
* Test managed hook counting, unmanaged hook counting, backup posture, and safe config disable detection.
* Test uninstall backup restore, surgical removal, absent hooks file, malformed no-backup refusal, and user hook preservation.
* Test env interpolation for `FACTIONOS_CLI=codex-cli`, `FACTIONOS_SERVER_URL`, `FACTIONOS_AUTH_TOKEN`, `FACTIONOS_FACTION`, and optional `FACTIONOS_HOME`.

### Integration Tests

* Run focused CLI tests:
  * `npx vitest run apps/cli/tests/codexInstaller.test.js apps/cli/tests/cliProvider.test.js apps/cli/tests/cliRuntime.test.js`
* Run focused hook map tests:
  * `npx vitest run apps/hooks/tests/codexHookMap.test.js`
* Run focused Biome checks for touched CLI and hook files.
* Run `git diff --check`.

### Manual Testing

* Review `factionos init --cli codex` output for start, Codex launch, and `/hooks` next steps.
* Review `factionos uninstall --cli codex` output for backup restore, surgical removal, malformed, and absent cases.
* Review `factionos status --cli codex` and `factionos doctor --cli codex` output to confirm no raw hook commands or sensitive values are printed.
* Review CLI and hooks README wording for no auth, provider, telemetry, model, profile, API key, plugin, hosted, or trust-bypass overclaim.

### Edge Cases

* `hooks.json` missing, empty, malformed, array-valued, or valid JSON with no top-level `hooks`.
* Existing hook entries with same event and matcher but user-owned commands.
* Existing FactionOS-managed hooks from an older root path or placeholder.
* Existing backup present before reinstall.
* `CODEX_HOME` points at a missing directory.
* `features.hooks = false` appears in simple config forms or comments.
* Environment values contain secrets that must affect installed command env only, not diagnostic output.

***

## 10. Dependencies

### External Libraries

* None new.

### Other Sessions

* **Depends on**: `phase10-session01-cli-provider-selection-and-installer-split`, `phase09-session03-codex-hook-map-and-codex-specific-handlers`, `phase09-session02-hook-runtime-normalization`
* **Depended by**: `phase10-session03-server-ingest-codex-lifecycle`, `phase10-session04-web-codex-awareness`, Phase 11 Codex hardening and validation

***

## 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/phase10-session02-codex-hook-install-uninstall-and-diagnostics/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.
