@claude-flow/plugin-gastown-bridge 0.1.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,4688 @@
1
+ import { EventEmitter } from 'events';
2
+ import { z } from 'zod';
3
+ import { GtBridge, BdBridge, SyncBridge } from './bridges.js';
4
+ export { AddressSchema, AgentDBEntry, AgentDBEntrySchema, BdArgumentSchema, BdBridgeConfig, BdBridgeError, BdErrorCode, BdLogger, BdResult, BdStreamResult, BeadIdSchema, BeadQuery, CliBead, CliBeadSchema, CliBeadType, CliBeadTypeSchema, CliSyncDirection, CliSyncDirectionSchema, CliSyncResult, ConflictStrategy, ConflictStrategySchema, CreateBeadParams, GasEstimate, GasLimitSchema, GasPriceSchema, GtArgumentSchema, GtBridgeConfig, GtBridgeError, GtErrorCode, GtIdentifierSchema, GtLogger, GtResult, GtSafeStringSchema, IAgentDBService, NetworkSchema, NetworkStatus, SyncBridgeConfig, SyncBridgeError, SyncConflict, SyncErrorCode, SyncLogger, SyncState, SyncStatus, SyncStatusSchema, TxHashSchema, TxStatus, createBdBridge, createGtBridge, createSyncBridge } from './bridges.js';
5
+ import 'child_process';
6
+
7
+ /**
8
+ * Gas Town Bridge Plugin - Type Definitions
9
+ *
10
+ * Core types for Gas Town integration including:
11
+ * - Beads: Git-backed issue tracking with graph semantics
12
+ * - Formulas: TOML-defined workflows (convoy, workflow, expansion, aspect)
13
+ * - Convoys: Work-order tracking for slung work
14
+ * - Steps/Legs: Workflow components
15
+ * - Variables: Template substitution
16
+ *
17
+ * @module gastown-bridge/types
18
+ * @version 0.1.0
19
+ */
20
+
21
+ /**
22
+ * Bead status enumeration
23
+ */
24
+ type BeadStatus = 'open' | 'in_progress' | 'closed';
25
+ /**
26
+ * Bead - Git-backed issue with graph semantics
27
+ */
28
+ interface Bead {
29
+ /** Unique identifier (e.g., "gt-abc12") */
30
+ readonly id: string;
31
+ /** Issue title */
32
+ readonly title: string;
33
+ /** Issue description */
34
+ readonly description: string;
35
+ /** Current status */
36
+ readonly status: BeadStatus;
37
+ /** Priority (0 = highest) */
38
+ readonly priority: number;
39
+ /** Issue labels */
40
+ readonly labels: string[];
41
+ /** Parent bead ID (for epics) */
42
+ readonly parentId?: string;
43
+ /** Creation timestamp */
44
+ readonly createdAt: Date;
45
+ /** Last update timestamp */
46
+ readonly updatedAt: Date;
47
+ /** Assigned agent/user */
48
+ readonly assignee?: string;
49
+ /** Gas Town rig name */
50
+ readonly rig?: string;
51
+ /** Blocking beads (dependencies) */
52
+ readonly blockedBy?: string[];
53
+ /** Beads this blocks */
54
+ readonly blocks?: string[];
55
+ }
56
+ /**
57
+ * Options for creating a new bead
58
+ */
59
+ interface CreateBeadOptions {
60
+ readonly title: string;
61
+ readonly description?: string;
62
+ readonly priority?: number;
63
+ readonly labels?: string[];
64
+ readonly parent?: string;
65
+ readonly rig?: string;
66
+ readonly assignee?: string;
67
+ }
68
+ /**
69
+ * Bead dependency relationship
70
+ */
71
+ interface BeadDependency {
72
+ readonly child: string;
73
+ readonly parent: string;
74
+ readonly type: 'blocks' | 'relates' | 'duplicates';
75
+ }
76
+ /**
77
+ * Formula type enumeration
78
+ */
79
+ type FormulaType = 'convoy' | 'workflow' | 'expansion' | 'aspect';
80
+ /**
81
+ * Workflow step definition
82
+ */
83
+ interface Step {
84
+ /** Step identifier */
85
+ readonly id: string;
86
+ /** Step title */
87
+ readonly title: string;
88
+ /** Step description */
89
+ readonly description: string;
90
+ /** Dependencies - step IDs that must complete first */
91
+ readonly needs?: string[];
92
+ /** Estimated duration in minutes */
93
+ readonly duration?: number;
94
+ /** Required capabilities */
95
+ readonly requires?: string[];
96
+ /** Step metadata */
97
+ readonly metadata?: Record<string, unknown>;
98
+ }
99
+ /**
100
+ * Convoy leg definition
101
+ */
102
+ interface Leg {
103
+ /** Leg identifier */
104
+ readonly id: string;
105
+ /** Leg title */
106
+ readonly title: string;
107
+ /** Focus area */
108
+ readonly focus: string;
109
+ /** Leg description */
110
+ readonly description: string;
111
+ /** Assigned agent type */
112
+ readonly agent?: string;
113
+ /** Leg sequence order */
114
+ readonly order?: number;
115
+ }
116
+ /**
117
+ * Formula variable definition
118
+ */
119
+ interface Var {
120
+ /** Variable name */
121
+ readonly name: string;
122
+ /** Variable description */
123
+ readonly description?: string;
124
+ /** Default value */
125
+ readonly default?: string;
126
+ /** Whether the variable is required */
127
+ readonly required?: boolean;
128
+ /** Validation pattern (regex) */
129
+ readonly pattern?: string;
130
+ /** Allowed values */
131
+ readonly enum?: string[];
132
+ }
133
+ /**
134
+ * Synthesis definition (convoy result combination)
135
+ */
136
+ interface Synthesis {
137
+ /** Synthesis strategy */
138
+ readonly strategy: 'merge' | 'sequential' | 'parallel';
139
+ /** Output format */
140
+ readonly format?: string;
141
+ /** Synthesis description */
142
+ readonly description?: string;
143
+ }
144
+ /**
145
+ * Template for expansion formulas
146
+ */
147
+ interface Template {
148
+ /** Template name */
149
+ readonly name: string;
150
+ /** Template content with variable placeholders */
151
+ readonly content: string;
152
+ /** Output path pattern */
153
+ readonly outputPath?: string;
154
+ }
155
+ /**
156
+ * Aspect definition for cross-cutting concerns
157
+ */
158
+ interface Aspect {
159
+ /** Aspect name */
160
+ readonly name: string;
161
+ /** Pointcut expression */
162
+ readonly pointcut: string;
163
+ /** Advice to apply */
164
+ readonly advice: string;
165
+ /** Aspect type */
166
+ readonly type: 'before' | 'after' | 'around';
167
+ }
168
+ /**
169
+ * Formula - TOML-defined workflow specification
170
+ */
171
+ interface Formula {
172
+ /** Formula name */
173
+ readonly name: string;
174
+ /** Formula description */
175
+ readonly description: string;
176
+ /** Formula type */
177
+ readonly type: FormulaType;
178
+ /** Formula version */
179
+ readonly version: number;
180
+ /** Convoy legs */
181
+ readonly legs?: Leg[];
182
+ /** Synthesis configuration */
183
+ readonly synthesis?: Synthesis;
184
+ /** Workflow steps */
185
+ readonly steps?: Step[];
186
+ /** Variable definitions */
187
+ readonly vars?: Record<string, Var>;
188
+ /** Expansion templates */
189
+ readonly templates?: Template[];
190
+ /** Cross-cutting aspects */
191
+ readonly aspects?: Aspect[];
192
+ /** Formula metadata */
193
+ readonly metadata?: Record<string, unknown>;
194
+ }
195
+ /**
196
+ * Cooked formula with variables substituted
197
+ */
198
+ interface CookedFormula extends Formula {
199
+ /** When the formula was cooked */
200
+ readonly cookedAt: Date;
201
+ /** Variables used for cooking */
202
+ readonly cookedVars: Record<string, string>;
203
+ /** Original (uncooked) formula name */
204
+ readonly originalName: string;
205
+ }
206
+ /**
207
+ * Convoy status enumeration
208
+ */
209
+ type ConvoyStatus = 'active' | 'landed' | 'failed' | 'paused';
210
+ /**
211
+ * Convoy progress tracking
212
+ */
213
+ interface ConvoyProgress {
214
+ /** Total issues tracked */
215
+ readonly total: number;
216
+ /** Closed issues */
217
+ readonly closed: number;
218
+ /** In-progress issues */
219
+ readonly inProgress: number;
220
+ /** Blocked issues */
221
+ readonly blocked: number;
222
+ }
223
+ /**
224
+ * Convoy - Work order tracking for slung work
225
+ */
226
+ interface Convoy {
227
+ /** Convoy identifier */
228
+ readonly id: string;
229
+ /** Convoy name */
230
+ readonly name: string;
231
+ /** Tracked issue IDs */
232
+ readonly trackedIssues: string[];
233
+ /** Convoy status */
234
+ readonly status: ConvoyStatus;
235
+ /** Start timestamp */
236
+ readonly startedAt: Date;
237
+ /** Completion timestamp */
238
+ readonly completedAt?: Date;
239
+ /** Progress tracking */
240
+ readonly progress: ConvoyProgress;
241
+ /** Formula used to create convoy */
242
+ readonly formula?: string;
243
+ /** Description */
244
+ readonly description?: string;
245
+ }
246
+ /**
247
+ * Options for creating a convoy
248
+ */
249
+ interface CreateConvoyOptions {
250
+ readonly name: string;
251
+ readonly issues: string[];
252
+ readonly description?: string;
253
+ readonly formula?: string;
254
+ }
255
+ /**
256
+ * Gas Town agent role
257
+ */
258
+ type GasTownAgentRole = 'mayor' | 'polecat' | 'refinery' | 'witness' | 'deacon' | 'dog' | 'crew';
259
+ /**
260
+ * Gas Town agent
261
+ */
262
+ interface GasTownAgent {
263
+ /** Agent name */
264
+ readonly name: string;
265
+ /** Agent role */
266
+ readonly role: GasTownAgentRole;
267
+ /** Rig assignment */
268
+ readonly rig?: string;
269
+ /** Current status */
270
+ readonly status: 'active' | 'idle' | 'busy';
271
+ /** Agent capabilities */
272
+ readonly capabilities?: string[];
273
+ }
274
+ /**
275
+ * Sling target type
276
+ */
277
+ type SlingTarget = 'polecat' | 'crew' | 'mayor';
278
+ /**
279
+ * Sling operation options
280
+ */
281
+ interface SlingOptions {
282
+ readonly beadId: string;
283
+ readonly target: SlingTarget;
284
+ readonly formula?: string;
285
+ readonly priority?: number;
286
+ }
287
+ /**
288
+ * Gas Town mail message
289
+ */
290
+ interface GasTownMail {
291
+ readonly id: string;
292
+ readonly from: string;
293
+ readonly to: string;
294
+ readonly subject: string;
295
+ readonly body: string;
296
+ readonly sentAt: Date;
297
+ readonly read: boolean;
298
+ }
299
+ /**
300
+ * Sync direction
301
+ */
302
+ type SyncDirection = 'pull' | 'push' | 'both';
303
+ /**
304
+ * Sync result
305
+ */
306
+ interface SyncResult {
307
+ readonly direction: SyncDirection;
308
+ readonly pulled: number;
309
+ readonly pushed: number;
310
+ readonly errors: string[];
311
+ readonly timestamp: Date;
312
+ }
313
+ /**
314
+ * Dependency graph for beads
315
+ */
316
+ interface BeadGraph {
317
+ readonly nodes: string[];
318
+ readonly edges: Array<[string, string]>;
319
+ }
320
+ /**
321
+ * Topological sort result
322
+ */
323
+ interface TopoSortResult {
324
+ readonly sorted: string[];
325
+ readonly hasCycle: boolean;
326
+ readonly cycleNodes?: string[];
327
+ }
328
+ /**
329
+ * Critical path result
330
+ */
331
+ interface CriticalPathResult {
332
+ readonly path: string[];
333
+ readonly totalDuration: number;
334
+ readonly slack: Map<string, number>;
335
+ }
336
+ /**
337
+ * Gas Town Bridge plugin configuration
338
+ */
339
+ interface GasTownConfig {
340
+ /** Path to Gas Town installation */
341
+ readonly townRoot: string;
342
+ /** Enable Beads sync with AgentDB */
343
+ readonly enableBeadsSync: boolean;
344
+ /** Sync interval in milliseconds */
345
+ readonly syncInterval: number;
346
+ /** Enable native formula parsing (WASM) */
347
+ readonly nativeFormulas: boolean;
348
+ /** Enable convoy tracking */
349
+ readonly enableConvoys: boolean;
350
+ /** Auto-create beads from Claude Flow tasks */
351
+ readonly autoCreateBeads: boolean;
352
+ /** Enable GUPP integration */
353
+ readonly enableGUPP: boolean;
354
+ /** GUPP check interval in milliseconds */
355
+ readonly guppCheckInterval: number;
356
+ /** CLI timeout in milliseconds */
357
+ readonly cliTimeout: number;
358
+ }
359
+ /**
360
+ * Default configuration values
361
+ */
362
+ declare const DEFAULT_CONFIG: GasTownConfig;
363
+ /**
364
+ * Gas Town Bridge error codes
365
+ */
366
+ declare const GasTownErrorCodes: {
367
+ readonly CLI_NOT_FOUND: "GT_CLI_NOT_FOUND";
368
+ readonly CLI_TIMEOUT: "GT_CLI_TIMEOUT";
369
+ readonly CLI_ERROR: "GT_CLI_ERROR";
370
+ readonly BEAD_NOT_FOUND: "GT_BEAD_NOT_FOUND";
371
+ readonly CONVOY_NOT_FOUND: "GT_CONVOY_NOT_FOUND";
372
+ readonly FORMULA_NOT_FOUND: "GT_FORMULA_NOT_FOUND";
373
+ readonly FORMULA_PARSE_ERROR: "GT_FORMULA_PARSE_ERROR";
374
+ readonly WASM_NOT_INITIALIZED: "GT_WASM_NOT_INITIALIZED";
375
+ readonly SYNC_ERROR: "GT_SYNC_ERROR";
376
+ readonly DEPENDENCY_CYCLE: "GT_DEPENDENCY_CYCLE";
377
+ readonly INVALID_SLING_TARGET: "GT_INVALID_SLING_TARGET";
378
+ };
379
+ type GasTownErrorCode$1 = (typeof GasTownErrorCodes)[keyof typeof GasTownErrorCodes];
380
+ /**
381
+ * Bead status schema
382
+ */
383
+ declare const BeadStatusSchema: z.ZodEnum<["open", "in_progress", "closed"]>;
384
+ /**
385
+ * Bead schema
386
+ */
387
+ declare const BeadSchema: z.ZodObject<{
388
+ id: z.ZodString;
389
+ title: z.ZodString;
390
+ description: z.ZodString;
391
+ status: z.ZodEnum<["open", "in_progress", "closed"]>;
392
+ priority: z.ZodNumber;
393
+ labels: z.ZodArray<z.ZodString, "many">;
394
+ parentId: z.ZodOptional<z.ZodString>;
395
+ createdAt: z.ZodDate;
396
+ updatedAt: z.ZodDate;
397
+ assignee: z.ZodOptional<z.ZodString>;
398
+ rig: z.ZodOptional<z.ZodString>;
399
+ blockedBy: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
400
+ blocks: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
401
+ }, "strip", z.ZodTypeAny, {
402
+ description: string;
403
+ id: string;
404
+ status: "open" | "in_progress" | "closed";
405
+ createdAt: Date;
406
+ updatedAt: Date;
407
+ priority: number;
408
+ title: string;
409
+ labels: string[];
410
+ parentId?: string | undefined;
411
+ assignee?: string | undefined;
412
+ rig?: string | undefined;
413
+ blockedBy?: string[] | undefined;
414
+ blocks?: string[] | undefined;
415
+ }, {
416
+ description: string;
417
+ id: string;
418
+ status: "open" | "in_progress" | "closed";
419
+ createdAt: Date;
420
+ updatedAt: Date;
421
+ priority: number;
422
+ title: string;
423
+ labels: string[];
424
+ parentId?: string | undefined;
425
+ assignee?: string | undefined;
426
+ rig?: string | undefined;
427
+ blockedBy?: string[] | undefined;
428
+ blocks?: string[] | undefined;
429
+ }>;
430
+ /**
431
+ * Create bead options schema
432
+ */
433
+ declare const CreateBeadOptionsSchema$1: z.ZodObject<{
434
+ title: z.ZodString;
435
+ description: z.ZodOptional<z.ZodString>;
436
+ priority: z.ZodOptional<z.ZodNumber>;
437
+ labels: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
438
+ parent: z.ZodOptional<z.ZodString>;
439
+ rig: z.ZodOptional<z.ZodString>;
440
+ assignee: z.ZodOptional<z.ZodString>;
441
+ }, "strip", z.ZodTypeAny, {
442
+ title: string;
443
+ description?: string | undefined;
444
+ priority?: number | undefined;
445
+ assignee?: string | undefined;
446
+ labels?: string[] | undefined;
447
+ rig?: string | undefined;
448
+ parent?: string | undefined;
449
+ }, {
450
+ title: string;
451
+ description?: string | undefined;
452
+ priority?: number | undefined;
453
+ assignee?: string | undefined;
454
+ labels?: string[] | undefined;
455
+ rig?: string | undefined;
456
+ parent?: string | undefined;
457
+ }>;
458
+ /**
459
+ * Formula type schema
460
+ */
461
+ declare const FormulaTypeSchema: z.ZodEnum<["convoy", "workflow", "expansion", "aspect"]>;
462
+ /**
463
+ * Step schema
464
+ */
465
+ declare const StepSchema: z.ZodObject<{
466
+ id: z.ZodString;
467
+ title: z.ZodString;
468
+ description: z.ZodString;
469
+ needs: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
470
+ duration: z.ZodOptional<z.ZodNumber>;
471
+ requires: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
472
+ metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
473
+ }, "strip", z.ZodTypeAny, {
474
+ description: string;
475
+ id: string;
476
+ title: string;
477
+ metadata?: Record<string, unknown> | undefined;
478
+ needs?: string[] | undefined;
479
+ duration?: number | undefined;
480
+ requires?: string[] | undefined;
481
+ }, {
482
+ description: string;
483
+ id: string;
484
+ title: string;
485
+ metadata?: Record<string, unknown> | undefined;
486
+ needs?: string[] | undefined;
487
+ duration?: number | undefined;
488
+ requires?: string[] | undefined;
489
+ }>;
490
+ /**
491
+ * Leg schema
492
+ */
493
+ declare const LegSchema: z.ZodObject<{
494
+ id: z.ZodString;
495
+ title: z.ZodString;
496
+ focus: z.ZodString;
497
+ description: z.ZodString;
498
+ agent: z.ZodOptional<z.ZodString>;
499
+ order: z.ZodOptional<z.ZodNumber>;
500
+ }, "strip", z.ZodTypeAny, {
501
+ description: string;
502
+ id: string;
503
+ title: string;
504
+ focus: string;
505
+ agent?: string | undefined;
506
+ order?: number | undefined;
507
+ }, {
508
+ description: string;
509
+ id: string;
510
+ title: string;
511
+ focus: string;
512
+ agent?: string | undefined;
513
+ order?: number | undefined;
514
+ }>;
515
+ /**
516
+ * Variable schema
517
+ */
518
+ declare const VarSchema: z.ZodObject<{
519
+ name: z.ZodString;
520
+ description: z.ZodOptional<z.ZodString>;
521
+ default: z.ZodOptional<z.ZodString>;
522
+ required: z.ZodOptional<z.ZodBoolean>;
523
+ pattern: z.ZodOptional<z.ZodString>;
524
+ enum: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
525
+ }, "strip", z.ZodTypeAny, {
526
+ name: string;
527
+ description?: string | undefined;
528
+ default?: string | undefined;
529
+ required?: boolean | undefined;
530
+ pattern?: string | undefined;
531
+ enum?: string[] | undefined;
532
+ }, {
533
+ name: string;
534
+ description?: string | undefined;
535
+ default?: string | undefined;
536
+ required?: boolean | undefined;
537
+ pattern?: string | undefined;
538
+ enum?: string[] | undefined;
539
+ }>;
540
+ /**
541
+ * Synthesis schema
542
+ */
543
+ declare const SynthesisSchema: z.ZodObject<{
544
+ strategy: z.ZodEnum<["merge", "sequential", "parallel"]>;
545
+ format: z.ZodOptional<z.ZodString>;
546
+ description: z.ZodOptional<z.ZodString>;
547
+ }, "strip", z.ZodTypeAny, {
548
+ strategy: "parallel" | "merge" | "sequential";
549
+ description?: string | undefined;
550
+ format?: string | undefined;
551
+ }, {
552
+ strategy: "parallel" | "merge" | "sequential";
553
+ description?: string | undefined;
554
+ format?: string | undefined;
555
+ }>;
556
+ /**
557
+ * Template schema
558
+ */
559
+ declare const TemplateSchema: z.ZodObject<{
560
+ name: z.ZodString;
561
+ content: z.ZodString;
562
+ outputPath: z.ZodOptional<z.ZodString>;
563
+ }, "strip", z.ZodTypeAny, {
564
+ name: string;
565
+ content: string;
566
+ outputPath?: string | undefined;
567
+ }, {
568
+ name: string;
569
+ content: string;
570
+ outputPath?: string | undefined;
571
+ }>;
572
+ /**
573
+ * Aspect schema
574
+ */
575
+ declare const AspectSchema: z.ZodObject<{
576
+ name: z.ZodString;
577
+ pointcut: z.ZodString;
578
+ advice: z.ZodString;
579
+ type: z.ZodEnum<["before", "after", "around"]>;
580
+ }, "strip", z.ZodTypeAny, {
581
+ name: string;
582
+ type: "before" | "after" | "around";
583
+ pointcut: string;
584
+ advice: string;
585
+ }, {
586
+ name: string;
587
+ type: "before" | "after" | "around";
588
+ pointcut: string;
589
+ advice: string;
590
+ }>;
591
+ /**
592
+ * Formula schema
593
+ */
594
+ declare const FormulaSchema: z.ZodObject<{
595
+ name: z.ZodString;
596
+ description: z.ZodString;
597
+ type: z.ZodEnum<["convoy", "workflow", "expansion", "aspect"]>;
598
+ version: z.ZodNumber;
599
+ legs: z.ZodOptional<z.ZodArray<z.ZodObject<{
600
+ id: z.ZodString;
601
+ title: z.ZodString;
602
+ focus: z.ZodString;
603
+ description: z.ZodString;
604
+ agent: z.ZodOptional<z.ZodString>;
605
+ order: z.ZodOptional<z.ZodNumber>;
606
+ }, "strip", z.ZodTypeAny, {
607
+ description: string;
608
+ id: string;
609
+ title: string;
610
+ focus: string;
611
+ agent?: string | undefined;
612
+ order?: number | undefined;
613
+ }, {
614
+ description: string;
615
+ id: string;
616
+ title: string;
617
+ focus: string;
618
+ agent?: string | undefined;
619
+ order?: number | undefined;
620
+ }>, "many">>;
621
+ synthesis: z.ZodOptional<z.ZodObject<{
622
+ strategy: z.ZodEnum<["merge", "sequential", "parallel"]>;
623
+ format: z.ZodOptional<z.ZodString>;
624
+ description: z.ZodOptional<z.ZodString>;
625
+ }, "strip", z.ZodTypeAny, {
626
+ strategy: "parallel" | "merge" | "sequential";
627
+ description?: string | undefined;
628
+ format?: string | undefined;
629
+ }, {
630
+ strategy: "parallel" | "merge" | "sequential";
631
+ description?: string | undefined;
632
+ format?: string | undefined;
633
+ }>>;
634
+ steps: z.ZodOptional<z.ZodArray<z.ZodObject<{
635
+ id: z.ZodString;
636
+ title: z.ZodString;
637
+ description: z.ZodString;
638
+ needs: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
639
+ duration: z.ZodOptional<z.ZodNumber>;
640
+ requires: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
641
+ metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
642
+ }, "strip", z.ZodTypeAny, {
643
+ description: string;
644
+ id: string;
645
+ title: string;
646
+ metadata?: Record<string, unknown> | undefined;
647
+ needs?: string[] | undefined;
648
+ duration?: number | undefined;
649
+ requires?: string[] | undefined;
650
+ }, {
651
+ description: string;
652
+ id: string;
653
+ title: string;
654
+ metadata?: Record<string, unknown> | undefined;
655
+ needs?: string[] | undefined;
656
+ duration?: number | undefined;
657
+ requires?: string[] | undefined;
658
+ }>, "many">>;
659
+ vars: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodObject<{
660
+ name: z.ZodString;
661
+ description: z.ZodOptional<z.ZodString>;
662
+ default: z.ZodOptional<z.ZodString>;
663
+ required: z.ZodOptional<z.ZodBoolean>;
664
+ pattern: z.ZodOptional<z.ZodString>;
665
+ enum: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
666
+ }, "strip", z.ZodTypeAny, {
667
+ name: string;
668
+ description?: string | undefined;
669
+ default?: string | undefined;
670
+ required?: boolean | undefined;
671
+ pattern?: string | undefined;
672
+ enum?: string[] | undefined;
673
+ }, {
674
+ name: string;
675
+ description?: string | undefined;
676
+ default?: string | undefined;
677
+ required?: boolean | undefined;
678
+ pattern?: string | undefined;
679
+ enum?: string[] | undefined;
680
+ }>>>;
681
+ templates: z.ZodOptional<z.ZodArray<z.ZodObject<{
682
+ name: z.ZodString;
683
+ content: z.ZodString;
684
+ outputPath: z.ZodOptional<z.ZodString>;
685
+ }, "strip", z.ZodTypeAny, {
686
+ name: string;
687
+ content: string;
688
+ outputPath?: string | undefined;
689
+ }, {
690
+ name: string;
691
+ content: string;
692
+ outputPath?: string | undefined;
693
+ }>, "many">>;
694
+ aspects: z.ZodOptional<z.ZodArray<z.ZodObject<{
695
+ name: z.ZodString;
696
+ pointcut: z.ZodString;
697
+ advice: z.ZodString;
698
+ type: z.ZodEnum<["before", "after", "around"]>;
699
+ }, "strip", z.ZodTypeAny, {
700
+ name: string;
701
+ type: "before" | "after" | "around";
702
+ pointcut: string;
703
+ advice: string;
704
+ }, {
705
+ name: string;
706
+ type: "before" | "after" | "around";
707
+ pointcut: string;
708
+ advice: string;
709
+ }>, "many">>;
710
+ metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
711
+ }, "strip", z.ZodTypeAny, {
712
+ name: string;
713
+ description: string;
714
+ type: "convoy" | "workflow" | "expansion" | "aspect";
715
+ version: number;
716
+ steps?: {
717
+ description: string;
718
+ id: string;
719
+ title: string;
720
+ metadata?: Record<string, unknown> | undefined;
721
+ needs?: string[] | undefined;
722
+ duration?: number | undefined;
723
+ requires?: string[] | undefined;
724
+ }[] | undefined;
725
+ legs?: {
726
+ description: string;
727
+ id: string;
728
+ title: string;
729
+ focus: string;
730
+ agent?: string | undefined;
731
+ order?: number | undefined;
732
+ }[] | undefined;
733
+ vars?: Record<string, {
734
+ name: string;
735
+ description?: string | undefined;
736
+ default?: string | undefined;
737
+ required?: boolean | undefined;
738
+ pattern?: string | undefined;
739
+ enum?: string[] | undefined;
740
+ }> | undefined;
741
+ metadata?: Record<string, unknown> | undefined;
742
+ synthesis?: {
743
+ strategy: "parallel" | "merge" | "sequential";
744
+ description?: string | undefined;
745
+ format?: string | undefined;
746
+ } | undefined;
747
+ templates?: {
748
+ name: string;
749
+ content: string;
750
+ outputPath?: string | undefined;
751
+ }[] | undefined;
752
+ aspects?: {
753
+ name: string;
754
+ type: "before" | "after" | "around";
755
+ pointcut: string;
756
+ advice: string;
757
+ }[] | undefined;
758
+ }, {
759
+ name: string;
760
+ description: string;
761
+ type: "convoy" | "workflow" | "expansion" | "aspect";
762
+ version: number;
763
+ steps?: {
764
+ description: string;
765
+ id: string;
766
+ title: string;
767
+ metadata?: Record<string, unknown> | undefined;
768
+ needs?: string[] | undefined;
769
+ duration?: number | undefined;
770
+ requires?: string[] | undefined;
771
+ }[] | undefined;
772
+ legs?: {
773
+ description: string;
774
+ id: string;
775
+ title: string;
776
+ focus: string;
777
+ agent?: string | undefined;
778
+ order?: number | undefined;
779
+ }[] | undefined;
780
+ vars?: Record<string, {
781
+ name: string;
782
+ description?: string | undefined;
783
+ default?: string | undefined;
784
+ required?: boolean | undefined;
785
+ pattern?: string | undefined;
786
+ enum?: string[] | undefined;
787
+ }> | undefined;
788
+ metadata?: Record<string, unknown> | undefined;
789
+ synthesis?: {
790
+ strategy: "parallel" | "merge" | "sequential";
791
+ description?: string | undefined;
792
+ format?: string | undefined;
793
+ } | undefined;
794
+ templates?: {
795
+ name: string;
796
+ content: string;
797
+ outputPath?: string | undefined;
798
+ }[] | undefined;
799
+ aspects?: {
800
+ name: string;
801
+ type: "before" | "after" | "around";
802
+ pointcut: string;
803
+ advice: string;
804
+ }[] | undefined;
805
+ }>;
806
+ /**
807
+ * Convoy status schema
808
+ */
809
+ declare const ConvoyStatusSchema: z.ZodEnum<["active", "landed", "failed", "paused"]>;
810
+ /**
811
+ * Convoy progress schema
812
+ */
813
+ declare const ConvoyProgressSchema: z.ZodObject<{
814
+ total: z.ZodNumber;
815
+ closed: z.ZodNumber;
816
+ inProgress: z.ZodNumber;
817
+ blocked: z.ZodNumber;
818
+ }, "strip", z.ZodTypeAny, {
819
+ closed: number;
820
+ total: number;
821
+ inProgress: number;
822
+ blocked: number;
823
+ }, {
824
+ closed: number;
825
+ total: number;
826
+ inProgress: number;
827
+ blocked: number;
828
+ }>;
829
+ /**
830
+ * Convoy schema
831
+ */
832
+ declare const ConvoySchema: z.ZodObject<{
833
+ id: z.ZodString;
834
+ name: z.ZodString;
835
+ trackedIssues: z.ZodArray<z.ZodString, "many">;
836
+ status: z.ZodEnum<["active", "landed", "failed", "paused"]>;
837
+ startedAt: z.ZodDate;
838
+ completedAt: z.ZodOptional<z.ZodDate>;
839
+ progress: z.ZodObject<{
840
+ total: z.ZodNumber;
841
+ closed: z.ZodNumber;
842
+ inProgress: z.ZodNumber;
843
+ blocked: z.ZodNumber;
844
+ }, "strip", z.ZodTypeAny, {
845
+ closed: number;
846
+ total: number;
847
+ inProgress: number;
848
+ blocked: number;
849
+ }, {
850
+ closed: number;
851
+ total: number;
852
+ inProgress: number;
853
+ blocked: number;
854
+ }>;
855
+ formula: z.ZodOptional<z.ZodString>;
856
+ description: z.ZodOptional<z.ZodString>;
857
+ }, "strip", z.ZodTypeAny, {
858
+ name: string;
859
+ id: string;
860
+ status: "active" | "landed" | "failed" | "paused";
861
+ trackedIssues: string[];
862
+ startedAt: Date;
863
+ progress: {
864
+ closed: number;
865
+ total: number;
866
+ inProgress: number;
867
+ blocked: number;
868
+ };
869
+ description?: string | undefined;
870
+ completedAt?: Date | undefined;
871
+ formula?: string | undefined;
872
+ }, {
873
+ name: string;
874
+ id: string;
875
+ status: "active" | "landed" | "failed" | "paused";
876
+ trackedIssues: string[];
877
+ startedAt: Date;
878
+ progress: {
879
+ closed: number;
880
+ total: number;
881
+ inProgress: number;
882
+ blocked: number;
883
+ };
884
+ description?: string | undefined;
885
+ completedAt?: Date | undefined;
886
+ formula?: string | undefined;
887
+ }>;
888
+ /**
889
+ * Create convoy options schema
890
+ */
891
+ declare const CreateConvoyOptionsSchema$1: z.ZodObject<{
892
+ name: z.ZodString;
893
+ issues: z.ZodArray<z.ZodString, "many">;
894
+ description: z.ZodOptional<z.ZodString>;
895
+ formula: z.ZodOptional<z.ZodString>;
896
+ }, "strip", z.ZodTypeAny, {
897
+ name: string;
898
+ issues: string[];
899
+ description?: string | undefined;
900
+ formula?: string | undefined;
901
+ }, {
902
+ name: string;
903
+ issues: string[];
904
+ description?: string | undefined;
905
+ formula?: string | undefined;
906
+ }>;
907
+ /**
908
+ * Gas Town agent role schema
909
+ */
910
+ declare const GasTownAgentRoleSchema: z.ZodEnum<["mayor", "polecat", "refinery", "witness", "deacon", "dog", "crew"]>;
911
+ /**
912
+ * Sling target schema
913
+ */
914
+ declare const SlingTargetSchema: z.ZodEnum<["polecat", "crew", "mayor"]>;
915
+ /**
916
+ * Sling options schema
917
+ */
918
+ declare const SlingOptionsSchema$1: z.ZodObject<{
919
+ beadId: z.ZodString;
920
+ target: z.ZodEnum<["polecat", "crew", "mayor"]>;
921
+ formula: z.ZodOptional<z.ZodString>;
922
+ priority: z.ZodOptional<z.ZodNumber>;
923
+ }, "strip", z.ZodTypeAny, {
924
+ beadId: string;
925
+ target: "mayor" | "polecat" | "crew";
926
+ priority?: number | undefined;
927
+ formula?: string | undefined;
928
+ }, {
929
+ beadId: string;
930
+ target: "mayor" | "polecat" | "crew";
931
+ priority?: number | undefined;
932
+ formula?: string | undefined;
933
+ }>;
934
+ /**
935
+ * Sync direction schema
936
+ */
937
+ declare const SyncDirectionSchema: z.ZodEnum<["pull", "push", "both"]>;
938
+ /**
939
+ * Configuration schema
940
+ */
941
+ declare const GasTownConfigSchema: z.ZodObject<{
942
+ townRoot: z.ZodDefault<z.ZodString>;
943
+ enableBeadsSync: z.ZodDefault<z.ZodBoolean>;
944
+ syncInterval: z.ZodDefault<z.ZodNumber>;
945
+ nativeFormulas: z.ZodDefault<z.ZodBoolean>;
946
+ enableConvoys: z.ZodDefault<z.ZodBoolean>;
947
+ autoCreateBeads: z.ZodDefault<z.ZodBoolean>;
948
+ enableGUPP: z.ZodDefault<z.ZodBoolean>;
949
+ guppCheckInterval: z.ZodDefault<z.ZodNumber>;
950
+ cliTimeout: z.ZodDefault<z.ZodNumber>;
951
+ }, "strip", z.ZodTypeAny, {
952
+ syncInterval: number;
953
+ townRoot: string;
954
+ enableBeadsSync: boolean;
955
+ nativeFormulas: boolean;
956
+ enableConvoys: boolean;
957
+ autoCreateBeads: boolean;
958
+ enableGUPP: boolean;
959
+ guppCheckInterval: number;
960
+ cliTimeout: number;
961
+ }, {
962
+ syncInterval?: number | undefined;
963
+ townRoot?: string | undefined;
964
+ enableBeadsSync?: boolean | undefined;
965
+ nativeFormulas?: boolean | undefined;
966
+ enableConvoys?: boolean | undefined;
967
+ autoCreateBeads?: boolean | undefined;
968
+ enableGUPP?: boolean | undefined;
969
+ guppCheckInterval?: number | undefined;
970
+ cliTimeout?: number | undefined;
971
+ }>;
972
+ /**
973
+ * Validate bead
974
+ */
975
+ declare function validateBead(input: unknown): Bead;
976
+ /**
977
+ * Validate create bead options
978
+ */
979
+ declare function validateCreateBeadOptions$1(input: unknown): CreateBeadOptions;
980
+ /**
981
+ * Validate formula
982
+ */
983
+ declare function validateFormula(input: unknown): Formula;
984
+ /**
985
+ * Validate convoy
986
+ */
987
+ declare function validateConvoy(input: unknown): Convoy;
988
+ /**
989
+ * Validate create convoy options
990
+ */
991
+ declare function validateCreateConvoyOptions$1(input: unknown): CreateConvoyOptions;
992
+ /**
993
+ * Validate sling options
994
+ */
995
+ declare function validateSlingOptions$1(input: unknown): SlingOptions;
996
+ /**
997
+ * Validate configuration
998
+ */
999
+ declare function validateConfig(input: unknown): GasTownConfig;
1000
+ /**
1001
+ * Dependency action type
1002
+ */
1003
+ type DepAction = 'add' | 'remove';
1004
+ /**
1005
+ * Convoy action type
1006
+ */
1007
+ type ConvoyAction = 'create' | 'track' | 'land' | 'pause' | 'resume';
1008
+ /**
1009
+ * Mail action type
1010
+ */
1011
+ type MailAction = 'send' | 'read' | 'list';
1012
+ /**
1013
+ * Agent role type (alias for GasTownAgentRole)
1014
+ */
1015
+ type AgentRole = GasTownAgentRole;
1016
+ /**
1017
+ * Target agent type (alias for SlingTarget)
1018
+ */
1019
+ type TargetAgent = SlingTarget;
1020
+ /**
1021
+ * Convoy strategy type
1022
+ */
1023
+ type ConvoyStrategy = 'parallel' | 'serial' | 'hybrid' | 'fastest' | 'balanced' | 'throughput' | 'minimal_context_switches';
1024
+ /**
1025
+ * Dependency action type (for graph operations)
1026
+ */
1027
+ type DependencyAction = 'topo_sort' | 'cycle_detect' | 'critical_path';
1028
+ /**
1029
+ * Formula AST (Abstract Syntax Tree) - alias for Formula
1030
+ */
1031
+ type FormulaAST = Formula;
1032
+ /**
1033
+ * Dependency resolution result
1034
+ */
1035
+ interface DependencyResolution {
1036
+ readonly action: DependencyAction;
1037
+ readonly sorted?: string[];
1038
+ readonly hasCycle?: boolean;
1039
+ readonly cycleNodes?: string[];
1040
+ readonly criticalPath?: string[];
1041
+ readonly totalDuration?: number;
1042
+ }
1043
+ /**
1044
+ * Pattern match result
1045
+ */
1046
+ interface PatternMatch {
1047
+ readonly index: number;
1048
+ readonly candidate: string;
1049
+ readonly similarity: number;
1050
+ }
1051
+ /**
1052
+ * Convoy optimization result
1053
+ */
1054
+ interface ConvoyOptimization {
1055
+ readonly convoyId: string;
1056
+ readonly strategy: string;
1057
+ readonly executionOrder: string[];
1058
+ readonly parallelGroups: string[][];
1059
+ readonly estimatedDuration: number;
1060
+ }
1061
+ /**
1062
+ * Gas Town Bridge interface
1063
+ */
1064
+ interface IGasTownBridge$1 {
1065
+ createBead(opts: CreateBeadOptions): Promise<Bead>;
1066
+ getReady(limit?: number, rig?: string, labels?: string[]): Promise<Bead[]>;
1067
+ showBead(beadId: string): Promise<{
1068
+ bead: Bead;
1069
+ dependencies: string[];
1070
+ dependents: string[];
1071
+ }>;
1072
+ manageDependency(action: DepAction, child: string, parent: string): Promise<void>;
1073
+ createConvoy(opts: CreateConvoyOptions): Promise<Convoy>;
1074
+ getConvoyStatus(convoyId?: string, detailed?: boolean): Promise<Convoy[]>;
1075
+ trackConvoy(convoyId: string, action: 'add' | 'remove', issues: string[]): Promise<void>;
1076
+ listFormulas(type?: FormulaType, includeBuiltin?: boolean): Promise<Array<{
1077
+ name: string;
1078
+ type: FormulaType;
1079
+ description: string;
1080
+ builtin: boolean;
1081
+ }>>;
1082
+ cookFormula(formula: Formula | string, vars: Record<string, string>): Promise<CookedFormula>;
1083
+ executeFormula(formula: Formula | string, vars: Record<string, string>, targetAgent?: string, dryRun?: boolean): Promise<{
1084
+ beads_created: string[];
1085
+ }>;
1086
+ createFormula(opts: {
1087
+ name: string;
1088
+ type: FormulaType;
1089
+ steps?: Step[];
1090
+ vars?: Record<string, unknown>;
1091
+ description?: string;
1092
+ }): Promise<{
1093
+ path: string;
1094
+ }>;
1095
+ sling(beadId: string, target: SlingTarget, formula?: string, priority?: number): Promise<void>;
1096
+ listAgents(rig?: string, role?: AgentRole, includeInactive?: boolean): Promise<GasTownAgent[]>;
1097
+ sendMail(to: string, subject: string, body: string): Promise<string>;
1098
+ readMail(mailId: string): Promise<GasTownMail>;
1099
+ listMail(limit?: number): Promise<GasTownMail[]>;
1100
+ }
1101
+ /**
1102
+ * Beads sync service interface
1103
+ */
1104
+ interface IBeadsSyncService {
1105
+ pullBeads(rig?: string, namespace?: string): Promise<{
1106
+ synced: number;
1107
+ conflicts: number;
1108
+ }>;
1109
+ pushTasks(namespace?: string): Promise<{
1110
+ pushed: number;
1111
+ conflicts: number;
1112
+ }>;
1113
+ }
1114
+ /**
1115
+ * Formula WASM interface
1116
+ */
1117
+ interface IFormulaWasm {
1118
+ isInitialized(): boolean;
1119
+ initialize(): Promise<void>;
1120
+ parseFormula(content: string, validate?: boolean): Promise<Formula>;
1121
+ cookFormula(formula: Formula | string, vars: Record<string, string>, isContent?: boolean): Promise<CookedFormula>;
1122
+ cookBatch(formulas: Array<{
1123
+ name: string;
1124
+ content: string;
1125
+ }>, vars: Record<string, string>[], continueOnError?: boolean): Promise<{
1126
+ cooked: CookedFormula[];
1127
+ errors: Array<{
1128
+ index: number;
1129
+ error: string;
1130
+ }>;
1131
+ }>;
1132
+ }
1133
+ /**
1134
+ * Dependency WASM interface
1135
+ */
1136
+ interface IDependencyWasm {
1137
+ isInitialized(): boolean;
1138
+ initialize(): Promise<void>;
1139
+ resolveDependencies(beads: Array<{
1140
+ id: string;
1141
+ dependencies?: string[];
1142
+ }>, action: DependencyAction): Promise<DependencyResolution>;
1143
+ matchPatterns(query: string, candidates: string[], k: number, threshold: number): Promise<PatternMatch[]>;
1144
+ optimizeConvoy(convoy: {
1145
+ id: string;
1146
+ trackedIssues: string[];
1147
+ }, strategy: ConvoyStrategy, constraints?: unknown): Promise<ConvoyOptimization>;
1148
+ }
1149
+
1150
+ /**
1151
+ * Gas Town Formula Executor - Hybrid WASM/CLI Implementation
1152
+ *
1153
+ * Provides formula execution with:
1154
+ * - WASM acceleration for parsing and cooking (352x faster)
1155
+ * - CLI bridge fallback for I/O operations
1156
+ * - Progress tracking with event emission
1157
+ * - Step dependency resolution
1158
+ * - Molecule generation from cooked formulas
1159
+ * - Cancellation support
1160
+ *
1161
+ * @module v3/plugins/gastown-bridge/formula/executor
1162
+ */
1163
+
1164
+ /**
1165
+ * WASM loader interface for formula operations
1166
+ */
1167
+ interface IWasmLoader {
1168
+ /** Check if WASM is initialized */
1169
+ isInitialized(): boolean;
1170
+ /** Parse TOML formula content to AST */
1171
+ parseFormula(content: string): Formula;
1172
+ /** Cook formula with variable substitution */
1173
+ cookFormula(formula: Formula, vars: Record<string, string>): CookedFormula;
1174
+ /** Batch cook multiple formulas */
1175
+ batchCook(formulas: Formula[], varsArray: Record<string, string>[]): CookedFormula[];
1176
+ /** Resolve step dependencies (topological sort) */
1177
+ resolveStepDependencies(steps: Step[]): Step[];
1178
+ /** Detect cycles in step dependencies */
1179
+ detectCycle(steps: Step[]): {
1180
+ hasCycle: boolean;
1181
+ cycleSteps?: string[];
1182
+ };
1183
+ }
1184
+ /**
1185
+ * Execution options
1186
+ */
1187
+ interface ExecuteOptions {
1188
+ /** Target agent for execution */
1189
+ targetAgent?: string;
1190
+ /** Whether to run in dry-run mode (no actual execution) */
1191
+ dryRun?: boolean;
1192
+ /** Timeout per step in milliseconds */
1193
+ stepTimeout?: number;
1194
+ /** Maximum parallel steps */
1195
+ maxParallel?: number;
1196
+ /** Abort signal for cancellation */
1197
+ signal?: AbortSignal;
1198
+ /** Custom step handler */
1199
+ stepHandler?: (step: Step, context: StepContext) => Promise<StepResult>;
1200
+ }
1201
+ /**
1202
+ * Step execution context
1203
+ */
1204
+ interface StepContext {
1205
+ /** Execution ID */
1206
+ executionId: string;
1207
+ /** Formula being executed */
1208
+ formula: CookedFormula;
1209
+ /** Current step index */
1210
+ stepIndex: number;
1211
+ /** Total steps */
1212
+ totalSteps: number;
1213
+ /** Variables available to the step */
1214
+ variables: Record<string, string>;
1215
+ /** Results from previous steps */
1216
+ previousResults: Map<string, StepResult>;
1217
+ /** Abort signal */
1218
+ signal?: AbortSignal;
1219
+ /** Execution start time */
1220
+ startTime: Date;
1221
+ }
1222
+ /**
1223
+ * Step execution result
1224
+ */
1225
+ interface StepResult {
1226
+ /** Step ID */
1227
+ stepId: string;
1228
+ /** Whether step succeeded */
1229
+ success: boolean;
1230
+ /** Step output data */
1231
+ output?: unknown;
1232
+ /** Error message if failed */
1233
+ error?: string;
1234
+ /** Duration in milliseconds */
1235
+ durationMs: number;
1236
+ /** Step metadata */
1237
+ metadata?: Record<string, unknown>;
1238
+ }
1239
+ /**
1240
+ * Molecule - Generated work unit from cooked formula
1241
+ */
1242
+ interface Molecule {
1243
+ /** Unique molecule ID */
1244
+ id: string;
1245
+ /** Parent formula name */
1246
+ formulaName: string;
1247
+ /** Molecule title */
1248
+ title: string;
1249
+ /** Molecule description */
1250
+ description: string;
1251
+ /** Molecule type (from formula type) */
1252
+ type: FormulaType;
1253
+ /** Associated step or leg */
1254
+ sourceId: string;
1255
+ /** Assigned agent */
1256
+ agent?: string;
1257
+ /** Dependencies (other molecule IDs) */
1258
+ dependencies: string[];
1259
+ /** Execution order */
1260
+ order: number;
1261
+ /** Molecule metadata */
1262
+ metadata: Record<string, unknown>;
1263
+ /** Creation timestamp */
1264
+ createdAt: Date;
1265
+ }
1266
+ /**
1267
+ * Execution progress
1268
+ */
1269
+ interface ExecutionProgress {
1270
+ /** Execution ID */
1271
+ executionId: string;
1272
+ /** Formula name */
1273
+ formulaName: string;
1274
+ /** Current status */
1275
+ status: 'pending' | 'running' | 'completed' | 'failed' | 'cancelled';
1276
+ /** Total steps/legs */
1277
+ totalSteps: number;
1278
+ /** Completed steps */
1279
+ completedSteps: number;
1280
+ /** Failed steps */
1281
+ failedSteps: number;
1282
+ /** Current step being executed */
1283
+ currentStep?: string;
1284
+ /** Start time */
1285
+ startTime: Date;
1286
+ /** End time (if completed) */
1287
+ endTime?: Date;
1288
+ /** Step results */
1289
+ stepResults: StepResult[];
1290
+ /** Error message (if failed) */
1291
+ error?: string;
1292
+ /** Progress percentage (0-100) */
1293
+ percentage: number;
1294
+ }
1295
+ /**
1296
+ * Executor events
1297
+ */
1298
+ interface ExecutorEvents {
1299
+ 'execution:start': (executionId: string, formula: CookedFormula) => void;
1300
+ 'execution:progress': (progress: ExecutionProgress) => void;
1301
+ 'execution:complete': (executionId: string, results: StepResult[]) => void;
1302
+ 'execution:error': (executionId: string, error: Error) => void;
1303
+ 'execution:cancelled': (executionId: string) => void;
1304
+ 'step:start': (executionId: string, step: Step) => void;
1305
+ 'step:complete': (executionId: string, result: StepResult) => void;
1306
+ 'step:error': (executionId: string, stepId: string, error: Error) => void;
1307
+ 'molecule:created': (molecule: Molecule) => void;
1308
+ }
1309
+ /**
1310
+ * Logger interface
1311
+ */
1312
+ interface ExecutorLogger {
1313
+ debug: (msg: string, meta?: Record<string, unknown>) => void;
1314
+ info: (msg: string, meta?: Record<string, unknown>) => void;
1315
+ warn: (msg: string, meta?: Record<string, unknown>) => void;
1316
+ error: (msg: string, meta?: Record<string, unknown>) => void;
1317
+ }
1318
+ /**
1319
+ * Hybrid Formula Executor
1320
+ *
1321
+ * Uses WASM for fast parsing and cooking operations,
1322
+ * falls back to CLI bridge for I/O operations.
1323
+ *
1324
+ * @example
1325
+ * ```typescript
1326
+ * const executor = new FormulaExecutor(gtBridge, wasmLoader);
1327
+ *
1328
+ * // Full execution
1329
+ * const results = await executor.execute('my-formula', { feature: 'auth' });
1330
+ *
1331
+ * // Just cook (WASM-accelerated)
1332
+ * const cooked = await executor.cook('my-formula', { feature: 'auth' });
1333
+ *
1334
+ * // Generate molecules
1335
+ * const molecules = await executor.generateMolecules(cooked);
1336
+ * ```
1337
+ */
1338
+ declare class FormulaExecutor extends EventEmitter {
1339
+ private readonly gtBridge;
1340
+ private readonly wasmLoader;
1341
+ private readonly logger;
1342
+ private readonly jsFallback;
1343
+ /** Active executions for progress tracking */
1344
+ private readonly executions;
1345
+ /** Cancellation controllers */
1346
+ private readonly cancellations;
1347
+ /** Debounced progress emitters per execution */
1348
+ private readonly progressEmitters;
1349
+ /** Default max parallel workers */
1350
+ private readonly defaultMaxParallel;
1351
+ constructor(gtBridge: GtBridge, wasmLoader?: IWasmLoader, logger?: ExecutorLogger);
1352
+ /**
1353
+ * Execute a formula with full lifecycle
1354
+ *
1355
+ * @param formulaName - Name of the formula to execute
1356
+ * @param vars - Variables for substitution
1357
+ * @param options - Execution options
1358
+ * @returns Array of step results
1359
+ */
1360
+ execute(formulaName: string, vars: Record<string, string>, options?: ExecuteOptions): Promise<StepResult[]>;
1361
+ /**
1362
+ * Cook a formula with variable substitution (WASM-accelerated)
1363
+ *
1364
+ * @param formulaName - Name of the formula or TOML content
1365
+ * @param vars - Variables for substitution
1366
+ * @returns Cooked formula with substituted variables
1367
+ */
1368
+ cook(formulaName: string, vars: Record<string, string>): Promise<CookedFormula>;
1369
+ /**
1370
+ * Generate molecules from a cooked formula
1371
+ *
1372
+ * Molecules are executable work units derived from formula steps/legs.
1373
+ * Uses object pooling for reduced allocations.
1374
+ *
1375
+ * @param cookedFormula - The cooked formula to generate molecules from
1376
+ * @returns Array of molecules
1377
+ */
1378
+ generateMolecules(cookedFormula: CookedFormula): Promise<Molecule[]>;
1379
+ /**
1380
+ * Run a single step
1381
+ *
1382
+ * @param step - Step to execute
1383
+ * @param context - Execution context
1384
+ * @param options - Execution options
1385
+ * @returns Step result
1386
+ */
1387
+ runStep(step: Step, context: StepContext, options?: ExecuteOptions): Promise<StepResult>;
1388
+ /**
1389
+ * Get execution progress
1390
+ *
1391
+ * @param executionId - Execution ID to get progress for
1392
+ * @returns Execution progress or undefined
1393
+ */
1394
+ getProgress(executionId: string): ExecutionProgress | undefined;
1395
+ /**
1396
+ * Cancel an execution
1397
+ *
1398
+ * @param executionId - Execution ID to cancel
1399
+ * @returns Whether cancellation was initiated
1400
+ */
1401
+ cancel(executionId: string): boolean;
1402
+ /**
1403
+ * List all active executions
1404
+ */
1405
+ getActiveExecutions(): ExecutionProgress[];
1406
+ /**
1407
+ * Check if WASM is available for acceleration
1408
+ */
1409
+ isWasmAvailable(): boolean;
1410
+ /**
1411
+ * Get cache statistics for performance monitoring
1412
+ */
1413
+ getCacheStats(): {
1414
+ stepResultCache: {
1415
+ entries: number;
1416
+ sizeBytes: number;
1417
+ };
1418
+ cookCache: {
1419
+ entries: number;
1420
+ sizeBytes: number;
1421
+ };
1422
+ };
1423
+ /**
1424
+ * Clear all executor caches
1425
+ */
1426
+ clearCaches(): void;
1427
+ /**
1428
+ * Parse formula content using WASM or JS fallback
1429
+ */
1430
+ private parseFormula;
1431
+ /**
1432
+ * Fetch formula from CLI
1433
+ */
1434
+ private fetchFormula;
1435
+ /**
1436
+ * Validate required variables are provided
1437
+ */
1438
+ private validateVariables;
1439
+ /**
1440
+ * Resolve step dependencies using WASM or JS fallback
1441
+ */
1442
+ private resolveStepDependencies;
1443
+ /**
1444
+ * Get ordered execution units (steps or legs) from formula
1445
+ */
1446
+ private getOrderedExecutionUnits;
1447
+ /**
1448
+ * Execute step via CLI bridge
1449
+ */
1450
+ private executeStepViaCli;
1451
+ /**
1452
+ * Merge multiple abort signals
1453
+ */
1454
+ private mergeSignals;
1455
+ }
1456
+ /**
1457
+ * Create a new FormulaExecutor instance
1458
+ */
1459
+ declare function createFormulaExecutor(gtBridge: GtBridge, wasmLoader?: IWasmLoader, logger?: ExecutorLogger): FormulaExecutor;
1460
+
1461
+ /**
1462
+ * Convoy Tracker
1463
+ *
1464
+ * Manages convoy lifecycle including creation, modification, progress
1465
+ * tracking, and completion. Convoys are work-order groups that track
1466
+ * related beads (issues) through their lifecycle.
1467
+ *
1468
+ * Features:
1469
+ * - Create and manage convoy groups
1470
+ * - Add/remove beads to convoys
1471
+ * - Track progress and status changes
1472
+ * - Event emission for status transitions
1473
+ * - Integration with bd-bridge for bead operations
1474
+ *
1475
+ * @module gastown-bridge/convoy/tracker
1476
+ */
1477
+
1478
+ /**
1479
+ * Convoy event types
1480
+ */
1481
+ type ConvoyEventType = 'convoy:created' | 'convoy:started' | 'convoy:progressed' | 'convoy:completed' | 'convoy:cancelled' | 'convoy:paused' | 'convoy:resumed' | 'convoy:issue:added' | 'convoy:issue:removed' | 'convoy:issue:updated';
1482
+ /**
1483
+ * Convoy event payload
1484
+ */
1485
+ interface ConvoyEvent {
1486
+ /** Event type */
1487
+ type: ConvoyEventType;
1488
+ /** Convoy ID */
1489
+ convoyId: string;
1490
+ /** Convoy name */
1491
+ convoyName: string;
1492
+ /** Event timestamp */
1493
+ timestamp: Date;
1494
+ /** Previous status (for status change events) */
1495
+ previousStatus?: ConvoyStatus;
1496
+ /** Current status */
1497
+ status: ConvoyStatus;
1498
+ /** Progress at time of event */
1499
+ progress: ConvoyProgress;
1500
+ /** Issue IDs affected (for issue events) */
1501
+ issues?: string[];
1502
+ /** Cancellation reason (for cancelled events) */
1503
+ reason?: string;
1504
+ /** Additional metadata */
1505
+ metadata?: Record<string, unknown>;
1506
+ }
1507
+ /**
1508
+ * Convoy tracker configuration
1509
+ */
1510
+ interface ConvoyTrackerConfig {
1511
+ /** BD bridge instance for bead operations */
1512
+ bdBridge: BdBridge;
1513
+ /** Auto-update progress on issue changes */
1514
+ autoUpdateProgress?: boolean;
1515
+ /** Progress update interval in milliseconds */
1516
+ progressUpdateInterval?: number;
1517
+ /** Enable persistent storage */
1518
+ persistConvoys?: boolean;
1519
+ /** Storage path for convoy data */
1520
+ storagePath?: string;
1521
+ }
1522
+ /**
1523
+ * Logger interface
1524
+ */
1525
+ interface ConvoyLogger {
1526
+ debug: (msg: string, meta?: Record<string, unknown>) => void;
1527
+ info: (msg: string, meta?: Record<string, unknown>) => void;
1528
+ warn: (msg: string, meta?: Record<string, unknown>) => void;
1529
+ error: (msg: string, meta?: Record<string, unknown>) => void;
1530
+ }
1531
+ /**
1532
+ * Convoy Tracker
1533
+ *
1534
+ * Manages convoy lifecycle and tracks progress of grouped work.
1535
+ *
1536
+ * @example
1537
+ * ```typescript
1538
+ * const tracker = new ConvoyTracker({
1539
+ * bdBridge: await createBdBridge().initialize(),
1540
+ * });
1541
+ *
1542
+ * // Create a convoy
1543
+ * const convoy = await tracker.create(
1544
+ * 'Sprint 1',
1545
+ * ['gt-abc12', 'gt-def34', 'gt-ghi56'],
1546
+ * 'First sprint tasks'
1547
+ * );
1548
+ *
1549
+ * // Monitor progress
1550
+ * tracker.on('convoy:progressed', (event) => {
1551
+ * console.log(`Progress: ${event.progress.closed}/${event.progress.total}`);
1552
+ * });
1553
+ *
1554
+ * // Check status
1555
+ * const status = await tracker.getStatus(convoy.id);
1556
+ * ```
1557
+ */
1558
+ declare class ConvoyTracker extends EventEmitter {
1559
+ private bdBridge;
1560
+ private convoys;
1561
+ private logger;
1562
+ private config;
1563
+ private progressTimers;
1564
+ constructor(config: ConvoyTrackerConfig, logger?: ConvoyLogger);
1565
+ /**
1566
+ * Create a new convoy
1567
+ *
1568
+ * @param name - Convoy name
1569
+ * @param issues - Issue IDs to include
1570
+ * @param description - Optional description
1571
+ * @returns Created convoy
1572
+ */
1573
+ create(name: string, issues: string[], description?: string): Promise<Convoy>;
1574
+ /**
1575
+ * Add issues to an existing convoy
1576
+ *
1577
+ * @param convoyId - Convoy ID
1578
+ * @param issues - Issue IDs to add
1579
+ * @returns Updated convoy
1580
+ */
1581
+ addIssues(convoyId: string, issues: string[]): Promise<Convoy>;
1582
+ /**
1583
+ * Remove issues from a convoy
1584
+ *
1585
+ * @param convoyId - Convoy ID
1586
+ * @param issues - Issue IDs to remove
1587
+ * @returns Updated convoy
1588
+ */
1589
+ removeIssues(convoyId: string, issues: string[]): Promise<Convoy>;
1590
+ /**
1591
+ * Get convoy status
1592
+ *
1593
+ * @param convoyId - Convoy ID
1594
+ * @returns Convoy with updated progress
1595
+ */
1596
+ getStatus(convoyId: string): Promise<Convoy>;
1597
+ /**
1598
+ * Mark convoy as complete
1599
+ *
1600
+ * @param convoyId - Convoy ID
1601
+ * @returns Completed convoy
1602
+ */
1603
+ complete(convoyId: string): Promise<Convoy>;
1604
+ /**
1605
+ * Cancel a convoy
1606
+ *
1607
+ * @param convoyId - Convoy ID
1608
+ * @param reason - Cancellation reason
1609
+ * @returns Cancelled convoy
1610
+ */
1611
+ cancel(convoyId: string, reason?: string): Promise<Convoy>;
1612
+ /**
1613
+ * Pause a convoy
1614
+ *
1615
+ * @param convoyId - Convoy ID
1616
+ * @returns Paused convoy
1617
+ */
1618
+ pause(convoyId: string): Promise<Convoy>;
1619
+ /**
1620
+ * Resume a paused convoy
1621
+ *
1622
+ * @param convoyId - Convoy ID
1623
+ * @returns Resumed convoy
1624
+ */
1625
+ resume(convoyId: string): Promise<Convoy>;
1626
+ /**
1627
+ * List all convoys
1628
+ *
1629
+ * @param status - Optional status filter
1630
+ * @returns Array of convoys
1631
+ */
1632
+ listConvoys(status?: ConvoyStatus): Convoy[];
1633
+ /**
1634
+ * Get convoy by ID
1635
+ *
1636
+ * @param convoyId - Convoy ID
1637
+ * @returns Convoy or undefined
1638
+ */
1639
+ getConvoy(convoyId: string): Convoy | undefined;
1640
+ /**
1641
+ * Delete a convoy
1642
+ *
1643
+ * @param convoyId - Convoy ID
1644
+ * @returns True if deleted
1645
+ */
1646
+ deleteConvoy(convoyId: string): boolean;
1647
+ /**
1648
+ * Calculate progress for a set of issues
1649
+ */
1650
+ private calculateProgress;
1651
+ /**
1652
+ * Verify issues exist
1653
+ */
1654
+ private verifyIssues;
1655
+ /**
1656
+ * Fetch beads by IDs
1657
+ */
1658
+ private fetchBeads;
1659
+ /**
1660
+ * Map CLI bead type to Gas Town status
1661
+ */
1662
+ private mapBeadStatus;
1663
+ /**
1664
+ * Start progress tracking timer
1665
+ */
1666
+ private startProgressTracking;
1667
+ /**
1668
+ * Stop progress tracking timer
1669
+ */
1670
+ private stopProgressTracking;
1671
+ /**
1672
+ * Emit convoy event
1673
+ */
1674
+ private emitConvoyEvent;
1675
+ /**
1676
+ * Clean up resources
1677
+ */
1678
+ dispose(): void;
1679
+ }
1680
+ /**
1681
+ * Create a new convoy tracker instance
1682
+ */
1683
+ declare function createConvoyTracker(config: ConvoyTrackerConfig, logger?: ConvoyLogger): ConvoyTracker;
1684
+
1685
+ /**
1686
+ * Object Pooling for Gas Town Bridge Plugin
1687
+ *
1688
+ * Provides high-performance object pooling to minimize GC pressure
1689
+ * and reduce memory allocations for frequently created objects.
1690
+ *
1691
+ * Target: 75% memory reduction, <10MB heap for 10k beads
1692
+ *
1693
+ * Pooled object types:
1694
+ * - Bead: Git-backed issue tracking objects
1695
+ * - Formula: TOML-defined workflow definitions
1696
+ * - Step: Individual workflow steps
1697
+ * - Convoy: Work-order tracking containers
1698
+ * - Molecule: Generated work units
1699
+ *
1700
+ * @module gastown-bridge/memory/pool
1701
+ */
1702
+
1703
+ /**
1704
+ * Poolable object interface - objects that can be reset and reused
1705
+ */
1706
+ interface Poolable {
1707
+ /** Reset object to initial state for reuse */
1708
+ reset?(): void;
1709
+ }
1710
+ /**
1711
+ * Pool statistics for monitoring
1712
+ */
1713
+ interface PoolStats {
1714
+ /** Total objects created (including pooled) */
1715
+ created: number;
1716
+ /** Objects currently in pool (available) */
1717
+ available: number;
1718
+ /** Objects currently in use */
1719
+ inUse: number;
1720
+ /** Number of times pool was empty on acquire */
1721
+ misses: number;
1722
+ /** Number of successful pool acquisitions */
1723
+ hits: number;
1724
+ /** Peak pool size reached */
1725
+ peakSize: number;
1726
+ /** Memory saved (estimated bytes) */
1727
+ memorySaved: number;
1728
+ }
1729
+ /**
1730
+ * Pool configuration
1731
+ */
1732
+ interface PoolConfig {
1733
+ /** Initial pool size */
1734
+ initialSize?: number;
1735
+ /** Maximum pool size (0 = unlimited) */
1736
+ maxSize?: number;
1737
+ /** Estimated object size in bytes (for memory tracking) */
1738
+ objectSizeBytes?: number;
1739
+ /** Whether to pre-warm the pool */
1740
+ preWarm?: boolean;
1741
+ }
1742
+ /**
1743
+ * High-performance generic object pool
1744
+ *
1745
+ * Uses a simple array-based free list for O(1) acquire/release.
1746
+ * Supports both factory functions and prototype-based object creation.
1747
+ *
1748
+ * @example
1749
+ * ```typescript
1750
+ * const beadPool = new ObjectPool<PooledBead>({
1751
+ * factory: () => new PooledBead(),
1752
+ * reset: (bead) => bead.reset(),
1753
+ * initialSize: 100,
1754
+ * maxSize: 10000,
1755
+ * });
1756
+ *
1757
+ * const bead = beadPool.acquire();
1758
+ * // ... use bead ...
1759
+ * beadPool.release(bead);
1760
+ * ```
1761
+ */
1762
+ declare class ObjectPool<T extends object> {
1763
+ private pool;
1764
+ private factory;
1765
+ private resetFn?;
1766
+ private config;
1767
+ private stats;
1768
+ constructor(factory: () => T, options?: PoolConfig & {
1769
+ reset?: (obj: T) => void;
1770
+ });
1771
+ /**
1772
+ * Acquire an object from the pool
1773
+ *
1774
+ * Returns a pooled object if available, otherwise creates a new one.
1775
+ * O(1) operation using array pop.
1776
+ */
1777
+ acquire(): T;
1778
+ /**
1779
+ * Release an object back to the pool
1780
+ *
1781
+ * Resets the object and returns it to the pool for reuse.
1782
+ * O(1) operation using array push.
1783
+ *
1784
+ * @param obj - Object to release
1785
+ */
1786
+ release(obj: T): void;
1787
+ /**
1788
+ * Release multiple objects at once (batch operation)
1789
+ */
1790
+ releaseAll(objects: T[]): void;
1791
+ /**
1792
+ * Pre-warm the pool with objects
1793
+ */
1794
+ preWarm(count: number): void;
1795
+ /**
1796
+ * Clear the pool and release all objects
1797
+ */
1798
+ clear(): void;
1799
+ /**
1800
+ * Get pool statistics
1801
+ */
1802
+ getStats(): Readonly<PoolStats>;
1803
+ /**
1804
+ * Get current pool size
1805
+ */
1806
+ get size(): number;
1807
+ /**
1808
+ * Get hit rate (percentage of successful pool acquisitions)
1809
+ */
1810
+ get hitRate(): number;
1811
+ }
1812
+ /**
1813
+ * Pooled Bead object with reset capability
1814
+ */
1815
+ declare class PooledBead implements Bead, Poolable {
1816
+ id: string;
1817
+ title: string;
1818
+ description: string;
1819
+ status: BeadStatus;
1820
+ priority: number;
1821
+ labels: string[];
1822
+ createdAt: Date;
1823
+ updatedAt: Date;
1824
+ parentId?: string;
1825
+ assignee?: string;
1826
+ rig?: string;
1827
+ blockedBy?: string[];
1828
+ blocks?: string[];
1829
+ reset(): void;
1830
+ /**
1831
+ * Initialize from a Bead-like object
1832
+ */
1833
+ initFrom(source: Partial<Bead>): this;
1834
+ }
1835
+ /**
1836
+ * Pooled Step object with reset capability
1837
+ */
1838
+ declare class PooledStep implements Step, Poolable {
1839
+ id: string;
1840
+ title: string;
1841
+ description: string;
1842
+ needs?: string[];
1843
+ duration?: number;
1844
+ requires?: string[];
1845
+ metadata?: Record<string, unknown>;
1846
+ reset(): void;
1847
+ initFrom(source: Partial<Step>): this;
1848
+ }
1849
+ /**
1850
+ * Pooled Formula object with reset capability
1851
+ */
1852
+ declare class PooledFormula implements Formula, Poolable {
1853
+ name: string;
1854
+ description: string;
1855
+ type: FormulaType;
1856
+ version: number;
1857
+ steps?: Step[];
1858
+ legs?: Formula['legs'];
1859
+ vars?: Formula['vars'];
1860
+ metadata?: Formula['metadata'];
1861
+ reset(): void;
1862
+ initFrom(source: Partial<Formula>): this;
1863
+ }
1864
+ /**
1865
+ * Pooled Convoy object with reset capability
1866
+ */
1867
+ declare class PooledConvoy implements Convoy, Poolable {
1868
+ id: string;
1869
+ name: string;
1870
+ trackedIssues: string[];
1871
+ status: ConvoyStatus;
1872
+ startedAt: Date;
1873
+ completedAt?: Date;
1874
+ progress: {
1875
+ total: number;
1876
+ closed: number;
1877
+ inProgress: number;
1878
+ blocked: number;
1879
+ };
1880
+ formula?: string;
1881
+ description?: string;
1882
+ reset(): void;
1883
+ initFrom(source: Partial<Convoy>): this;
1884
+ }
1885
+ /**
1886
+ * Pooled Molecule object with reset capability
1887
+ */
1888
+ declare class PooledMolecule implements Molecule, Poolable {
1889
+ id: string;
1890
+ formulaName: string;
1891
+ title: string;
1892
+ description: string;
1893
+ type: FormulaType;
1894
+ sourceId: string;
1895
+ agent?: string;
1896
+ dependencies: string[];
1897
+ order: number;
1898
+ metadata: Record<string, unknown>;
1899
+ createdAt: Date;
1900
+ reset(): void;
1901
+ initFrom(source: Partial<Molecule>): this;
1902
+ }
1903
+ /**
1904
+ * Global Bead pool - optimized for 10k beads target
1905
+ * Estimated size per bead: ~512 bytes
1906
+ */
1907
+ declare const beadPool: ObjectPool<PooledBead>;
1908
+ /**
1909
+ * Global Formula pool
1910
+ * Estimated size per formula: ~1KB
1911
+ */
1912
+ declare const formulaPool: ObjectPool<PooledFormula>;
1913
+ /**
1914
+ * Global Step pool
1915
+ * Estimated size per step: ~256 bytes
1916
+ */
1917
+ declare const stepPool: ObjectPool<PooledStep>;
1918
+ /**
1919
+ * Global Convoy pool
1920
+ * Estimated size per convoy: ~768 bytes
1921
+ */
1922
+ declare const convoyPool: ObjectPool<PooledConvoy>;
1923
+ /**
1924
+ * Global Molecule pool
1925
+ * Estimated size per molecule: ~384 bytes
1926
+ */
1927
+ declare const moleculePool: ObjectPool<PooledMolecule>;
1928
+ /**
1929
+ * All managed pools
1930
+ */
1931
+ declare const allPools: {
1932
+ readonly bead: ObjectPool<PooledBead>;
1933
+ readonly formula: ObjectPool<PooledFormula>;
1934
+ readonly step: ObjectPool<PooledStep>;
1935
+ readonly convoy: ObjectPool<PooledConvoy>;
1936
+ readonly molecule: ObjectPool<PooledMolecule>;
1937
+ };
1938
+ type PoolType = keyof typeof allPools;
1939
+ /**
1940
+ * Get statistics for all pools
1941
+ */
1942
+ declare function getAllPoolStats(): Record<PoolType, PoolStats>;
1943
+ /**
1944
+ * Get total memory saved across all pools
1945
+ */
1946
+ declare function getTotalMemorySaved(): number;
1947
+ /**
1948
+ * Clear all pools
1949
+ */
1950
+ declare function clearAllPools(): void;
1951
+ /**
1952
+ * Pre-warm all pools with default sizes
1953
+ */
1954
+ declare function preWarmAllPools(): void;
1955
+ /**
1956
+ * Get a summary of pool efficiency
1957
+ */
1958
+ declare function getPoolEfficiencySummary(): {
1959
+ totalHitRate: number;
1960
+ totalMemorySavedKB: number;
1961
+ totalObjectsInUse: number;
1962
+ totalObjectsAvailable: number;
1963
+ };
1964
+
1965
+ /**
1966
+ * Arena Allocator for Gas Town Bridge Plugin
1967
+ *
1968
+ * Provides bulk memory allocation with single-operation deallocation.
1969
+ * Ideal for batch operations where many objects are created and then
1970
+ * discarded together (e.g., convoy graph operations, formula parsing).
1971
+ *
1972
+ * Benefits:
1973
+ * - O(1) reset/clear operation
1974
+ * - Reduced GC pressure for batch operations
1975
+ * - Better memory locality
1976
+ * - Predictable memory usage
1977
+ *
1978
+ * @module gastown-bridge/memory/arena
1979
+ */
1980
+
1981
+ /**
1982
+ * Arena statistics
1983
+ */
1984
+ interface ArenaStats {
1985
+ /** Total allocations since creation */
1986
+ totalAllocations: number;
1987
+ /** Current allocations (not yet reset) */
1988
+ currentAllocations: number;
1989
+ /** Number of reset operations */
1990
+ resetCount: number;
1991
+ /** Peak allocations before reset */
1992
+ peakAllocations: number;
1993
+ /** Estimated memory in use (bytes) */
1994
+ memoryUsed: number;
1995
+ /** Total memory saved via bulk reset (bytes) */
1996
+ memorySaved: number;
1997
+ }
1998
+ /**
1999
+ * Arena configuration
2000
+ */
2001
+ interface ArenaConfig {
2002
+ /** Name for debugging */
2003
+ name?: string;
2004
+ /** Initial capacity hint */
2005
+ initialCapacity?: number;
2006
+ /** Maximum allocations before forced reset */
2007
+ maxAllocations?: number;
2008
+ /** Enable automatic pool return on reset */
2009
+ returnToPool?: boolean;
2010
+ }
2011
+ /**
2012
+ * Arena Allocator
2013
+ *
2014
+ * Manages bulk allocations that are reset together. Uses underlying
2015
+ * object pools when available for maximum efficiency.
2016
+ *
2017
+ * @example
2018
+ * ```typescript
2019
+ * const arena = new Arena('convoy-analysis');
2020
+ *
2021
+ * // Allocate objects for batch operation
2022
+ * const beads = arena.allocateMany('bead', 100);
2023
+ * const steps = arena.allocateMany('step', 50);
2024
+ *
2025
+ * // Process...
2026
+ *
2027
+ * // Single O(1) reset clears everything
2028
+ * arena.reset();
2029
+ * ```
2030
+ */
2031
+ declare class Arena {
2032
+ private name;
2033
+ private config;
2034
+ private allocations;
2035
+ private stats;
2036
+ private beadPool;
2037
+ private stepPool;
2038
+ private formulaPool;
2039
+ private convoyPool;
2040
+ private moleculePool;
2041
+ constructor(name?: string, config?: ArenaConfig);
2042
+ /**
2043
+ * Allocate an object from the arena
2044
+ *
2045
+ * Uses pooled objects when available for the given type.
2046
+ */
2047
+ allocate<T>(factory: () => T, sizeBytes?: number): T;
2048
+ /**
2049
+ * Allocate a typed object from the arena pools
2050
+ */
2051
+ allocateTyped<K extends AllocatableType>(type: K): TypeMap[K];
2052
+ /**
2053
+ * Allocate multiple typed objects
2054
+ */
2055
+ allocateMany<K extends AllocatableType>(type: K, count: number): TypeMap[K][];
2056
+ /**
2057
+ * Reset the arena, returning all objects to their pools
2058
+ *
2059
+ * This is an O(n) operation where n is the number of allocations,
2060
+ * but it's a single operation instead of n individual deallocations.
2061
+ */
2062
+ reset(): void;
2063
+ /**
2064
+ * Get arena statistics
2065
+ */
2066
+ getStats(): Readonly<ArenaStats>;
2067
+ /**
2068
+ * Get current allocation count
2069
+ */
2070
+ get allocationCount(): number;
2071
+ /**
2072
+ * Get arena name
2073
+ */
2074
+ get arenaName(): string;
2075
+ /**
2076
+ * Dispose the arena and all its resources
2077
+ */
2078
+ dispose(): void;
2079
+ private trackAllocation;
2080
+ private checkMaxAllocations;
2081
+ private returnToPool;
2082
+ }
2083
+ /**
2084
+ * Allocatable type names
2085
+ */
2086
+ type AllocatableType = 'bead' | 'step' | 'formula' | 'convoy' | 'molecule';
2087
+ /**
2088
+ * Type map for allocatable types
2089
+ */
2090
+ interface TypeMap {
2091
+ bead: PooledBead;
2092
+ step: PooledStep;
2093
+ formula: PooledFormula;
2094
+ convoy: PooledConvoy;
2095
+ molecule: PooledMolecule;
2096
+ }
2097
+ /**
2098
+ * Scoped arena that auto-resets when disposed
2099
+ *
2100
+ * Useful for RAII-style memory management with try/finally patterns.
2101
+ *
2102
+ * @example
2103
+ * ```typescript
2104
+ * using arena = scopedArena('batch-operation');
2105
+ * const beads = arena.allocateMany('bead', 100);
2106
+ * // ... process beads ...
2107
+ * // Arena automatically resets when scope exits
2108
+ * ```
2109
+ */
2110
+ declare function scopedArena(name: string, config?: ArenaConfig): Arena & Disposable;
2111
+ /**
2112
+ * Execute a function with a scoped arena
2113
+ *
2114
+ * The arena is automatically reset after the function completes.
2115
+ */
2116
+ declare function withArena<T>(name: string, fn: (arena: Arena) => T | Promise<T>, config?: ArenaConfig): Promise<T>;
2117
+ /**
2118
+ * Synchronous version of withArena
2119
+ */
2120
+ declare function withArenaSync<T>(name: string, fn: (arena: Arena) => T, config?: ArenaConfig): T;
2121
+ /**
2122
+ * Manages multiple arenas for different operation types
2123
+ */
2124
+ declare class ArenaManager {
2125
+ private arenas;
2126
+ private stats;
2127
+ /**
2128
+ * Get or create an arena by name
2129
+ */
2130
+ getArena(name: string, config?: ArenaConfig): Arena;
2131
+ /**
2132
+ * Reset a specific arena
2133
+ */
2134
+ resetArena(name: string): void;
2135
+ /**
2136
+ * Reset all arenas
2137
+ */
2138
+ resetAll(): void;
2139
+ /**
2140
+ * Dispose an arena
2141
+ */
2142
+ disposeArena(name: string): void;
2143
+ /**
2144
+ * Dispose all arenas
2145
+ */
2146
+ disposeAll(): void;
2147
+ /**
2148
+ * Get manager statistics
2149
+ */
2150
+ getStats(): typeof this.stats & {
2151
+ arenaStats: Record<string, ArenaStats>;
2152
+ };
2153
+ }
2154
+ /**
2155
+ * Global arena manager instance
2156
+ */
2157
+ declare const arenaManager: ArenaManager;
2158
+
2159
+ /**
2160
+ * Memory Monitoring for Gas Town Bridge Plugin
2161
+ *
2162
+ * Provides comprehensive memory monitoring, limits, and pressure callbacks.
2163
+ * Integrates with object pools and arena allocators to track memory usage.
2164
+ *
2165
+ * Target: <10MB heap for 10k beads
2166
+ *
2167
+ * Features:
2168
+ * - Real-time memory usage tracking
2169
+ * - Configurable memory limits
2170
+ * - Memory pressure callbacks
2171
+ * - Automatic cleanup triggers
2172
+ * - Integration with V8 GC hooks (when available)
2173
+ *
2174
+ * @module gastown-bridge/memory/monitor
2175
+ */
2176
+
2177
+ /**
2178
+ * Memory statistics snapshot
2179
+ */
2180
+ interface MemoryStats {
2181
+ /** Heap memory used (bytes) */
2182
+ heapUsed: number;
2183
+ /** Heap memory total (bytes) */
2184
+ heapTotal: number;
2185
+ /** External memory (bytes) */
2186
+ external: number;
2187
+ /** Array buffers memory (bytes) */
2188
+ arrayBuffers: number;
2189
+ /** RSS (Resident Set Size) in bytes */
2190
+ rss: number;
2191
+ /** Pool memory stats */
2192
+ pools: {
2193
+ totalMemorySaved: number;
2194
+ hitRate: number;
2195
+ objectsInUse: number;
2196
+ objectsAvailable: number;
2197
+ };
2198
+ /** Arena memory stats */
2199
+ arenas: {
2200
+ activeArenas: number;
2201
+ totalMemoryUsed: number;
2202
+ totalMemorySaved: number;
2203
+ };
2204
+ /** Timestamp of snapshot */
2205
+ timestamp: Date;
2206
+ /** Whether under memory pressure */
2207
+ underPressure: boolean;
2208
+ }
2209
+ /**
2210
+ * Memory pressure levels
2211
+ */
2212
+ type MemoryPressureLevel = 'none' | 'low' | 'medium' | 'high' | 'critical';
2213
+ /**
2214
+ * Memory pressure callback
2215
+ */
2216
+ type MemoryPressureCallback = (level: MemoryPressureLevel, stats: MemoryStats) => void;
2217
+ /**
2218
+ * Memory monitor configuration
2219
+ */
2220
+ interface MemoryMonitorConfig {
2221
+ /** Memory limit in bytes (0 = no limit) */
2222
+ memoryLimit?: number;
2223
+ /** Low pressure threshold (0-1 of limit) */
2224
+ lowPressureThreshold?: number;
2225
+ /** Medium pressure threshold (0-1 of limit) */
2226
+ mediumPressureThreshold?: number;
2227
+ /** High pressure threshold (0-1 of limit) */
2228
+ highPressureThreshold?: number;
2229
+ /** Critical pressure threshold (0-1 of limit) */
2230
+ criticalPressureThreshold?: number;
2231
+ /** Polling interval in ms (0 = manual only) */
2232
+ pollInterval?: number;
2233
+ /** Enable automatic cleanup on pressure */
2234
+ autoCleanup?: boolean;
2235
+ /** Enable GC hints when available */
2236
+ gcHints?: boolean;
2237
+ }
2238
+ /**
2239
+ * Memory monitor events
2240
+ */
2241
+ interface MemoryMonitorEvents {
2242
+ 'pressure:none': (stats: MemoryStats) => void;
2243
+ 'pressure:low': (stats: MemoryStats) => void;
2244
+ 'pressure:medium': (stats: MemoryStats) => void;
2245
+ 'pressure:high': (stats: MemoryStats) => void;
2246
+ 'pressure:critical': (stats: MemoryStats) => void;
2247
+ 'limit:exceeded': (stats: MemoryStats) => void;
2248
+ 'cleanup:triggered': (beforeStats: MemoryStats, afterStats: MemoryStats) => void;
2249
+ 'snapshot': (stats: MemoryStats) => void;
2250
+ }
2251
+ /**
2252
+ * Memory Monitor
2253
+ *
2254
+ * Tracks memory usage and triggers pressure callbacks when thresholds
2255
+ * are exceeded. Integrates with object pools and arenas.
2256
+ *
2257
+ * @example
2258
+ * ```typescript
2259
+ * const monitor = new MemoryMonitor({
2260
+ * memoryLimit: 10 * 1024 * 1024, // 10MB
2261
+ * pollInterval: 1000,
2262
+ * autoCleanup: true,
2263
+ * });
2264
+ *
2265
+ * monitor.onMemoryPressure((level, stats) => {
2266
+ * console.log(`Memory pressure: ${level}`, stats);
2267
+ * });
2268
+ *
2269
+ * monitor.start();
2270
+ * ```
2271
+ */
2272
+ declare class MemoryMonitor extends EventEmitter {
2273
+ private config;
2274
+ private pollTimer?;
2275
+ private pressureCallbacks;
2276
+ private lastPressureLevel;
2277
+ private running;
2278
+ private statsHistory;
2279
+ private maxHistorySize;
2280
+ constructor(config?: MemoryMonitorConfig);
2281
+ /**
2282
+ * Get current memory usage statistics
2283
+ */
2284
+ getMemoryUsage(): MemoryStats;
2285
+ /**
2286
+ * Set memory limit
2287
+ */
2288
+ setMemoryLimit(bytes: number): void;
2289
+ /**
2290
+ * Get current memory limit
2291
+ */
2292
+ getMemoryLimit(): number;
2293
+ /**
2294
+ * Register a memory pressure callback
2295
+ */
2296
+ onMemoryPressure(callback: MemoryPressureCallback): () => void;
2297
+ /**
2298
+ * Check current pressure level
2299
+ */
2300
+ checkPressure(): MemoryPressureLevel;
2301
+ /**
2302
+ * Start monitoring
2303
+ */
2304
+ start(): void;
2305
+ /**
2306
+ * Stop monitoring
2307
+ */
2308
+ stop(): void;
2309
+ /**
2310
+ * Manual poll (also called automatically if pollInterval > 0)
2311
+ */
2312
+ poll(): void;
2313
+ /**
2314
+ * Trigger memory cleanup
2315
+ */
2316
+ triggerCleanup(): void;
2317
+ /**
2318
+ * Get memory trend (bytes/second)
2319
+ */
2320
+ getMemoryTrend(): number;
2321
+ /**
2322
+ * Estimate time until limit reached (ms)
2323
+ */
2324
+ estimateTimeToLimit(): number | null;
2325
+ /**
2326
+ * Get pool-specific statistics
2327
+ */
2328
+ getPoolStats(): Record<string, PoolStats>;
2329
+ /**
2330
+ * Get historical stats
2331
+ */
2332
+ getHistory(): MemoryStats[];
2333
+ /**
2334
+ * Clear historical stats
2335
+ */
2336
+ clearHistory(): void;
2337
+ /**
2338
+ * Check if running
2339
+ */
2340
+ isRunning(): boolean;
2341
+ /**
2342
+ * Get configuration
2343
+ */
2344
+ getConfig(): Readonly<Required<MemoryMonitorConfig>>;
2345
+ /**
2346
+ * Update configuration
2347
+ */
2348
+ updateConfig(config: Partial<MemoryMonitorConfig>): void;
2349
+ }
2350
+ /**
2351
+ * Get current memory usage (simple API)
2352
+ */
2353
+ declare function getMemoryUsage(): MemoryStats;
2354
+ /**
2355
+ * Set a memory limit and callback (simple API)
2356
+ */
2357
+ declare function setMemoryLimit(bytes: number, onPressure?: MemoryPressureCallback): MemoryMonitor;
2358
+ declare function onMemoryPressure(callback: MemoryPressureCallback): () => void;
2359
+ /**
2360
+ * Get the default monitor instance
2361
+ */
2362
+ declare function getDefaultMonitor(): MemoryMonitor | null;
2363
+ /**
2364
+ * Stop and dispose the default monitor
2365
+ */
2366
+ declare function disposeDefaultMonitor(): void;
2367
+ /**
2368
+ * Memory budget for component-level tracking
2369
+ */
2370
+ interface MemoryBudget {
2371
+ name: string;
2372
+ allocated: number;
2373
+ used: number;
2374
+ limit: number;
2375
+ }
2376
+ /**
2377
+ * Memory budget manager
2378
+ */
2379
+ declare class MemoryBudgetManager {
2380
+ private budgets;
2381
+ private totalLimit;
2382
+ constructor(totalLimit?: number);
2383
+ /**
2384
+ * Allocate a budget for a component
2385
+ */
2386
+ allocateBudget(name: string, limit: number): boolean;
2387
+ /**
2388
+ * Update usage for a budget
2389
+ */
2390
+ updateUsage(name: string, used: number): void;
2391
+ /**
2392
+ * Check if a budget is exceeded
2393
+ */
2394
+ isExceeded(name: string): boolean;
2395
+ /**
2396
+ * Get budget for a component
2397
+ */
2398
+ getBudget(name: string): MemoryBudget | undefined;
2399
+ /**
2400
+ * Get all budgets
2401
+ */
2402
+ getAllBudgets(): MemoryBudget[];
2403
+ /**
2404
+ * Get total allocated budget
2405
+ */
2406
+ getTotalAllocated(): number;
2407
+ /**
2408
+ * Get total used
2409
+ */
2410
+ getTotalUsed(): number;
2411
+ /**
2412
+ * Free a budget
2413
+ */
2414
+ freeBudget(name: string): void;
2415
+ /**
2416
+ * Get total limit
2417
+ */
2418
+ getTotalLimit(): number;
2419
+ /**
2420
+ * Set total limit
2421
+ */
2422
+ setTotalLimit(limit: number): void;
2423
+ }
2424
+ /**
2425
+ * Global memory budget manager for 10MB target
2426
+ */
2427
+ declare const memoryBudget: MemoryBudgetManager;
2428
+
2429
+ /**
2430
+ * Lazy Loading Utilities for Gas Town Bridge Plugin
2431
+ *
2432
+ * Provides lazy initialization patterns to defer resource loading
2433
+ * until first use, reducing initial memory footprint and startup time.
2434
+ *
2435
+ * Features:
2436
+ * - Lazy WASM module loading
2437
+ * - Deferred convoy observer initialization
2438
+ * - Lazy bridge initialization
2439
+ * - Resource cleanup on idle
2440
+ *
2441
+ * @module gastown-bridge/memory/lazy
2442
+ */
2443
+ /**
2444
+ * Lazy value state
2445
+ */
2446
+ type LazyState = 'uninitialized' | 'initializing' | 'initialized' | 'error' | 'disposed';
2447
+ /**
2448
+ * Lazy initialization options
2449
+ */
2450
+ interface LazyOptions<T> {
2451
+ /** Factory function to create the value */
2452
+ factory: () => T | Promise<T>;
2453
+ /** Optional cleanup function */
2454
+ cleanup?: (value: T) => void | Promise<void>;
2455
+ /** Auto-dispose after idle time (ms, 0 = never) */
2456
+ idleTimeout?: number;
2457
+ /** Error handler */
2458
+ onError?: (error: Error) => void;
2459
+ /** Name for debugging */
2460
+ name?: string;
2461
+ }
2462
+ /**
2463
+ * Lazy loader statistics
2464
+ */
2465
+ interface LazyStats {
2466
+ name: string;
2467
+ state: LazyState;
2468
+ initCount: number;
2469
+ disposeCount: number;
2470
+ errorCount: number;
2471
+ lastInitTime?: Date;
2472
+ lastAccessTime?: Date;
2473
+ initDurationMs?: number;
2474
+ }
2475
+ /**
2476
+ * Lazy value wrapper with automatic initialization
2477
+ *
2478
+ * @example
2479
+ * ```typescript
2480
+ * const lazyWasm = new Lazy({
2481
+ * name: 'wasm-module',
2482
+ * factory: async () => await loadWasmModule(),
2483
+ * cleanup: (wasm) => wasm.dispose(),
2484
+ * idleTimeout: 60000, // Auto-dispose after 1 minute of inactivity
2485
+ * });
2486
+ *
2487
+ * // First access triggers initialization
2488
+ * const wasm = await lazyWasm.get();
2489
+ *
2490
+ * // Check if initialized without triggering
2491
+ * if (lazyWasm.isInitialized()) { ... }
2492
+ *
2493
+ * // Manual disposal
2494
+ * await lazyWasm.dispose();
2495
+ * ```
2496
+ */
2497
+ declare class Lazy<T> {
2498
+ private value?;
2499
+ private state;
2500
+ private initPromise?;
2501
+ private idleTimer?;
2502
+ private options;
2503
+ private stats;
2504
+ constructor(options: LazyOptions<T>);
2505
+ /**
2506
+ * Get the lazy value, initializing if necessary
2507
+ */
2508
+ get(): Promise<T>;
2509
+ /**
2510
+ * Get synchronously (throws if not initialized)
2511
+ */
2512
+ getSync(): T;
2513
+ /**
2514
+ * Check if initialized
2515
+ */
2516
+ isInitialized(): boolean;
2517
+ /**
2518
+ * Get current state
2519
+ */
2520
+ getState(): LazyState;
2521
+ /**
2522
+ * Initialize without returning value
2523
+ */
2524
+ initialize(): Promise<T>;
2525
+ /**
2526
+ * Dispose the lazy value
2527
+ */
2528
+ dispose(): Promise<void>;
2529
+ /**
2530
+ * Get statistics
2531
+ */
2532
+ getStats(): Readonly<LazyStats>;
2533
+ private resetIdleTimer;
2534
+ private clearIdleTimer;
2535
+ }
2536
+ /**
2537
+ * Get or create a lazy singleton
2538
+ */
2539
+ declare function getLazySingleton<T>(key: string, options: LazyOptions<T>): Lazy<T>;
2540
+ /**
2541
+ * Dispose a lazy singleton
2542
+ */
2543
+ declare function disposeLazySingleton(key: string): Promise<void>;
2544
+ /**
2545
+ * Dispose all lazy singletons
2546
+ */
2547
+ declare function disposeAllLazySingletons(): Promise<void>;
2548
+ /**
2549
+ * Lazy module loader for dynamic imports
2550
+ *
2551
+ * @example
2552
+ * ```typescript
2553
+ * const wasmLoader = new LazyModule(() => import('./wasm-loader.js'));
2554
+ * const { parseFormula } = await wasmLoader.get();
2555
+ * ```
2556
+ */
2557
+ declare class LazyModule<T> {
2558
+ private lazy;
2559
+ constructor(importer: () => Promise<T>, options?: Omit<LazyOptions<T>, 'factory'>);
2560
+ /**
2561
+ * Get the module
2562
+ */
2563
+ get(): Promise<T>;
2564
+ /**
2565
+ * Check if loaded
2566
+ */
2567
+ isLoaded(): boolean;
2568
+ /**
2569
+ * Dispose module
2570
+ */
2571
+ dispose(): Promise<void>;
2572
+ }
2573
+ /**
2574
+ * Lazy bridge wrapper for Gas Town bridges
2575
+ *
2576
+ * Defers bridge initialization until first use.
2577
+ */
2578
+ declare class LazyBridge<T extends {
2579
+ initialize?: () => Promise<void>;
2580
+ }> {
2581
+ private lazy;
2582
+ constructor(factory: () => T | Promise<T>, options?: Omit<LazyOptions<T>, 'factory'>);
2583
+ /**
2584
+ * Get the bridge
2585
+ */
2586
+ get(): Promise<T>;
2587
+ /**
2588
+ * Check if initialized
2589
+ */
2590
+ isInitialized(): boolean;
2591
+ /**
2592
+ * Dispose bridge
2593
+ */
2594
+ dispose(): Promise<void>;
2595
+ /**
2596
+ * Get stats
2597
+ */
2598
+ getStats(): LazyStats;
2599
+ }
2600
+ /**
2601
+ * Lazy WASM module loader with caching
2602
+ */
2603
+ declare class LazyWasm<T> {
2604
+ private lazy;
2605
+ private cached;
2606
+ constructor(loader: () => Promise<T>, options?: {
2607
+ name?: string;
2608
+ idleTimeout?: number;
2609
+ onError?: (error: Error) => void;
2610
+ });
2611
+ /**
2612
+ * Get the WASM module
2613
+ */
2614
+ get(): Promise<T>;
2615
+ /**
2616
+ * Check if loaded
2617
+ */
2618
+ isLoaded(): boolean;
2619
+ /**
2620
+ * Clear cache (module will be reloaded on next access)
2621
+ */
2622
+ clearCache(): void;
2623
+ /**
2624
+ * Get stats
2625
+ */
2626
+ getStats(): LazyStats;
2627
+ }
2628
+ /**
2629
+ * Lazy observer pattern for convoy watching
2630
+ *
2631
+ * Defers observer creation until first watch request.
2632
+ */
2633
+ declare class LazyObserver<T> {
2634
+ private lazy;
2635
+ private watchCount;
2636
+ constructor(factory: () => T | Promise<T>, options?: Omit<LazyOptions<T>, 'factory'>);
2637
+ /**
2638
+ * Start watching (initializes observer if needed)
2639
+ */
2640
+ watch(): Promise<T>;
2641
+ /**
2642
+ * Stop watching (disposes observer if no more watchers)
2643
+ */
2644
+ unwatch(): Promise<void>;
2645
+ /**
2646
+ * Get current watch count
2647
+ */
2648
+ getWatchCount(): number;
2649
+ /**
2650
+ * Check if active
2651
+ */
2652
+ isActive(): boolean;
2653
+ /**
2654
+ * Force dispose
2655
+ */
2656
+ dispose(): Promise<void>;
2657
+ }
2658
+ /**
2659
+ * Create a lazy property getter
2660
+ */
2661
+ declare function createLazyProperty<T>(factory: () => T | Promise<T>, options?: Omit<LazyOptions<T>, 'factory'>): {
2662
+ get: () => Promise<T>;
2663
+ isInitialized: () => boolean;
2664
+ };
2665
+
2666
+ /**
2667
+ * Memory Management Module for Gas Town Bridge Plugin
2668
+ *
2669
+ * Provides comprehensive memory optimization through:
2670
+ * - Object pooling for frequently allocated objects (Bead, Formula, Step, Convoy, Molecule)
2671
+ * - Arena allocators for batch operations with O(1) reset
2672
+ * - Memory monitoring with pressure callbacks
2673
+ * - Lazy loading for deferred resource initialization
2674
+ *
2675
+ * Target: 75% memory reduction, <10MB heap for 10k beads
2676
+ *
2677
+ * @module gastown-bridge/memory
2678
+ */
2679
+
2680
+ /**
2681
+ * Memory system configuration
2682
+ */
2683
+ interface MemorySystemConfig {
2684
+ /** Memory limit in bytes (default: 10MB) */
2685
+ memoryLimit?: number;
2686
+ /** Enable auto-cleanup on pressure */
2687
+ autoCleanup?: boolean;
2688
+ /** Pre-warm pools on init */
2689
+ preWarmPools?: boolean;
2690
+ /** Polling interval for monitor (ms) */
2691
+ pollInterval?: number;
2692
+ }
2693
+ /**
2694
+ * Memory system state
2695
+ */
2696
+ interface MemorySystemState {
2697
+ initialized: boolean;
2698
+ monitor: MemoryMonitor | null;
2699
+ config: MemorySystemConfig;
2700
+ }
2701
+ /**
2702
+ * Initialize the memory management system
2703
+ *
2704
+ * @example
2705
+ * ```typescript
2706
+ * import { initializeMemorySystem, getSystemMemoryStats } from './memory/index.js';
2707
+ *
2708
+ * await initializeMemorySystem({
2709
+ * memoryLimit: 10 * 1024 * 1024, // 10MB
2710
+ * autoCleanup: true,
2711
+ * preWarmPools: true,
2712
+ * });
2713
+ *
2714
+ * // Monitor memory usage
2715
+ * const stats = getSystemMemoryStats();
2716
+ * console.log('Heap used:', stats.heapUsed);
2717
+ * ```
2718
+ */
2719
+ declare function initializeMemorySystem(config?: MemorySystemConfig): void;
2720
+ /**
2721
+ * Get system memory statistics
2722
+ */
2723
+ declare function getSystemMemoryStats(): MemoryStats | null;
2724
+ /**
2725
+ * Get comprehensive memory report
2726
+ */
2727
+ declare function getMemoryReport(): {
2728
+ system: MemoryStats | null;
2729
+ pools: ReturnType<typeof getAllPoolStats>;
2730
+ poolEfficiency: ReturnType<typeof getPoolEfficiencySummary>;
2731
+ arenas: ReturnType<typeof arenaManager.getStats>;
2732
+ config: MemorySystemConfig;
2733
+ };
2734
+ /**
2735
+ * Trigger manual memory cleanup
2736
+ */
2737
+ declare function triggerMemoryCleanup(): void;
2738
+ /**
2739
+ * Shutdown the memory system
2740
+ */
2741
+ declare function shutdownMemorySystem(): Promise<void>;
2742
+ /**
2743
+ * Check if memory system is initialized
2744
+ */
2745
+ declare function isMemorySystemInitialized(): boolean;
2746
+ /**
2747
+ * Get memory system monitor
2748
+ */
2749
+ declare function getMemoryMonitor(): MemoryMonitor | null;
2750
+
2751
+ /**
2752
+ * Acquire a pooled bead
2753
+ */
2754
+ declare function acquireBead(): PooledBead;
2755
+ /**
2756
+ * Release a pooled bead
2757
+ */
2758
+ declare function releaseBead(bead: PooledBead): void;
2759
+ /**
2760
+ * Acquire a pooled step
2761
+ */
2762
+ declare function acquireStep(): PooledStep;
2763
+ /**
2764
+ * Release a pooled step
2765
+ */
2766
+ declare function releaseStep(step: PooledStep): void;
2767
+ /**
2768
+ * Acquire a pooled formula
2769
+ */
2770
+ declare function acquireFormula(): PooledFormula;
2771
+ /**
2772
+ * Release a pooled formula
2773
+ */
2774
+ declare function releaseFormula(formula: PooledFormula): void;
2775
+ /**
2776
+ * Acquire a pooled convoy
2777
+ */
2778
+ declare function acquireConvoy(): PooledConvoy;
2779
+ /**
2780
+ * Release a pooled convoy
2781
+ */
2782
+ declare function releaseConvoy(convoy: PooledConvoy): void;
2783
+ /**
2784
+ * Acquire a pooled molecule
2785
+ */
2786
+ declare function acquireMolecule(): PooledMolecule;
2787
+ /**
2788
+ * Release a pooled molecule
2789
+ */
2790
+ declare function releaseMolecule(molecule: PooledMolecule): void;
2791
+
2792
+ /**
2793
+ * Convoy Observer
2794
+ *
2795
+ * Monitors convoy completion by observing issue state changes
2796
+ * and detecting when all tracked issues are complete. Uses
2797
+ * WASM-accelerated graph analysis for dependency resolution.
2798
+ *
2799
+ * Features:
2800
+ * - Watch convoys for completion
2801
+ * - Detect blocking issues
2802
+ * - Identify ready-to-work issues
2803
+ * - WASM-accelerated dependency graph analysis
2804
+ * - Configurable polling intervals
2805
+ *
2806
+ * @module gastown-bridge/convoy/observer
2807
+ */
2808
+
2809
+ /**
2810
+ * WASM graph module interface
2811
+ */
2812
+ interface WasmGraphModule {
2813
+ /** Check if dependency graph has cycles */
2814
+ has_cycle(beadsJson: string): boolean;
2815
+ /** Find nodes participating in cycles */
2816
+ find_cycle_nodes(beadsJson: string): string;
2817
+ /** Get beads with no unresolved dependencies */
2818
+ get_ready_beads(beadsJson: string): string;
2819
+ /** Compute execution levels for parallel processing */
2820
+ compute_levels(beadsJson: string): string;
2821
+ /** Topological sort of beads */
2822
+ topo_sort(beadsJson: string): string;
2823
+ /** Critical path analysis */
2824
+ critical_path(beadsJson: string): string;
2825
+ }
2826
+ /**
2827
+ * Completion callback signature
2828
+ */
2829
+ type CompletionCallback = (convoy: Convoy, allComplete: boolean) => void;
2830
+ /**
2831
+ * Observer watch handle
2832
+ */
2833
+ interface WatchHandle {
2834
+ /** Convoy ID being watched */
2835
+ convoyId: string;
2836
+ /** Stop watching */
2837
+ stop(): void;
2838
+ /** Check if still watching */
2839
+ isActive(): boolean;
2840
+ }
2841
+ /**
2842
+ * Observer configuration
2843
+ */
2844
+ interface ConvoyObserverConfig {
2845
+ /** BD bridge instance */
2846
+ bdBridge: BdBridge;
2847
+ /** Convoy tracker instance */
2848
+ tracker: ConvoyTracker;
2849
+ /** Optional WASM graph module */
2850
+ wasmModule?: WasmGraphModule;
2851
+ /** Initial polling interval in milliseconds */
2852
+ pollInterval?: number;
2853
+ /** Maximum poll attempts before giving up */
2854
+ maxPollAttempts?: number;
2855
+ /** Enable WASM acceleration (falls back to JS if unavailable) */
2856
+ useWasm?: boolean;
2857
+ /** Enable exponential backoff for polling */
2858
+ useExponentialBackoff?: boolean;
2859
+ /** Maximum backoff interval in milliseconds */
2860
+ maxBackoffInterval?: number;
2861
+ /** Backoff multiplier (default: 1.5) */
2862
+ backoffMultiplier?: number;
2863
+ /** Enable delta-based updates (only emit on changes) */
2864
+ deltaUpdatesOnly?: boolean;
2865
+ /** Debounce interval for progress updates in milliseconds */
2866
+ progressDebounceMs?: number;
2867
+ }
2868
+ /**
2869
+ * Blocker information
2870
+ */
2871
+ interface BlockerInfo {
2872
+ /** Issue ID that is blocked */
2873
+ blockedIssue: string;
2874
+ /** Issue IDs that are blocking */
2875
+ blockers: string[];
2876
+ /** True if blockers are from within the convoy */
2877
+ internalBlockers: boolean;
2878
+ }
2879
+ /**
2880
+ * Ready issue information
2881
+ */
2882
+ interface ReadyIssueInfo {
2883
+ /** Issue ID */
2884
+ id: string;
2885
+ /** Issue title */
2886
+ title: string;
2887
+ /** Priority */
2888
+ priority: number;
2889
+ /** Execution level (for parallel processing) */
2890
+ level: number;
2891
+ }
2892
+ /**
2893
+ * Completion check result
2894
+ */
2895
+ interface CompletionCheckResult {
2896
+ /** True if all issues are complete */
2897
+ allComplete: boolean;
2898
+ /** Progress statistics */
2899
+ progress: ConvoyProgress;
2900
+ /** Issues that are still open */
2901
+ openIssues: string[];
2902
+ /** Issues that are in progress */
2903
+ inProgressIssues: string[];
2904
+ /** Issues that are blocked */
2905
+ blockedIssues: BlockerInfo[];
2906
+ /** Issues ready to work on */
2907
+ readyIssues: ReadyIssueInfo[];
2908
+ /** True if there are dependency cycles */
2909
+ hasCycles: boolean;
2910
+ /** Issues involved in cycles */
2911
+ cycleIssues: string[];
2912
+ }
2913
+ /**
2914
+ * Logger interface
2915
+ */
2916
+ interface ObserverLogger {
2917
+ debug: (msg: string, meta?: Record<string, unknown>) => void;
2918
+ info: (msg: string, meta?: Record<string, unknown>) => void;
2919
+ warn: (msg: string, meta?: Record<string, unknown>) => void;
2920
+ error: (msg: string, meta?: Record<string, unknown>) => void;
2921
+ }
2922
+ /**
2923
+ * Convoy Observer
2924
+ *
2925
+ * Monitors convoys for completion and provides dependency analysis.
2926
+ *
2927
+ * @example
2928
+ * ```typescript
2929
+ * const observer = new ConvoyObserver({
2930
+ * bdBridge,
2931
+ * tracker,
2932
+ * pollInterval: 5000,
2933
+ * useWasm: true,
2934
+ * });
2935
+ *
2936
+ * // Watch for completion
2937
+ * const handle = observer.watch(convoyId, (convoy, complete) => {
2938
+ * if (complete) {
2939
+ * console.log('Convoy complete!');
2940
+ * }
2941
+ * });
2942
+ *
2943
+ * // Check blockers
2944
+ * const blockers = await observer.getBlockers(convoyId);
2945
+ *
2946
+ * // Get ready issues
2947
+ * const ready = await observer.getReadyIssues(convoyId);
2948
+ *
2949
+ * // Stop watching
2950
+ * handle.stop();
2951
+ * ```
2952
+ */
2953
+ declare class ConvoyObserver extends EventEmitter {
2954
+ private bdBridge;
2955
+ private tracker;
2956
+ private wasmModule?;
2957
+ private logger;
2958
+ private config;
2959
+ private watchers;
2960
+ private readonly beadCache;
2961
+ private readonly completionCache;
2962
+ private readonly fetchDedup;
2963
+ private readonly progressEmitters;
2964
+ private pendingSubscriptions;
2965
+ private subscriptionFlushTimer;
2966
+ constructor(config: ConvoyObserverConfig, logger?: ObserverLogger);
2967
+ /**
2968
+ * Watch a convoy for completion
2969
+ *
2970
+ * @param convoyId - Convoy ID to watch
2971
+ * @param callback - Called on each check with completion status
2972
+ * @returns Watch handle to stop watching
2973
+ */
2974
+ watch(convoyId: string, callback: CompletionCallback): WatchHandle;
2975
+ /**
2976
+ * Batch subscribe to multiple convoys
2977
+ * Subscriptions are batched and flushed together for efficiency
2978
+ *
2979
+ * @param convoyId - Convoy ID to watch
2980
+ * @param callback - Callback for completion status
2981
+ */
2982
+ batchSubscribe(convoyId: string, callback: CompletionCallback): void;
2983
+ /**
2984
+ * Flush pending subscriptions
2985
+ */
2986
+ private flushSubscriptions;
2987
+ /**
2988
+ * Check if all issues in a convoy are complete
2989
+ *
2990
+ * @param convoyId - Convoy ID
2991
+ * @returns Completion check result with detailed status
2992
+ */
2993
+ checkCompletion(convoyId: string): Promise<CompletionCheckResult>;
2994
+ /**
2995
+ * Get blockers for all issues in a convoy
2996
+ *
2997
+ * @param convoyId - Convoy ID
2998
+ * @returns Array of blocker information
2999
+ */
3000
+ getBlockers(convoyId: string): Promise<BlockerInfo[]>;
3001
+ /**
3002
+ * Get issues ready to work on (no unresolved dependencies)
3003
+ *
3004
+ * @param convoyId - Convoy ID
3005
+ * @returns Array of ready issue information
3006
+ */
3007
+ getReadyIssues(convoyId: string): Promise<ReadyIssueInfo[]>;
3008
+ /**
3009
+ * Get execution order for convoy issues
3010
+ *
3011
+ * @param convoyId - Convoy ID
3012
+ * @returns Ordered array of issue IDs
3013
+ */
3014
+ getExecutionOrder(convoyId: string): Promise<string[]>;
3015
+ /**
3016
+ * Stop watching a convoy
3017
+ */
3018
+ stopWatching(convoyId: string): void;
3019
+ /**
3020
+ * Stop all watchers
3021
+ */
3022
+ stopAll(): void;
3023
+ /**
3024
+ * Set WASM module
3025
+ */
3026
+ setWasmModule(module: WasmGraphModule): void;
3027
+ /**
3028
+ * Check if WASM is available
3029
+ */
3030
+ isWasmAvailable(): boolean;
3031
+ /**
3032
+ * Poll convoy for completion with exponential backoff
3033
+ */
3034
+ private pollConvoyWithBackoff;
3035
+ /**
3036
+ * Legacy poll convoy method (without backoff)
3037
+ * @deprecated Use pollConvoyWithBackoff instead
3038
+ */
3039
+ private pollConvoy;
3040
+ /**
3041
+ * Fetch beads by IDs with caching, batch deduplication, and object pooling.
3042
+ * Uses PooledBead from memory module for reduced allocations.
3043
+ */
3044
+ private fetchBeads;
3045
+ /**
3046
+ * Map CLI bead type to Gas Town status
3047
+ */
3048
+ private mapBeadStatus;
3049
+ /**
3050
+ * Convert beads to WASM node format
3051
+ */
3052
+ private beadsToWasmNodes;
3053
+ /**
3054
+ * Analyze dependencies with WASM
3055
+ */
3056
+ private analyzeWithWasm;
3057
+ /**
3058
+ * Analyze dependencies with JavaScript (fallback)
3059
+ */
3060
+ private analyzeWithJS;
3061
+ /**
3062
+ * Detect cycles using DFS (JavaScript)
3063
+ */
3064
+ private detectCyclesJS;
3065
+ /**
3066
+ * Find nodes in cycles (JavaScript)
3067
+ */
3068
+ private findCycleNodesJS;
3069
+ /**
3070
+ * Topological sort using Kahn's algorithm (JavaScript)
3071
+ */
3072
+ private topoSortJS;
3073
+ /**
3074
+ * Clean up resources
3075
+ */
3076
+ dispose(): void;
3077
+ }
3078
+ /**
3079
+ * Create a new convoy observer instance
3080
+ */
3081
+ declare function createConvoyObserver(config: ConvoyObserverConfig, logger?: ObserverLogger): ConvoyObserver;
3082
+ /**
3083
+ * Create a lazy-initialized convoy observer.
3084
+ * The observer is only created when first accessed (via watch() or checkCompletion()).
3085
+ * Useful for deferring initialization until convoy monitoring is actually needed.
3086
+ *
3087
+ * @example
3088
+ * ```typescript
3089
+ * const lazyObserver = createLazyConvoyObserver(config);
3090
+ *
3091
+ * // Observer is NOT created yet
3092
+ * console.log(lazyObserver.getWatchCount()); // 0
3093
+ *
3094
+ * // First watch triggers observer creation
3095
+ * const observer = await lazyObserver.watch();
3096
+ * const handle = observer.watch(convoyId, callback);
3097
+ *
3098
+ * // When done, unwatch to potentially dispose
3099
+ * await lazyObserver.unwatch();
3100
+ * ```
3101
+ */
3102
+ declare function createLazyConvoyObserver(config: ConvoyObserverConfig, logger?: ObserverLogger): LazyObserver<ConvoyObserver>;
3103
+ /**
3104
+ * Get lazy observer statistics
3105
+ */
3106
+ declare function getLazyObserverStats(lazyObserver: LazyObserver<ConvoyObserver>): {
3107
+ isActive: boolean;
3108
+ watchCount: number;
3109
+ };
3110
+
3111
+ /**
3112
+ * Gas Town Bridge Plugin - MCP Tools
3113
+ *
3114
+ * Implements 20 MCP tools for Gas Town orchestrator integration:
3115
+ *
3116
+ * Beads Integration (5 tools) - CLI Bridge:
3117
+ * 1. gt_beads_create - Create a bead/issue in Beads
3118
+ * 2. gt_beads_ready - List ready beads (no blockers)
3119
+ * 3. gt_beads_show - Show bead details
3120
+ * 4. gt_beads_dep - Manage bead dependencies
3121
+ * 5. gt_beads_sync - Sync beads with AgentDB
3122
+ *
3123
+ * Convoy Operations (3 tools) - CLI Bridge:
3124
+ * 6. gt_convoy_create - Create a convoy (work order)
3125
+ * 7. gt_convoy_status - Check convoy status
3126
+ * 8. gt_convoy_track - Add/remove issues from convoy
3127
+ *
3128
+ * Formula Engine (4 tools) - WASM Accelerated:
3129
+ * 9. gt_formula_list - List available formulas
3130
+ * 10. gt_formula_cook - Cook formula into protomolecule (352x faster)
3131
+ * 11. gt_formula_execute - Execute a formula
3132
+ * 12. gt_formula_create - Create custom formula
3133
+ *
3134
+ * Orchestration (3 tools) - CLI Bridge:
3135
+ * 13. gt_sling - Sling work to an agent
3136
+ * 14. gt_agents - List Gas Town agents
3137
+ * 15. gt_mail - Send/receive Gas Town mail
3138
+ *
3139
+ * WASM Computation (5 tools) - Pure WASM:
3140
+ * 16. gt_wasm_parse_formula - Parse TOML formula to AST
3141
+ * 17. gt_wasm_resolve_deps - Resolve dependency graph
3142
+ * 18. gt_wasm_cook_batch - Batch cook multiple formulas
3143
+ * 19. gt_wasm_match_pattern - Find similar formulas/beads
3144
+ * 20. gt_wasm_optimize_convoy - Optimize convoy execution order
3145
+ *
3146
+ * Based on ADR-043: Gas Town Bridge Plugin for Claude Flow V3
3147
+ *
3148
+ * @module v3/plugins/gastown-bridge/mcp-tools
3149
+ */
3150
+
3151
+ /**
3152
+ * MCP Tool definition
3153
+ */
3154
+ interface MCPTool<TInput = unknown, TOutput = unknown> {
3155
+ /** Tool name (e.g., "gt_beads_create") */
3156
+ name: string;
3157
+ /** Tool description */
3158
+ description: string;
3159
+ /** Tool category */
3160
+ category: string;
3161
+ /** Tool version */
3162
+ version: string;
3163
+ /** Execution layer (cli, wasm, hybrid) */
3164
+ layer: 'cli' | 'wasm' | 'hybrid';
3165
+ /** Input schema */
3166
+ inputSchema: z.ZodType<TInput, z.ZodTypeDef, unknown>;
3167
+ /** Handler function */
3168
+ handler: (input: TInput, context: ToolContext) => Promise<MCPToolResult<TOutput>>;
3169
+ }
3170
+ /**
3171
+ * Tool execution context
3172
+ */
3173
+ interface ToolContext {
3174
+ /** Key-value store for cross-tool state */
3175
+ get<T>(key: string): T | undefined;
3176
+ set<T>(key: string, value: T): void;
3177
+ /** Bridge instances */
3178
+ bridges: {
3179
+ gastown: IGasTownBridge$1;
3180
+ beadsSync: IBeadsSyncService;
3181
+ formulaWasm: IFormulaWasm;
3182
+ dependencyWasm: IDependencyWasm;
3183
+ };
3184
+ /** Configuration */
3185
+ config: {
3186
+ townRoot: string;
3187
+ allowedRigs: string[];
3188
+ maxBeadsLimit: number;
3189
+ maskSecrets: boolean;
3190
+ enableWasm: boolean;
3191
+ };
3192
+ }
3193
+ /**
3194
+ * MCP Tool result format
3195
+ */
3196
+ interface MCPToolResult<T = unknown> {
3197
+ content: Array<{
3198
+ type: 'text';
3199
+ text: string;
3200
+ }>;
3201
+ data?: T;
3202
+ }
3203
+ /**
3204
+ * All Gas Town Bridge MCP Tools (20 total)
3205
+ */
3206
+ declare const gasTownBridgeTools: MCPTool[];
3207
+ /**
3208
+ * Tool name to handler map
3209
+ */
3210
+ declare const toolHandlers: Map<string, (input: unknown, context: ToolContext) => Promise<MCPToolResult<unknown>>>;
3211
+ /**
3212
+ * Tool categories for documentation
3213
+ */
3214
+ declare const toolCategories: {
3215
+ beads: string[];
3216
+ convoy: string[];
3217
+ formula: string[];
3218
+ orchestration: string[];
3219
+ wasm: string[];
3220
+ };
3221
+ /**
3222
+ * Get tool by name
3223
+ */
3224
+ declare function getTool(name: string): MCPTool | undefined;
3225
+ /**
3226
+ * Get tools by layer
3227
+ */
3228
+ declare function getToolsByLayer(layer: 'cli' | 'wasm' | 'hybrid'): MCPTool[];
3229
+
3230
+ /**
3231
+ * Gas Town Bridge Plugin - WASM Loader
3232
+ *
3233
+ * Provides lazy-loading and caching for WASM modules with graceful
3234
+ * JavaScript fallback. Includes typed wrapper functions for all WASM exports
3235
+ * and performance timing for benchmarks.
3236
+ *
3237
+ * WASM Modules:
3238
+ * - gastown-formula-wasm: TOML parsing and formula cooking (352x faster)
3239
+ * - ruvector-gnn-wasm: Graph operations and neural network (150x faster)
3240
+ *
3241
+ * @module gastown-bridge/wasm-loader
3242
+ * @version 0.1.0
3243
+ */
3244
+
3245
+ /**
3246
+ * Performance timing result
3247
+ */
3248
+ interface PerformanceTiming {
3249
+ /** Operation name */
3250
+ readonly operation: string;
3251
+ /** Duration in milliseconds */
3252
+ readonly durationMs: number;
3253
+ /** Whether WASM was used */
3254
+ readonly usedWasm: boolean;
3255
+ /** Timestamp when operation started */
3256
+ readonly startedAt: number;
3257
+ }
3258
+ /**
3259
+ * WASM module exports for gastown-formula-wasm
3260
+ */
3261
+ interface FormulaWasmExports {
3262
+ /** Initialize the WASM module */
3263
+ default?: () => Promise<void>;
3264
+ /** Parse TOML content to Formula AST */
3265
+ parse_toml: (content: string) => string;
3266
+ /** Cook a formula with variable substitution */
3267
+ cook_formula: (formulaJson: string, varsJson: string) => string;
3268
+ /** Batch cook multiple formulas */
3269
+ cook_batch: (formulasJson: string, varsArrayJson: string) => string;
3270
+ /** Get WASM version */
3271
+ version: () => string;
3272
+ }
3273
+ /**
3274
+ * WASM module exports for ruvector-gnn-wasm
3275
+ */
3276
+ interface GnnWasmExports {
3277
+ /** Initialize the WASM module */
3278
+ default?: () => Promise<void>;
3279
+ /** Topological sort of dependency graph */
3280
+ topo_sort: (nodesJson: string, edgesJson: string) => string;
3281
+ /** Detect cycles in dependency graph */
3282
+ detect_cycles: (nodesJson: string, edgesJson: string) => string;
3283
+ /** Calculate critical path */
3284
+ critical_path: (nodesJson: string, edgesJson: string, weightsJson: string) => string;
3285
+ /** Get WASM version */
3286
+ version: () => string;
3287
+ }
3288
+ /**
3289
+ * Graph edge representation
3290
+ */
3291
+ interface GraphEdge {
3292
+ readonly from: string;
3293
+ readonly to: string;
3294
+ }
3295
+ /**
3296
+ * Node weight for critical path calculation
3297
+ */
3298
+ interface NodeWeight {
3299
+ readonly nodeId: string;
3300
+ readonly weight: number;
3301
+ }
3302
+ /**
3303
+ * Cycle detection result
3304
+ */
3305
+ interface CycleDetectionResult {
3306
+ readonly hasCycle: boolean;
3307
+ readonly cycleNodes: string[];
3308
+ }
3309
+ /**
3310
+ * Check if WASM is available in the current environment.
3311
+ *
3312
+ * @returns True if WASM is supported, false otherwise
3313
+ *
3314
+ * @example
3315
+ * ```typescript
3316
+ * if (isWasmAvailable()) {
3317
+ * console.log('WASM acceleration enabled');
3318
+ * } else {
3319
+ * console.log('Using JavaScript fallback');
3320
+ * }
3321
+ * ```
3322
+ */
3323
+ declare function isWasmAvailable(): boolean;
3324
+ /**
3325
+ * Get performance log for benchmarking.
3326
+ *
3327
+ * @returns Array of performance timing records
3328
+ *
3329
+ * @example
3330
+ * ```typescript
3331
+ * const timings = getPerformanceLog();
3332
+ * const avgWasmTime = timings
3333
+ * .filter(t => t.usedWasm)
3334
+ * .reduce((acc, t) => acc + t.durationMs, 0) / timings.length;
3335
+ * ```
3336
+ */
3337
+ declare function getPerformanceLog(): readonly PerformanceTiming[];
3338
+ /**
3339
+ * Clear performance log.
3340
+ */
3341
+ declare function clearPerformanceLog(): void;
3342
+ /**
3343
+ * Lazy-load the gastown-formula-wasm module.
3344
+ * Uses LazyWasm for true lazy loading - only loads when first accessed.
3345
+ * Includes idle timeout for automatic memory cleanup.
3346
+ *
3347
+ * @returns The loaded WASM module exports, or null if unavailable
3348
+ *
3349
+ * @example
3350
+ * ```typescript
3351
+ * const formulaWasm = await loadFormulaWasm();
3352
+ * if (formulaWasm) {
3353
+ * const result = formulaWasm.parse_toml(tomlContent);
3354
+ * }
3355
+ * ```
3356
+ */
3357
+ declare function loadFormulaWasm(): Promise<FormulaWasmExports | null>;
3358
+ /**
3359
+ * Lazy-load the ruvector-gnn-wasm module.
3360
+ * Uses LazyWasm for true lazy loading - only loads when first accessed.
3361
+ * Includes idle timeout for automatic memory cleanup.
3362
+ *
3363
+ * @returns The loaded WASM module exports, or null if unavailable
3364
+ *
3365
+ * @example
3366
+ * ```typescript
3367
+ * const gnnWasm = await loadGnnWasm();
3368
+ * if (gnnWasm) {
3369
+ * const result = gnnWasm.topo_sort(nodesJson, edgesJson);
3370
+ * }
3371
+ * ```
3372
+ */
3373
+ declare function loadGnnWasm(): Promise<GnnWasmExports | null>;
3374
+ /**
3375
+ * Check if formula WASM module is currently loaded.
3376
+ * Does not trigger loading.
3377
+ */
3378
+ declare function isFormulaWasmLoaded(): boolean;
3379
+ /**
3380
+ * Check if GNN WASM module is currently loaded.
3381
+ * Does not trigger loading.
3382
+ */
3383
+ declare function isGnnWasmLoaded(): boolean;
3384
+ /**
3385
+ * Get lazy loading statistics for WASM modules.
3386
+ */
3387
+ declare function getWasmLazyStats(): {
3388
+ formulaWasm: LazyStats;
3389
+ gnnWasm: LazyStats;
3390
+ };
3391
+ /**
3392
+ * Parse TOML formula content to a Formula object.
3393
+ * Uses WASM if available (352x faster), falls back to JavaScript.
3394
+ *
3395
+ * @param content - TOML string content to parse
3396
+ * @returns Parsed Formula object
3397
+ *
3398
+ * @example
3399
+ * ```typescript
3400
+ * const formula = await parseFormula(`
3401
+ * name = "my-workflow"
3402
+ * type = "workflow"
3403
+ * version = 1
3404
+ *
3405
+ * [[steps]]
3406
+ * id = "step-1"
3407
+ * title = "First step"
3408
+ * `);
3409
+ * ```
3410
+ */
3411
+ declare function parseFormula(content: string): Promise<Formula>;
3412
+ /**
3413
+ * Cook a formula by substituting variables.
3414
+ * Uses WASM if available (352x faster), falls back to JavaScript.
3415
+ *
3416
+ * @param formula - Formula to cook
3417
+ * @param vars - Variables to substitute
3418
+ * @returns Cooked formula with variables substituted
3419
+ *
3420
+ * @example
3421
+ * ```typescript
3422
+ * const cooked = await cookFormula(formula, {
3423
+ * projectName: 'my-project',
3424
+ * author: 'developer'
3425
+ * });
3426
+ * ```
3427
+ */
3428
+ declare function cookFormula(formula: Formula, vars: Record<string, string>): Promise<Formula>;
3429
+ /**
3430
+ * Batch cook multiple formulas with corresponding variables.
3431
+ * Uses WASM if available (352x faster), falls back to JavaScript.
3432
+ *
3433
+ * @param formulas - Array of formulas to cook
3434
+ * @param varsArray - Array of variable objects (one per formula)
3435
+ * @returns Array of cooked formulas
3436
+ *
3437
+ * @example
3438
+ * ```typescript
3439
+ * const cooked = await cookBatch(
3440
+ * [formula1, formula2],
3441
+ * [{ name: 'a' }, { name: 'b' }]
3442
+ * );
3443
+ * ```
3444
+ */
3445
+ declare function cookBatch(formulas: Formula[], varsArray: Record<string, string>[]): Promise<Formula[]>;
3446
+ /**
3447
+ * Perform topological sort on a dependency graph.
3448
+ * Uses WASM if available (150x faster), falls back to JavaScript.
3449
+ *
3450
+ * @param nodes - Array of node identifiers
3451
+ * @param edges - Array of edges (from -> to dependencies)
3452
+ * @returns Topological sort result with sorted order and cycle detection
3453
+ *
3454
+ * @example
3455
+ * ```typescript
3456
+ * const result = await topoSort(
3457
+ * ['a', 'b', 'c'],
3458
+ * [{ from: 'a', to: 'b' }, { from: 'b', to: 'c' }]
3459
+ * );
3460
+ * console.log(result.sorted); // ['a', 'b', 'c']
3461
+ * ```
3462
+ */
3463
+ declare function topoSort(nodes: string[], edges: GraphEdge[]): Promise<TopoSortResult>;
3464
+ /**
3465
+ * Detect cycles in a dependency graph.
3466
+ * Uses WASM if available (150x faster), falls back to JavaScript.
3467
+ *
3468
+ * @param nodes - Array of node identifiers
3469
+ * @param edges - Array of edges (from -> to dependencies)
3470
+ * @returns Cycle detection result
3471
+ *
3472
+ * @example
3473
+ * ```typescript
3474
+ * const result = await detectCycles(
3475
+ * ['a', 'b', 'c'],
3476
+ * [{ from: 'a', to: 'b' }, { from: 'b', to: 'a' }]
3477
+ * );
3478
+ * console.log(result.hasCycle); // true
3479
+ * console.log(result.cycleNodes); // ['a', 'b']
3480
+ * ```
3481
+ */
3482
+ declare function detectCycles(nodes: string[], edges: GraphEdge[]): Promise<CycleDetectionResult>;
3483
+ /**
3484
+ * Calculate the critical path through a weighted dependency graph.
3485
+ * Uses WASM if available (150x faster), falls back to JavaScript.
3486
+ *
3487
+ * @param nodes - Array of node identifiers
3488
+ * @param edges - Array of edges (from -> to dependencies)
3489
+ * @param weights - Array of node weights (durations)
3490
+ * @returns Critical path result with path, duration, and slack times
3491
+ *
3492
+ * @example
3493
+ * ```typescript
3494
+ * const result = await criticalPath(
3495
+ * ['a', 'b', 'c'],
3496
+ * [{ from: 'a', to: 'b' }, { from: 'b', to: 'c' }],
3497
+ * [
3498
+ * { nodeId: 'a', weight: 5 },
3499
+ * { nodeId: 'b', weight: 3 },
3500
+ * { nodeId: 'c', weight: 2 }
3501
+ * ]
3502
+ * );
3503
+ * console.log(result.path); // ['a', 'b', 'c']
3504
+ * console.log(result.totalDuration); // 10
3505
+ * ```
3506
+ */
3507
+ declare function criticalPath(nodes: string[], edges: GraphEdge[], weights: NodeWeight[]): Promise<CriticalPathResult>;
3508
+ /**
3509
+ * Preload all WASM modules.
3510
+ * Call this during initialization for best performance.
3511
+ *
3512
+ * @returns Object indicating which modules were loaded
3513
+ *
3514
+ * @example
3515
+ * ```typescript
3516
+ * const status = await preloadWasmModules();
3517
+ * console.log(status);
3518
+ * // { formulaWasm: true, gnnWasm: true }
3519
+ * ```
3520
+ */
3521
+ declare function preloadWasmModules(): Promise<{
3522
+ formulaWasm: boolean;
3523
+ gnnWasm: boolean;
3524
+ }>;
3525
+ /**
3526
+ * Get WASM module versions.
3527
+ *
3528
+ * @returns Object with version strings, or null if module not loaded
3529
+ */
3530
+ declare function getWasmVersions(): Promise<{
3531
+ formulaWasm: string | null;
3532
+ gnnWasm: string | null;
3533
+ }>;
3534
+ /**
3535
+ * Reset the WASM module cache.
3536
+ * Clears lazy loader cache and forces reload on next access.
3537
+ * Useful for testing or when modules need to be reloaded.
3538
+ */
3539
+ declare function resetWasmCache(): void;
3540
+ /**
3541
+ * Schedule idle-time preloading of WASM modules.
3542
+ * Uses requestIdleCallback in browser, setImmediate in Node.
3543
+ * Does not block the main thread.
3544
+ *
3545
+ * @example
3546
+ * ```typescript
3547
+ * // Call during app initialization
3548
+ * scheduleIdlePreload();
3549
+ * ```
3550
+ */
3551
+ declare function scheduleIdlePreload(): void;
3552
+ /**
3553
+ * Get cache statistics for performance monitoring.
3554
+ *
3555
+ * @returns Object with cache stats for each cache type
3556
+ *
3557
+ * @example
3558
+ * ```typescript
3559
+ * const stats = getCacheStats();
3560
+ * console.log(`Parse cache: ${stats.parseCache.entries} entries`);
3561
+ * console.log(`Cook cache hit rate: ${stats.cookCache.hitRate}`);
3562
+ * ```
3563
+ */
3564
+ declare function getCacheStats(): {
3565
+ parseCache: {
3566
+ entries: number;
3567
+ sizeBytes: number;
3568
+ hitRate: number;
3569
+ };
3570
+ cookCache: {
3571
+ entries: number;
3572
+ sizeBytes: number;
3573
+ hitRate: number;
3574
+ };
3575
+ topoSortCache: {
3576
+ entries: number;
3577
+ sizeBytes: number;
3578
+ hitRate: number;
3579
+ };
3580
+ astCache: {
3581
+ entries: number;
3582
+ sizeBytes: number;
3583
+ };
3584
+ preloader: {
3585
+ queued: number;
3586
+ loaded: number;
3587
+ errors: number;
3588
+ isPreloading: boolean;
3589
+ };
3590
+ deduplicator: {
3591
+ parsePending: number;
3592
+ cookPending: number;
3593
+ graphPending: number;
3594
+ };
3595
+ };
3596
+ /**
3597
+ * Clear all result caches.
3598
+ * Useful for testing or when formulas have been modified.
3599
+ */
3600
+ declare function clearAllCaches(): void;
3601
+ declare const _default: {
3602
+ isWasmAvailable: typeof isWasmAvailable;
3603
+ loadFormulaWasm: typeof loadFormulaWasm;
3604
+ parseFormula: typeof parseFormula;
3605
+ cookFormula: typeof cookFormula;
3606
+ cookBatch: typeof cookBatch;
3607
+ loadGnnWasm: typeof loadGnnWasm;
3608
+ topoSort: typeof topoSort;
3609
+ detectCycles: typeof detectCycles;
3610
+ criticalPath: typeof criticalPath;
3611
+ preloadWasmModules: typeof preloadWasmModules;
3612
+ getWasmVersions: typeof getWasmVersions;
3613
+ resetWasmCache: typeof resetWasmCache;
3614
+ isFormulaWasmLoaded: typeof isFormulaWasmLoaded;
3615
+ isGnnWasmLoaded: typeof isGnnWasmLoaded;
3616
+ getWasmLazyStats: typeof getWasmLazyStats;
3617
+ scheduleIdlePreload: typeof scheduleIdlePreload;
3618
+ getCacheStats: typeof getCacheStats;
3619
+ clearAllCaches: typeof clearAllCaches;
3620
+ getPerformanceLog: typeof getPerformanceLog;
3621
+ clearPerformanceLog: typeof clearPerformanceLog;
3622
+ };
3623
+
3624
+ /**
3625
+ * Gas Town Bridge Plugin - Typed Error Classes
3626
+ *
3627
+ * Provides a hierarchy of typed error classes for the Gas Town Bridge Plugin:
3628
+ * - GasTownError: Base error class for all Gas Town errors
3629
+ * - BeadsError: Errors related to bead operations
3630
+ * - ValidationError: Input validation failures
3631
+ * - CLIExecutionError: CLI command execution failures
3632
+ *
3633
+ * All errors include:
3634
+ * - Typed error codes for programmatic handling
3635
+ * - Stack traces for debugging
3636
+ * - Contextual information about the failure
3637
+ *
3638
+ * @module gastown-bridge/errors
3639
+ * @version 0.1.0
3640
+ */
3641
+ /**
3642
+ * Gas Town error codes enumeration
3643
+ */
3644
+ declare const GasTownErrorCode: {
3645
+ readonly UNKNOWN: "GT_UNKNOWN";
3646
+ readonly INITIALIZATION_FAILED: "GT_INITIALIZATION_FAILED";
3647
+ readonly NOT_INITIALIZED: "GT_NOT_INITIALIZED";
3648
+ readonly CONFIGURATION_ERROR: "GT_CONFIGURATION_ERROR";
3649
+ readonly VALIDATION_FAILED: "GT_VALIDATION_FAILED";
3650
+ readonly INVALID_INPUT: "GT_INVALID_INPUT";
3651
+ readonly INVALID_BEAD_ID: "GT_INVALID_BEAD_ID";
3652
+ readonly INVALID_FORMULA_NAME: "GT_INVALID_FORMULA_NAME";
3653
+ readonly INVALID_CONVOY_ID: "GT_INVALID_CONVOY_ID";
3654
+ readonly INVALID_ARGUMENTS: "GT_INVALID_ARGUMENTS";
3655
+ readonly COMMAND_INJECTION_DETECTED: "GT_COMMAND_INJECTION_DETECTED";
3656
+ readonly PATH_TRAVERSAL_DETECTED: "GT_PATH_TRAVERSAL_DETECTED";
3657
+ readonly BEAD_NOT_FOUND: "GT_BEAD_NOT_FOUND";
3658
+ readonly BEAD_CREATE_FAILED: "GT_BEAD_CREATE_FAILED";
3659
+ readonly BEAD_UPDATE_FAILED: "GT_BEAD_UPDATE_FAILED";
3660
+ readonly BEAD_DELETE_FAILED: "GT_BEAD_DELETE_FAILED";
3661
+ readonly BEAD_PARSE_FAILED: "GT_BEAD_PARSE_FAILED";
3662
+ readonly FORMULA_NOT_FOUND: "GT_FORMULA_NOT_FOUND";
3663
+ readonly FORMULA_PARSE_FAILED: "GT_FORMULA_PARSE_FAILED";
3664
+ readonly FORMULA_COOK_FAILED: "GT_FORMULA_COOK_FAILED";
3665
+ readonly FORMULA_INVALID_TYPE: "GT_FORMULA_INVALID_TYPE";
3666
+ readonly CONVOY_NOT_FOUND: "GT_CONVOY_NOT_FOUND";
3667
+ readonly CONVOY_CREATE_FAILED: "GT_CONVOY_CREATE_FAILED";
3668
+ readonly CLI_NOT_FOUND: "GT_CLI_NOT_FOUND";
3669
+ readonly CLI_TIMEOUT: "GT_CLI_TIMEOUT";
3670
+ readonly CLI_EXECUTION_FAILED: "GT_CLI_EXECUTION_FAILED";
3671
+ readonly CLI_INVALID_OUTPUT: "GT_CLI_INVALID_OUTPUT";
3672
+ readonly WASM_NOT_AVAILABLE: "GT_WASM_NOT_AVAILABLE";
3673
+ readonly WASM_EXECUTION_FAILED: "GT_WASM_EXECUTION_FAILED";
3674
+ readonly SYNC_FAILED: "GT_SYNC_FAILED";
3675
+ readonly SYNC_CONFLICT: "GT_SYNC_CONFLICT";
3676
+ readonly DEPENDENCY_CYCLE: "GT_DEPENDENCY_CYCLE";
3677
+ readonly GRAPH_ERROR: "GT_GRAPH_ERROR";
3678
+ };
3679
+ type GasTownErrorCodeType = (typeof GasTownErrorCode)[keyof typeof GasTownErrorCode];
3680
+ /**
3681
+ * Base error class for all Gas Town Bridge errors
3682
+ *
3683
+ * @example
3684
+ * ```typescript
3685
+ * throw new GasTownError(
3686
+ * 'Failed to initialize plugin',
3687
+ * GasTownErrorCode.INITIALIZATION_FAILED,
3688
+ * { configPath: '/path/to/config' }
3689
+ * );
3690
+ * ```
3691
+ */
3692
+ declare class GasTownError extends Error {
3693
+ /** Error code for programmatic handling */
3694
+ readonly code: GasTownErrorCodeType;
3695
+ /** Timestamp when error occurred */
3696
+ readonly timestamp: Date;
3697
+ /** Additional context about the error */
3698
+ readonly context?: Record<string, unknown>;
3699
+ /** Original error if this wraps another error */
3700
+ readonly cause?: Error;
3701
+ constructor(message: string, code?: GasTownErrorCodeType, context?: Record<string, unknown>, cause?: Error);
3702
+ /**
3703
+ * Convert error to JSON for logging/serialization
3704
+ */
3705
+ toJSON(): Record<string, unknown>;
3706
+ /**
3707
+ * Create a human-readable string representation
3708
+ */
3709
+ toString(): string;
3710
+ }
3711
+ /**
3712
+ * Error class for bead-related operations
3713
+ *
3714
+ * @example
3715
+ * ```typescript
3716
+ * throw new BeadsError(
3717
+ * 'Bead not found',
3718
+ * GasTownErrorCode.BEAD_NOT_FOUND,
3719
+ * { beadId: 'gt-abc12' }
3720
+ * );
3721
+ * ```
3722
+ */
3723
+ declare class BeadsError extends GasTownError {
3724
+ /** Bead ID if applicable */
3725
+ readonly beadId?: string;
3726
+ /** Operation being performed */
3727
+ readonly operation?: string;
3728
+ constructor(message: string, code?: GasTownErrorCodeType, context?: Record<string, unknown>, cause?: Error);
3729
+ /**
3730
+ * Create a BeadsError for a not found scenario
3731
+ */
3732
+ static notFound(beadId: string): BeadsError;
3733
+ /**
3734
+ * Create a BeadsError for a create failure
3735
+ */
3736
+ static createFailed(reason: string, cause?: Error): BeadsError;
3737
+ /**
3738
+ * Create a BeadsError for a parse failure
3739
+ */
3740
+ static parseFailed(rawOutput: string, cause?: Error): BeadsError;
3741
+ }
3742
+ /**
3743
+ * Validation constraint that was violated
3744
+ */
3745
+ interface ValidationConstraint {
3746
+ /** Field or parameter that failed validation */
3747
+ field: string;
3748
+ /** Expected constraint (e.g., "alphanumeric", "max-length:64") */
3749
+ constraint: string;
3750
+ /** Actual value (sanitized for logging) */
3751
+ actual?: string;
3752
+ /** Expected value or pattern */
3753
+ expected?: string;
3754
+ }
3755
+ /**
3756
+ * Error class for input validation failures
3757
+ *
3758
+ * @example
3759
+ * ```typescript
3760
+ * throw new ValidationError(
3761
+ * 'Invalid bead ID format',
3762
+ * GasTownErrorCode.INVALID_BEAD_ID,
3763
+ * [{ field: 'beadId', constraint: 'alphanumeric', actual: 'abc;rm -rf' }]
3764
+ * );
3765
+ * ```
3766
+ */
3767
+ declare class ValidationError extends GasTownError {
3768
+ /** Validation constraints that were violated */
3769
+ readonly constraints: ValidationConstraint[];
3770
+ constructor(message: string, code?: GasTownErrorCodeType, constraints?: ValidationConstraint[], cause?: Error);
3771
+ /**
3772
+ * Create a ValidationError for an invalid bead ID
3773
+ */
3774
+ static invalidBeadId(beadId: string): ValidationError;
3775
+ /**
3776
+ * Create a ValidationError for an invalid formula name
3777
+ */
3778
+ static invalidFormulaName(name: string): ValidationError;
3779
+ /**
3780
+ * Create a ValidationError for an invalid convoy ID
3781
+ */
3782
+ static invalidConvoyId(convoyId: string): ValidationError;
3783
+ /**
3784
+ * Create a ValidationError for command injection attempt
3785
+ */
3786
+ static commandInjection(field: string, detected: string): ValidationError;
3787
+ /**
3788
+ * Create a ValidationError for path traversal attempt
3789
+ */
3790
+ static pathTraversal(field: string): ValidationError;
3791
+ /**
3792
+ * Combine multiple validation errors
3793
+ */
3794
+ static combine(errors: ValidationError[]): ValidationError;
3795
+ }
3796
+ /**
3797
+ * Error class for CLI command execution failures
3798
+ *
3799
+ * @example
3800
+ * ```typescript
3801
+ * throw new CLIExecutionError(
3802
+ * 'gt command failed',
3803
+ * GasTownErrorCode.CLI_EXECUTION_FAILED,
3804
+ * { command: 'gt', args: ['beads', 'list'], exitCode: 1, stderr: 'error message' }
3805
+ * );
3806
+ * ```
3807
+ */
3808
+ declare class CLIExecutionError extends GasTownError {
3809
+ /** CLI command that was executed */
3810
+ readonly command: string;
3811
+ /** Arguments passed to the command (sanitized) */
3812
+ readonly args: string[];
3813
+ /** Exit code from the process */
3814
+ readonly exitCode?: number;
3815
+ /** Standard error output (truncated) */
3816
+ readonly stderr?: string;
3817
+ /** Execution duration in milliseconds */
3818
+ readonly durationMs?: number;
3819
+ constructor(message: string, code: GasTownErrorCodeType | undefined, details: {
3820
+ command: string;
3821
+ args?: string[];
3822
+ exitCode?: number;
3823
+ stderr?: string;
3824
+ durationMs?: number;
3825
+ }, cause?: Error);
3826
+ /**
3827
+ * Create a CLIExecutionError for command not found
3828
+ */
3829
+ static notFound(command: string): CLIExecutionError;
3830
+ /**
3831
+ * Create a CLIExecutionError for timeout
3832
+ */
3833
+ static timeout(command: string, args: string[], timeoutMs: number): CLIExecutionError;
3834
+ /**
3835
+ * Create a CLIExecutionError for execution failure
3836
+ */
3837
+ static failed(command: string, args: string[], exitCode: number, stderr: string, durationMs?: number): CLIExecutionError;
3838
+ /**
3839
+ * Create a CLIExecutionError for invalid output
3840
+ */
3841
+ static invalidOutput(command: string, reason: string): CLIExecutionError;
3842
+ }
3843
+ /**
3844
+ * Error class for formula-related operations
3845
+ */
3846
+ declare class FormulaError extends GasTownError {
3847
+ /** Formula name if applicable */
3848
+ readonly formulaName?: string;
3849
+ /** Formula type if applicable */
3850
+ readonly formulaType?: string;
3851
+ constructor(message: string, code?: GasTownErrorCodeType, context?: Record<string, unknown>, cause?: Error);
3852
+ /**
3853
+ * Create a FormulaError for not found
3854
+ */
3855
+ static notFound(formulaName: string): FormulaError;
3856
+ /**
3857
+ * Create a FormulaError for parse failure
3858
+ */
3859
+ static parseFailed(formulaName: string, reason: string, cause?: Error): FormulaError;
3860
+ /**
3861
+ * Create a FormulaError for cook failure
3862
+ */
3863
+ static cookFailed(formulaName: string, reason: string, cause?: Error): FormulaError;
3864
+ }
3865
+ /**
3866
+ * Error class for convoy-related operations
3867
+ */
3868
+ declare class ConvoyError extends GasTownError {
3869
+ /** Convoy ID if applicable */
3870
+ readonly convoyId?: string;
3871
+ constructor(message: string, code?: GasTownErrorCodeType, context?: Record<string, unknown>, cause?: Error);
3872
+ /**
3873
+ * Create a ConvoyError for not found
3874
+ */
3875
+ static notFound(convoyId: string): ConvoyError;
3876
+ /**
3877
+ * Create a ConvoyError for create failure
3878
+ */
3879
+ static createFailed(reason: string, cause?: Error): ConvoyError;
3880
+ }
3881
+ /**
3882
+ * Type guard for GasTownError
3883
+ */
3884
+ declare function isGasTownError(error: unknown): error is GasTownError;
3885
+ /**
3886
+ * Type guard for ValidationError
3887
+ */
3888
+ declare function isValidationError(error: unknown): error is ValidationError;
3889
+ /**
3890
+ * Type guard for CLIExecutionError
3891
+ */
3892
+ declare function isCLIExecutionError(error: unknown): error is CLIExecutionError;
3893
+ /**
3894
+ * Type guard for BeadsError
3895
+ */
3896
+ declare function isBeadsError(error: unknown): error is BeadsError;
3897
+ /**
3898
+ * Wrap an unknown error as a GasTownError
3899
+ */
3900
+ declare function wrapError(error: unknown, code?: GasTownErrorCodeType): GasTownError;
3901
+ /**
3902
+ * Extract error message safely
3903
+ */
3904
+ declare function getErrorMessage(error: unknown): string;
3905
+
3906
+ /**
3907
+ * Gas Town Bridge Plugin - Input Validators
3908
+ *
3909
+ * Provides comprehensive input validation for the Gas Town Bridge Plugin:
3910
+ * - validateBeadId: Validate bead IDs (alphanumeric only)
3911
+ * - validateFormulaName: Validate formula names (safe path characters)
3912
+ * - validateConvoyId: Validate convoy IDs (UUID format)
3913
+ * - validateGtArgs: Validate and escape CLI arguments
3914
+ *
3915
+ * Security Features:
3916
+ * - Allowlist-based validation (only permit known-safe patterns)
3917
+ * - Command injection prevention
3918
+ * - Path traversal prevention
3919
+ * - Null byte injection prevention
3920
+ * - Shell metacharacter blocking
3921
+ *
3922
+ * All validators follow OWASP guidelines for input validation.
3923
+ *
3924
+ * @module gastown-bridge/validators
3925
+ * @version 0.1.0
3926
+ */
3927
+
3928
+ /**
3929
+ * Shell metacharacters that are never allowed in any input
3930
+ */
3931
+ declare const SHELL_METACHARACTERS: RegExp;
3932
+ /**
3933
+ * Path traversal patterns
3934
+ */
3935
+ declare const PATH_TRAVERSAL_PATTERNS: RegExp[];
3936
+ /**
3937
+ * Allowed bead ID formats
3938
+ * - gt-{4-16 alphanumeric chars}
3939
+ * - Numeric IDs (1-10 digits)
3940
+ */
3941
+ declare const BEAD_ID_PATTERN: RegExp;
3942
+ /**
3943
+ * Allowed formula name format
3944
+ * - Starts with letter
3945
+ * - Contains only alphanumeric, dash, underscore
3946
+ * - 1-64 characters
3947
+ */
3948
+ declare const FORMULA_NAME_PATTERN: RegExp;
3949
+ /**
3950
+ * UUID v4 pattern for convoy IDs
3951
+ */
3952
+ declare const UUID_PATTERN: RegExp;
3953
+ /**
3954
+ * Alternative convoy ID format (conv-{hash})
3955
+ */
3956
+ declare const CONVOY_HASH_PATTERN: RegExp;
3957
+ /**
3958
+ * Maximum lengths for inputs
3959
+ */
3960
+ declare const MAX_LENGTHS: {
3961
+ readonly beadId: 32;
3962
+ readonly formulaName: 64;
3963
+ readonly convoyId: 36;
3964
+ readonly argument: 512;
3965
+ readonly stringValue: 4096;
3966
+ readonly arrayLength: 100;
3967
+ };
3968
+ /**
3969
+ * Schema for bead ID validation
3970
+ */
3971
+ declare const BeadIdSchema: z.ZodEffects<z.ZodEffects<z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, string, string>, string, string>, string, string>;
3972
+ /**
3973
+ * Schema for formula name validation
3974
+ */
3975
+ declare const FormulaNameSchema: z.ZodEffects<z.ZodEffects<z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, string, string>, string, string>, string, string>;
3976
+ /**
3977
+ * Schema for convoy ID validation (UUID format)
3978
+ */
3979
+ declare const ConvoyIdSchema: z.ZodEffects<z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, string, string>, string, string>;
3980
+ /**
3981
+ * Schema for CLI arguments array
3982
+ */
3983
+ declare const GtArgsSchema: z.ZodArray<z.ZodEffects<z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, string, string>, string, string>, "many">;
3984
+ /**
3985
+ * Schema for safe string values
3986
+ */
3987
+ declare const SafeStringSchema: z.ZodEffects<z.ZodString, string, string>;
3988
+ /**
3989
+ * Schema for rig name
3990
+ */
3991
+ declare const RigNameSchema: z.ZodEffects<z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, string, string>, string, string>;
3992
+ /**
3993
+ * Schema for priority
3994
+ */
3995
+ declare const PrioritySchema: z.ZodNumber;
3996
+ /**
3997
+ * Schema for labels array
3998
+ */
3999
+ declare const LabelsSchema: z.ZodArray<z.ZodEffects<z.ZodString, string, string>, "many">;
4000
+ /**
4001
+ * Validate a bead ID
4002
+ *
4003
+ * Accepts:
4004
+ * - gt-{4-16 alphanumeric chars} (e.g., "gt-abc12", "gt-a1b2c3d4")
4005
+ * - Numeric IDs (e.g., "123", "9999999999")
4006
+ *
4007
+ * Rejects:
4008
+ * - Empty strings
4009
+ * - Shell metacharacters
4010
+ * - Path traversal sequences
4011
+ * - Invalid formats
4012
+ *
4013
+ * @param id - The bead ID to validate
4014
+ * @returns The validated and trimmed bead ID
4015
+ * @throws {ValidationError} If validation fails
4016
+ *
4017
+ * @example
4018
+ * ```typescript
4019
+ * const validId = validateBeadId('gt-abc12'); // Returns 'gt-abc12'
4020
+ * validateBeadId('gt-abc; rm -rf /'); // Throws ValidationError
4021
+ * ```
4022
+ */
4023
+ declare function validateBeadId(id: string): string;
4024
+ /**
4025
+ * Validate a formula name
4026
+ *
4027
+ * Accepts:
4028
+ * - Starts with letter
4029
+ * - Contains only alphanumeric, dash, underscore
4030
+ * - 1-64 characters
4031
+ *
4032
+ * Rejects:
4033
+ * - Starting with number
4034
+ * - Shell metacharacters
4035
+ * - Path traversal sequences
4036
+ *
4037
+ * @param name - The formula name to validate
4038
+ * @returns The validated and trimmed formula name
4039
+ * @throws {ValidationError} If validation fails
4040
+ *
4041
+ * @example
4042
+ * ```typescript
4043
+ * const validName = validateFormulaName('my-formula'); // Returns 'my-formula'
4044
+ * validateFormulaName('../etc/passwd'); // Throws ValidationError
4045
+ * ```
4046
+ */
4047
+ declare function validateFormulaName(name: string): string;
4048
+ /**
4049
+ * Validate a convoy ID
4050
+ *
4051
+ * Accepts:
4052
+ * - UUID v4 format (e.g., "550e8400-e29b-41d4-a716-446655440000")
4053
+ * - conv-{hash} format (e.g., "conv-abc123def")
4054
+ *
4055
+ * Rejects:
4056
+ * - Invalid UUID format
4057
+ * - Shell metacharacters
4058
+ * - Path traversal sequences
4059
+ *
4060
+ * @param id - The convoy ID to validate
4061
+ * @returns The validated and normalized convoy ID (lowercase)
4062
+ * @throws {ValidationError} If validation fails
4063
+ *
4064
+ * @example
4065
+ * ```typescript
4066
+ * const validId = validateConvoyId('550e8400-e29b-41d4-a716-446655440000');
4067
+ * validateConvoyId('not-a-uuid'); // Throws ValidationError
4068
+ * ```
4069
+ */
4070
+ declare function validateConvoyId(id: string): string;
4071
+ /**
4072
+ * Validate and escape CLI arguments
4073
+ *
4074
+ * Validates each argument in the array:
4075
+ * - No null bytes
4076
+ * - No shell metacharacters
4077
+ * - No path traversal sequences
4078
+ * - Maximum length enforced
4079
+ *
4080
+ * @param args - Array of CLI arguments to validate
4081
+ * @returns Array of validated arguments
4082
+ * @throws {ValidationError} If any argument fails validation
4083
+ *
4084
+ * @example
4085
+ * ```typescript
4086
+ * const validArgs = validateGtArgs(['beads', 'list', '--limit', '10']);
4087
+ * validateGtArgs(['rm', '-rf', '/']); // Throws ValidationError
4088
+ * ```
4089
+ */
4090
+ declare function validateGtArgs(args: string[]): string[];
4091
+ /**
4092
+ * Schema for CreateBeadOptions
4093
+ */
4094
+ declare const CreateBeadOptionsSchema: z.ZodObject<{
4095
+ title: z.ZodEffects<z.ZodString, string, string>;
4096
+ description: z.ZodOptional<z.ZodString>;
4097
+ priority: z.ZodDefault<z.ZodOptional<z.ZodNumber>>;
4098
+ labels: z.ZodDefault<z.ZodOptional<z.ZodArray<z.ZodEffects<z.ZodString, string, string>, "many">>>;
4099
+ parent: z.ZodOptional<z.ZodEffects<z.ZodEffects<z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, string, string>, string, string>, string, string>>;
4100
+ rig: z.ZodOptional<z.ZodEffects<z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, string, string>, string, string>>;
4101
+ assignee: z.ZodOptional<z.ZodEffects<z.ZodString, string, string>>;
4102
+ }, "strip", z.ZodTypeAny, {
4103
+ priority: number;
4104
+ title: string;
4105
+ labels: string[];
4106
+ description?: string | undefined;
4107
+ assignee?: string | undefined;
4108
+ rig?: string | undefined;
4109
+ parent?: string | undefined;
4110
+ }, {
4111
+ title: string;
4112
+ description?: string | undefined;
4113
+ priority?: number | undefined;
4114
+ assignee?: string | undefined;
4115
+ labels?: string[] | undefined;
4116
+ rig?: string | undefined;
4117
+ parent?: string | undefined;
4118
+ }>;
4119
+ /**
4120
+ * Schema for CreateConvoyOptions
4121
+ */
4122
+ declare const CreateConvoyOptionsSchema: z.ZodObject<{
4123
+ name: z.ZodEffects<z.ZodString, string, string>;
4124
+ issues: z.ZodArray<z.ZodEffects<z.ZodEffects<z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, string, string>, string, string>, string, string>, "many">;
4125
+ description: z.ZodOptional<z.ZodString>;
4126
+ formula: z.ZodOptional<z.ZodEffects<z.ZodEffects<z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, string, string>, string, string>, string, string>>;
4127
+ }, "strip", z.ZodTypeAny, {
4128
+ name: string;
4129
+ issues: string[];
4130
+ description?: string | undefined;
4131
+ formula?: string | undefined;
4132
+ }, {
4133
+ name: string;
4134
+ issues: string[];
4135
+ description?: string | undefined;
4136
+ formula?: string | undefined;
4137
+ }>;
4138
+ /**
4139
+ * Schema for SlingOptions
4140
+ */
4141
+ declare const SlingOptionsSchema: z.ZodObject<{
4142
+ beadId: z.ZodEffects<z.ZodEffects<z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, string, string>, string, string>, string, string>;
4143
+ target: z.ZodEnum<["polecat", "crew", "mayor"]>;
4144
+ formula: z.ZodOptional<z.ZodEffects<z.ZodEffects<z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, string, string>, string, string>, string, string>>;
4145
+ priority: z.ZodOptional<z.ZodNumber>;
4146
+ }, "strip", z.ZodTypeAny, {
4147
+ beadId: string;
4148
+ target: "mayor" | "polecat" | "crew";
4149
+ priority?: number | undefined;
4150
+ formula?: string | undefined;
4151
+ }, {
4152
+ beadId: string;
4153
+ target: "mayor" | "polecat" | "crew";
4154
+ priority?: number | undefined;
4155
+ formula?: string | undefined;
4156
+ }>;
4157
+ /**
4158
+ * Validate CreateBeadOptions
4159
+ */
4160
+ declare function validateCreateBeadOptions(options: unknown): z.infer<typeof CreateBeadOptionsSchema>;
4161
+ /**
4162
+ * Validate CreateConvoyOptions
4163
+ */
4164
+ declare function validateCreateConvoyOptions(options: unknown): z.infer<typeof CreateConvoyOptionsSchema>;
4165
+ /**
4166
+ * Validate SlingOptions
4167
+ */
4168
+ declare function validateSlingOptions(options: unknown): z.infer<typeof SlingOptionsSchema>;
4169
+ /**
4170
+ * Check if a string contains shell metacharacters
4171
+ */
4172
+ declare function containsShellMetacharacters(input: string): boolean;
4173
+ /**
4174
+ * Check if a string contains path traversal sequences
4175
+ */
4176
+ declare function containsPathTraversal(input: string): boolean;
4177
+ /**
4178
+ * Check if a string is safe for use in CLI arguments
4179
+ */
4180
+ declare function isSafeArgument(input: string): boolean;
4181
+ /**
4182
+ * Check if a bead ID is valid
4183
+ */
4184
+ declare function isValidBeadId(id: string): boolean;
4185
+ /**
4186
+ * Check if a formula name is valid
4187
+ */
4188
+ declare function isValidFormulaName(name: string): boolean;
4189
+ /**
4190
+ * Check if a convoy ID is valid
4191
+ */
4192
+ declare function isValidConvoyId(id: string): boolean;
4193
+
4194
+ /**
4195
+ * Gas Town Bridge Plugin - Output Sanitizers
4196
+ *
4197
+ * Provides output sanitization for the Gas Town Bridge Plugin:
4198
+ * - sanitizeBeadOutput: Parse and sanitize bead CLI output
4199
+ * - sanitizeFormulaOutput: Parse and sanitize formula CLI output
4200
+ * - Remove sensitive data from outputs
4201
+ *
4202
+ * Security Features:
4203
+ * - JSON parsing with validation
4204
+ * - Sensitive field redaction (tokens, keys, passwords)
4205
+ * - Output size limits to prevent DoS
4206
+ * - Type coercion and validation
4207
+ *
4208
+ * All sanitizers follow OWASP guidelines for output encoding.
4209
+ *
4210
+ * @module gastown-bridge/sanitizers
4211
+ * @version 0.1.0
4212
+ */
4213
+
4214
+ /**
4215
+ * Maximum output sizes to prevent DoS
4216
+ */
4217
+ declare const MAX_OUTPUT_SIZE: {
4218
+ readonly single: number;
4219
+ readonly list: number;
4220
+ readonly field: 65536;
4221
+ };
4222
+ /**
4223
+ * Sensitive field patterns that should be redacted
4224
+ */
4225
+ declare const SENSITIVE_FIELD_PATTERNS: RegExp[];
4226
+ /**
4227
+ * Fields that should always be removed from output
4228
+ */
4229
+ declare const REDACTED_FIELDS: Set<string>;
4230
+ /**
4231
+ * Sanitize raw bead output from CLI
4232
+ *
4233
+ * Parses JSON output, validates structure, redacts sensitive fields,
4234
+ * and normalizes the data to the Bead interface.
4235
+ *
4236
+ * @param raw - Raw string output from CLI
4237
+ * @returns Sanitized Bead object
4238
+ * @throws {BeadsError} If parsing or validation fails
4239
+ *
4240
+ * @example
4241
+ * ```typescript
4242
+ * const bead = sanitizeBeadOutput('{"id":"gt-abc12","title":"Test"}');
4243
+ * console.log(bead.id); // 'gt-abc12'
4244
+ * ```
4245
+ */
4246
+ declare function sanitizeBeadOutput(raw: string): Bead;
4247
+ /**
4248
+ * Sanitize raw formula output from CLI
4249
+ *
4250
+ * Parses JSON/TOML output, validates structure, redacts sensitive fields,
4251
+ * and normalizes the data to the Formula interface.
4252
+ *
4253
+ * @param raw - Raw string output from CLI
4254
+ * @returns Sanitized Formula object
4255
+ * @throws {FormulaError} If parsing or validation fails
4256
+ *
4257
+ * @example
4258
+ * ```typescript
4259
+ * const formula = sanitizeFormulaOutput('{"name":"test","type":"workflow"}');
4260
+ * console.log(formula.name); // 'test'
4261
+ * ```
4262
+ */
4263
+ declare function sanitizeFormulaOutput(raw: string): Formula;
4264
+ /**
4265
+ * Sanitize raw convoy output from CLI
4266
+ *
4267
+ * @param raw - Raw string output from CLI
4268
+ * @returns Sanitized Convoy object
4269
+ * @throws {ConvoyError} If parsing or validation fails
4270
+ */
4271
+ declare function sanitizeConvoyOutput(raw: string): Convoy;
4272
+ /**
4273
+ * Sanitize a list of beads from JSONL output
4274
+ *
4275
+ * @param raw - Raw JSONL string (one JSON object per line)
4276
+ * @returns Array of sanitized Bead objects
4277
+ */
4278
+ declare function sanitizeBeadsListOutput(raw: string): Bead[];
4279
+ /**
4280
+ * Recursively redact sensitive fields from an object
4281
+ */
4282
+ declare function redactSensitiveFields(obj: Record<string, unknown>): void;
4283
+ /**
4284
+ * Sanitize a string value with length limit
4285
+ */
4286
+ declare function sanitizeString(value: string | undefined | null, maxLength: number): string;
4287
+ /**
4288
+ * Sanitize a path value (remove traversal sequences)
4289
+ */
4290
+ declare function sanitizePath(value: string): string;
4291
+ /**
4292
+ * Parse a date value
4293
+ */
4294
+ declare function parseDate(value: string | Date | undefined | null): Date | undefined;
4295
+ /**
4296
+ * Sanitize metadata object
4297
+ */
4298
+ declare function sanitizeMetadata(metadata: Record<string, unknown>): Record<string, unknown>;
4299
+
4300
+ /**
4301
+ * Gas Town Bridge Plugin - Main Entry Point
4302
+ *
4303
+ * GasTownBridgePlugin class implementing the IPlugin interface:
4304
+ * - register(): Register with claude-flow plugin system
4305
+ * - initialize(): Load WASM modules, set up bridges
4306
+ * - shutdown(): Cleanup resources
4307
+ *
4308
+ * Provides integration with Steve Yegge's Gas Town orchestrator:
4309
+ * - Beads: Git-backed issue tracking with graph semantics
4310
+ * - Formulas: TOML-defined workflows (convoy, workflow, expansion, aspect)
4311
+ * - Convoys: Work-order tracking for slung work
4312
+ * - WASM: 352x faster formula parsing and graph analysis
4313
+ *
4314
+ * @module gastown-bridge
4315
+ * @version 0.1.0
4316
+ */
4317
+
4318
+ /**
4319
+ * Plugin context interface
4320
+ */
4321
+ interface PluginContext {
4322
+ get<T>(key: string): T;
4323
+ set<T>(key: string, value: T): void;
4324
+ has(key: string): boolean;
4325
+ }
4326
+ /**
4327
+ * MCP Tool definition for plugin interface
4328
+ */
4329
+ interface PluginMCPTool {
4330
+ name: string;
4331
+ description: string;
4332
+ category: string;
4333
+ version: string;
4334
+ inputSchema: {
4335
+ type: 'object';
4336
+ properties: Record<string, unknown>;
4337
+ required?: string[];
4338
+ };
4339
+ handler: (input: unknown, context: PluginContext) => Promise<{
4340
+ content: Array<{
4341
+ type: 'text';
4342
+ text: string;
4343
+ }>;
4344
+ }>;
4345
+ }
4346
+ /**
4347
+ * Hook priority type
4348
+ */
4349
+ type HookPriority = number;
4350
+ /**
4351
+ * Plugin hook definition
4352
+ */
4353
+ interface PluginHook {
4354
+ name: string;
4355
+ event: string;
4356
+ priority: HookPriority;
4357
+ description: string;
4358
+ handler: (context: PluginContext, payload: unknown) => Promise<unknown>;
4359
+ }
4360
+ /**
4361
+ * Plugin interface
4362
+ */
4363
+ interface IPlugin {
4364
+ readonly name: string;
4365
+ readonly version: string;
4366
+ readonly description: string;
4367
+ register(context: PluginContext): Promise<void>;
4368
+ initialize(context: PluginContext): Promise<{
4369
+ success: boolean;
4370
+ error?: string;
4371
+ }>;
4372
+ shutdown(context: PluginContext): Promise<{
4373
+ success: boolean;
4374
+ error?: string;
4375
+ }>;
4376
+ getCapabilities(): string[];
4377
+ getMCPTools(): PluginMCPTool[];
4378
+ getHooks(): PluginHook[];
4379
+ }
4380
+ /**
4381
+ * Gas Town CLI bridge interface
4382
+ */
4383
+ interface IGasTownBridge {
4384
+ gt(args: string[]): Promise<string>;
4385
+ bd(args: string[]): Promise<string>;
4386
+ createBead(opts: CreateBeadOptions): Promise<Bead>;
4387
+ getReady(limit?: number, rig?: string): Promise<Bead[]>;
4388
+ showBead(beadId: string): Promise<Bead>;
4389
+ addDep(child: string, parent: string): Promise<void>;
4390
+ removeDep(child: string, parent: string): Promise<void>;
4391
+ sling(opts: SlingOptions): Promise<void>;
4392
+ }
4393
+ /**
4394
+ * Formula engine interface
4395
+ */
4396
+ interface IFormulaEngine {
4397
+ parse(content: string): Formula;
4398
+ cook(formula: Formula, vars: Record<string, string>): Formula;
4399
+ toMolecule(formula: Formula, bridge: IGasTownBridge): Promise<string[]>;
4400
+ }
4401
+ /**
4402
+ * WASM bridge interface
4403
+ */
4404
+ interface IWasmBridge {
4405
+ initialize(): Promise<void>;
4406
+ isInitialized(): boolean;
4407
+ dispose(): Promise<void>;
4408
+ parseFormula(content: string): Formula;
4409
+ cookFormula(formula: Formula, vars: Record<string, string>): Formula;
4410
+ resolveDeps(beads: Bead[]): TopoSortResult;
4411
+ detectCycle(graph: BeadGraph): boolean;
4412
+ criticalPath(beads: Bead[], durations: Map<string, number>): CriticalPathResult;
4413
+ batchCook(formulas: Formula[], vars: Record<string, string>[]): Formula[];
4414
+ }
4415
+ /**
4416
+ * Sync service interface
4417
+ */
4418
+ interface ISyncService {
4419
+ pullBeads(rig?: string): Promise<number>;
4420
+ pushTasks(namespace: string): Promise<number>;
4421
+ sync(direction: 'pull' | 'push' | 'both', rig?: string): Promise<SyncResult>;
4422
+ }
4423
+ /**
4424
+ * Gas Town Bridge Plugin configuration
4425
+ */
4426
+ interface GasTownBridgeConfig {
4427
+ /** Base Gas Town configuration */
4428
+ gastown: Partial<GasTownConfig>;
4429
+ /** GtBridge configuration */
4430
+ gtBridge?: {
4431
+ /** Path to gt CLI binary */
4432
+ gtPath?: string;
4433
+ /** CLI execution timeout in ms */
4434
+ timeout?: number;
4435
+ /** Working directory */
4436
+ cwd?: string;
4437
+ };
4438
+ /** BdBridge configuration */
4439
+ bdBridge?: {
4440
+ /** Path to bd CLI binary */
4441
+ bdPath?: string;
4442
+ /** CLI execution timeout in ms */
4443
+ timeout?: number;
4444
+ /** Working directory */
4445
+ cwd?: string;
4446
+ };
4447
+ /** SyncBridge configuration */
4448
+ syncBridge?: {
4449
+ /** AgentDB namespace for beads */
4450
+ namespace?: string;
4451
+ /** Sync interval in ms */
4452
+ syncInterval?: number;
4453
+ /** Enable auto-sync */
4454
+ autoSync?: boolean;
4455
+ };
4456
+ /** FormulaExecutor configuration */
4457
+ formulaExecutor?: {
4458
+ /** Enable WASM acceleration */
4459
+ useWasm?: boolean;
4460
+ /** Step execution timeout in ms */
4461
+ stepTimeout?: number;
4462
+ /** Maximum parallel steps */
4463
+ maxParallel?: number;
4464
+ };
4465
+ /** ConvoyTracker configuration */
4466
+ convoyTracker?: {
4467
+ /** Auto-update progress on issue changes */
4468
+ autoUpdateProgress?: boolean;
4469
+ /** Progress update interval in ms */
4470
+ progressUpdateInterval?: number;
4471
+ /** Enable persistent storage */
4472
+ persistConvoys?: boolean;
4473
+ /** Storage path for convoy data */
4474
+ storagePath?: string;
4475
+ };
4476
+ /** ConvoyObserver configuration */
4477
+ convoyObserver?: {
4478
+ /** Polling interval in ms */
4479
+ pollInterval?: number;
4480
+ /** Maximum poll attempts (0 = unlimited) */
4481
+ maxPollAttempts?: number;
4482
+ /** Enable WASM for graph analysis */
4483
+ useWasm?: boolean;
4484
+ };
4485
+ /** WASM configuration */
4486
+ wasm?: {
4487
+ /** Enable WASM acceleration */
4488
+ enabled?: boolean;
4489
+ /** Preload WASM modules on init */
4490
+ preload?: boolean;
4491
+ };
4492
+ /** GUPP (Git Universal Pull/Push) adapter configuration */
4493
+ gupp?: {
4494
+ /** Enable GUPP adapter */
4495
+ enabled?: boolean;
4496
+ /** GUPP endpoint URL */
4497
+ endpoint?: string;
4498
+ /** Authentication token */
4499
+ authToken?: string;
4500
+ };
4501
+ /** Logger configuration */
4502
+ logger?: {
4503
+ /** Log level */
4504
+ level?: 'debug' | 'info' | 'warn' | 'error';
4505
+ /** Enable structured logging */
4506
+ structured?: boolean;
4507
+ };
4508
+ }
4509
+ /**
4510
+ * GUPP (Git Universal Pull/Push) Adapter
4511
+ *
4512
+ * Provides integration with external Git services for cross-repository
4513
+ * bead synchronization. This is a stub implementation - full implementation
4514
+ * would connect to GUPP services.
4515
+ */
4516
+ interface IGuppAdapter {
4517
+ /** Check if GUPP is available */
4518
+ isAvailable(): boolean;
4519
+ /** Pull beads from remote */
4520
+ pull(options?: {
4521
+ rig?: string;
4522
+ since?: Date;
4523
+ }): Promise<Bead[]>;
4524
+ /** Push beads to remote */
4525
+ push(beads: Bead[]): Promise<{
4526
+ pushed: number;
4527
+ errors: string[];
4528
+ }>;
4529
+ /** Sync with remote */
4530
+ sync(): Promise<{
4531
+ pulled: number;
4532
+ pushed: number;
4533
+ conflicts: string[];
4534
+ }>;
4535
+ }
4536
+ /**
4537
+ * Gas Town Bridge Plugin for Claude Flow V3
4538
+ *
4539
+ * Provides integration with Gas Town orchestrator:
4540
+ * - 5 Beads MCP tools (CLI-based)
4541
+ * - 3 Convoy MCP tools
4542
+ * - 4 Formula MCP tools (WASM-accelerated)
4543
+ * - 5 WASM computation tools
4544
+ * - 3 Orchestration tools
4545
+ */
4546
+ declare class GasTownBridgePlugin extends EventEmitter implements IPlugin {
4547
+ readonly name = "@claude-flow/plugin-gastown-bridge";
4548
+ readonly version = "0.1.0";
4549
+ readonly description = "Gas Town orchestrator integration with WASM-accelerated formula parsing and graph analysis";
4550
+ private config;
4551
+ private pluginContext;
4552
+ private logger;
4553
+ private gtBridge;
4554
+ private bdBridge;
4555
+ private syncBridge;
4556
+ private formulaExecutor;
4557
+ private convoyTracker;
4558
+ private convoyObserver;
4559
+ private wasmLoader;
4560
+ private guppAdapter;
4561
+ private wasmInitialized;
4562
+ private cliAvailable;
4563
+ private initialized;
4564
+ constructor(config?: Partial<GasTownBridgeConfig>);
4565
+ /**
4566
+ * Register the plugin with claude-flow
4567
+ */
4568
+ register(context: PluginContext): Promise<void>;
4569
+ /**
4570
+ * Initialize the plugin (load WASM, set up bridges)
4571
+ */
4572
+ initialize(context: PluginContext): Promise<{
4573
+ success: boolean;
4574
+ error?: string;
4575
+ }>;
4576
+ /**
4577
+ * Shutdown the plugin (cleanup resources)
4578
+ */
4579
+ shutdown(_context: PluginContext): Promise<{
4580
+ success: boolean;
4581
+ error?: string;
4582
+ }>;
4583
+ /**
4584
+ * Get plugin capabilities
4585
+ */
4586
+ getCapabilities(): string[];
4587
+ /**
4588
+ * Get plugin MCP tools
4589
+ */
4590
+ getMCPTools(): PluginMCPTool[];
4591
+ /**
4592
+ * Get plugin hooks
4593
+ */
4594
+ getHooks(): PluginHook[];
4595
+ /**
4596
+ * Get the current configuration
4597
+ */
4598
+ getConfig(): GasTownBridgeConfig;
4599
+ /**
4600
+ * Update configuration
4601
+ */
4602
+ updateConfig(config: Partial<GasTownBridgeConfig>): void;
4603
+ /**
4604
+ * Check if WASM is initialized
4605
+ */
4606
+ isWasmReady(): boolean;
4607
+ /**
4608
+ * Check if CLI tools are available
4609
+ */
4610
+ isCliAvailable(): boolean;
4611
+ /**
4612
+ * Get bridge instances
4613
+ */
4614
+ getBridges(): {
4615
+ gt: GtBridge | null;
4616
+ bd: BdBridge | null;
4617
+ sync: SyncBridge | null;
4618
+ };
4619
+ /**
4620
+ * Get formula executor
4621
+ */
4622
+ getFormulaExecutor(): FormulaExecutor | null;
4623
+ /**
4624
+ * Get convoy tracker
4625
+ */
4626
+ getConvoyTracker(): ConvoyTracker | null;
4627
+ /**
4628
+ * Get convoy observer
4629
+ */
4630
+ getConvoyObserver(): ConvoyObserver | null;
4631
+ /**
4632
+ * Get GUPP adapter
4633
+ */
4634
+ getGuppAdapter(): IGuppAdapter | null;
4635
+ /**
4636
+ * Get plugin metadata
4637
+ */
4638
+ getMetadata(): {
4639
+ name: string;
4640
+ version: string;
4641
+ description: string;
4642
+ author: string;
4643
+ license: string;
4644
+ repository: string;
4645
+ keywords: string[];
4646
+ mcpTools: string[];
4647
+ capabilities: string[];
4648
+ };
4649
+ private mergeConfig;
4650
+ private initializeWasm;
4651
+ private checkCliAvailable;
4652
+ private initializeBridges;
4653
+ private initializeFormulaExecutor;
4654
+ private initializeConvoyComponents;
4655
+ private initializeGuppAdapter;
4656
+ /**
4657
+ * Create a stub AgentDB service for SyncBridge initialization.
4658
+ * This stub stores data in-memory and should be replaced with
4659
+ * the real AgentDB service from the plugin context.
4660
+ */
4661
+ private createStubAgentDB;
4662
+ private convertMcpTool;
4663
+ private zodToJsonSchema;
4664
+ private createToolContext;
4665
+ /**
4666
+ * Create the bridge facade for MCP tools.
4667
+ *
4668
+ * NOTE: This facade bridges between the plugin's internal types (from bd-bridge, etc.)
4669
+ * and the external interface types (from types.ts). Type casts are necessary because
4670
+ * the underlying bridges use different type definitions. A future refactor should
4671
+ * unify these type systems.
4672
+ */
4673
+ private createBridgeFacade;
4674
+ private createSyncFacade;
4675
+ private createFormulaWasmFacade;
4676
+ private createDependencyWasmFacade;
4677
+ private simpleSimilarity;
4678
+ private createPreTaskHook;
4679
+ private createPostTaskHook;
4680
+ private createBeadsSyncHook;
4681
+ private createConvoyProgressHook;
4682
+ }
4683
+ /**
4684
+ * Create a new Gas Town Bridge Plugin instance
4685
+ */
4686
+ declare function createGasTownBridgePlugin(config?: Partial<GasTownBridgeConfig>): GasTownBridgePlugin;
4687
+
4688
+ export { type AgentRole, type AllocatableType, Arena, type ArenaConfig, ArenaManager, type ArenaStats, type Aspect, AspectSchema, BEAD_ID_PATTERN, BdBridge, type Bead, type BeadDependency, type BeadGraph, BeadIdSchema as BeadIdValidationSchema, BeadSchema, type BeadStatus, BeadStatusSchema, BeadsError, type BlockerInfo, CLIExecutionError, CONVOY_HASH_PATTERN, type CompletionCallback, type CompletionCheckResult, type Convoy, type ConvoyAction, ConvoyError, type ConvoyEvent, type ConvoyEventType, ConvoyIdSchema, type ConvoyLogger, ConvoyObserver, type ConvoyObserverConfig, type ConvoyOptimization, type ConvoyProgress, ConvoyProgressSchema, ConvoySchema, type ConvoyStatus, ConvoyStatusSchema, type ConvoyStrategy, ConvoyTracker, type ConvoyTrackerConfig, type CookedFormula, type CreateBeadOptions, CreateBeadOptionsSchema$1 as CreateBeadOptionsSchema, type CreateConvoyOptions, CreateConvoyOptionsSchema$1 as CreateConvoyOptionsSchema, type CriticalPathResult, type CycleDetectionResult, DEFAULT_CONFIG, type DepAction, type DependencyAction, type DependencyResolution, GasTownErrorCode as ErrorCodes, type ExecuteOptions, type ExecutionProgress, type ExecutorEvents, FORMULA_NAME_PATTERN, type Formula, type FormulaAST, FormulaError, FormulaExecutor, FormulaNameSchema, FormulaSchema, type FormulaType, FormulaTypeSchema, type GasTownAgent, type GasTownAgentRole, GasTownAgentRoleSchema, type GasTownBridgeConfig, GasTownBridgePlugin, type GasTownConfig, GasTownConfigSchema, GasTownError, type GasTownErrorCode$1 as GasTownErrorCode, type GasTownErrorCodeType, GasTownErrorCodes, type GasTownMail, type GraphEdge, GtArgsSchema, GtBridge, type HookPriority, type IBeadsSyncService, type IDependencyWasm, type IFormulaEngine, type IFormulaWasm, type IGasTownBridge, type IGuppAdapter, type IPlugin, type ISyncService, type IWasmBridge, type IWasmLoader, LabelsSchema, Lazy, LazyBridge, LazyModule, LazyObserver, type LazyOptions, type LazyState, type LazyStats, LazyWasm, type Leg, LegSchema, MAX_LENGTHS, MAX_OUTPUT_SIZE, type MCPTool, type MCPToolResult, type MailAction, type MemoryBudget, MemoryBudgetManager, MemoryMonitor, type MemoryMonitorConfig, type MemoryMonitorEvents, type MemoryPressureCallback, type MemoryPressureLevel, type MemoryStats, type MemorySystemConfig, type MemorySystemState, type Molecule, type NodeWeight, ObjectPool, type ObserverLogger, PATH_TRAVERSAL_PATTERNS, type PatternMatch, type PerformanceTiming, type PluginContext, type PluginHook, type PluginMCPTool, type PoolConfig, type PoolStats, type PoolType, type Poolable, PooledBead, PooledConvoy, PooledFormula, PooledMolecule, PooledStep, PrioritySchema, REDACTED_FIELDS, type ReadyIssueInfo, RigNameSchema, SENSITIVE_FIELD_PATTERNS, SHELL_METACHARACTERS, type SlingOptions, SlingOptionsSchema$1 as SlingOptionsSchema, type SlingTarget, SlingTargetSchema, type Step, type StepContext, type StepResult, StepSchema, SyncBridge, type SyncDirection, SyncDirectionSchema, type SyncResult, type Synthesis, SynthesisSchema, type TargetAgent, type Template, TemplateSchema, type ToolContext, type TopoSortResult, type TypeMap, UUID_PATTERN, type ValidationConstraint, ValidationError, SafeStringSchema as ValidatorSafeStringSchema, type Var, VarSchema, type WasmGraphModule, _default as WasmLoader, type WatchHandle, acquireBead, acquireConvoy, acquireFormula, acquireMolecule, acquireStep, arenaManager, beadPool, clearAllPools, clearPerformanceLog, containsPathTraversal, containsShellMetacharacters, convoyPool, cookBatch, cookFormula, createConvoyObserver, createConvoyTracker, createFormulaExecutor, createGasTownBridgePlugin, createLazyConvoyObserver, createLazyProperty, criticalPath, GasTownBridgePlugin as default, detectCycles, disposeAllLazySingletons, disposeDefaultMonitor, disposeLazySingleton, formulaPool, gasTownBridgeTools, getAllPoolStats, getDefaultMonitor, getErrorMessage, getLazyObserverStats, getLazySingleton, getMemoryMonitor, getMemoryReport, getMemoryUsage, getPerformanceLog, getPoolEfficiencySummary, getSystemMemoryStats, getTool, getToolsByLayer, getTotalMemorySaved, getWasmVersions, initializeMemorySystem, isBeadsError, isCLIExecutionError, isGasTownError, isMemorySystemInitialized, isSafeArgument, isValidBeadId, isValidConvoyId, isValidFormulaName, isValidationError, isWasmAvailable, loadFormulaWasm, loadGnnWasm, memoryBudget, moleculePool, onMemoryPressure, parseDate, parseFormula, preWarmAllPools, preloadWasmModules, redactSensitiveFields, releaseBead, releaseConvoy, releaseFormula, releaseMolecule, releaseStep, resetWasmCache, sanitizeBeadOutput, sanitizeBeadsListOutput, sanitizeConvoyOutput, sanitizeFormulaOutput, sanitizeMetadata, sanitizePath, sanitizeString, scopedArena, setMemoryLimit, shutdownMemorySystem, stepPool, toolCategories, toolHandlers, topoSort, triggerMemoryCleanup, validateBead, validateBeadId, validateCreateBeadOptions as validateBeadOptions, validateConfig, validateConvoy, validateConvoyId, validateCreateConvoyOptions as validateConvoyOptions, validateCreateBeadOptions$1 as validateCreateBeadOptions, validateCreateConvoyOptions$1 as validateCreateConvoyOptions, validateFormula, validateFormulaName, validateGtArgs, validateSlingOptions as validateSling, validateSlingOptions$1 as validateSlingOptions, withArena, withArenaSync, wrapError };