Skip to content

Pre and PostCompact hooks #17148

Open
Open

Description

@jmarianski

What variant of Codex are you using?

CLI

What feature would you like to see?

Like in the title: hooks that are covered . When working in claude code it was quite efficient to gather a full conversation transcript, prepare it and feed it directly the conversation transcript (stripped from unnecessary parts) to keep the conversation flow going on. There are also other uses: prompt injecting summarization agent with additional instructions on how the conversation should be shaped in the summary without the need to adjust the summarization prompt.

Both of these uses are possible when having proper injections. However, there are other lifecycle possibilities, like: reinjecting AGENTS.md after summarization (for better alignment after summarization), reminders etc.

Additional information

Pull request that can easily be re-targeted at openai/codex: jmarianski#1

There are other hooks that are important in the lifecycle of an application, however most are already covered: SubAgentStart is replaced with SessionStart for an agent (however it would be nice to give some kind of distinction: subagents may need different message on SessionStart than a main agent (so that they are less talkative, or more talkative - if we would like to adjust that behavior)), pre and post tool use hooks are there, same as stop hook.

Activity

  1. added
    CLIIssues related to the Codex CLI
    hooksIssues related to event hooks
    contextIssues related to context management (including compaction)
    on Apr 8, 2026
  2. github-actions commented on Apr 8, 2026

    @github-actions
    Contributor

    Potential duplicates detected. Please review them and close your issue if it is a duplicate.

    Powered by Codex Action

  3. jmarianski commented on Apr 8, 2026

    @jmarianski
    Author

    While it clearly relates to the #16098 and it is a duplicate, however it is closed (as duplicate?) and I don't think it covers all the bases. We should be able to handle events just before compaction and just after compaction without adjusting the actual compaction behavior.

    And while I talk about distinguishing main agent from subagents, this issue is not about that as it's part of subagent events.

  4. removed
    CLIIssues related to the Codex CLI
    contextIssues related to context management (including compaction)
    on Apr 8, 2026
  5. permaevidence commented on Apr 23, 2026

    @permaevidence

    +1 for PostCompact in particular. This is important for external memory and persistence workflows. Without a dedicated lifecycle hook after compaction, integrations are forced into fragile workarounds. Claude Code has a cleaner lifecycle point for this class of use case. Including metadata like thread_id, session_id, and turn_id would make the hook much more usable.

  6. hilyfux commented on Apr 23, 2026

    @hilyfux

    This would unblock a much cleaner pattern than just "memory persistence" in the abstract.

    The practical gap is deterministic reinjection. PreCompact is useful for harvesting the current thread, but PostCompact is the lifecycle point that lets an external memory layer decide, exactly once, what should be restored into the fresh context window. Without that hook, integrations end up guessing from token usage, polling transcript changes, or reinjecting too often, which creates drift and duplicate instructions.

    A good contract here would be small but explicit: thread/session identifier, whether compaction was automatic or manual, a stable compaction event id, and maybe counts like messages/tokens removed. Then external tools can stay idempotent: summarize what was lost, rank durable facts vs temporary task state, and rehydrate only the top few items the next turn actually needs.

    We ran into this enough that we built knowledge-graph around the same problem space. It is git-native, zero-dependency, and works across both Claude Code and Codex, but the fragile part on Codex today is exactly the missing post-compaction lifecycle. If Codex exposed a first-class PostCompact hook, tools like this could become much simpler and more reliable.

  7. oxysoft commented on May 8, 2026

    @oxysoft

    Indexed this hook ticket in the umbrella tracker: #21753

    Goal: collect the scattered Codex hook requests and bugs into one parity matrix for Full Claude Code Hook Parity (29+), while preserving this issue as the detailed thread for its specific behavior.

  8. caioribeiroclw-pixel commented on Jun 1, 2026

    @caioribeiroclw-pixel

    +1 to treating PreCompact / PostCompact as lifecycle events, not just memory hooks.

    The contract I’d want to consume is small, but it should make resume safety auditable:

    • compaction_event_id
    • session_id / thread_id / parent-child agent id if present
    • trigger: manual / automatic / context-limit / resume
    • input transcript range or hash covered by the compacted summary
    • output summary hash / token count, not raw summary text
    • instruction sources reloaded after compaction: AGENTS.md, user/project rules, MCP/tool manifests, skills/playbooks
    • explicit lost/kept fields: open todos, plan state, approvals, active tools/subagents, files touched, pending user asks
    • safe_to_resume: true / false / unknown, with reasons

    The important distinction is: PreCompact can capture “what was about to be summarized”; PostCompact should prove “what actually survived and what was re-injected.” Without that, external memory layers can restore context, but they can’t tell whether the run is safe to continue or just plausibly coherent.

    This would also make Codex-compatible automation less brittle than polling token counts or re-injecting AGENTS.md blindly after every resume.

  9. SaravananJaichandar commented on Jun 6, 2026

    @SaravananJaichandar

    v0.7.5 of world-model-mcp shipped a Codex CLI adapter yesterday that does exactly this for PostCompact (and PreToolUse for constraint enforcement). It wires through the documented [[hooks.PostCompact]] Codex hook surface to inject curated state as additionalContext post-compaction. Bundled config + install command lives at the package's world_model_server/adapters/codex/.

    A few things I learned shipping the adapter that might be useful for this feature request:

    1. The server name in [mcp_servers.<name>] matters. Codex's tool-name sanitizer in codex-rs/codex-mcp/src/mcp/mod.rs silently strips hyphens, so world-model becomes world_model model-side and risks colliding with a sibling underscore-named server. Worth specifying the canonical form in any official compaction-hook docs.

    2. The hook output schema is strict camelCase with deny_unknown_fields (verified against codex-rs/hooks/src/schema.rs). PR Tighten hook output event schemas #24962 in v0.136 tightened it further by requiring hookEventName to literal-match the registered event. Any spec for PreCompact/PostCompact will inherit this constraint, which is fine but should be called out for adapter authors.

    3. tool_timeout_sec (not the older timeout) and default_tools_approval_mode (not the older trust) are the current field names since v0.130. The compaction-hook spec would compose with these without changes.

    Repo: https://github.com/SaravananJaichandar/world-model-mcp ; Codex adapter docs: https://github.com/SaravananJaichandar/world-model-mcp/tree/main/adapters/codex

  10. trevi00 commented on Jul 25, 2026

    @trevi00

    Update (2026-07-30): I completed a rebased, focused implementation against current main for PostCompact model-context reinjection.

    Behavior:

    • accepts strict hookSpecificOutput: { hookEventName: "PostCompact", additionalContext };
    • records context only when the hook continues, making it visible on the next model request;
    • uses Codex's existing per-handler additionalContextLimit contract (default 2,500 estimated tokens) and spill-to-file handling for oversized output;
    • keeps PostCompact and SessionStart(source="compact") as independent lifecycle events. A focused interaction test verifies that both contexts are preserved exactly once.

    Focused validation:

    • codex-hooks: 129/129 tests passed;
    • manual compaction and compact-source SessionStart interaction: passed;
    • token-budget compaction: passed;
    • generated PostCompact schema, formatting, and diff checks: passed.

    The older combined dbd9eed commit is superseded and should be treated only as an early prototype.

    Is next-model-request injection the intended contract for PostCompact.additionalContext, and does reusing the existing per-handler limit/spill infrastructure align with the maintainers' preferred design?

    I understand external PRs are invitation-only. If this direction aligns with the roadmap, I would be happy to prepare the focused branch for an invited PR.

  11. trevi00 commented on Aug 1, 2026

    @trevi00

    Verified against the exact official rust-v0.146.0 tag (e363b08c9175ac1cbe5893615dd2cb9ddf95043b): the PostCompact lifecycle event exists, but hookSpecificOutput.additionalContext is not injected into subsequent model context. The focused implementation described above therefore remains relevant.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or requesthooksIssues related to event hooks

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions