opencode-swarm-plugin 0.14.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,786 @@
1
+ /**
2
+ * Mandate Storage Module - Persistent storage for agent voting system
3
+ *
4
+ * Provides unified storage interface for mandate entries and votes:
5
+ * - semantic-memory (default) - Persistent with semantic search
6
+ * - in-memory - For testing and ephemeral sessions
7
+ *
8
+ * Collections:
9
+ * - `swarm-mandates` - Mandate entry storage
10
+ * - `swarm-votes` - Vote storage
11
+ *
12
+ * Score calculation uses 90-day half-life decay matching learning.ts patterns.
13
+ *
14
+ * @example
15
+ * ```typescript
16
+ * // Use default semantic-memory storage
17
+ * const storage = createMandateStorage();
18
+ *
19
+ * // Or in-memory for testing
20
+ * const storage = createMandateStorage({ backend: "memory" });
21
+ *
22
+ * // Store a mandate
23
+ * await storage.store({
24
+ * id: "mandate-123",
25
+ * content: "Always use Effect for async operations",
26
+ * content_type: "tip",
27
+ * author_agent: "BlueLake",
28
+ * created_at: new Date().toISOString(),
29
+ * status: "candidate",
30
+ * tags: ["async", "effect"]
31
+ * });
32
+ *
33
+ * // Cast a vote
34
+ * await storage.vote({
35
+ * id: "vote-456",
36
+ * mandate_id: "mandate-123",
37
+ * agent_name: "BlueLake",
38
+ * vote_type: "upvote",
39
+ * timestamp: new Date().toISOString(),
40
+ * weight: 1.0
41
+ * });
42
+ *
43
+ * // Calculate score with decay
44
+ * const score = await storage.calculateScore("mandate-123");
45
+ * ```
46
+ */
47
+
48
+ import type {
49
+ MandateEntry,
50
+ Vote,
51
+ MandateScore,
52
+ MandateStatus,
53
+ MandateContentType,
54
+ MandateDecayConfig,
55
+ ScoreCalculationResult,
56
+ } from "./schemas/mandate";
57
+ import { DEFAULT_MANDATE_DECAY_CONFIG } from "./schemas/mandate";
58
+ import { calculateDecayedValue } from "./learning";
59
+
60
+ // ============================================================================
61
+ // Command Resolution (copied from storage.ts pattern)
62
+ // ============================================================================
63
+
64
+ /**
65
+ * Cached semantic-memory command (native or bunx fallback)
66
+ */
67
+ let cachedCommand: string[] | null = null;
68
+
69
+ /**
70
+ * Resolve the semantic-memory command
71
+ *
72
+ * Checks for native install first, falls back to bunx.
73
+ * Result is cached for the session.
74
+ */
75
+ async function resolveSemanticMemoryCommand(): Promise<string[]> {
76
+ if (cachedCommand) return cachedCommand;
77
+
78
+ // Try native install first
79
+ const nativeResult = await Bun.$`which semantic-memory`.quiet().nothrow();
80
+ if (nativeResult.exitCode === 0) {
81
+ cachedCommand = ["semantic-memory"];
82
+ return cachedCommand;
83
+ }
84
+
85
+ // Fall back to bunx
86
+ cachedCommand = ["bunx", "semantic-memory"];
87
+ return cachedCommand;
88
+ }
89
+
90
+ /**
91
+ * Execute semantic-memory command with args
92
+ */
93
+ async function execSemanticMemory(
94
+ args: string[],
95
+ ): Promise<{ exitCode: number; stdout: Buffer; stderr: Buffer }> {
96
+ try {
97
+ const cmd = await resolveSemanticMemoryCommand();
98
+ const fullCmd = [...cmd, ...args];
99
+
100
+ // Use Bun.spawn for dynamic command arrays
101
+ const proc = Bun.spawn(fullCmd, {
102
+ stdout: "pipe",
103
+ stderr: "pipe",
104
+ });
105
+
106
+ try {
107
+ const stdout = Buffer.from(await new Response(proc.stdout).arrayBuffer());
108
+ const stderr = Buffer.from(await new Response(proc.stderr).arrayBuffer());
109
+ const exitCode = await proc.exited;
110
+
111
+ return { exitCode, stdout, stderr };
112
+ } finally {
113
+ // Ensure process cleanup
114
+ proc.kill();
115
+ }
116
+ } catch (error) {
117
+ // Return structured error result on exceptions
118
+ const errorMessage = error instanceof Error ? error.message : String(error);
119
+ return {
120
+ exitCode: 1,
121
+ stdout: Buffer.from(""),
122
+ stderr: Buffer.from(`Error executing semantic-memory: ${errorMessage}`),
123
+ };
124
+ }
125
+ }
126
+
127
+ /**
128
+ * Reset the cached command (for testing)
129
+ */
130
+ export function resetCommandCache(): void {
131
+ cachedCommand = null;
132
+ }
133
+
134
+ // ============================================================================
135
+ // Configuration
136
+ // ============================================================================
137
+
138
+ /**
139
+ * Storage backend type
140
+ */
141
+ export type MandateStorageBackend = "semantic-memory" | "memory";
142
+
143
+ /**
144
+ * Collection names for semantic-memory
145
+ */
146
+ export interface MandateStorageCollections {
147
+ mandates: string;
148
+ votes: string;
149
+ }
150
+
151
+ /**
152
+ * Storage configuration
153
+ */
154
+ export interface MandateStorageConfig {
155
+ /** Backend to use (default: "semantic-memory") */
156
+ backend: MandateStorageBackend;
157
+ /** Collection names for semantic-memory backend */
158
+ collections: MandateStorageCollections;
159
+ /** Decay configuration */
160
+ decay: MandateDecayConfig;
161
+ /** Whether to use semantic search for queries (default: true) */
162
+ useSemanticSearch: boolean;
163
+ }
164
+
165
+ export const DEFAULT_MANDATE_STORAGE_CONFIG: MandateStorageConfig = {
166
+ backend: "semantic-memory",
167
+ collections: {
168
+ mandates: "swarm-mandates",
169
+ votes: "swarm-votes",
170
+ },
171
+ decay: DEFAULT_MANDATE_DECAY_CONFIG,
172
+ useSemanticSearch: true,
173
+ };
174
+
175
+ // ============================================================================
176
+ // Unified Storage Interface
177
+ // ============================================================================
178
+
179
+ /**
180
+ * Unified storage interface for mandate data
181
+ */
182
+ export interface MandateStorage {
183
+ // Entry operations
184
+ store(entry: MandateEntry): Promise<void>;
185
+ get(id: string): Promise<MandateEntry | null>;
186
+ find(query: string, limit?: number): Promise<MandateEntry[]>;
187
+ list(filter?: {
188
+ status?: MandateStatus;
189
+ content_type?: MandateContentType;
190
+ }): Promise<MandateEntry[]>;
191
+ update(id: string, updates: Partial<MandateEntry>): Promise<void>;
192
+
193
+ // Vote operations
194
+ vote(vote: Vote): Promise<void>;
195
+ getVotes(mandateId: string): Promise<Vote[]>;
196
+ hasVoted(mandateId: string, agentName: string): Promise<boolean>;
197
+
198
+ // Score calculation
199
+ calculateScore(mandateId: string): Promise<MandateScore>;
200
+
201
+ // Lifecycle
202
+ close(): Promise<void>;
203
+ }
204
+
205
+ // ============================================================================
206
+ // Semantic Memory Storage Implementation
207
+ // ============================================================================
208
+
209
+ /**
210
+ * Semantic-memory backed mandate storage
211
+ *
212
+ * Uses the semantic-memory CLI for persistence with semantic search.
213
+ * Data survives across sessions and can be searched by meaning.
214
+ */
215
+ export class SemanticMemoryMandateStorage implements MandateStorage {
216
+ private config: MandateStorageConfig;
217
+
218
+ constructor(config: Partial<MandateStorageConfig> = {}) {
219
+ this.config = { ...DEFAULT_MANDATE_STORAGE_CONFIG, ...config };
220
+ }
221
+
222
+ // -------------------------------------------------------------------------
223
+ // Helpers
224
+ // -------------------------------------------------------------------------
225
+
226
+ private async storeInternal(
227
+ collection: string,
228
+ data: unknown,
229
+ metadata?: Record<string, unknown>,
230
+ ): Promise<void> {
231
+ const content = typeof data === "string" ? data : JSON.stringify(data);
232
+ const args = ["store", content, "--collection", collection];
233
+
234
+ if (metadata) {
235
+ args.push("--metadata", JSON.stringify(metadata));
236
+ }
237
+
238
+ await execSemanticMemory(args);
239
+ }
240
+
241
+ private async findInternal<T>(
242
+ collection: string,
243
+ query: string,
244
+ limit: number = 10,
245
+ useFts: boolean = false,
246
+ ): Promise<T[]> {
247
+ const args = [
248
+ "find",
249
+ query,
250
+ "--collection",
251
+ collection,
252
+ "--limit",
253
+ String(limit),
254
+ "--json",
255
+ ];
256
+
257
+ if (useFts) {
258
+ args.push("--fts");
259
+ }
260
+
261
+ const result = await execSemanticMemory(args);
262
+
263
+ if (result.exitCode !== 0) {
264
+ console.warn(
265
+ `[mandate-storage] semantic-memory find() failed with exit code ${result.exitCode}: ${result.stderr.toString().trim()}`,
266
+ );
267
+ return [];
268
+ }
269
+
270
+ try {
271
+ const output = result.stdout.toString().trim();
272
+ if (!output) return [];
273
+
274
+ const parsed = JSON.parse(output);
275
+ // semantic-memory returns { results: [...] } or just [...]
276
+ const results = Array.isArray(parsed) ? parsed : parsed.results || [];
277
+
278
+ // Extract the stored content from each result
279
+ return results.map((r: { content?: string; information?: string }) => {
280
+ const content = r.content || r.information || "";
281
+ try {
282
+ return JSON.parse(content);
283
+ } catch {
284
+ return content;
285
+ }
286
+ });
287
+ } catch (error) {
288
+ console.warn(
289
+ `[mandate-storage] Failed to parse semantic-memory find() output: ${error instanceof Error ? error.message : String(error)}`,
290
+ );
291
+ return [];
292
+ }
293
+ }
294
+
295
+ private async listInternal<T>(collection: string): Promise<T[]> {
296
+ const result = await execSemanticMemory([
297
+ "list",
298
+ "--collection",
299
+ collection,
300
+ "--json",
301
+ ]);
302
+
303
+ if (result.exitCode !== 0) {
304
+ console.warn(
305
+ `[mandate-storage] semantic-memory list() failed with exit code ${result.exitCode}: ${result.stderr.toString().trim()}`,
306
+ );
307
+ return [];
308
+ }
309
+
310
+ try {
311
+ const output = result.stdout.toString().trim();
312
+ if (!output) return [];
313
+
314
+ const parsed = JSON.parse(output);
315
+ const items = Array.isArray(parsed) ? parsed : parsed.items || [];
316
+
317
+ return items.map((item: { content?: string; information?: string }) => {
318
+ const content = item.content || item.information || "";
319
+ try {
320
+ return JSON.parse(content);
321
+ } catch {
322
+ return content;
323
+ }
324
+ });
325
+ } catch (error) {
326
+ console.warn(
327
+ `[mandate-storage] Failed to parse semantic-memory list() output: ${error instanceof Error ? error.message : String(error)}`,
328
+ );
329
+ return [];
330
+ }
331
+ }
332
+
333
+ // -------------------------------------------------------------------------
334
+ // Entry Operations
335
+ // -------------------------------------------------------------------------
336
+
337
+ async store(entry: MandateEntry): Promise<void> {
338
+ await this.storeInternal(this.config.collections.mandates, entry, {
339
+ id: entry.id,
340
+ content_type: entry.content_type,
341
+ author_agent: entry.author_agent,
342
+ status: entry.status,
343
+ tags: entry.tags.join(","),
344
+ created_at: entry.created_at,
345
+ });
346
+ }
347
+
348
+ async get(id: string): Promise<MandateEntry | null> {
349
+ // List all and filter by ID - FTS search by ID is unreliable
350
+ const all = await this.listInternal<MandateEntry>(
351
+ this.config.collections.mandates,
352
+ );
353
+ return all.find((entry) => entry.id === id) || null;
354
+ }
355
+
356
+ async find(query: string, limit: number = 10): Promise<MandateEntry[]> {
357
+ return this.findInternal<MandateEntry>(
358
+ this.config.collections.mandates,
359
+ query,
360
+ limit,
361
+ !this.config.useSemanticSearch,
362
+ );
363
+ }
364
+
365
+ async list(filter?: {
366
+ status?: MandateStatus;
367
+ content_type?: MandateContentType;
368
+ }): Promise<MandateEntry[]> {
369
+ const all = await this.listInternal<MandateEntry>(
370
+ this.config.collections.mandates,
371
+ );
372
+
373
+ if (!filter) return all;
374
+
375
+ return all.filter((entry) => {
376
+ if (filter.status && entry.status !== filter.status) return false;
377
+ if (filter.content_type && entry.content_type !== filter.content_type)
378
+ return false;
379
+ return true;
380
+ });
381
+ }
382
+
383
+ async update(id: string, updates: Partial<MandateEntry>): Promise<void> {
384
+ const existing = await this.get(id);
385
+ if (!existing) {
386
+ throw new Error(`Mandate ${id} not found`);
387
+ }
388
+
389
+ const updated = { ...existing, ...updates };
390
+ await this.store(updated);
391
+ }
392
+
393
+ // -------------------------------------------------------------------------
394
+ // Vote Operations
395
+ // -------------------------------------------------------------------------
396
+
397
+ async vote(vote: Vote): Promise<void> {
398
+ // Check for duplicate votes
399
+ const existing = await this.hasVoted(vote.mandate_id, vote.agent_name);
400
+ if (existing) {
401
+ throw new Error(
402
+ `Agent ${vote.agent_name} has already voted on mandate ${vote.mandate_id}`,
403
+ );
404
+ }
405
+
406
+ await this.storeInternal(this.config.collections.votes, vote, {
407
+ id: vote.id,
408
+ mandate_id: vote.mandate_id,
409
+ agent_name: vote.agent_name,
410
+ vote_type: vote.vote_type,
411
+ timestamp: vote.timestamp,
412
+ weight: vote.weight,
413
+ });
414
+ }
415
+
416
+ async getVotes(mandateId: string): Promise<Vote[]> {
417
+ // List all votes and filter by mandate_id
418
+ const all = await this.listInternal<Vote>(this.config.collections.votes);
419
+ return all.filter((vote) => vote.mandate_id === mandateId);
420
+ }
421
+
422
+ async hasVoted(mandateId: string, agentName: string): Promise<boolean> {
423
+ const votes = await this.getVotes(mandateId);
424
+ return votes.some((vote) => vote.agent_name === agentName);
425
+ }
426
+
427
+ // -------------------------------------------------------------------------
428
+ // Score Calculation
429
+ // -------------------------------------------------------------------------
430
+
431
+ async calculateScore(mandateId: string): Promise<MandateScore> {
432
+ const votes = await this.getVotes(mandateId);
433
+ const now = new Date();
434
+
435
+ let rawUpvotes = 0;
436
+ let rawDownvotes = 0;
437
+ let decayedUpvotes = 0;
438
+ let decayedDownvotes = 0;
439
+
440
+ for (const vote of votes) {
441
+ const decayed = calculateDecayedValue(
442
+ vote.timestamp,
443
+ now,
444
+ this.config.decay.halfLifeDays,
445
+ );
446
+ const value = vote.weight * decayed;
447
+
448
+ if (vote.vote_type === "upvote") {
449
+ rawUpvotes++;
450
+ decayedUpvotes += value;
451
+ } else {
452
+ rawDownvotes++;
453
+ decayedDownvotes += value;
454
+ }
455
+ }
456
+
457
+ const totalDecayed = decayedUpvotes + decayedDownvotes;
458
+ const voteRatio = totalDecayed > 0 ? decayedUpvotes / totalDecayed : 0;
459
+ const netVotes = decayedUpvotes - decayedDownvotes;
460
+
461
+ // Score combines net votes with vote ratio
462
+ // Higher ratio = more consensus, net votes = strength
463
+ const decayedScore = netVotes * voteRatio;
464
+
465
+ return {
466
+ mandate_id: mandateId,
467
+ net_votes: netVotes,
468
+ vote_ratio: voteRatio,
469
+ decayed_score: decayedScore,
470
+ last_calculated: now.toISOString(),
471
+ raw_upvotes: rawUpvotes,
472
+ raw_downvotes: rawDownvotes,
473
+ decayed_upvotes: decayedUpvotes,
474
+ decayed_downvotes: decayedDownvotes,
475
+ };
476
+ }
477
+
478
+ async close(): Promise<void> {
479
+ // No cleanup needed for CLI-based storage
480
+ }
481
+ }
482
+
483
+ // ============================================================================
484
+ // In-Memory Storage Implementation
485
+ // ============================================================================
486
+
487
+ /**
488
+ * In-memory mandate storage
489
+ *
490
+ * Useful for testing and ephemeral sessions.
491
+ */
492
+ export class InMemoryMandateStorage implements MandateStorage {
493
+ private entries: Map<string, MandateEntry> = new Map();
494
+ private votes: Map<string, Vote> = new Map();
495
+ private config: MandateDecayConfig;
496
+
497
+ constructor(config: Partial<MandateStorageConfig> = {}) {
498
+ const fullConfig = { ...DEFAULT_MANDATE_STORAGE_CONFIG, ...config };
499
+ this.config = fullConfig.decay;
500
+ }
501
+
502
+ // Entry operations
503
+ async store(entry: MandateEntry): Promise<void> {
504
+ this.entries.set(entry.id, entry);
505
+ }
506
+
507
+ async get(id: string): Promise<MandateEntry | null> {
508
+ return this.entries.get(id) || null;
509
+ }
510
+
511
+ async find(query: string, limit: number = 10): Promise<MandateEntry[]> {
512
+ // Simple text search for in-memory (no semantic search)
513
+ const lowerQuery = query.toLowerCase();
514
+ const results = Array.from(this.entries.values()).filter(
515
+ (entry) =>
516
+ entry.content.toLowerCase().includes(lowerQuery) ||
517
+ entry.tags.some((tag) => tag.toLowerCase().includes(lowerQuery)),
518
+ );
519
+ return results.slice(0, limit);
520
+ }
521
+
522
+ async list(filter?: {
523
+ status?: MandateStatus;
524
+ content_type?: MandateContentType;
525
+ }): Promise<MandateEntry[]> {
526
+ let results = Array.from(this.entries.values());
527
+
528
+ if (filter) {
529
+ results = results.filter((entry) => {
530
+ if (filter.status && entry.status !== filter.status) return false;
531
+ if (filter.content_type && entry.content_type !== filter.content_type)
532
+ return false;
533
+ return true;
534
+ });
535
+ }
536
+
537
+ return results;
538
+ }
539
+
540
+ async update(id: string, updates: Partial<MandateEntry>): Promise<void> {
541
+ const existing = await this.get(id);
542
+ if (!existing) {
543
+ throw new Error(`Mandate ${id} not found`);
544
+ }
545
+
546
+ const updated = { ...existing, ...updates };
547
+ this.entries.set(id, updated);
548
+ }
549
+
550
+ // Vote operations
551
+ async vote(vote: Vote): Promise<void> {
552
+ // Check for duplicate votes
553
+ const existing = await this.hasVoted(vote.mandate_id, vote.agent_name);
554
+ if (existing) {
555
+ throw new Error(
556
+ `Agent ${vote.agent_name} has already voted on mandate ${vote.mandate_id}`,
557
+ );
558
+ }
559
+
560
+ this.votes.set(vote.id, vote);
561
+ }
562
+
563
+ async getVotes(mandateId: string): Promise<Vote[]> {
564
+ return Array.from(this.votes.values()).filter(
565
+ (vote) => vote.mandate_id === mandateId,
566
+ );
567
+ }
568
+
569
+ async hasVoted(mandateId: string, agentName: string): Promise<boolean> {
570
+ const votes = await this.getVotes(mandateId);
571
+ return votes.some((vote) => vote.agent_name === agentName);
572
+ }
573
+
574
+ // Score calculation
575
+ async calculateScore(mandateId: string): Promise<MandateScore> {
576
+ const votes = await this.getVotes(mandateId);
577
+ const now = new Date();
578
+
579
+ let rawUpvotes = 0;
580
+ let rawDownvotes = 0;
581
+ let decayedUpvotes = 0;
582
+ let decayedDownvotes = 0;
583
+
584
+ for (const vote of votes) {
585
+ const decayed = calculateDecayedValue(
586
+ vote.timestamp,
587
+ now,
588
+ this.config.halfLifeDays,
589
+ );
590
+ const value = vote.weight * decayed;
591
+
592
+ if (vote.vote_type === "upvote") {
593
+ rawUpvotes++;
594
+ decayedUpvotes += value;
595
+ } else {
596
+ rawDownvotes++;
597
+ decayedDownvotes += value;
598
+ }
599
+ }
600
+
601
+ const totalDecayed = decayedUpvotes + decayedDownvotes;
602
+ const voteRatio = totalDecayed > 0 ? decayedUpvotes / totalDecayed : 0;
603
+ const netVotes = decayedUpvotes - decayedDownvotes;
604
+
605
+ // Score combines net votes with vote ratio
606
+ const decayedScore = netVotes * voteRatio;
607
+
608
+ return {
609
+ mandate_id: mandateId,
610
+ net_votes: netVotes,
611
+ vote_ratio: voteRatio,
612
+ decayed_score: decayedScore,
613
+ last_calculated: now.toISOString(),
614
+ raw_upvotes: rawUpvotes,
615
+ raw_downvotes: rawDownvotes,
616
+ decayed_upvotes: decayedUpvotes,
617
+ decayed_downvotes: decayedDownvotes,
618
+ };
619
+ }
620
+
621
+ async close(): Promise<void> {
622
+ // No cleanup needed
623
+ }
624
+ }
625
+
626
+ // ============================================================================
627
+ // Factory
628
+ // ============================================================================
629
+
630
+ /**
631
+ * Create a mandate storage instance
632
+ *
633
+ * @param config - Storage configuration (default: semantic-memory)
634
+ * @returns Configured storage instance
635
+ *
636
+ * @example
637
+ * ```typescript
638
+ * // Default semantic-memory storage
639
+ * const storage = createMandateStorage();
640
+ *
641
+ * // In-memory for testing
642
+ * const storage = createMandateStorage({ backend: "memory" });
643
+ *
644
+ * // Custom collections
645
+ * const storage = createMandateStorage({
646
+ * backend: "semantic-memory",
647
+ * collections: {
648
+ * mandates: "my-mandates",
649
+ * votes: "my-votes",
650
+ * },
651
+ * });
652
+ * ```
653
+ */
654
+ export function createMandateStorage(
655
+ config: Partial<MandateStorageConfig> = {},
656
+ ): MandateStorage {
657
+ const fullConfig = { ...DEFAULT_MANDATE_STORAGE_CONFIG, ...config };
658
+
659
+ switch (fullConfig.backend) {
660
+ case "semantic-memory":
661
+ return new SemanticMemoryMandateStorage(fullConfig);
662
+ case "memory":
663
+ return new InMemoryMandateStorage(fullConfig);
664
+ default:
665
+ throw new Error(`Unknown storage backend: ${fullConfig.backend}`);
666
+ }
667
+ }
668
+
669
+ // ============================================================================
670
+ // Status Update Helpers
671
+ // ============================================================================
672
+
673
+ /**
674
+ * Update mandate status based on calculated score
675
+ *
676
+ * Applies thresholds from decay config to determine status transitions:
677
+ * - mandate: net_votes >= 5 AND vote_ratio >= 0.7
678
+ * - established: net_votes >= 2
679
+ * - rejected: net_votes <= -3
680
+ * - candidate: otherwise
681
+ *
682
+ * @param mandateId - Mandate ID
683
+ * @param storage - Storage instance
684
+ * @returns Score calculation result with status update
685
+ */
686
+ export async function updateMandateStatus(
687
+ mandateId: string,
688
+ storage: MandateStorage,
689
+ ): Promise<ScoreCalculationResult> {
690
+ const entry = await storage.get(mandateId);
691
+ if (!entry) {
692
+ throw new Error(`Mandate ${mandateId} not found`);
693
+ }
694
+
695
+ const score = await storage.calculateScore(mandateId);
696
+ const previousStatus = entry.status;
697
+
698
+ // Determine new status based on thresholds
699
+ let newStatus: MandateStatus;
700
+ const config = DEFAULT_MANDATE_DECAY_CONFIG;
701
+
702
+ if (
703
+ score.net_votes >= config.mandateNetVotesThreshold &&
704
+ score.vote_ratio >= config.mandateVoteRatioThreshold
705
+ ) {
706
+ newStatus = "mandate";
707
+ } else if (score.net_votes <= config.rejectedNetVotesThreshold) {
708
+ newStatus = "rejected";
709
+ } else if (score.net_votes >= config.establishedNetVotesThreshold) {
710
+ newStatus = "established";
711
+ } else {
712
+ newStatus = "candidate";
713
+ }
714
+
715
+ // Update status if changed
716
+ if (newStatus !== previousStatus) {
717
+ await storage.update(mandateId, { status: newStatus });
718
+ }
719
+
720
+ return {
721
+ mandate_id: mandateId,
722
+ previous_status: previousStatus,
723
+ new_status: newStatus,
724
+ score,
725
+ status_changed: newStatus !== previousStatus,
726
+ };
727
+ }
728
+
729
+ /**
730
+ * Batch update all mandate statuses
731
+ *
732
+ * Useful for periodic recalculation of scores/status across all mandates.
733
+ *
734
+ * @param storage - Storage instance
735
+ * @returns Array of score calculation results
736
+ */
737
+ export async function updateAllMandateStatuses(
738
+ storage: MandateStorage,
739
+ ): Promise<ScoreCalculationResult[]> {
740
+ const allEntries = await storage.list();
741
+ const results: ScoreCalculationResult[] = [];
742
+
743
+ for (const entry of allEntries) {
744
+ const result = await updateMandateStatus(entry.id, storage);
745
+ results.push(result);
746
+ }
747
+
748
+ return results;
749
+ }
750
+
751
+ // ============================================================================
752
+ // Global Storage Instance
753
+ // ============================================================================
754
+
755
+ let globalMandateStorage: MandateStorage | null = null;
756
+
757
+ /**
758
+ * Get or create the global mandate storage instance
759
+ *
760
+ * Uses semantic-memory by default.
761
+ */
762
+ export function getMandateStorage(): MandateStorage {
763
+ if (!globalMandateStorage) {
764
+ globalMandateStorage = createMandateStorage();
765
+ }
766
+ return globalMandateStorage;
767
+ }
768
+
769
+ /**
770
+ * Set the global mandate storage instance
771
+ *
772
+ * Useful for testing or custom configurations.
773
+ */
774
+ export function setMandateStorage(storage: MandateStorage): void {
775
+ globalMandateStorage = storage;
776
+ }
777
+
778
+ /**
779
+ * Reset the global mandate storage instance
780
+ */
781
+ export async function resetMandateStorage(): Promise<void> {
782
+ if (globalMandateStorage) {
783
+ await globalMandateStorage.close();
784
+ globalMandateStorage = null;
785
+ }
786
+ }