Hooks System
Relevant source files
The following files were used as context for generating this wiki page:
The Hooks System in OpenCode Swarm provides a robust middleware-style architecture for intercepting and enhancing agent communications, tool executions, and session lifecycle events. It enables the system to inject context, enforce guardrails, and automate knowledge management without tightly coupling these concerns to the core agent logic.
Hooks are primarily used for system prompt enhancement, detecting adversarial agent pairings, monitoring "slop" (low-quality or redundant code patterns), and managing "dark matter" (unresolved architectural gaps). By leveraging these extension points, the system can maintain high-quality outputs and ensure adherence to project-specific constraints and engineering invariants.
Sources: src/hooks/system-enhancer.ts, src/hooks/index.ts
Core Architecture and Lifecycle
The system utilizes several lifecycle event hooks provided by the underlying plugin host. These hooks allow for transformations of system messages, session compaction, and post-execution analysis.
Hook Categories
| Hook Name | Trigger Point | Primary Purpose |
|---|---|---|
experimental.chat.system.transform | Before system prompt is finalized | Injects phase, task, and project context. |
experimental.session.compacting | During conversation history compaction | Preserves critical project state (plan, decisions). |
toolAfter | Immediately after a tool execution | Triggers post-run audits like dark matter detection. |
messagesTransform | Before messages are sent to the LLM | Validates delegation patterns and content size. |
Sources: src/hooks/system-enhancer.ts:404-406, src/hooks/compaction-customizer.ts, src/hooks/dark-matter-detector.ts:68-70
Execution Flow
The following diagram illustrates how the Hooks System intercepts the standard agent communication flow to enhance the system's state awareness.
This flow ensures that every interaction is grounded in the current project plan and that learnings are captured immediately after tasks complete.
Sources: src/hooks/system-enhancer.ts:414-777, src/hooks/knowledge-curator.ts
System Enhancer
The SystemEnhancer is the most critical hook, responsible for building the context-aware system prompt that guides agents. It reads project files like plan.md and context.md to provide a "live" view of the build process.
Context Injection Priorities
When building the system prompt, the enhancer ranks information to fit within a configured max_injection_tokens budget (defaulting to 4000).
- Phase Header: Minimal current phase information.
- Plan Cursor: A compressed summary of the implementation plan.
- Handoff Brief: Context for resuming sessions after model switches.
- Key Decisions: Technical decisions extracted from
context.md. - Agent Context: Recent tool activity relevant to the specific agent role (e.g., Coder sees Reviewer's activity).
Sources: src/hooks/system-enhancer.ts:430-600, src/hooks/system-enhancer.ts:1146-1180
Language-Specific Constraints
The enhancer dynamically builds constraints based on the files touched in the current task. It uses file extensions to identify the language profile and appends specific coding or review rules.
function buildLanguageCoderConstraints(currentTaskText: string | null): string | null {
// Extracts file paths like "src/tools/lint.ts"
// Matches them against language profiles
// Returns [LANGUAGE-SPECIFIC CONSTRAINTS — TypeScript]
}
Sources: src/hooks/system-enhancer.ts:316-350
Guardrails and Detectors
Adversarial Detector
This hook prevents "same-model adversarial pairings" where the same LLM might act as both the implementer (Coder) and the verifier (Reviewer). If such a pairing is detected, the hook injects a warning or blocks the action based on policy.
Sources: src/hooks/adversarial-detector.ts:10-40
Slop Detector
The Slop Detector monitors code changes for low-quality patterns, such as redundant comments, excessive class counts, or oversized diffs that indicate "LLM slop."
| Parameter | Default Value | Description |
|---|---|---|
classThreshold | 3 | Maximum new classes allowed per task before warning. |
commentStripThreshold | 5 | Triggers warning if too many comments are removed without logic changes. |
diffLineThreshold | 200 | Warns if a single task modifies an excessive number of lines. |
Sources: src/hooks/slop-detector.ts, src/config/constants.ts:1016-1021
Dark Matter Detector
Unresolved coupling gaps or "dark matter" are tracked in .swarm/dark-matter.md. The detector hook fires every 10 tool calls, scanning for unresolved items and logging reminders to the user.
Knowledge and Compaction
Knowledge Curator
The KnowledgeCurator hook triggers whenever .swarm/plan.md is updated. It extracts bullet points from the ### Lessons Learned section and stores them as structured entries in .swarm/knowledge.jsonl. It also supports a RETRACT: prefix to remove or quarantine outdated knowledge.
Sources: src/hooks/knowledge-curator.ts
Compaction Customizer
When an OpenCode session reaches its context limit and undergoes compaction, this hook ensures that critical Swarm state is preserved in the resulting summary. It captures the current phase, pending tasks, and recent technical decisions to ensure the agent maintains continuity after compaction.
Sources: src/hooks/compaction-customizer.ts
Conclusion
The Hooks System provides the necessary infrastructure to implement OpenCode Swarm's complex multi-agent orchestration. By intercepting events at key points in the lifecycle, it enables sophisticated features like context ranking, cross-agent awareness, and automated quality enforcement, ensuring that the swarm operates safely and efficiently.