opencode-swarm-plugin 0.15.0 → 0.16.0

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.
@@ -0,0 +1,540 @@
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`,
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}`,
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`,
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
+ };
@@ -75,3 +75,30 @@ export {
75
75
  type AgentProgress,
76
76
  type SwarmStatus,
77
77
  } from "./task";
78
+
79
+ // Mandate schemas
80
+ export {
81
+ MandateContentTypeSchema,
82
+ MandateStatusSchema,
83
+ VoteTypeSchema,
84
+ MandateEntrySchema,
85
+ VoteSchema,
86
+ MandateScoreSchema,
87
+ CreateMandateArgsSchema,
88
+ CastVoteArgsSchema,
89
+ QueryMandatesArgsSchema,
90
+ ScoreCalculationResultSchema,
91
+ DEFAULT_MANDATE_DECAY_CONFIG,
92
+ mandateSchemas,
93
+ type MandateContentType,
94
+ type MandateStatus,
95
+ type VoteType,
96
+ type MandateEntry,
97
+ type Vote,
98
+ type MandateScore,
99
+ type MandateDecayConfig,
100
+ type CreateMandateArgs,
101
+ type CastVoteArgs,
102
+ type QueryMandatesArgs,
103
+ type ScoreCalculationResult,
104
+ } from "./mandate";