opencode-swarm-plugin 0.44.0 → 0.44.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (205) hide show
  1. package/bin/swarm.serve.test.ts +6 -4
  2. package/bin/swarm.ts +16 -10
  3. package/dist/compaction-prompt-scoring.js +139 -0
  4. package/dist/eval-capture.js +12811 -0
  5. package/dist/hive.d.ts.map +1 -1
  6. package/dist/index.js +7644 -62599
  7. package/dist/plugin.js +23766 -78721
  8. package/dist/swarm-orchestrate.d.ts.map +1 -1
  9. package/dist/swarm-prompts.d.ts.map +1 -1
  10. package/dist/swarm-review.d.ts.map +1 -1
  11. package/package.json +17 -5
  12. package/.changeset/swarm-insights-data-layer.md +0 -63
  13. package/.hive/analysis/eval-failure-analysis-2025-12-25.md +0 -331
  14. package/.hive/analysis/session-data-quality-audit.md +0 -320
  15. package/.hive/eval-results.json +0 -483
  16. package/.hive/issues.jsonl +0 -138
  17. package/.hive/memories.jsonl +0 -729
  18. package/.opencode/eval-history.jsonl +0 -327
  19. package/.turbo/turbo-build.log +0 -9
  20. package/CHANGELOG.md +0 -2286
  21. package/SCORER-ANALYSIS.md +0 -598
  22. package/docs/analysis/subagent-coordination-patterns.md +0 -902
  23. package/docs/analysis-socratic-planner-pattern.md +0 -504
  24. package/docs/planning/ADR-001-monorepo-structure.md +0 -171
  25. package/docs/planning/ADR-002-package-extraction.md +0 -393
  26. package/docs/planning/ADR-003-performance-improvements.md +0 -451
  27. package/docs/planning/ADR-004-message-queue-features.md +0 -187
  28. package/docs/planning/ADR-005-devtools-observability.md +0 -202
  29. package/docs/planning/ADR-007-swarm-enhancements-worktree-review.md +0 -168
  30. package/docs/planning/ADR-008-worker-handoff-protocol.md +0 -293
  31. package/docs/planning/ADR-009-oh-my-opencode-patterns.md +0 -353
  32. package/docs/planning/ADR-010-cass-inhousing.md +0 -1215
  33. package/docs/planning/ROADMAP.md +0 -368
  34. package/docs/semantic-memory-cli-syntax.md +0 -123
  35. package/docs/swarm-mail-architecture.md +0 -1147
  36. package/docs/testing/context-recovery-test.md +0 -470
  37. package/evals/ARCHITECTURE.md +0 -1189
  38. package/evals/README.md +0 -768
  39. package/evals/compaction-prompt.eval.ts +0 -149
  40. package/evals/compaction-resumption.eval.ts +0 -289
  41. package/evals/coordinator-behavior.eval.ts +0 -307
  42. package/evals/coordinator-session.eval.ts +0 -154
  43. package/evals/evalite.config.ts.bak +0 -15
  44. package/evals/example.eval.ts +0 -31
  45. package/evals/fixtures/cass-baseline.ts +0 -217
  46. package/evals/fixtures/compaction-cases.ts +0 -350
  47. package/evals/fixtures/compaction-prompt-cases.ts +0 -311
  48. package/evals/fixtures/coordinator-sessions.ts +0 -328
  49. package/evals/fixtures/decomposition-cases.ts +0 -105
  50. package/evals/lib/compaction-loader.test.ts +0 -248
  51. package/evals/lib/compaction-loader.ts +0 -320
  52. package/evals/lib/data-loader.evalite-test.ts +0 -289
  53. package/evals/lib/data-loader.test.ts +0 -345
  54. package/evals/lib/data-loader.ts +0 -281
  55. package/evals/lib/llm.ts +0 -115
  56. package/evals/scorers/compaction-prompt-scorers.ts +0 -145
  57. package/evals/scorers/compaction-scorers.ts +0 -305
  58. package/evals/scorers/coordinator-discipline.evalite-test.ts +0 -539
  59. package/evals/scorers/coordinator-discipline.ts +0 -325
  60. package/evals/scorers/index.test.ts +0 -146
  61. package/evals/scorers/index.ts +0 -328
  62. package/evals/scorers/outcome-scorers.evalite-test.ts +0 -27
  63. package/evals/scorers/outcome-scorers.ts +0 -349
  64. package/evals/swarm-decomposition.eval.ts +0 -121
  65. package/examples/commands/swarm.md +0 -745
  66. package/examples/plugin-wrapper-template.ts +0 -2515
  67. package/examples/skills/hive-workflow/SKILL.md +0 -212
  68. package/examples/skills/skill-creator/SKILL.md +0 -223
  69. package/examples/skills/swarm-coordination/SKILL.md +0 -292
  70. package/global-skills/cli-builder/SKILL.md +0 -344
  71. package/global-skills/cli-builder/references/advanced-patterns.md +0 -244
  72. package/global-skills/learning-systems/SKILL.md +0 -644
  73. package/global-skills/skill-creator/LICENSE.txt +0 -202
  74. package/global-skills/skill-creator/SKILL.md +0 -352
  75. package/global-skills/skill-creator/references/output-patterns.md +0 -82
  76. package/global-skills/skill-creator/references/workflows.md +0 -28
  77. package/global-skills/swarm-coordination/SKILL.md +0 -995
  78. package/global-skills/swarm-coordination/references/coordinator-patterns.md +0 -235
  79. package/global-skills/swarm-coordination/references/strategies.md +0 -138
  80. package/global-skills/system-design/SKILL.md +0 -213
  81. package/global-skills/testing-patterns/SKILL.md +0 -430
  82. package/global-skills/testing-patterns/references/dependency-breaking-catalog.md +0 -586
  83. package/opencode-swarm-plugin-0.30.7.tgz +0 -0
  84. package/opencode-swarm-plugin-0.31.0.tgz +0 -0
  85. package/scripts/cleanup-test-memories.ts +0 -346
  86. package/scripts/init-skill.ts +0 -222
  87. package/scripts/migrate-unknown-sessions.ts +0 -349
  88. package/scripts/validate-skill.ts +0 -204
  89. package/src/agent-mail.ts +0 -1724
  90. package/src/anti-patterns.test.ts +0 -1167
  91. package/src/anti-patterns.ts +0 -448
  92. package/src/compaction-capture.integration.test.ts +0 -257
  93. package/src/compaction-hook.test.ts +0 -838
  94. package/src/compaction-hook.ts +0 -1204
  95. package/src/compaction-observability.integration.test.ts +0 -139
  96. package/src/compaction-observability.test.ts +0 -187
  97. package/src/compaction-observability.ts +0 -324
  98. package/src/compaction-prompt-scorers.test.ts +0 -475
  99. package/src/compaction-prompt-scoring.ts +0 -300
  100. package/src/contributor-tools.test.ts +0 -133
  101. package/src/contributor-tools.ts +0 -201
  102. package/src/dashboard.test.ts +0 -611
  103. package/src/dashboard.ts +0 -462
  104. package/src/error-enrichment.test.ts +0 -403
  105. package/src/error-enrichment.ts +0 -219
  106. package/src/eval-capture.test.ts +0 -1015
  107. package/src/eval-capture.ts +0 -929
  108. package/src/eval-gates.test.ts +0 -306
  109. package/src/eval-gates.ts +0 -218
  110. package/src/eval-history.test.ts +0 -508
  111. package/src/eval-history.ts +0 -214
  112. package/src/eval-learning.test.ts +0 -378
  113. package/src/eval-learning.ts +0 -360
  114. package/src/eval-runner.test.ts +0 -223
  115. package/src/eval-runner.ts +0 -402
  116. package/src/export-tools.test.ts +0 -476
  117. package/src/export-tools.ts +0 -257
  118. package/src/hive.integration.test.ts +0 -2241
  119. package/src/hive.ts +0 -1628
  120. package/src/index.ts +0 -940
  121. package/src/learning.integration.test.ts +0 -1815
  122. package/src/learning.ts +0 -1079
  123. package/src/logger.test.ts +0 -189
  124. package/src/logger.ts +0 -135
  125. package/src/mandate-promotion.test.ts +0 -473
  126. package/src/mandate-promotion.ts +0 -239
  127. package/src/mandate-storage.integration.test.ts +0 -601
  128. package/src/mandate-storage.test.ts +0 -578
  129. package/src/mandate-storage.ts +0 -794
  130. package/src/mandates.ts +0 -540
  131. package/src/memory-tools.test.ts +0 -195
  132. package/src/memory-tools.ts +0 -344
  133. package/src/memory.integration.test.ts +0 -334
  134. package/src/memory.test.ts +0 -158
  135. package/src/memory.ts +0 -527
  136. package/src/model-selection.test.ts +0 -188
  137. package/src/model-selection.ts +0 -68
  138. package/src/observability-tools.test.ts +0 -359
  139. package/src/observability-tools.ts +0 -871
  140. package/src/output-guardrails.test.ts +0 -438
  141. package/src/output-guardrails.ts +0 -381
  142. package/src/pattern-maturity.test.ts +0 -1160
  143. package/src/pattern-maturity.ts +0 -525
  144. package/src/planning-guardrails.test.ts +0 -491
  145. package/src/planning-guardrails.ts +0 -438
  146. package/src/plugin.ts +0 -23
  147. package/src/post-compaction-tracker.test.ts +0 -251
  148. package/src/post-compaction-tracker.ts +0 -237
  149. package/src/query-tools.test.ts +0 -636
  150. package/src/query-tools.ts +0 -324
  151. package/src/rate-limiter.integration.test.ts +0 -466
  152. package/src/rate-limiter.ts +0 -774
  153. package/src/replay-tools.test.ts +0 -496
  154. package/src/replay-tools.ts +0 -240
  155. package/src/repo-crawl.integration.test.ts +0 -441
  156. package/src/repo-crawl.ts +0 -610
  157. package/src/schemas/cell-events.test.ts +0 -347
  158. package/src/schemas/cell-events.ts +0 -807
  159. package/src/schemas/cell.ts +0 -257
  160. package/src/schemas/evaluation.ts +0 -166
  161. package/src/schemas/index.test.ts +0 -199
  162. package/src/schemas/index.ts +0 -286
  163. package/src/schemas/mandate.ts +0 -232
  164. package/src/schemas/swarm-context.ts +0 -115
  165. package/src/schemas/task.ts +0 -161
  166. package/src/schemas/worker-handoff.test.ts +0 -302
  167. package/src/schemas/worker-handoff.ts +0 -131
  168. package/src/sessions/agent-discovery.test.ts +0 -137
  169. package/src/sessions/agent-discovery.ts +0 -112
  170. package/src/sessions/index.ts +0 -15
  171. package/src/skills.integration.test.ts +0 -1192
  172. package/src/skills.test.ts +0 -643
  173. package/src/skills.ts +0 -1549
  174. package/src/storage.integration.test.ts +0 -341
  175. package/src/storage.ts +0 -884
  176. package/src/structured.integration.test.ts +0 -817
  177. package/src/structured.test.ts +0 -1046
  178. package/src/structured.ts +0 -762
  179. package/src/swarm-decompose.test.ts +0 -188
  180. package/src/swarm-decompose.ts +0 -1302
  181. package/src/swarm-deferred.integration.test.ts +0 -157
  182. package/src/swarm-deferred.test.ts +0 -38
  183. package/src/swarm-insights.test.ts +0 -214
  184. package/src/swarm-insights.ts +0 -459
  185. package/src/swarm-mail.integration.test.ts +0 -970
  186. package/src/swarm-mail.ts +0 -739
  187. package/src/swarm-orchestrate.integration.test.ts +0 -282
  188. package/src/swarm-orchestrate.test.ts +0 -548
  189. package/src/swarm-orchestrate.ts +0 -3084
  190. package/src/swarm-prompts.test.ts +0 -1270
  191. package/src/swarm-prompts.ts +0 -2077
  192. package/src/swarm-research.integration.test.ts +0 -701
  193. package/src/swarm-research.test.ts +0 -698
  194. package/src/swarm-research.ts +0 -472
  195. package/src/swarm-review.integration.test.ts +0 -285
  196. package/src/swarm-review.test.ts +0 -879
  197. package/src/swarm-review.ts +0 -709
  198. package/src/swarm-strategies.ts +0 -407
  199. package/src/swarm-worktree.test.ts +0 -501
  200. package/src/swarm-worktree.ts +0 -575
  201. package/src/swarm.integration.test.ts +0 -2377
  202. package/src/swarm.ts +0 -38
  203. package/src/tool-adapter.integration.test.ts +0 -1221
  204. package/src/tool-availability.ts +0 -461
  205. package/tsconfig.json +0 -28
