---
schema_version: 1
revision: "22ce5d34dbcb5a78"
id: "foundations-hooks-and-context-hygiene"
title: "Control agent lifecycle with hooks and context hygiene"
---

# Control agent lifecycle with hooks and context hygiene

> Original source pages and recordings require authorized access. The full article text here is public.

Start with context hygiene: compacting or forking long conversations so the next branch focuses only on what matters, such as a specific test file or active goal. John then teaches the three core hook moments in an agent loop: User Prompt, Tool Use, and Stop. From there, he explains the Ralph Loop, demonstrates a #human User Prompt hook that opens a live progress dashboard, and argues that plugins are the better tool when you want deterministic control instead of relying on a skill description being inferred correctly.

## Working outcomes

- Manage context with compaction and conversation forking
- Wire user-prompt, tool-use, and stop hooks into your workflow
- Choose between skills and plugins and run a Ralph loop

## Concepts and consequences

### Compaction and conversation forking

Compaction is the move of shrinking a long conversation down to the pieces that still matter. John framed it as useful when you fork a conversation and want the new branch to focus on one topic, like a specific test file, instead of carrying unrelated history forward. The practical benefits he called out were fewer tokens, faster runs, lower budget/quota pressure, and a clearer sense of what the agent is working on.

**Why it matters:** Long conversations can carry a lot of irrelevant context. Forking plus focused compaction gives the next session a cleaner starting point.

### The big three hooks

John breaks the agent loop into three core events: User Prompt, Tool Use, and Stop. User Prompt fires when you type something and submit it, Tool Use fires when a tool runs, and Stop fires when the conversation would normally end and wait for you. These are the main places where a hook can do something with the session.

**Why it matters:** Once you understand these three events, plugins stop feeling mysterious. They become small programs attached to predictable moments in the agent lifecycle.

### The Ralph Loop

The Ralph Loop is John's shorthand for a Stop-hook-driven loop. When the agent tries to stop, the hook can tell the harness not to stop yet, look back at what the user originally asked for, and keep working until a condition is met. John described this as the basic idea behind goal-style sessions.

**Why it matters:** This matters when you want an agent to keep working on a goal instead of handing control back after one assistant turn.

### Skills versus plugins

John contrasts skills with plugins as a difference between context-based guidance and deterministic control. Skills put descriptions into the model's context so the agent can infer when and how to use them. Plugins can hook into events and enforce behavior, including starting or stopping things, allowing or disallowing actions, or calling specific tools.

**Why it matters:** For workflows you want to enforce, John recommends reaching for a plugin with hooks instead of trying to make skill instructions clearer and clearer.

### Custom grammar triggers

A custom grammar trigger is a small token like #human, #toolsmith, #memory, or #search that a User Prompt hook can detect before the agent proceeds. John likes this because it keeps Codex vanilla by default and only loads the specific system, plugin, skill, or context bundle when he explicitly asks for it.

**Why it matters:** This gives you a clean way to personalize sessions without polluting every conversation with skills or context the task does not need.

## Reference tools and resources

### Codex Plugins documentation

The main OpenAI developer documentation John opened for Codex plugins.

**Use when:** Use it when you want to understand how plugins package and install things like hooks and skills.

