opencode-swarm-plugin 0.43.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 (208) hide show
  1. package/bin/cass.characterization.test.ts +422 -0
  2. package/bin/swarm.serve.test.ts +6 -4
  3. package/bin/swarm.test.ts +68 -0
  4. package/bin/swarm.ts +81 -8
  5. package/dist/compaction-prompt-scoring.js +139 -0
  6. package/dist/contributor-tools.d.ts +42 -0
  7. package/dist/contributor-tools.d.ts.map +1 -0
  8. package/dist/eval-capture.js +12811 -0
  9. package/dist/hive.d.ts.map +1 -1
  10. package/dist/index.d.ts +12 -0
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +7728 -62590
  13. package/dist/plugin.js +23833 -78695
  14. package/dist/sessions/agent-discovery.d.ts +59 -0
  15. package/dist/sessions/agent-discovery.d.ts.map +1 -0
  16. package/dist/sessions/index.d.ts +10 -0
  17. package/dist/sessions/index.d.ts.map +1 -0
  18. package/dist/swarm-orchestrate.d.ts.map +1 -1
  19. package/dist/swarm-prompts.d.ts.map +1 -1
  20. package/dist/swarm-review.d.ts.map +1 -1
  21. package/package.json +17 -5
  22. package/.changeset/swarm-insights-data-layer.md +0 -63
  23. package/.hive/analysis/eval-failure-analysis-2025-12-25.md +0 -331
  24. package/.hive/analysis/session-data-quality-audit.md +0 -320
  25. package/.hive/eval-results.json +0 -483
  26. package/.hive/issues.jsonl +0 -138
  27. package/.hive/memories.jsonl +0 -729
  28. package/.opencode/eval-history.jsonl +0 -327
  29. package/.turbo/turbo-build.log +0 -9
  30. package/CHANGELOG.md +0 -2255
  31. package/SCORER-ANALYSIS.md +0 -598
  32. package/docs/analysis/subagent-coordination-patterns.md +0 -902
  33. package/docs/analysis-socratic-planner-pattern.md +0 -504
  34. package/docs/planning/ADR-001-monorepo-structure.md +0 -171
  35. package/docs/planning/ADR-002-package-extraction.md +0 -393
  36. package/docs/planning/ADR-003-performance-improvements.md +0 -451
  37. package/docs/planning/ADR-004-message-queue-features.md +0 -187
  38. package/docs/planning/ADR-005-devtools-observability.md +0 -202
  39. package/docs/planning/ADR-007-swarm-enhancements-worktree-review.md +0 -168
  40. package/docs/planning/ADR-008-worker-handoff-protocol.md +0 -293
  41. package/docs/planning/ADR-009-oh-my-opencode-patterns.md +0 -353
  42. package/docs/planning/ROADMAP.md +0 -368
  43. package/docs/semantic-memory-cli-syntax.md +0 -123
  44. package/docs/swarm-mail-architecture.md +0 -1147
  45. package/docs/testing/context-recovery-test.md +0 -470
  46. package/evals/ARCHITECTURE.md +0 -1189
  47. package/evals/README.md +0 -768
  48. package/evals/compaction-prompt.eval.ts +0 -149
  49. package/evals/compaction-resumption.eval.ts +0 -289
  50. package/evals/coordinator-behavior.eval.ts +0 -307
  51. package/evals/coordinator-session.eval.ts +0 -154
  52. package/evals/evalite.config.ts.bak +0 -15
  53. package/evals/example.eval.ts +0 -31
  54. package/evals/fixtures/compaction-cases.ts +0 -350
  55. package/evals/fixtures/compaction-prompt-cases.ts +0 -311
  56. package/evals/fixtures/coordinator-sessions.ts +0 -328
  57. package/evals/fixtures/decomposition-cases.ts +0 -105
  58. package/evals/lib/compaction-loader.test.ts +0 -248
  59. package/evals/lib/compaction-loader.ts +0 -320
  60. package/evals/lib/data-loader.evalite-test.ts +0 -289
  61. package/evals/lib/data-loader.test.ts +0 -345
  62. package/evals/lib/data-loader.ts +0 -281
  63. package/evals/lib/llm.ts +0 -115
  64. package/evals/scorers/compaction-prompt-scorers.ts +0 -145
  65. package/evals/scorers/compaction-scorers.ts +0 -305
  66. package/evals/scorers/coordinator-discipline.evalite-test.ts +0 -539
  67. package/evals/scorers/coordinator-discipline.ts +0 -325
  68. package/evals/scorers/index.test.ts +0 -146
  69. package/evals/scorers/index.ts +0 -328
  70. package/evals/scorers/outcome-scorers.evalite-test.ts +0 -27
  71. package/evals/scorers/outcome-scorers.ts +0 -349
  72. package/evals/swarm-decomposition.eval.ts +0 -121
  73. package/examples/commands/swarm.md +0 -745
  74. package/examples/plugin-wrapper-template.ts +0 -2426
  75. package/examples/skills/hive-workflow/SKILL.md +0 -212
  76. package/examples/skills/skill-creator/SKILL.md +0 -223
  77. package/examples/skills/swarm-coordination/SKILL.md +0 -292
  78. package/global-skills/cli-builder/SKILL.md +0 -344
  79. package/global-skills/cli-builder/references/advanced-patterns.md +0 -244
  80. package/global-skills/learning-systems/SKILL.md +0 -644
  81. package/global-skills/skill-creator/LICENSE.txt +0 -202
  82. package/global-skills/skill-creator/SKILL.md +0 -352
  83. package/global-skills/skill-creator/references/output-patterns.md +0 -82
  84. package/global-skills/skill-creator/references/workflows.md +0 -28
  85. package/global-skills/swarm-coordination/SKILL.md +0 -995
  86. package/global-skills/swarm-coordination/references/coordinator-patterns.md +0 -235
  87. package/global-skills/swarm-coordination/references/strategies.md +0 -138
  88. package/global-skills/system-design/SKILL.md +0 -213
  89. package/global-skills/testing-patterns/SKILL.md +0 -430
  90. package/global-skills/testing-patterns/references/dependency-breaking-catalog.md +0 -586
  91. package/opencode-swarm-plugin-0.30.7.tgz +0 -0
  92. package/opencode-swarm-plugin-0.31.0.tgz +0 -0
  93. package/scripts/cleanup-test-memories.ts +0 -346
  94. package/scripts/init-skill.ts +0 -222
  95. package/scripts/migrate-unknown-sessions.ts +0 -349
  96. package/scripts/validate-skill.ts +0 -204
  97. package/src/agent-mail.ts +0 -1724
  98. package/src/anti-patterns.test.ts +0 -1167
  99. package/src/anti-patterns.ts +0 -448
  100. package/src/compaction-capture.integration.test.ts +0 -257
  101. package/src/compaction-hook.test.ts +0 -838
  102. package/src/compaction-hook.ts +0 -1204
  103. package/src/compaction-observability.integration.test.ts +0 -139
  104. package/src/compaction-observability.test.ts +0 -187
  105. package/src/compaction-observability.ts +0 -324
  106. package/src/compaction-prompt-scorers.test.ts +0 -475
  107. package/src/compaction-prompt-scoring.ts +0 -300
  108. package/src/dashboard.test.ts +0 -611
  109. package/src/dashboard.ts +0 -462
  110. package/src/error-enrichment.test.ts +0 -403
  111. package/src/error-enrichment.ts +0 -219
  112. package/src/eval-capture.test.ts +0 -1015
  113. package/src/eval-capture.ts +0 -929
  114. package/src/eval-gates.test.ts +0 -306
  115. package/src/eval-gates.ts +0 -218
  116. package/src/eval-history.test.ts +0 -508
  117. package/src/eval-history.ts +0 -214
  118. package/src/eval-learning.test.ts +0 -378
  119. package/src/eval-learning.ts +0 -360
  120. package/src/eval-runner.test.ts +0 -223
  121. package/src/eval-runner.ts +0 -402
  122. package/src/export-tools.test.ts +0 -476
  123. package/src/export-tools.ts +0 -257
  124. package/src/hive.integration.test.ts +0 -2241
  125. package/src/hive.ts +0 -1628
  126. package/src/index.ts +0 -935
  127. package/src/learning.integration.test.ts +0 -1815
  128. package/src/learning.ts +0 -1079
  129. package/src/logger.test.ts +0 -189
  130. package/src/logger.ts +0 -135
  131. package/src/mandate-promotion.test.ts +0 -473
  132. package/src/mandate-promotion.ts +0 -239
  133. package/src/mandate-storage.integration.test.ts +0 -601
  134. package/src/mandate-storage.test.ts +0 -578
  135. package/src/mandate-storage.ts +0 -794
  136. package/src/mandates.ts +0 -540
  137. package/src/memory-tools.test.ts +0 -195
  138. package/src/memory-tools.ts +0 -344
  139. package/src/memory.integration.test.ts +0 -334
  140. package/src/memory.test.ts +0 -158
  141. package/src/memory.ts +0 -527
  142. package/src/model-selection.test.ts +0 -188
  143. package/src/model-selection.ts +0 -68
  144. package/src/observability-tools.test.ts +0 -359
  145. package/src/observability-tools.ts +0 -871
  146. package/src/output-guardrails.test.ts +0 -438
  147. package/src/output-guardrails.ts +0 -381
  148. package/src/pattern-maturity.test.ts +0 -1160
  149. package/src/pattern-maturity.ts +0 -525
  150. package/src/planning-guardrails.test.ts +0 -491
  151. package/src/planning-guardrails.ts +0 -438
  152. package/src/plugin.ts +0 -23
  153. package/src/post-compaction-tracker.test.ts +0 -251
  154. package/src/post-compaction-tracker.ts +0 -237
  155. package/src/query-tools.test.ts +0 -636
  156. package/src/query-tools.ts +0 -324
  157. package/src/rate-limiter.integration.test.ts +0 -466
  158. package/src/rate-limiter.ts +0 -774
  159. package/src/replay-tools.test.ts +0 -496
  160. package/src/replay-tools.ts +0 -240
  161. package/src/repo-crawl.integration.test.ts +0 -441
  162. package/src/repo-crawl.ts +0 -610
  163. package/src/schemas/cell-events.test.ts +0 -347
  164. package/src/schemas/cell-events.ts +0 -807
  165. package/src/schemas/cell.ts +0 -257
  166. package/src/schemas/evaluation.ts +0 -166
  167. package/src/schemas/index.test.ts +0 -199
  168. package/src/schemas/index.ts +0 -286
  169. package/src/schemas/mandate.ts +0 -232
  170. package/src/schemas/swarm-context.ts +0 -115
  171. package/src/schemas/task.ts +0 -161
  172. package/src/schemas/worker-handoff.test.ts +0 -302
  173. package/src/schemas/worker-handoff.ts +0 -131
  174. package/src/skills.integration.test.ts +0 -1192
  175. package/src/skills.test.ts +0 -643
  176. package/src/skills.ts +0 -1549
  177. package/src/storage.integration.test.ts +0 -341
  178. package/src/storage.ts +0 -884
  179. package/src/structured.integration.test.ts +0 -817
  180. package/src/structured.test.ts +0 -1046
  181. package/src/structured.ts +0 -762
  182. package/src/swarm-decompose.test.ts +0 -188
  183. package/src/swarm-decompose.ts +0 -1302
  184. package/src/swarm-deferred.integration.test.ts +0 -157
  185. package/src/swarm-deferred.test.ts +0 -38
  186. package/src/swarm-insights.test.ts +0 -214
  187. package/src/swarm-insights.ts +0 -459
  188. package/src/swarm-mail.integration.test.ts +0 -970
  189. package/src/swarm-mail.ts +0 -739
  190. package/src/swarm-orchestrate.integration.test.ts +0 -282
  191. package/src/swarm-orchestrate.test.ts +0 -548
  192. package/src/swarm-orchestrate.ts +0 -3084
  193. package/src/swarm-prompts.test.ts +0 -1270
  194. package/src/swarm-prompts.ts +0 -2077
  195. package/src/swarm-research.integration.test.ts +0 -701
  196. package/src/swarm-research.test.ts +0 -698
  197. package/src/swarm-research.ts +0 -472
  198. package/src/swarm-review.integration.test.ts +0 -285
  199. package/src/swarm-review.test.ts +0 -879
  200. package/src/swarm-review.ts +0 -709
  201. package/src/swarm-strategies.ts +0 -407
  202. package/src/swarm-worktree.test.ts +0 -501
  203. package/src/swarm-worktree.ts +0 -575
  204. package/src/swarm.integration.test.ts +0 -2377
  205. package/src/swarm.ts +0 -38
  206. package/src/tool-adapter.integration.test.ts +0 -1221
  207. package/src/tool-availability.ts +0 -461
  208. package/tsconfig.json +0 -28