package/src/index.ts DELETED
@@ -1,940 +0,0 @@
1
- /**
2
- * OpenCode Swarm Plugin
3
- *
4
- * A type-safe plugin for multi-agent coordination with hive issue tracking
5
- * and Agent Mail integration. Provides structured tools for swarm operations.
6
- *
7
- * @module opencode-swarm-plugin
8
- *
9
- * @example
10
- * ```typescript
11
- * // In opencode.jsonc
12
- * {
13
- * "plugins": ["opencode-swarm-plugin"]
14
- * }
15
- * ```
16
- *
17
- * @example
18
- * ```typescript
19
- * // Programmatic usage (hive is the new name, beads is deprecated)
20
- * import { hiveTools, beadsTools, agentMailTools, swarmMailTools } from "opencode-swarm-plugin"
21
- * ```
22
- */
23
- import type { Plugin, PluginInput, Hooks } from "@opencode-ai/plugin";
24
-
25
- import {
26
- hiveTools,
27
- beadsTools,
28
- setHiveWorkingDirectory,
29
- setBeadsWorkingDirectory,
30
- } from "./hive";
31
- import {
32
- agentMailTools,
33
- setAgentMailProjectDirectory,
34
- type AgentMailState,
35
- AGENT_MAIL_URL,
36
- } from "./agent-mail";
37
- import {
38
- swarmMailTools,
39
- setSwarmMailProjectDirectory,
40
- type SwarmMailState,
41
- } from "./swarm-mail";
42
- import { structuredTools } from "./structured";
43
- import { swarmTools } from "./swarm";
44
- import { worktreeTools } from "./swarm-worktree";
45
- import { reviewTools } from "./swarm-review";
46
- import { repoCrawlTools } from "./repo-crawl";
47
- import { skillsTools, setSkillsProjectDirectory } from "./skills";
48
- import { mandateTools } from "./mandates";
49
- import { memoryTools } from "./memory-tools";
50
- import { observabilityTools } from "./observability-tools";
51
- import { researchTools } from "./swarm-research";
52
- import { evalTools } from "./eval-runner";
53
- import { contributorTools } from "./contributor-tools";
54
- import {
55
- guardrailOutput,
56
- DEFAULT_GUARDRAIL_CONFIG,
57
- type GuardrailResult,
58
- } from "./output-guardrails";
59
- import {
60
- analyzeTodoWrite,
61
- shouldAnalyzeTool,
62
- detectCoordinatorViolation,
63
- isInCoordinatorContext,
64
- getCoordinatorContext,
65
- setCoordinatorContext,
66
- clearCoordinatorContext,
67
- } from "./planning-guardrails";
68
- import { createCompactionHook } from "./compaction-hook";
69
-
70
- /**
71
- * OpenCode Swarm Plugin
72
- *
73
- * Registers all swarm coordination tools:
74
- * - hive:* - Type-safe hive issue tracker wrappers (primary)
75
- * - beads:* - Legacy aliases for hive tools (deprecated, use hive:* instead)
76
- * - agent-mail:* - Multi-agent coordination via Agent Mail MCP (legacy)
77
- * - swarm-mail:* - Multi-agent coordination with embedded event sourcing (recommended)
78
- * - structured:* - Structured output parsing and validation
79
- * - swarm:* - Swarm orchestration and task decomposition
80
- * - repo-crawl:* - GitHub API tools for repository research
81
- * - skills:* - Agent skills discovery, activation, and execution
82
- * - mandate:* - Agent voting system for collaborative knowledge curation
83
- * - semantic-memory:* - Semantic memory with vector embeddings (Ollama + PGLite)
84
- * - contributor_lookup - GitHub contributor profile lookup with changeset credit generation
85
- *
86
- * @param input - Plugin context from OpenCode
87
- * @returns Plugin hooks including tools, events, and tool execution hooks
88
- */
89
- const SwarmPlugin: Plugin = async (
90
- input: PluginInput,
91
- ): Promise<Hooks> => {
92
- const { $, directory, client } = input;
93
-
94
- // Set the working directory for hive commands
95
- // This ensures hive operations run in the project directory, not ~/.config/opencode
96
- setHiveWorkingDirectory(directory);
97
-
98
- // Set the project directory for skills discovery
99
- // Skills are discovered from .opencode/skills/, .claude/skills/, or skills/
100
- setSkillsProjectDirectory(directory);
101
-
102
- // Set the project directory for Agent Mail (legacy MCP-based)
103
- // This ensures agentmail_init uses the correct project path by default
104
- // (prevents using plugin directory when working in a different project)
105
- setAgentMailProjectDirectory(directory);
106
-
107
- // Set the project directory for Swarm Mail (embedded event-sourced)
108
- // This ensures swarmmail_init uses the correct project path by default
109
- setSwarmMailProjectDirectory(directory);
110
-
111
- /** Track active sessions for cleanup */
112
- let activeAgentMailState: AgentMailState | null = null;
113
-
114
- /**
115
- * Release all file reservations for the active agent
116
- * Best-effort cleanup - errors are logged but not thrown
117
- */
118
- async function releaseReservations(): Promise<void> {
119
- if (
120
- !activeAgentMailState ||
121
- activeAgentMailState.reservations.length === 0
122
- ) {
123
- return;
124
- }
125
-
126
- try {
127
- const response = await fetch(`${AGENT_MAIL_URL}/mcp/`, {
128
- method: "POST",
129
- headers: { "Content-Type": "application/json" },
130
- body: JSON.stringify({
131
- jsonrpc: "2.0",
132
- id: crypto.randomUUID(),
133
- method: "tools/call",
134
- params: {
135
- name: "release_file_reservations",
136
- arguments: {
137
- project_key: activeAgentMailState.projectKey,
138
- agent_name: activeAgentMailState.agentName,
139
- },
140
- },
141
- }),
142
- });
143
-
144
- if (response.ok) {
145
- activeAgentMailState.reservations = [];
146
- }
147
- } catch (error) {
148
- // Agent Mail might not be running - that's ok
149
- console.warn(
150
- `[swarm-plugin] Could not auto-release reservations: ${error instanceof Error ? error.message : String(error)}`,
151
- );
152
- }
153
- }
154
-
155
- return {
156
- /**
157
- * Register all tools from modules
158
- *
159
- * Tools are namespaced by module:
160
- * - hive:create, hive:query, hive:update, etc. (primary)
161
- * - beads:* - Legacy aliases (deprecated, use hive:* instead)
162
- * - agent-mail:init, agent-mail:send, agent-mail:reserve, etc. (legacy MCP)
163
- * - swarm-mail:init, swarm-mail:send, swarm-mail:reserve, etc. (embedded)
164
- * - repo-crawl:readme, repo-crawl:structure, etc.
165
- * - mandate:file, mandate:vote, mandate:query, etc.
166
- * - semantic-memory:store, semantic-memory:find, semantic-memory:get, etc.
167
- * - contributor_lookup - GitHub contributor profile lookup with changeset credits
168
- */
169
- tool: {
170
- ...hiveTools,
171
- ...swarmMailTools,
172
- ...structuredTools,
173
- ...swarmTools,
174
- ...worktreeTools,
175
- ...reviewTools,
176
- ...repoCrawlTools,
177
- ...skillsTools,
178
- ...mandateTools,
179
- ...memoryTools,
180
- ...observabilityTools,
181
- ...researchTools,
182
- ...evalTools,
183
- ...contributorTools,
184
- },
185
-
186
- /**
187
- * Event hook for session lifecycle
188
- *
189
- * Handles cleanup when session becomes idle:
190
- * - Releases any held file reservations
191
- */
192
- event: async ({ event }) => {
193
- // Auto-release reservations on session idle
194
- if (event.type === "session.idle") {
195
- await releaseReservations();
196
- }
197
- },
198
-
199
- /**
200
- * Hook before tool execution for planning guardrails
201
- *
202
- * Warns when agents are about to make planning mistakes:
203
- * - Using todowrite for multi-file implementation (should use swarm)
204
- * - Coordinator editing files directly (should spawn workers)
205
- * - Coordinator running tests (workers should run tests)
206
- */
207
- "tool.execute.before": async (input, output) => {
208
- const toolName = input.tool;
209
-
210
- // Check for planning anti-patterns
211
- if (shouldAnalyzeTool(toolName)) {
212
- const analysis = analyzeTodoWrite(output.args);
213
- if (analysis.warning) {
214
- console.warn(`[swarm-plugin] ${analysis.warning}`);
215
- }
216
- }
217
-
218
- // Check for coordinator violations when in coordinator context
219
- if (isInCoordinatorContext()) {
220
- const ctx = getCoordinatorContext();
221
- const violation = detectCoordinatorViolation({
222
- sessionId: input.sessionID || "unknown",
223
- epicId: ctx.epicId || "unknown",
224
- toolName,
225
- toolArgs: output.args as Record<string, unknown>,
226
- agentContext: "coordinator",
227
- });
228
-
229
- if (violation.isViolation) {
230
- console.warn(`[swarm-plugin] ${violation.message}`);
231
- }
232
- }
233
-
234
- // Activate coordinator context when swarm tools are used
235
- if (toolName === "hive_create_epic" || toolName === "swarm_decompose") {
236
- setCoordinatorContext({
237
- isCoordinator: true,
238
- sessionId: input.sessionID,
239
- });
240
- }
241
-
242
- // Capture epic ID when epic is created
243
- if (toolName === "hive_create_epic" && output.args) {
244
- const args = output.args as { epic_title?: string };
245
- // Epic ID will be set after execution in tool.execute.after
246
- }
247
- },
248
-
249
- /**
250
- * Hook after tool execution for automatic cleanup and guardrails
251
- *
252
- * - Applies output guardrails to prevent context blowout from MCP tools
253
- * - Auto-releases file reservations after swarm:complete or hive:close
254
- * - Auto-syncs cells after closing
255
- */
256
- "tool.execute.after": async (input, output) => {
257
- const toolName = input.tool;
258
-
259
- // Apply output guardrails to prevent context blowout
260
- // Skip if output is empty or tool is in skip list
261
- if (output.output && typeof output.output === "string") {
262
- const guardrailResult = guardrailOutput(toolName, output.output);
263
- if (guardrailResult.truncated) {
264
- output.output = guardrailResult.output;
265
- }
266
- }
267
-
268
- // Track Agent Mail state for cleanup
269
- if (toolName === "agentmail_init" && output.output) {
270
- try {
271
- const result = JSON.parse(output.output);
272
- if (result.agent) {
273
- activeAgentMailState = {
274
- projectKey: result.project?.human_key || "",
275
- agentName: result.agent.name,
276
- reservations: [],
277
- startedAt: new Date().toISOString(),
278
- };
279
- }
280
- } catch {
281
- // Parsing failed - ignore
282
- }
283
- }
284
-
285
- // Track reservations from output
286
- if (
287
- toolName === "agentmail_reserve" &&
288
- output.output &&
289
- activeAgentMailState
290
- ) {
291
- // Extract reservation count from output if present
292
- const match = output.output.match(/Reserved (\d+) path/);
293
- if (match) {
294
- // Track reservation for cleanup
295
- activeAgentMailState.reservations.push(Date.now());
296
- }
297
- }
298
-
299
- // Auto-release after swarm:complete
300
- if (toolName === "swarm_complete" && activeAgentMailState) {
301
- await releaseReservations();
302
- }
303
-
304
- // Capture epic ID when epic is created (for coordinator context)
305
- if (toolName === "hive_create_epic" && output.output) {
306
- try {
307
- const result = JSON.parse(output.output);
308
- if (result.epic?.id) {
309
- setCoordinatorContext({
310
- isCoordinator: true,
311
- epicId: result.epic.id,
312
- sessionId: input.sessionID,
313
- });
314
- }
315
- } catch {
316
- // Parsing failed - ignore
317
- }
318
- }
319
-
320
- // Clear coordinator context when epic is closed
321
- if (toolName === "hive_close" && output.output && isInCoordinatorContext()) {
322
- const ctx = getCoordinatorContext();
323
- try {
324
- // Check if the closed cell is the active epic
325
- const result = JSON.parse(output.output);
326
- if (result.id === ctx.epicId) {
327
- clearCoordinatorContext();
328
- }
329
- } catch {
330
- // Parsing failed - ignore
331
- }
332
- }
333
-
334
- // Note: hive_sync should be called explicitly at session end
335
- // Auto-sync was removed because bd CLI is deprecated
336
- // The hive_sync tool handles flushing to JSONL and git commit/push
337
- },
338
-
339
- /**
340
- * Compaction hook for swarm context preservation
341
- *
342
- * When OpenCode compacts session context, this hook injects swarm state
343
- * to ensure coordinators can resume orchestration seamlessly.
344
- *
345
- * Uses SDK client to scan actual session messages for precise swarm state
346
- * (epic IDs, subtask status, agent names) rather than relying solely on
347
- * heuristic detection from hive/swarm-mail.
348
- *
349
- * Note: This hook is experimental and may not be in the published Hooks type yet.
350
- */
351
- "experimental.session.compacting": createCompactionHook(client),
352
- } as Hooks & {
353
- "experimental.session.compacting"?: (
354
- input: { sessionID: string },
355
- output: { context: string[] },
356
- ) => Promise<void>;
357
- };
358
- };
359
-
360
- /**
361
- * Default export for OpenCode plugin loading
362
- *
363
- * OpenCode loads plugins by their default export, so this allows:
364
- * ```json
365
- * { "plugins": ["opencode-swarm-plugin"] }
366
- * ```
367
- */
368
- export default SwarmPlugin;
369
-
370
- // =============================================================================
371
- // Re-exports for programmatic use
372
- // =============================================================================
373
-
374
- /**
375
- * Re-export all schemas for type-safe usage
376
- */
377
- export * from "./schemas";
378
-
379
- /**
380
- * Re-export hive module (primary) and beads module (deprecated aliases)
381
- *
382
- * Includes:
383
- * - hiveTools - All hive tool definitions (primary)
384
- * - beadsTools - Legacy aliases for backward compatibility (deprecated)
385
- * - Individual tool exports (hive_create, hive_query, etc.)
386
- * - Legacy aliases (hive_create, hive_query, etc.)
387
- * - HiveError, HiveValidationError (and BeadError, BeadValidationError aliases)
388
- *
389
- * DEPRECATED: Use hive_* tools instead of beads_* tools
390
- */
391
- export * from "./hive";
392
-
393
- /**
394
- * Re-export agent-mail module (legacy MCP-based)
395
- *
396
- * Includes:
397
- * - agentMailTools - All agent mail tool definitions
398
- * - AgentMailError, FileReservationConflictError - Error classes
399
- * - AgentMailState - Session state type
400
- *
401
- * NOTE: For OpenCode plugin usage, import from "opencode-swarm-plugin/plugin" instead
402
- * to avoid the plugin loader trying to call these classes as functions.
403
- *
404
- * DEPRECATED: Use swarm-mail module instead for embedded event-sourced implementation.
405
- */
406
- export {
407
- agentMailTools,
408
- AgentMailError,
409
- AgentMailNotInitializedError,
410
- FileReservationConflictError,
411
- createAgentMailError,
412
- setAgentMailProjectDirectory,
413
- getAgentMailProjectDirectory,
414
- mcpCallWithAutoInit,
415
- isProjectNotFoundError,
416
- isAgentNotFoundError,
417
- type AgentMailState,
418
- } from "./agent-mail";
419
-
420
- /**
421
- * Re-export swarm-mail module (embedded event-sourced)
422
- *
423
- * Includes:
424
- * - swarmMailTools - All swarm mail tool definitions
425
- * - setSwarmMailProjectDirectory, getSwarmMailProjectDirectory - Directory management
426
- * - clearSessionState - Session cleanup
427
- * - SwarmMailState - Session state type
428
- *
429
- * Features:
430
- * - Embedded PGLite storage (no external server dependency)
431
- * - Event sourcing for full audit trail
432
- * - Offset-based resumability
433
- * - Materialized views for fast queries
434
- * - File reservation with conflict detection
435
- */
436
- export {
437
- swarmMailTools,
438
- setSwarmMailProjectDirectory,
439
- getSwarmMailProjectDirectory,
440
- clearSessionState,
441
- type SwarmMailState,
442
- } from "./swarm-mail";
443
-
444
- /**
445
- * Re-export shared types from swarm-mail package
446
- *
447
- * Includes:
448
- * - MailSessionState - Shared session state type for Agent Mail and Swarm Mail
449
- */
450
- export { type MailSessionState } from "swarm-mail";
451
-
452
- /**
453
- * Re-export structured module
454
- *
455
- * Includes:
456
- * - structuredTools - Structured output parsing tools
457
- * - Utility functions for JSON extraction
458
- */
459
- export {
460
- structuredTools,
461
- extractJsonFromText,
462
- formatZodErrors,
463
- getSchemaByName,
464
- } from "./structured";
465
-
466
- /**
467
- * Re-export swarm module
468
- *
469
- * Includes:
470
- * - swarmTools - Swarm orchestration tools
471
- * - SwarmError, DecompositionError - Error classes
472
- * - formatSubtaskPrompt, formatEvaluationPrompt - Prompt helpers
473
- * - selectStrategy, formatStrategyGuidelines - Strategy selection helpers
474
- * - STRATEGIES - Strategy definitions
475
- *
476
- * Types:
477
- * - DecompositionStrategy - Strategy type union
478
- * - StrategyDefinition - Strategy definition interface
479
- *
480
- * NOTE: Prompt template strings (DECOMPOSITION_PROMPT, etc.) are NOT exported
481
- * to avoid confusing the plugin loader which tries to call all exports as functions
482
- */
483
- export {
484
- swarmTools,
485
- SwarmError,
486
- DecompositionError,
487
- formatSubtaskPrompt,
488
- formatSubtaskPromptV2,
489
- formatEvaluationPrompt,
490
- SUBTASK_PROMPT_V2,
491
- // Strategy exports
492
- STRATEGIES,
493
- selectStrategy,
494
- formatStrategyGuidelines,
495
- type DecompositionStrategy,
496
- type StrategyDefinition,
497
- } from "./swarm";
498
-
499
- // =============================================================================
500
- // Unified Tool Registry for CLI
501
- // =============================================================================
502
-
503
- /**
504
- * All tools in a single registry for CLI tool execution
505
- *
506
- * This is used by `swarm tool <name>` command to dynamically execute tools.
507
- * Each tool has an `execute` function that takes (args, ctx) and returns a string.
508
- *
509
- * Note: hiveTools includes both hive_* and beads_* (legacy aliases)
510
- */
511
- export const allTools = {
512
- ...hiveTools,
513
- ...swarmMailTools,
514
- ...structuredTools,
515
- ...swarmTools,
516
- ...worktreeTools,
517
- ...reviewTools,
518
- ...repoCrawlTools,
519
- ...skillsTools,
520
- ...mandateTools,
521
- ...memoryTools,
522
- ...observabilityTools,
523
- ...contributorTools,
524
- } as const;
525
-
526
- /**
527
- * Type for CLI tool names (all available tools)
528
- */
529
- export type CLIToolName = keyof typeof allTools;
530
-
531
- /**
532
- * Re-export storage module
533
- *
534
- * Includes:
535
- * - createStorage, createStorageWithFallback - Factory functions
536
- * - getStorage, setStorage, resetStorage - Global instance management
537
- * - InMemoryStorage, SemanticMemoryStorage - Storage implementations
538
- * - isSemanticMemoryAvailable - Availability check
539
- * - DEFAULT_STORAGE_CONFIG - Default configuration
540
- *
541
- * Types:
542
- * - LearningStorage - Unified storage interface
543
- * - StorageConfig, StorageBackend, StorageCollections - Configuration types
544
- */
545
- export {
546
- createStorage,
547
- createStorageWithFallback,
548
- getStorage,
549
- setStorage,
550
- resetStorage,
551
- InMemoryStorage,
552
- SemanticMemoryStorage,
553
- isSemanticMemoryAvailable,
554
- DEFAULT_STORAGE_CONFIG,
555
- type LearningStorage,
556
- type StorageConfig,
557
- type StorageBackend,
558
- type StorageCollections,
559
- } from "./storage";
560
-
561
- /**
562
- * Re-export tool-availability module
563
- *
564
- * Includes:
565
- * - checkTool, isToolAvailable - Check individual tool availability
566
- * - checkAllTools - Check all tools at once
567
- * - withToolFallback, ifToolAvailable - Execute with graceful fallback
568
- * - formatToolAvailability - Format availability for display
569
- * - resetToolCache - Reset cached availability (for testing)
570
- *
571
- * Types:
572
- * - ToolName - Supported tool names
573
- * - ToolStatus, ToolAvailability - Status types
574
- */
575
- export {
576
- checkTool,
577
- isToolAvailable,
578
- checkAllTools,
579
- getToolAvailability,
580
- withToolFallback,
581
- ifToolAvailable,
582
- warnMissingTool,
583
- requireTool,
584
- formatToolAvailability,
585
- resetToolCache,
586
- type ToolName,
587
- type ToolStatus,
588
- type ToolAvailability,
589
- } from "./tool-availability";
590
-
591
- /**
592
- * Re-export repo-crawl module
593
- *
594
- * Includes:
595
- * - repoCrawlTools - All GitHub API repository research tools
596
- * - repo_readme, repo_structure, repo_tree, repo_file, repo_search - Individual tools
597
- * - RepoCrawlError - Error class
598
- *
599
- * Features:
600
- * - Parse repos from various formats (owner/repo, URLs)
601
- * - Optional GITHUB_TOKEN auth for higher rate limits (5000 vs 60 req/hour)
602
- * - Tech stack detection from file patterns
603
- * - Graceful rate limit handling
604
- */
605
- export { repoCrawlTools, RepoCrawlError } from "./repo-crawl";
606
-
607
- /**
608
- * Re-export skills module
609
- *
610
- * Implements Anthropic's Agent Skills specification for OpenCode.
611
- *
612
- * Includes:
613
- * - skillsTools - All skills tools (list, use, execute, read)
614
- * - discoverSkills, getSkill, listSkills - Discovery functions
615
- * - parseFrontmatter - YAML frontmatter parser
616
- * - getSkillsContextForSwarm - Swarm integration helper
617
- * - findRelevantSkills - Task-based skill matching
618
- *
619
- * Types:
620
- * - Skill, SkillMetadata, SkillRef - Skill data types
621
- */
622
- export {
623
- skillsTools,
624
- discoverSkills,
625
- getSkill,
626
- listSkills,
627
- parseFrontmatter,
628
- setSkillsProjectDirectory,
629
- invalidateSkillsCache,
630
- getSkillsContextForSwarm,
631
- findRelevantSkills,
632
- type Skill,
633
- type SkillMetadata,
634
- type SkillRef,
635
- } from "./skills";
636
-
637
- /**
638
- * Re-export mandates module
639
- *
640
- * Agent voting system for collaborative knowledge curation.
641
- *
642
- * Includes:
643
- * - mandateTools - All mandate tools (file, vote, query, list, stats)
644
- * - MandateError - Error class
645
- *
646
- * Features:
647
- * - Submit ideas, tips, lore, snippets, and feature requests
648
- * - Vote on entries (upvote/downvote) with 90-day decay
649
- * - Semantic search for relevant mandates
650
- * - Status transitions based on consensus (candidate → established → mandate)
651
- * - Persistent storage with semantic-memory
652
- *
653
- * Types:
654
- * - MandateEntry, Vote, MandateScore - Core data types
655
- * - MandateStatus, MandateContentType - Enum types
656
- */
657
- export { mandateTools, MandateError } from "./mandates";
658
-
659
- /**
660
- * Re-export mandate-storage module
661
- *
662
- * Includes:
663
- * - createMandateStorage - Factory function
664
- * - getMandateStorage, setMandateStorage, resetMandateStorage - Global instance management
665
- * - updateMandateStatus, updateAllMandateStatuses - Status update helpers
666
- * - InMemoryMandateStorage, SemanticMemoryMandateStorage - Storage implementations
667
- *
668
- * Types:
669
- * - MandateStorage - Unified storage interface
670
- * - MandateStorageConfig, MandateStorageBackend, MandateStorageCollections - Configuration types
671
- */
672
- export {
673
- createMandateStorage,
674
- getMandateStorage,
675
- setMandateStorage,
676
- resetMandateStorage,
677
- updateMandateStatus,
678
- updateAllMandateStatuses,
679
- InMemoryMandateStorage,
680
- SemanticMemoryMandateStorage,
681
- DEFAULT_MANDATE_STORAGE_CONFIG,
682
- type MandateStorage,
683
- type MandateStorageConfig,
684
- type MandateStorageBackend,
685
- type MandateStorageCollections,
686
- } from "./mandate-storage";
687
-
688
- /**
689
- * Re-export mandate-promotion module
690
- *
691
- * Includes:
692
- * - evaluatePromotion - Evaluate status transitions
693
- * - shouldPromote - Determine new status based on score
694
- * - formatPromotionResult - Format promotion result for display
695
- * - evaluateBatchPromotions, getStatusChanges, groupByTransition - Batch helpers
696
- *
697
- * Types:
698
- * - PromotionResult - Promotion evaluation result
699
- */
700
- export {
701
- evaluatePromotion,
702
- shouldPromote,
703
- formatPromotionResult,
704
- evaluateBatchPromotions,
705
- getStatusChanges,
706
- groupByTransition,
707
- type PromotionResult,
708
- } from "./mandate-promotion";
709
-
710
- /**
711
- * Re-export output-guardrails module
712
- *
713
- * Includes:
714
- * - guardrailOutput - Main entry point for truncating tool output
715
- * - truncateWithBoundaries - Smart truncation preserving structure
716
- * - getToolLimit - Get character limit for a tool
717
- * - DEFAULT_GUARDRAIL_CONFIG - Default configuration
718
- *
719
- * Types:
720
- * - GuardrailConfig - Configuration interface
721
- * - GuardrailResult - Result of guardrail processing
722
- * - GuardrailMetrics - Analytics data
723
- */
724
- export {
725
- guardrailOutput,
726
- truncateWithBoundaries,
727
- createMetrics,
728
- DEFAULT_GUARDRAIL_CONFIG,
729
- type GuardrailConfig,
730
- type GuardrailResult,
731
- type GuardrailMetrics,
732
- } from "./output-guardrails";
733
-
734
- /**
735
- * Re-export compaction-hook module
736
- *
737
- * Includes:
738
- * - SWARM_COMPACTION_CONTEXT - Prompt text for swarm state preservation
739
- * - createCompactionHook - Factory function for the compaction hook
740
- * - scanSessionMessages - Scan session for swarm state
741
- * - ScannedSwarmState - Scanned state interface
742
- *
743
- * Usage:
744
- * ```typescript
745
- * import { createCompactionHook } from "opencode-swarm-plugin";
746
- *
747
- * const hooks = {
748
- * "experimental.session.compacting": createCompactionHook(),
749
- * };
750
- * ```
751
- */
752
- export {
753
- SWARM_COMPACTION_CONTEXT,
754
- createCompactionHook,
755
- scanSessionMessages,
756
- type ScannedSwarmState,
757
- } from "./compaction-hook";
758
-
759
- /**
760
- * Re-export compaction-observability module
761
- *
762
- * Includes:
763
- * - CompactionPhase - Enum of compaction phases
764
- * - createMetricsCollector - Create a metrics collector
765
- * - recordPhaseStart, recordPhaseComplete - Phase timing
766
- * - recordPatternExtracted, recordPatternSkipped - Pattern tracking
767
- * - getMetricsSummary - Get metrics summary
768
- *
769
- * Types:
770
- * - CompactionMetrics - Mutable metrics collector
771
- * - CompactionMetricsSummary - Read-only summary snapshot
772
- *
773
- * Features:
774
- * - Phase timing breakdown (START, GATHER, DETECT, INJECT, COMPLETE)
775
- * - Pattern extraction tracking with reasons
776
- * - Success rate calculation
777
- * - Debug mode for verbose details
778
- * - JSON serializable for persistence
779
- *
780
- * Usage:
781
- * ```typescript
782
- * import { createMetricsCollector, CompactionPhase, recordPhaseStart } from "opencode-swarm-plugin";
783
- *
784
- * const metrics = createMetricsCollector({ session_id: "abc123" });
785
- * recordPhaseStart(metrics, CompactionPhase.DETECT);
786
- * // ... work ...
787
- * recordPhaseComplete(metrics, CompactionPhase.DETECT);
788
- * const summary = getMetricsSummary(metrics);
789
- * ```
790
- */
791
- export {
792
- CompactionPhase,
793
- createMetricsCollector,
794
- recordPhaseStart,
795
- recordPhaseComplete,
796
- recordPatternExtracted,
797
- recordPatternSkipped,
798
- getMetricsSummary,
799
- type CompactionMetrics,
800
- type CompactionMetricsSummary,
801
- } from "./compaction-observability";
802
-
803
- /**
804
- * Re-export memory module
805
- *
806
- * Includes:
807
- * - memoryTools - All semantic-memory tools (store, find, get, remove, validate, list, stats, check)
808
- * - createMemoryAdapter - Factory function for memory adapter
809
- * - resetMemoryCache - Cache management for testing
810
- *
811
- * Types:
812
- * - MemoryAdapter - Memory adapter interface
813
- * - StoreArgs, FindArgs, IdArgs, ListArgs - Tool argument types
814
- * - StoreResult, FindResult, StatsResult, HealthResult, OperationResult - Result types
815
- */
816
- export {
817
- memoryTools,
818
- createMemoryAdapter,
819
- resetMemoryCache,
820
- type MemoryAdapter,
821
- type StoreArgs,
822
- type FindArgs,
823
- type IdArgs,
824
- type ListArgs,
825
- type StoreResult,
826
- type FindResult,
827
- type StatsResult,
828
- type HealthResult,
829
- type OperationResult,
830
- } from "./memory-tools";
831
- export type { Memory, SearchResult, SearchOptions } from "swarm-mail";
832
-
833
- /**
834
- * Re-export eval-history module
835
- *
836
- * Includes:
837
- * - recordEvalRun - Record eval run to JSONL history
838
- * - getScoreHistory - Get score history for a specific eval
839
- * - getPhase - Get current phase based on run count and variance
840
- * - calculateVariance - Calculate statistical variance of scores
841
- * - ensureEvalHistoryDir - Ensure history directory exists
842
- * - getEvalHistoryPath - Get path to eval history file
843
- *
844
- * Constants:
845
- * - DEFAULT_EVAL_HISTORY_PATH - Default path (.opencode/eval-history.jsonl)
846
- * - VARIANCE_THRESHOLD - Variance threshold for production phase (0.1)
847
- * - BOOTSTRAP_THRESHOLD - Run count for bootstrap phase (10)
848
- * - STABILIZATION_THRESHOLD - Run count for stabilization phase (50)
849
- *
850
- * Types:
851
- * - Phase - Progressive phases (bootstrap | stabilization | production)
852
- * - EvalRunRecord - Single eval run record
853
- */
854
- export {
855
- recordEvalRun,
856
- getScoreHistory,
857
- getPhase,
858
- calculateVariance,
859
- ensureEvalHistoryDir,
860
- getEvalHistoryPath,
861
- DEFAULT_EVAL_HISTORY_PATH,
862
- VARIANCE_THRESHOLD,
863
- BOOTSTRAP_THRESHOLD,
864
- STABILIZATION_THRESHOLD,
865
- type Phase,
866
- type EvalRunRecord,
867
- } from "./eval-history";
868
-
869
- /**
870
- * Re-export eval-gates module
871
- *
872
- * Includes:
873
- * - checkGate - Check if current score passes quality gate
874
- * - DEFAULT_THRESHOLDS - Default regression thresholds by phase
875
- *
876
- * Types:
877
- * - GateResult - Result from gate check
878
- * - GateConfig - Configuration for gate thresholds
879
- *
880
- * Features:
881
- * - Phase-based regression thresholds (Bootstrap: none, Stabilization: 10%, Production: 5%)
882
- * - Configurable thresholds via GateConfig
883
- * - Clear pass/fail messages with baseline comparison
884
- * - Handles edge cases (division by zero, no history)
885
- */
886
- export {
887
- checkGate,
888
- DEFAULT_THRESHOLDS,
889
- type GateResult,
890
- type GateConfig,
891
- } from "./eval-gates";
892
-
893
- /**
894
- * Re-export logger infrastructure
895
- *
896
- * Includes:
897
- * - getLogger - Gets or creates the main logger instance
898
- * - createChildLogger - Creates a module-specific child logger with separate log file
899
- * - logger - Default logger instance for immediate use
900
- *
901
- * Features:
902
- * - Daily log rotation via pino-roll (numeric format: swarm.1log, swarm.2log, etc.)
903
- * - 14-day retention
904
- * - Module-specific child loggers
905
- * - Pretty mode for development (SWARM_LOG_PRETTY=1)
906
- * - Logs to ~/.config/swarm-tools/logs/
907
- *
908
- * @example
909
- * ```typescript
910
- * import { logger, createChildLogger } from "opencode-swarm-plugin";
911
- *
912
- * // Use default logger
913
- * logger.info("Application started");
914
- *
915
- * // Create module-specific logger
916
- * const compactionLog = createChildLogger("compaction");
917
- * compactionLog.info("Compaction started");
918
- * ```
919
- */
920
- export { getLogger, createChildLogger, logger } from "./logger";
921
-
922
- /**
923
- * Re-export swarm-research module
924
- *
925
- * Includes:
926
- * - discoverDocTools - Discover available documentation tools
927
- * - getInstalledVersions - Get installed package versions from lockfile
928
- * - researchTools - Plugin tools for tool discovery and version detection
929
- *
930
- * Types:
931
- * - DiscoveredTool - Tool discovery result interface
932
- * - VersionInfo - Package version information
933
- */
934
- export {
935
- discoverDocTools,
936
- getInstalledVersions,
937
- researchTools,
938
- type DiscoveredTool,
939
- type VersionInfo,
940
- } from "./swarm-research";