[Reference](https://developers.openai.com/codex/plugins)

### Codex Build Plugins guide

The OpenAI guide John showed as a starting point for creating plugin projects.

**Use when:** Use it as source material when asking an agent to generate a documented starter plugin or hook example.

[Reference](https://developers.openai.com/codex/plugins/build)

### Codex Hooks documentation

The OpenAI reference John opened for hook behavior.

**Use when:** Use it when learning what User Prompt, Tool Use, and Stop hooks can do, or when feeding hook docs to an agent so it can build an example.

[Reference](https://developers.openai.com/codex/hooks)

### Better Plugins repository

John Lindquist's prototype repository containing examples such as human-view, Gemini Video, and Toolsmith.

**Use when:** Use it as a reference repo for real plugin patterns, while remembering that John described this work as prototype-stage and personally configured.

[Reference](https://github.com/johnlindquist/better-plugins/tree/main/plugins)

### human-view plugin

A Better Plugins example that activates with #human and opens a live browser dashboard showing task progress and tool-call activity.

**Use when:** Reach for this when you want to study the #human pattern John demonstrated: a User Prompt hook that starts a live progress view for a session.

[Reference](https://github.com/johnlindquist/better-plugins/tree/main/plugins/human-view)

### toolsmith plugin

A Better Plugins example John described as recording tool calls and conversation activity so you can query the log for workflow improvements.

**Use when:** Reach for this when you want to study how recorded tool use could reveal missing scripts, missing tools, or repeatable workflow improvements.

[Reference](https://github.com/johnlindquist/better-plugins/tree/main/plugins/toolsmith)

### gemini-video plugin

A Better Plugins example John described as detecting a dragged-in .mp4 file path and sending it through Gemini scripts so the video can be parsed into the conversation.

**Use when:** Use it as an example of a plugin that reacts to a file path, but expect to adapt it because John said it was configured for his own setup.

[Reference](https://github.com/johnlindquist/better-plugins/tree/main/plugins/gemini-video)

### MarkSnip Chrome extension

A browser extension John used to copy documentation pages into Markdown.

**Use when:** Use it when you want to paste documentation into an agent directly instead of spending an extra tool call having the agent scrape the page.

[Reference](https://chromewebstore.google.com/detail/marksnip-webpage-to-markd/kcbaglhfgbkjdnpeokaamjjkddempipm)

## Recommendations and best practices

- When a session gets long, fork it and compact around the specific thing you want next, such as the test file or active goal, instead of continuing with unrelated history.
- Use User Prompt, Tool Use, and Stop as your basic mental model for plugin design: decide which lifecycle moment actually needs intervention.
- Use the Codex plugin and hook docs as source material, then ask an agent to build a fully documented example and review or test what it creates.
- Use a Stop hook for Ralph Loop-style continuation when you can define the condition the agent should keep working toward.
- Prefer a plugin over a skill when the workflow must be enforced, such as starting or stopping something, allowing or disallowing actions, or calling a specific tool.
- Keep default sessions as vanilla as possible, then use explicit triggers like #human, #toolsmith, #memory, or #search to opt into extra behavior only when the task needs it.
- Treat John's Better Plugins repo as prototype reference material, not as polished drop-in infrastructure for every machine.

## Practice and acceptance criteria

Practice trimming noisy context, recognizing the main hook events, and choosing plugins when you need deterministic workflows instead of fuzzy skill behavior.

### Checklist

1. Pick one recurring workflow you currently handle with a long prompt, skill, or repeated manual instruction.
2. Decide which lifecycle moment actually needs control: User Prompt for triggers, Tool Use for tools, or Stop for continuation.
3. Use the Codex plugin and hook docs as source material and ask an agent to create a documented starter plugin or hook example.
4. Add a custom trigger such as #review, #human, or #toolsmith to a User Prompt hook, and confirm normal prompts do not activate the extra behavior.
5. Try a Stop-hook/Ralph Loop pattern only when you can state the condition the agent should keep working toward.
6. Review a Toolsmith-style record of tool calls and look for one missing script, missing tool, or repeated workflow worth improving.
7. Keep the default session minimal, then load context bundles, skills, or plugin behavior only when your custom trigger calls for them.

### Compact-and-Fork Drill

**Difficulty:** Easy

Take a messy or long Codex conversation, fork it, then write a compact handoff that keeps only the active goal, relevant files, failing test, and next action.

**Done when:** A new session can understand the focused task without needing unrelated earlier discussion.

### Custom Trigger Plugin

**Difficulty:** Medium

Build or ask an agent to build a small plugin that watches for #myflow in the User Prompt hook and conditionally loads a short workflow instruction or helper behavior.

**Done when:** Prompts with #myflow activate the behavior, while normal prompts run without the extra context or behavior.

### Toolsmith-Style Review

**Difficulty:** Medium

Prototype or adapt a workflow that records tool calls, then review or query those records for one repeated pattern worth turning into a script, tool, or plugin.

**Done when:** You can point to one workflow improvement based on actual repeated agent behavior.

### Ralph Loop Prototype

**Difficulty:** Hard

Ask an agent to help create a Stop-hook plugin for a toy task that tells the agent to continue working until a specific condition is met.

**Done when:** The agent continues past an attempted stop, works toward the original task, and exits once the condition is satisfied.

## Questions to test understanding

### A Codex session has grown long and now contains several unrelated debugging trails. What is the best next move before asking the agent to focus on one failing test file?

- **A.** Fork the conversation and compact the new branch around the relevant test file and current goal.
- **B.** Keep the same conversation open so the model has maximum history available.
- **C.** Paste the entire transcript into a new prompt and ask the model to remember everything.
- **D.** Convert the whole conversation into a global skill so it loads in every future session.

**Answer: A.** Forking plus focused compaction preserves what matters while dropping unrelated noise. John called out fewer tokens, faster runs, lower budget pressure, and clearer focus as the practical benefits.

### Which lifecycle hook is the natural place to detect a custom trigger like #human or #toolsmith before the agent starts working?

- **A.** Stop hook
- **B.** Tool Use hook
- **C.** User Prompt hook
- **D.** Compaction hook

**Answer: C.** The User Prompt hook fires when the user submits text, so it can parse custom grammar before the agent proceeds. That is the pattern John demonstrated with #human.

### You want every tool call in a session to be recorded so you can later ask what scripts, tools, or workflow improvements might be missing. Should this be a skill or a plugin?

- **A.** A skill, because the model can decide when logging feels appropriate.
- **B.** A plugin with a Tool Use hook, because Tool Use is the lifecycle moment around tool calls.
- **C.** A Stop hook only, because tool activity should be recorded after the task is over.
- **D.** A compaction instruction, because logging is mainly about shrinking context.

**Answer: B.** John identified Tool Use as the hook event that fires when tools run, and described Toolsmith as recording tool calls so you can query them for workflow improvements.

### What makes the Ralph Loop different from simply prompting the model to 'keep going until done'?

- **A.** It uses a Stop hook to structurally continue the session when the agent would normally hand control back.
- **B.** It loads every available skill so the model has more options.
- **C.** It prevents the agent from using tools until the user approves each command.
- **D.** It replaces compaction with a larger context window.

**Answer: A.** John described the Ralph Loop as a Stop-hook pattern: when the agent tries to stop, the hook tells it to look back at the original task and keep working until a condition is met.

### Why does John like using custom # triggers instead of loading every repeatable workflow as a default skill?

- **A.** They keep Codex vanilla by default and load only the specific system or context bundle when requested.
- **B.** They make compaction unnecessary for long conversations.
- **C.** They prevent the agent from using tools.
- **D.** They replace the need to read plugin or hook documentation.

**Answer: A.** John's preference is to avoid polluting every session with skill descriptions or context the task does not need. A trigger like #human or #toolsmith lets him opt into extra behavior only for sessions that need it.

## Reflection prompts

- Which workflows are you currently handling as skills or long prompts but actually need deterministic plugin control?
- Where are you loading skills or context by default that could instead be loaded only through a # trigger?
- What is one task where a Ralph Loop would help, and what exact condition would tell it to stop?

## Further applications

1. Ask an agent to build a fully documented Hello World plugin or hook example from the Codex plugin and hook docs, then read through the result and ask follow-up questions.
2. Convert one recurring skill-like workflow into a #your-trigger plugin that conditionally loads the behavior only when the trigger appears.
3. Study the human-view pattern as a concrete example of #human activating a live dashboard that tracks progress and tool-call activity.
4. Study the Toolsmith pattern as an example of recording tool calls and querying that record for workflow improvements.
5. Study the Gemini Video pattern as an example of detecting an .mp4 file path and routing it through a video-processing script, while expecting to adapt it for your own setup.

## Applied exercises

Exercise: Transition from Soft Skills to Deterministic Plugins

**Objective:**  Developers will replace a high-context prompt structure or an inference-based agent "Skill" with a low-level programmatic Plugin.

**Requirements:** Identify a repeatable task workflow that you currently execute by passing detailed text instructions to an LLM skill.Instead of using a skill, create a custom Codex Plugin structure utilizing a hooks.json mapping configuration.Configure a custom syntax grammar key (e.g., #YourWorkflowName) handled inside the User Prompt hook listener.Write a Python script mapping to ensure that when this character trigger is registered, specific environmental checks, system rules, or tool executions are programmatically enforced rather than relying on model inferences.

## Questions and answers

### Do you have any ideas on how to create levers for agents so they can do big data stuff without having all the data in their context?

John explicitly says he is not an expert in big-data engineering integrations and does not offer a validated big-data recipe. The adjacent hook discussion offers a structural principle: keep large data in external processes; pass references or concise execution metrics through tool hooks rather than loading everything into active context. This is not a demonstrated big-data integration.

### i saw you use /compact, when do you use this skill? what is the skill?

compact is a method used to compress long conversations down to essential details. John explains that he historically ran single conversations straight through to completion and then closed them out. However, automated /goal execution runs can alter this workflow because long tasks cycle through several automated compactions while running unattended to remain safely inside the token window limit without blowing through operational limits.

### are you organizing your general knowledge somehow? pulling in meeting transcripts, emails, conversations with agents, and organizing them in such a way to retrieve them later as needed, agents having access to all, but perhaps synthesizing (basic memories) and mining for insights... i saw earlier you use pieces mcp, bee.computer, etc...

John details a workflow using custom syntax triggers like #memory or #search. Rather than feeding a massive knowledge graph into every agent session globally, he prefers keeping his default Codex instances as vanilla as possible. He recommends implementing custom grammar listeners inside the user prompt hooks to dynamically grab and resolve target context bundles exactly when explicitly requested.

### What are the basic lifecycle events in an agent harness?

John steps back at 03:14:32 to lay down fundamental context setting. He explicitly abstracts the core pipeline events of any agent harness down to the basic three hooks: User Prompt, Tool Use, and Stop Hook, providing a baseline architecture breakdown before showing any more complex code configurations.

### John do you subscribe to this idea that the context window has a smart zone (first 100k tokens) and dumb zone and to try and keep the work in the smart zone? If so how do you keep the /goal sessions in the smart zone? I have noticed long running goals really chew through tokens which makes me think there might be context management sacrifices being made to unlock long running tasks.

John acknowledges that long-running automated goals change how context degradation is handled. Because long sessions continuously consume heavy token counts, using /goal strategies forces systems to use progressive automated compaction steps over their lifecycles. To maintain high accuracy without model degradation, he builds custom plugins that use explicit Python runtime rules to tightly control context instead of letting the agent continuously guess its state.

## Operational playbooks

- [Ralph Loop stop-hook continuation](/topics/foundations-ralph-loop-playbook/)

- [Codex Primitive Field Guide](/topics/foundations-codex-primitives-field-guide/)

## Recording references

- [Recording](https://codex-workshop-followup.pages.dev/video/lessons/lesson-07.mp4)

[Timestamped source page](https://codex-workshop-followup.pages.dev/lesson-07.html)

### Visual reference index

- [03:12:05](https://codex-workshop-followup.pages.dev/lesson-07.html#clip-07-1): Dark terminal/conversation context during the post-lunch compaction discussion.
- [03:14:45](https://codex-workshop-followup.pages.dev/lesson-07.html#clip-07-2): Terminal prompt area during the setup for explaining user prompt, tool use, and stop hooks.
- [03:17:15](https://codex-workshop-followup.pages.dev/lesson-07.html#clip-07-3): Terminal/file-list view before the browser documentation walkthrough fully appears.
- [03:18:55](https://codex-workshop-followup.pages.dev/lesson-07.html#clip-07-4): OpenAI Developers Hooks documentation page with the MarkSnip extension overlay visible.
- [03:20:45](https://codex-workshop-followup.pages.dev/lesson-07.html): Terminal view rendering generated hook/project instructions and script text.
- [03:22:20](https://codex-workshop-followup.pages.dev/lesson-07.html): Terminal prompt context while preparing the custom #human hook trigger example.
- [03:23:15](https://codex-workshop-followup.pages.dev/lesson-07.html): Split workspace with terminal logs on the left and a live typing-game dashboard in the browser.
- [03:24:18](https://codex-workshop-followup.pages.dev/lesson-07.html): GitHub repository view for johnlindquist/better-plugins showing plugin folders.
- [03:30:15](https://codex-workshop-followup.pages.dev/lesson-07.html): GitHub repository view inside better-plugins, showing individual plugin/script files.

## Original references

- [Agent foundations: Control agent lifecycle with hooks and context hygiene (authorized access required)](https://codex-workshop-followup.pages.dev/lesson-07.html)