package/src/mandates.ts DELETED
@@ -1,540 +0,0 @@
1
- /**
2
- * Mandates Module - Agent voting system for collaborative knowledge curation
3
- *
4
- * Agents file and vote on ideas, tips, lore, snippets, and feature requests.
5
- * High-consensus items become "mandates" that influence future behavior.
6
- *
7
- * Voting patterns:
8
- * - Each agent votes once per entry (upvote/downvote)
9
- * - Votes decay with 90-day half-life (matches learning.ts patterns)
10
- * - Status transitions:
11
- * - candidate → established: net_votes >= 2
12
- * - established → mandate: net_votes >= 5 AND vote_ratio >= 0.7
13
- * - any → rejected: net_votes <= -3
14
- *
15
- * Key responsibilities:
16
- * - Submit new mandate entries (ideas, tips, lore, snippets, feature requests)
17
- * - Cast votes on existing entries
18
- * - Query mandates with semantic search
19
- * - Calculate scores with decay
20
- * - Track voting statistics
21
- */
22
- import { tool } from "@opencode-ai/plugin";
23
- import {
24
- CreateMandateArgsSchema,
25
- MandateEntrySchema,
26
- VoteSchema,
27
- CastVoteArgsSchema,
28
- type MandateEntry,
29
- type Vote,
30
- type MandateContentType,
31
- type MandateStatus,
32
- } from "./schemas/mandate";
33
- import { getMandateStorage, updateMandateStatus } from "./mandate-storage";
34
- import { evaluatePromotion, formatPromotionResult } from "./mandate-promotion";
35
-
36
- // ============================================================================
37
- // Errors
38
- // ============================================================================
39
-
40
- export class MandateError extends Error {
41
- constructor(
42
- message: string,
43
- public readonly operation: string,
44
- public readonly details?: unknown,
45
- ) {
46
- super(message);
47
- this.name = "MandateError";
48
- }
49
- }
50
-
51
- // ============================================================================
52
- // ID Generation
53
- // ============================================================================
54
-
55
- /**
56
- * Generate a unique mandate ID
57
- *
58
- * Format: mandate-<timestamp>-<random>
59
- */
60
- function generateMandateId(): string {
61
- const timestamp = Date.now().toString(36);
62
- const random = Math.random().toString(36).substring(2, 8);
63
- return `mandate-${timestamp}-${random}`;
64
- }
65
-
66
- /**
67
- * Generate a unique vote ID
68
- *
69
- * Format: vote-<timestamp>-<random>
70
- */
71
- function generateVoteId(): string {
72
- const timestamp = Date.now().toString(36);
73
- const random = Math.random().toString(36).substring(2, 8);
74
- return `vote-${timestamp}-${random}`;
75
- }
76
-
77
- // ============================================================================
78
- // Tool Definitions
79
- // ============================================================================
80
-
81
- /**
82
- * Submit a new mandate entry
83
- *
84
- * Creates a new entry in the mandate system for voting.
85
- * Entries start in "candidate" status and can be promoted based on votes.
86
- */
87
- export const mandate_file = tool({
88
- description:
89
- "Submit a new idea, tip, lore, snippet, or feature request to the mandate system",
90
- args: {
91
- content: tool.schema.string().min(1).describe("The content to submit"),
92
- content_type: tool.schema
93
- .enum(["idea", "tip", "lore", "snippet", "feature_request"])
94
- .describe("Type of content"),
95
- tags: tool.schema
96
- .array(tool.schema.string())
97
- .optional()
98
- .describe("Optional tags for categorization"),
99
- metadata: tool.schema
100
- .record(tool.schema.string(), tool.schema.unknown())
101
- .optional()
102
- .describe("Optional metadata (e.g., code language for snippets)"),
103
- },
104
- async execute(args) {
105
- // Validate args
106
- const validated = CreateMandateArgsSchema.parse(args);
107
-
108
- // Get agent name from args or use default
109
- const agentName = "system";
110
-
111
- // Generate entry
112
- const entry: MandateEntry = {
113
- id: generateMandateId(),
114
- content: validated.content,
115
- content_type: validated.content_type,
116
- author_agent: agentName,
117
- created_at: new Date().toISOString(),
118
- status: "candidate",
119
- tags: validated.tags || [],
120
- metadata: validated.metadata,
121
- };
122
-
123
- // Validate schema
124
- const validatedEntry = MandateEntrySchema.parse(entry);
125
-
126
- // Store
127
- const storage = getMandateStorage();
128
- try {
129
- await storage.store(validatedEntry);
130
- } catch (error) {
131
- throw new MandateError(
132
- `Failed to store mandate: ${error instanceof Error ? error.message : String(error)}`,
133
- "mandate_file",
134
- error,
135
- );
136
- }
137
-
138
- return JSON.stringify(
139
- {
140
- success: true,
141
- mandate: validatedEntry,
142
- message: `Mandate ${validatedEntry.id} filed successfully`,
143
- },
144
- null,
145
- 2,
146
- );
147
- },
148
- });
149
-
150
- /**
151
- * Cast a vote on an existing mandate
152
- *
153
- * Each agent can vote once per mandate. Duplicate votes are rejected.
154
- * Votes influence mandate status through consensus scoring.
155
- */
156
- export const mandate_vote = tool({
157
- description: "Cast a vote (upvote or downvote) on an existing mandate",
158
- args: {
159
- mandate_id: tool.schema.string().describe("Mandate ID to vote on"),
160
- vote_type: tool.schema
161
- .enum(["upvote", "downvote"])
162
- .describe("Type of vote"),
163
- agent_name: tool.schema.string().describe("Agent name casting the vote"),
164
- },
165
- async execute(args) {
166
- // Validate args
167
- const validated = CastVoteArgsSchema.parse({
168
- mandate_id: args.mandate_id,
169
- vote_type: args.vote_type,
170
- weight: 1.0,
171
- });
172
-
173
- // Get storage
174
- const storage = getMandateStorage();
175
-
176
- // Check if mandate exists
177
- const mandate = await storage.get(validated.mandate_id);
178
- if (!mandate) {
179
- throw new MandateError(
180
- `Mandate '${validated.mandate_id}' not found. Use mandate_list() to see available mandates, or check the ID is correct.`,
181
- "mandate_vote",
182
- );
183
- }
184
-
185
- // Check if agent already voted
186
- const hasVoted = await storage.hasVoted(
187
- validated.mandate_id,
188
- args.agent_name,
189
- );
190
- if (hasVoted) {
191
- throw new MandateError(
192
- `Agent '${args.agent_name}' has already voted on mandate '${validated.mandate_id}'. Each agent can vote once per mandate. This is expected behavior to prevent vote manipulation.`,
193
- "mandate_vote",
194
- );
195
- }
196
-
197
- // Create vote
198
- const vote: Vote = {
199
- id: generateVoteId(),
200
- mandate_id: validated.mandate_id,
201
- agent_name: args.agent_name,
202
- vote_type: validated.vote_type,
203
- timestamp: new Date().toISOString(),
204
- weight: validated.weight,
205
- };
206
-
207
- // Validate schema
208
- const validatedVote = VoteSchema.parse(vote);
209
-
210
- // Store vote
211
- try {
212
- await storage.vote(validatedVote);
213
- } catch (error) {
214
- throw new MandateError(
215
- `Failed to cast vote: ${error instanceof Error ? error.message : String(error)}`,
216
- "mandate_vote",
217
- error,
218
- );
219
- }
220
-
221
- // Recalculate score and update status
222
- const promotion = await updateMandateStatus(validated.mandate_id, storage);
223
-
224
- return JSON.stringify(
225
- {
226
- success: true,
227
- vote: validatedVote,
228
- promotion: {
229
- previous_status: promotion.previous_status,
230
- new_status: promotion.new_status,
231
- status_changed: promotion.status_changed,
232
- score: promotion.score,
233
- },
234
- message: formatPromotionResult({
235
- mandate_id: promotion.mandate_id,
236
- previous_status: promotion.previous_status,
237
- new_status: promotion.new_status,
238
- score: promotion.score,
239
- promoted: promotion.status_changed,
240
- reason:
241
- evaluatePromotion(mandate, promotion.score).reason ||
242
- "Vote recorded",
243
- }),
244
- },
245
- null,
246
- 2,
247
- );
248
- },
249
- });
250
-
251
- /**
252
- * Search for relevant mandates using semantic search
253
- *
254
- * Queries the mandate system by meaning, not just keywords.
255
- * Useful for finding past decisions or patterns related to a topic.
256
- */
257
- export const mandate_query = tool({
258
- description:
259
- "Search for relevant mandates using semantic search (by meaning, not keywords)",
260
- args: {
261
- query: tool.schema.string().min(1).describe("Natural language query"),
262
- limit: tool.schema
263
- .number()
264
- .int()
265
- .positive()
266
- .optional()
267
- .describe("Max results to return (default: 5)"),
268
- status: tool.schema
269
- .enum(["candidate", "established", "mandate", "rejected"])
270
- .optional()
271
- .describe("Filter by status"),
272
- content_type: tool.schema
273
- .enum(["idea", "tip", "lore", "snippet", "feature_request"])
274
- .optional()
275
- .describe("Filter by content type"),
276
- },
277
- async execute(args) {
278
- const storage = getMandateStorage();
279
- const limit = args.limit ?? 5;
280
-
281
- try {
282
- // Semantic search for mandates
283
- let results = await storage.find(args.query, limit * 2); // Get extra for filtering
284
-
285
- // Apply filters
286
- if (args.status) {
287
- results = results.filter((m) => m.status === args.status);
288
- }
289
- if (args.content_type) {
290
- results = results.filter((m) => m.content_type === args.content_type);
291
- }
292
-
293
- // Limit results
294
- results = results.slice(0, limit);
295
-
296
- // Calculate scores for results
297
- const resultsWithScores = await Promise.all(
298
- results.map(async (mandate) => {
299
- const score = await storage.calculateScore(mandate.id);
300
- return { mandate, score };
301
- }),
302
- );
303
-
304
- // Sort by decayed score (highest first)
305
- resultsWithScores.sort(
306
- (a, b) => b.score.decayed_score - a.score.decayed_score,
307
- );
308
-
309
- return JSON.stringify(
310
- {
311
- query: args.query,
312
- count: resultsWithScores.length,
313
- results: resultsWithScores.map(({ mandate, score }) => ({
314
- id: mandate.id,
315
- content: mandate.content,
316
- content_type: mandate.content_type,
317
- status: mandate.status,
318
- author: mandate.author_agent,
319
- created_at: mandate.created_at,
320
- tags: mandate.tags,
321
- score: {
322
- net_votes: score.net_votes,
323
- vote_ratio: score.vote_ratio,
324
- decayed_score: score.decayed_score,
325
- },
326
- })),
327
- },
328
- null,
329
- 2,
330
- );
331
- } catch (error) {
332
- throw new MandateError(
333
- `Failed to query mandates: ${error instanceof Error ? error.message : String(error)}`,
334
- "mandate_query",
335
- error,
336
- );
337
- }
338
- },
339
- });
340
-
341
- /**
342
- * List mandates with optional filters
343
- *
344
- * Retrieves mandates by status, content type, or both.
345
- * Does not use semantic search - returns all matching mandates.
346
- */
347
- export const mandate_list = tool({
348
- description: "List mandates with optional filters (status, content type)",
349
- args: {
350
- status: tool.schema
351
- .enum(["candidate", "established", "mandate", "rejected"])
352
- .optional()
353
- .describe("Filter by status"),
354
- content_type: tool.schema
355
- .enum(["idea", "tip", "lore", "snippet", "feature_request"])
356
- .optional()
357
- .describe("Filter by content type"),
358
- limit: tool.schema
359
- .number()
360
- .int()
361
- .positive()
362
- .optional()
363
- .describe("Max results to return (default: 20)"),
364
- },
365
- async execute(args) {
366
- const storage = getMandateStorage();
367
- const limit = args.limit ?? 20;
368
-
369
- try {
370
- // List with filters
371
- let results = await storage.list({
372
- status: args.status as MandateStatus | undefined,
373
- content_type: args.content_type as MandateContentType | undefined,
374
- });
375
-
376
- // Limit results
377
- results = results.slice(0, limit);
378
-
379
- // Calculate scores for results
380
- const resultsWithScores = await Promise.all(
381
- results.map(async (mandate) => {
382
- const score = await storage.calculateScore(mandate.id);
383
- return { mandate, score };
384
- }),
385
- );
386
-
387
- // Sort by decayed score (highest first)
388
- resultsWithScores.sort(
389
- (a, b) => b.score.decayed_score - a.score.decayed_score,
390
- );
391
-
392
- return JSON.stringify(
393
- {
394
- filters: {
395
- status: args.status || "all",
396
- content_type: args.content_type || "all",
397
- },
398
- count: resultsWithScores.length,
399
- results: resultsWithScores.map(({ mandate, score }) => ({
400
- id: mandate.id,
401
- content: mandate.content.slice(0, 200), // Truncate for list view
402
- content_type: mandate.content_type,
403
- status: mandate.status,
404
- author: mandate.author_agent,
405
- created_at: mandate.created_at,
406
- tags: mandate.tags,
407
- score: {
408
- net_votes: score.net_votes,
409
- vote_ratio: score.vote_ratio,
410
- decayed_score: score.decayed_score,
411
- },
412
- })),
413
- },
414
- null,
415
- 2,
416
- );
417
- } catch (error) {
418
- throw new MandateError(
419
- `Failed to list mandates: ${error instanceof Error ? error.message : String(error)}`,
420
- "mandate_list",
421
- error,
422
- );
423
- }
424
- },
425
- });
426
-
427
- /**
428
- * Get voting statistics for a mandate or overall system
429
- *
430
- * If mandate_id is provided, returns detailed stats for that mandate.
431
- * Otherwise, returns aggregate stats across all mandates.
432
- */
433
- export const mandate_stats = tool({
434
- description: "Get voting statistics for a specific mandate or overall system",
435
- args: {
436
- mandate_id: tool.schema
437
- .string()
438
- .optional()
439
- .describe("Mandate ID (omit for overall stats)"),
440
- },
441
- async execute(args) {
442
- const storage = getMandateStorage();
443
-
444
- try {
445
- if (args.mandate_id) {
446
- // Stats for specific mandate
447
- const mandate = await storage.get(args.mandate_id);
448
- if (!mandate) {
449
- throw new MandateError(
450
- `Mandate '${args.mandate_id}' not found. Use mandate_list() to see available mandates, or check the ID is correct.`,
451
- "mandate_stats",
452
- );
453
- }
454
-
455
- const score = await storage.calculateScore(args.mandate_id);
456
- const votes = await storage.getVotes(args.mandate_id);
457
-
458
- return JSON.stringify(
459
- {
460
- mandate_id: args.mandate_id,
461
- status: mandate.status,
462
- content_type: mandate.content_type,
463
- author: mandate.author_agent,
464
- created_at: mandate.created_at,
465
- votes: {
466
- total: votes.length,
467
- raw_upvotes: score.raw_upvotes,
468
- raw_downvotes: score.raw_downvotes,
469
- decayed_upvotes: score.decayed_upvotes,
470
- decayed_downvotes: score.decayed_downvotes,
471
- net_votes: score.net_votes,
472
- vote_ratio: score.vote_ratio,
473
- decayed_score: score.decayed_score,
474
- },
475
- voters: votes.map((v) => ({
476
- agent: v.agent_name,
477
- vote_type: v.vote_type,
478
- timestamp: v.timestamp,
479
- })),
480
- },
481
- null,
482
- 2,
483
- );
484
- } else {
485
- // Overall system stats
486
- const allMandates = await storage.list();
487
-
488
- // Calculate aggregate stats
489
- const stats = {
490
- total_mandates: allMandates.length,
491
- by_status: {
492
- candidate: 0,
493
- established: 0,
494
- mandate: 0,
495
- rejected: 0,
496
- },
497
- by_content_type: {
498
- idea: 0,
499
- tip: 0,
500
- lore: 0,
501
- snippet: 0,
502
- feature_request: 0,
503
- },
504
- total_votes: 0,
505
- };
506
-
507
- for (const mandate of allMandates) {
508
- stats.by_status[mandate.status]++;
509
- stats.by_content_type[mandate.content_type]++;
510
-
511
- const votes = await storage.getVotes(mandate.id);
512
- stats.total_votes += votes.length;
513
- }
514
-
515
- return JSON.stringify(stats, null, 2);
516
- }
517
- } catch (error) {
518
- if (error instanceof MandateError) {
519
- throw error;
520
- }
521
- throw new MandateError(
522
- `Failed to get mandate stats: ${error instanceof Error ? error.message : String(error)}`,
523
- "mandate_stats",
524
- error,
525
- );
526
- }
527
- },
528
- });
529
-
530
- // ============================================================================
531
- // Export all tools
532
- // ============================================================================
533
-
534
- export const mandateTools = {
535
- mandate_file,
536
- mandate_vote,
537
- mandate_query,
538
- mandate_list,
539
- mandate_stats,
540
- };