swarm-engine 1.3.0 → 1.41.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.
Files changed (145) hide show
  1. package/README.md +45 -7
  2. package/dist/cli/commands/memory.js +117 -0
  3. package/dist/cli/commands/memory.js.map +1 -1
  4. package/dist/core/patterns.d.ts +7 -1
  5. package/dist/core/patterns.d.ts.map +1 -1
  6. package/dist/core/patterns.js +23 -0
  7. package/dist/core/patterns.js.map +1 -1
  8. package/dist/core/types.d.ts +39 -0
  9. package/dist/core/types.d.ts.map +1 -1
  10. package/dist/core/types.js.map +1 -1
  11. package/dist/index.d.ts +55 -0
  12. package/dist/index.d.ts.map +1 -1
  13. package/dist/index.js +40 -0
  14. package/dist/index.js.map +1 -1
  15. package/dist/memory/index.d.ts +37 -0
  16. package/dist/memory/index.d.ts.map +1 -1
  17. package/dist/memory/index.js +91 -0
  18. package/dist/memory/index.js.map +1 -1
  19. package/dist/runtime/adaptive.d.ts +1 -0
  20. package/dist/runtime/adaptive.d.ts.map +1 -1
  21. package/dist/runtime/adaptive.js +18 -4
  22. package/dist/runtime/adaptive.js.map +1 -1
  23. package/dist/runtime/agent-runner.d.ts +18 -0
  24. package/dist/runtime/agent-runner.d.ts.map +1 -1
  25. package/dist/runtime/agent-runner.js +147 -4
  26. package/dist/runtime/agent-runner.js.map +1 -1
  27. package/dist/runtime/backends/claude-session.d.ts +49 -0
  28. package/dist/runtime/backends/claude-session.d.ts.map +1 -0
  29. package/dist/runtime/backends/claude-session.js +237 -0
  30. package/dist/runtime/backends/claude-session.js.map +1 -0
  31. package/dist/runtime/backends/claude.d.ts.map +1 -1
  32. package/dist/runtime/backends/claude.js +90 -4
  33. package/dist/runtime/backends/claude.js.map +1 -1
  34. package/dist/runtime/backends/types.d.ts +31 -1
  35. package/dist/runtime/backends/types.d.ts.map +1 -1
  36. package/dist/runtime/compaction.d.ts +7 -1
  37. package/dist/runtime/compaction.d.ts.map +1 -1
  38. package/dist/runtime/compaction.js +12 -2
  39. package/dist/runtime/compaction.js.map +1 -1
  40. package/dist/runtime/distiller.d.ts +1 -0
  41. package/dist/runtime/distiller.d.ts.map +1 -1
  42. package/dist/runtime/distiller.js +8 -2
  43. package/dist/runtime/distiller.js.map +1 -1
  44. package/dist/runtime/engine.d.ts +48 -2
  45. package/dist/runtime/engine.d.ts.map +1 -1
  46. package/dist/runtime/engine.js +600 -8
  47. package/dist/runtime/engine.js.map +1 -1
  48. package/dist/runtime/execution-graph.d.ts +86 -0
  49. package/dist/runtime/execution-graph.d.ts.map +1 -0
  50. package/dist/runtime/execution-graph.js +441 -0
  51. package/dist/runtime/execution-graph.js.map +1 -0
  52. package/dist/runtime/executor.d.ts +7 -1
  53. package/dist/runtime/executor.d.ts.map +1 -1
  54. package/dist/runtime/executor.js +20 -0
  55. package/dist/runtime/executor.js.map +1 -1
  56. package/dist/runtime/graph-adversarial.d.ts +88 -0
  57. package/dist/runtime/graph-adversarial.d.ts.map +1 -0
  58. package/dist/runtime/graph-adversarial.js +378 -0
  59. package/dist/runtime/graph-adversarial.js.map +1 -0
  60. package/dist/runtime/graph-analyzer.d.ts +106 -0
  61. package/dist/runtime/graph-analyzer.d.ts.map +1 -0
  62. package/dist/runtime/graph-analyzer.js +321 -0
  63. package/dist/runtime/graph-analyzer.js.map +1 -0
  64. package/dist/runtime/graph-causal.d.ts +91 -0
  65. package/dist/runtime/graph-causal.d.ts.map +1 -0
  66. package/dist/runtime/graph-causal.js +292 -0
  67. package/dist/runtime/graph-causal.js.map +1 -0
  68. package/dist/runtime/graph-context-router.d.ts +73 -0
  69. package/dist/runtime/graph-context-router.d.ts.map +1 -0
  70. package/dist/runtime/graph-context-router.js +162 -0
  71. package/dist/runtime/graph-context-router.js.map +1 -0
  72. package/dist/runtime/graph-discovery.d.ts +71 -0
  73. package/dist/runtime/graph-discovery.d.ts.map +1 -0
  74. package/dist/runtime/graph-discovery.js +364 -0
  75. package/dist/runtime/graph-discovery.js.map +1 -0
  76. package/dist/runtime/graph-dropout.d.ts +59 -0
  77. package/dist/runtime/graph-dropout.d.ts.map +1 -0
  78. package/dist/runtime/graph-dropout.js +204 -0
  79. package/dist/runtime/graph-dropout.js.map +1 -0
  80. package/dist/runtime/graph-embeddings.d.ts +58 -0
  81. package/dist/runtime/graph-embeddings.d.ts.map +1 -0
  82. package/dist/runtime/graph-embeddings.js +299 -0
  83. package/dist/runtime/graph-embeddings.js.map +1 -0
  84. package/dist/runtime/graph-feedback.d.ts +30 -0
  85. package/dist/runtime/graph-feedback.d.ts.map +1 -0
  86. package/dist/runtime/graph-feedback.js +80 -0
  87. package/dist/runtime/graph-feedback.js.map +1 -0
  88. package/dist/runtime/graph-gnn.d.ts +120 -0
  89. package/dist/runtime/graph-gnn.d.ts.map +1 -0
  90. package/dist/runtime/graph-gnn.js +524 -0
  91. package/dist/runtime/graph-gnn.js.map +1 -0
  92. package/dist/runtime/graph-learner.d.ts +70 -0
  93. package/dist/runtime/graph-learner.d.ts.map +1 -0
  94. package/dist/runtime/graph-learner.js +265 -0
  95. package/dist/runtime/graph-learner.js.map +1 -0
  96. package/dist/runtime/graph-meta-adversarial.d.ts +113 -0
  97. package/dist/runtime/graph-meta-adversarial.d.ts.map +1 -0
  98. package/dist/runtime/graph-meta-adversarial.js +366 -0
  99. package/dist/runtime/graph-meta-adversarial.js.map +1 -0
  100. package/dist/runtime/graph-meta.d.ts +115 -0
  101. package/dist/runtime/graph-meta.d.ts.map +1 -0
  102. package/dist/runtime/graph-meta.js +465 -0
  103. package/dist/runtime/graph-meta.js.map +1 -0
  104. package/dist/runtime/graph-self-evolve.d.ts +92 -0
  105. package/dist/runtime/graph-self-evolve.d.ts.map +1 -0
  106. package/dist/runtime/graph-self-evolve.js +422 -0
  107. package/dist/runtime/graph-self-evolve.js.map +1 -0
  108. package/dist/runtime/graph-synthesis.d.ts +47 -0
  109. package/dist/runtime/graph-synthesis.d.ts.map +1 -0
  110. package/dist/runtime/graph-synthesis.js +232 -0
  111. package/dist/runtime/graph-synthesis.js.map +1 -0
  112. package/dist/runtime/graph-trajectory.d.ts +88 -0
  113. package/dist/runtime/graph-trajectory.d.ts.map +1 -0
  114. package/dist/runtime/graph-trajectory.js +334 -0
  115. package/dist/runtime/graph-trajectory.js.map +1 -0
  116. package/dist/runtime/learning-engine.d.ts +12 -0
  117. package/dist/runtime/learning-engine.d.ts.map +1 -1
  118. package/dist/runtime/learning-engine.js +70 -0
  119. package/dist/runtime/learning-engine.js.map +1 -1
  120. package/dist/runtime/prompt-compressor.d.ts +16 -0
  121. package/dist/runtime/prompt-compressor.d.ts.map +1 -0
  122. package/dist/runtime/prompt-compressor.js +68 -0
  123. package/dist/runtime/prompt-compressor.js.map +1 -0
  124. package/dist/runtime/repo-map.d.ts +40 -0
  125. package/dist/runtime/repo-map.d.ts.map +1 -0
  126. package/dist/runtime/repo-map.js +358 -0
  127. package/dist/runtime/repo-map.js.map +1 -0
  128. package/dist/runtime/sdk-mcp-server.d.ts +44 -0
  129. package/dist/runtime/sdk-mcp-server.d.ts.map +1 -0
  130. package/dist/runtime/sdk-mcp-server.js +133 -0
  131. package/dist/runtime/sdk-mcp-server.js.map +1 -0
  132. package/dist/runtime/structured-handoff.d.ts +41 -0
  133. package/dist/runtime/structured-handoff.d.ts.map +1 -0
  134. package/dist/runtime/structured-handoff.js +279 -0
  135. package/dist/runtime/structured-handoff.js.map +1 -0
  136. package/dist/runtime/token-analytics.d.ts +38 -0
  137. package/dist/runtime/token-analytics.d.ts.map +1 -0
  138. package/dist/runtime/token-analytics.js +59 -0
  139. package/dist/runtime/token-analytics.js.map +1 -0
  140. package/dist/runtime/verifier.d.ts +10 -0
  141. package/dist/runtime/verifier.d.ts.map +1 -1
  142. package/dist/runtime/verifier.js +97 -1
  143. package/dist/runtime/verifier.js.map +1 -1
  144. package/package.json +2 -2
  145. package/skills/swarm-output-style/SKILL.md +71 -33
@@ -0,0 +1,292 @@
1
+ // ─── Engine ──────────────────────────────────────────────────────────
2
+ /**
3
+ * Causal inference engine that builds structural causal models from execution
4
+ * traces and estimates causal effects using backdoor adjustment.
5
+ *
6
+ * Extracts observations from the execution knowledge graph, computes normalized
7
+ * mutual information between variables, identifies confounders, and estimates
8
+ * average treatment effects using a tiered approach (raw → stratified → backdoor).
9
+ */
10
+ export class CausalGraphEngine {
11
+ graph;
12
+ constructor(graph) {
13
+ this.graph = graph;
14
+ }
15
+ /**
16
+ * Extract observations from the execution graph.
17
+ *
18
+ * Walks orchestration → phase → agent subgraphs via BFS (depth 3),
19
+ * mapping each agent to an observation with model, agentType, fileSetSize,
20
+ * contextQuality, and outcome.
21
+ */
22
+ extractObservations(orchestrationId) {
23
+ const observations = [];
24
+ let orchNodes;
25
+ if (orchestrationId) {
26
+ const node = this.graph.getNode(orchestrationId);
27
+ orchNodes = node && node.type === 'orchestration' ? [node] : [];
28
+ }
29
+ else {
30
+ orchNodes = this.graph.getNodesByType('orchestration');
31
+ }
32
+ for (const orch of orchNodes) {
33
+ // BFS depth 3: orch(0) → phase(1) → agent(2) → file(3)
34
+ const { nodes } = this.graph.bfs(orch.id, 3);
35
+ const agents = nodes.filter((n) => n.type === 'agent');
36
+ for (const agent of agents) {
37
+ const model = agent.properties.model || 'unknown';
38
+ const agentType = agent.label;
39
+ // Count touched_file edges to classify file set size
40
+ const touchedEdges = this.graph.getEdges(agent.id, 'outgoing').filter((e) => e.type === 'touched_file');
41
+ const fileCount = touchedEdges.length;
42
+ let fileSetSize;
43
+ if (fileCount < 5)
44
+ fileSetSize = 'small';
45
+ else if (fileCount <= 20)
46
+ fileSetSize = 'medium';
47
+ else
48
+ fileSetSize = 'large';
49
+ // Context quality: default to 'medium' (no reflection confidence stored on phase nodes)
50
+ const contextQuality = 'medium';
51
+ // Outcome: agent status 'idle' = success, anything else = failure
52
+ const status = agent.properties.status;
53
+ const outcome = status === 'idle' ? 'success' : 'failure';
54
+ observations.push({
55
+ orchestrationId: orch.id,
56
+ model,
57
+ agentType,
58
+ fileSetSize,
59
+ contextQuality,
60
+ outcome,
61
+ });
62
+ }
63
+ }
64
+ return observations;
65
+ }
66
+ /**
67
+ * Compute Normalized Mutual Information between two categorical variables.
68
+ *
69
+ * NMI = I(X;Y) / sqrt(H(X) * H(Y))
70
+ * where H(X) = -Σ p(x) log2(p(x))
71
+ * and I(X;Y) = Σ p(x,y) log2(p(x,y) / (p(x)*p(y)))
72
+ *
73
+ * Returns 0 when either variable has zero entropy (constant).
74
+ * Returns 1.0 when a variable is compared with itself.
75
+ */
76
+ computeNMI(observations, var1, var2) {
77
+ if (observations.length === 0)
78
+ return 0;
79
+ const n = observations.length;
80
+ const freq1 = new Map();
81
+ const freq2 = new Map();
82
+ const joint = new Map();
83
+ for (const obs of observations) {
84
+ const v1 = obs[var1];
85
+ const v2 = obs[var2];
86
+ freq1.set(v1, (freq1.get(v1) ?? 0) + 1);
87
+ freq2.set(v2, (freq2.get(v2) ?? 0) + 1);
88
+ const key = `${v1}\0${v2}`; // NUL separator avoids collisions in value strings
89
+ joint.set(key, (joint.get(key) ?? 0) + 1);
90
+ }
91
+ const entropy = (freq) => {
92
+ let h = 0;
93
+ for (const count of freq.values()) {
94
+ const p = count / n;
95
+ if (p > 0)
96
+ h -= p * Math.log2(p);
97
+ }
98
+ return h;
99
+ };
100
+ const h1 = entropy(freq1);
101
+ const h2 = entropy(freq2);
102
+ if (h1 === 0 || h2 === 0)
103
+ return 0;
104
+ // Mutual information
105
+ let mi = 0;
106
+ for (const [key, count] of joint) {
107
+ const [v1, v2] = key.split('\0');
108
+ const pxy = count / n;
109
+ const px = (freq1.get(v1) ?? 0) / n;
110
+ const py = (freq2.get(v2) ?? 0) / n;
111
+ if (pxy > 0 && px > 0 && py > 0) {
112
+ mi += pxy * Math.log2(pxy / (px * py));
113
+ }
114
+ }
115
+ return mi / Math.sqrt(h1 * h2);
116
+ }
117
+ /**
118
+ * Identify confounders for a treatment → outcome relationship.
119
+ *
120
+ * A variable C is a confounder if:
121
+ * NMI(C, treatment) > 0.05 AND NMI(C, outcome) > 0.05
122
+ */
123
+ identifyConfounders(observations, treatment) {
124
+ const candidates = ['model', 'agentType', 'fileSetSize', 'contextQuality'].filter((v) => v !== treatment);
125
+ const confounders = [];
126
+ for (const candidate of candidates) {
127
+ const nmiTreatment = this.computeNMI(observations, candidate, treatment);
128
+ const nmiOutcome = this.computeNMI(observations, candidate, 'outcome');
129
+ if (nmiTreatment > 0.05 && nmiOutcome > 0.05) {
130
+ confounders.push(candidate);
131
+ }
132
+ }
133
+ return confounders;
134
+ }
135
+ /**
136
+ * Estimate Average Treatment Effect using a tiered approach:
137
+ *
138
+ * - Tier 1 (N < 3): insufficient data → effect=0, low confidence
139
+ * - Tier 2 (3–9): raw comparison of success rates
140
+ * - Tier 3 (10–49): stratify by top 1 confounder, weighted average
141
+ * - Tier 4 (50+): full backdoor adjustment with all confounders
142
+ *
143
+ * Effect is always clamped to [-1, 1].
144
+ */
145
+ estimateCausalEffect(treatment, treatmentValue, controlValue, orchestrationId) {
146
+ const obs = this.extractObservations(orchestrationId);
147
+ const treated = obs.filter((o) => o[treatment] === treatmentValue);
148
+ const control = obs.filter((o) => o[treatment] === controlValue);
149
+ const total = treated.length + control.length;
150
+ // Tier 1: insufficient data
151
+ if (total < 3) {
152
+ return { effect: 0, confidence: 'low', sampleCount: total, adjustedFor: [], method: 'raw' };
153
+ }
154
+ const confounders = this.identifyConfounders(obs, treatment);
155
+ const successRate = (group) => {
156
+ if (group.length === 0)
157
+ return 0;
158
+ return group.filter((o) => o.outcome === 'success').length / group.length;
159
+ };
160
+ const clamp = (v) => Math.max(-1, Math.min(1, v));
161
+ // Tier 2: raw comparison (3–9 samples)
162
+ if (total < 10) {
163
+ const ate = successRate(treated) - successRate(control);
164
+ return { effect: clamp(ate), confidence: 'low', sampleCount: total, adjustedFor: [], method: 'raw' };
165
+ }
166
+ // Tier 3: stratified by top 1 confounder (10–49 samples)
167
+ if (total < 50) {
168
+ if (confounders.length > 0) {
169
+ const confounder = confounders[0];
170
+ const ate = this.stratifiedATE(obs, treatment, treatmentValue, controlValue, [confounder], successRate);
171
+ return {
172
+ effect: clamp(ate),
173
+ confidence: 'medium',
174
+ sampleCount: total,
175
+ adjustedFor: [confounder],
176
+ method: 'stratified',
177
+ };
178
+ }
179
+ // No confounders: fall back to raw
180
+ const ate = successRate(treated) - successRate(control);
181
+ return { effect: clamp(ate), confidence: 'medium', sampleCount: total, adjustedFor: [], method: 'raw' };
182
+ }
183
+ // Tier 4: full backdoor adjustment (50+ samples)
184
+ if (confounders.length > 0) {
185
+ const ate = this.stratifiedATE(obs, treatment, treatmentValue, controlValue, confounders, successRate);
186
+ return {
187
+ effect: clamp(ate),
188
+ confidence: 'high',
189
+ sampleCount: total,
190
+ adjustedFor: confounders,
191
+ method: 'backdoor',
192
+ };
193
+ }
194
+ const ate = successRate(treated) - successRate(control);
195
+ return { effect: clamp(ate), confidence: 'high', sampleCount: total, adjustedFor: [], method: 'backdoor' };
196
+ }
197
+ /**
198
+ * Suggest interventions for a failed orchestration by estimating the causal
199
+ * effect of switching each variable to an alternative value observed in
200
+ * historical data.
201
+ *
202
+ * Returns suggestions ranked by estimated effect (descending), filtered
203
+ * to only positive effects.
204
+ */
205
+ suggestIntervention(failedOrchestrationId) {
206
+ const obs = this.extractObservations();
207
+ const failedObs = this.extractObservations(failedOrchestrationId);
208
+ if (!failedObs.length)
209
+ return [];
210
+ const suggestions = [];
211
+ // Try model changes
212
+ const currentModel = failedObs[0].model;
213
+ const allModels = [...new Set(obs.map((o) => o.model))];
214
+ for (const alt of allModels) {
215
+ if (alt === currentModel)
216
+ continue;
217
+ const est = this.estimateCausalEffect('model', alt, currentModel);
218
+ if (est.effect > 0) {
219
+ suggestions.push({
220
+ intervention: { variable: 'model', from: currentModel, to: alt },
221
+ estimatedEffect: est.effect,
222
+ confidence: est.confidence,
223
+ reasoning: `Switching model from ${currentModel} to ${alt} has an estimated +${Math.round(est.effect * 100)}% effect on success rate (${est.method}, n=${est.sampleCount})`,
224
+ });
225
+ }
226
+ }
227
+ // Try agentType changes
228
+ const currentAgentType = failedObs[0].agentType;
229
+ const allAgentTypes = [...new Set(obs.map((o) => o.agentType))];
230
+ for (const alt of allAgentTypes) {
231
+ if (alt === currentAgentType)
232
+ continue;
233
+ const est = this.estimateCausalEffect('agentType', alt, currentAgentType);
234
+ if (est.effect > 0) {
235
+ suggestions.push({
236
+ intervention: { variable: 'agentType', from: currentAgentType, to: alt },
237
+ estimatedEffect: est.effect,
238
+ confidence: est.confidence,
239
+ reasoning: `Switching agentType from ${currentAgentType} to ${alt} has an estimated +${Math.round(est.effect * 100)}% effect on success rate (${est.method}, n=${est.sampleCount})`,
240
+ });
241
+ }
242
+ }
243
+ // Try fileSetSize changes
244
+ const currentFileSetSize = failedObs[0].fileSetSize;
245
+ const allFileSizes = ['small', 'medium', 'large'];
246
+ for (const alt of allFileSizes) {
247
+ if (alt === currentFileSetSize)
248
+ continue;
249
+ const est = this.estimateCausalEffect('fileSetSize', alt, currentFileSetSize);
250
+ if (est.effect > 0) {
251
+ suggestions.push({
252
+ intervention: { variable: 'fileSetSize', from: currentFileSetSize, to: alt },
253
+ estimatedEffect: est.effect,
254
+ confidence: est.confidence,
255
+ reasoning: `Switching fileSetSize from ${currentFileSetSize} to ${alt} has an estimated +${Math.round(est.effect * 100)}% effect on success rate (${est.method}, n=${est.sampleCount})`,
256
+ });
257
+ }
258
+ }
259
+ return suggestions.sort((a, b) => b.estimatedEffect - a.estimatedEffect);
260
+ }
261
+ // ─── Private Helpers ───────────────────────────────────────────────
262
+ /**
263
+ * Compute stratified ATE: partition observations by confounder strata,
264
+ * compute per-stratum ATE, then take a weighted average (weight = stratum size).
265
+ */
266
+ stratifiedATE(obs, treatment, treatmentValue, controlValue, confounders, successRate) {
267
+ const strataKey = (o) => confounders.map((c) => o[c]).join('\0');
268
+ const strata = new Map();
269
+ for (const o of obs) {
270
+ const key = strataKey(o);
271
+ if (!strata.has(key))
272
+ strata.set(key, { treated: [], control: [] });
273
+ const s = strata.get(key);
274
+ if (o[treatment] === treatmentValue)
275
+ s.treated.push(o);
276
+ else if (o[treatment] === controlValue)
277
+ s.control.push(o);
278
+ }
279
+ let weightedAte = 0;
280
+ let totalWeight = 0;
281
+ for (const [, s] of strata) {
282
+ if (s.treated.length > 0 && s.control.length > 0) {
283
+ const weight = s.treated.length + s.control.length;
284
+ const stratumAte = successRate(s.treated) - successRate(s.control);
285
+ weightedAte += stratumAte * weight;
286
+ totalWeight += weight;
287
+ }
288
+ }
289
+ return totalWeight > 0 ? weightedAte / totalWeight : 0;
290
+ }
291
+ }
292
+ //# sourceMappingURL=graph-causal.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"graph-causal.js","sourceRoot":"","sources":["../../src/runtime/graph-causal.ts"],"names":[],"mappings":"AA8BA,wEAAwE;AAExE;;;;;;;GAOG;AACH,MAAM,OAAO,iBAAiB;IACR;IAApB,YAAoB,KAAqB;QAArB,UAAK,GAAL,KAAK,CAAgB;IAAG,CAAC;IAE7C;;;;;;OAMG;IACH,mBAAmB,CAAC,eAAwB;QAC1C,MAAM,YAAY,GAAkB,EAAE,CAAC;QAEvC,IAAI,SAAS,CAAC;QACd,IAAI,eAAe,EAAE,CAAC;YACpB,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,eAAe,CAAC,CAAC;YACjD,SAAS,GAAG,IAAI,IAAI,IAAI,CAAC,IAAI,KAAK,eAAe,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;QAClE,CAAC;aAAM,CAAC;YACN,SAAS,GAAG,IAAI,CAAC,KAAK,CAAC,cAAc,CAAC,eAAe,CAAC,CAAC;QACzD,CAAC;QAED,KAAK,MAAM,IAAI,IAAI,SAAS,EAAE,CAAC;YAC7B,uDAAuD;YACvD,MAAM,EAAE,KAAK,EAAE,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC;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AC,EAAE,CAAC,CAAC,IAAI,MAAM,EAAE,CAAC;YAC3B,IAAI,CAAC,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,IAAI,CAAC,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;gBACjD,MAAM,MAAM,GAAG,CAAC,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC,OAAO,CAAC,MAAM,CAAC;gBACnD,MAAM,UAAU,GAAG,WAAW,CAAC,CAAC,CAAC,OAAO,CAAC,GAAG,WAAW,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC;gBACnE,WAAW,IAAI,UAAU,GAAG,MAAM,CAAC;gBACnC,WAAW,IAAI,MAAM,CAAC;YACxB,CAAC;QACH,CAAC;QAED,OAAO,WAAW,GAAG,CAAC,CAAC,CAAC,CAAC,WAAW,GAAG,WAAW,CAAC,CAAC,CAAC,CAAC,CAAC;IACzD,CAAC;CACF"}
@@ -0,0 +1,73 @@
1
+ import type { GraphNode, GraphEdge, GraphNodeType, GraphEdgeType } from '../core/types.js';
2
+ /**
3
+ * Minimal read interface for the ExecutionGraph.
4
+ * Decouples the router from the concrete graph implementation,
5
+ * allowing independent compilation and testing.
6
+ */
7
+ export interface ExecutionGraphReader {
8
+ stats(): {
9
+ nodeCount: number;
10
+ edgeCount: number;
11
+ };
12
+ getNodesByType(type: GraphNodeType): GraphNode[];
13
+ getNeighbors(nodeId: string, edgeType?: GraphEdgeType): GraphNode[];
14
+ getEdgesByType(type: GraphEdgeType): GraphEdge[];
15
+ }
16
+ export interface ContextRouterOptions {
17
+ /** Max characters for assembled context (default: 80000 ≈ 20k tokens) */
18
+ tokenBudget?: number;
19
+ /** Max prior phases to include (default: 5) */
20
+ maxSources?: number;
21
+ /** Fallback to dump-all if graph unavailable (default: 'graph') */
22
+ strategy?: 'graph' | 'all';
23
+ }
24
+ /**
25
+ * Graph-traversal-based context selection for agents.
26
+ *
27
+ * Instead of dumping all prior phase outputs into every agent's prompt,
28
+ * this router scores phases by relevance using the execution graph:
29
+ * 1. Extract file references from the agent's task description
30
+ * 2. Find which prior agents touched those same files (via graph edges)
31
+ * 3. Rank phase outputs by file overlap, then by dependency signals
32
+ * 4. Truncate to a token budget
33
+ *
34
+ * Falls back to including all outputs (existing behavior) when the graph
35
+ * is unavailable or empty.
36
+ */
37
+ export declare class GraphContextRouter {
38
+ private graph;
39
+ constructor(graph: ExecutionGraphReader | null);
40
+ /**
41
+ * Build context for an agent based on graph topology.
42
+ */
43
+ buildContext(agentId: string, agentTask: string, phaseOutputs: Map<string, string[]>, options?: ContextRouterOptions): string;
44
+ /**
45
+ * Build context with intra-phase outputs merged in. Called mid-phase when
46
+ * agents within the same phase have produced partial outputs that should
47
+ * be visible to sibling agents for live re-routing.
48
+ */
49
+ buildContextWithIntraPhase(agentId: string, agentTask: string, phaseOutputs: Map<string, string[]>, intraPhaseOutputs: Map<string, string[]>, options?: ContextRouterOptions): string;
50
+ /**
51
+ * Score each phase's relevance to the current agent's task.
52
+ *
53
+ * Scoring weights:
54
+ * - File overlap with task: +10 per shared file (strongest signal)
55
+ * - Phase has downstream consumers: +2 (indicates reusable output)
56
+ * - Base: +1 (preserves chronological fallback ordering)
57
+ */
58
+ private scorePhaseRelevance;
59
+ /**
60
+ * Extract file-like references from a task description.
61
+ * Matches patterns like "src/runtime/foo.ts", "test/bar.spec.js", "file.ext".
62
+ */
63
+ private extractFileReferences;
64
+ /**
65
+ * Render ranked phases into a context string, respecting the character budget.
66
+ */
67
+ private renderContext;
68
+ /**
69
+ * Fallback: include all phase outputs within budget (mirrors existing behavior).
70
+ */
71
+ private buildAllContext;
72
+ }
73
+ //# sourceMappingURL=graph-context-router.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"graph-context-router.d.ts","sourceRoot":"","sources":["../../src/runtime/graph-context-router.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,SAAS,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,kBAAkB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AAO,CAAC,eAAe;CAuBxB"}
@@ -0,0 +1,162 @@
1
+ /**
2
+ * Graph-traversal-based context selection for agents.
3
+ *
4
+ * Instead of dumping all prior phase outputs into every agent's prompt,
5
+ * this router scores phases by relevance using the execution graph:
6
+ * 1. Extract file references from the agent's task description
7
+ * 2. Find which prior agents touched those same files (via graph edges)
8
+ * 3. Rank phase outputs by file overlap, then by dependency signals
9
+ * 4. Truncate to a token budget
10
+ *
11
+ * Falls back to including all outputs (existing behavior) when the graph
12
+ * is unavailable or empty.
13
+ */
14
+ export class GraphContextRouter {
15
+ graph;
16
+ constructor(graph) {
17
+ this.graph = graph;
18
+ }
19
+ /**
20
+ * Build context for an agent based on graph topology.
21
+ */
22
+ buildContext(agentId, agentTask, phaseOutputs, options) {
23
+ const budget = options?.tokenBudget ?? 80000;
24
+ const maxSources = options?.maxSources ?? 5;
25
+ if (!this.graph || this.graph.stats().nodeCount === 0 || options?.strategy === 'all') {
26
+ return this.buildAllContext(phaseOutputs, budget);
27
+ }
28
+ const scores = this.scorePhaseRelevance(agentId, agentTask, phaseOutputs);
29
+ const ranked = [...scores.entries()].sort((a, b) => b[1] - a[1]).slice(0, maxSources);
30
+ return this.renderContext(ranked, phaseOutputs, budget);
31
+ }
32
+ /**
33
+ * Build context with intra-phase outputs merged in. Called mid-phase when
34
+ * agents within the same phase have produced partial outputs that should
35
+ * be visible to sibling agents for live re-routing.
36
+ */
37
+ buildContextWithIntraPhase(agentId, agentTask, phaseOutputs, intraPhaseOutputs, options) {
38
+ // Merge intraPhaseOutputs into a copy of phaseOutputs
39
+ const merged = new Map(phaseOutputs);
40
+ for (const [key, outputs] of intraPhaseOutputs) {
41
+ const existing = merged.get(key) ?? [];
42
+ merged.set(key, [...existing, ...outputs]);
43
+ }
44
+ return this.buildContext(agentId, agentTask, merged, options);
45
+ }
46
+ /**
47
+ * Score each phase's relevance to the current agent's task.
48
+ *
49
+ * Scoring weights:
50
+ * - File overlap with task: +10 per shared file (strongest signal)
51
+ * - Phase has downstream consumers: +2 (indicates reusable output)
52
+ * - Base: +1 (preserves chronological fallback ordering)
53
+ */
54
+ scorePhaseRelevance(_agentId, agentTask, phaseOutputs) {
55
+ const scores = new Map();
56
+ const taskFiles = this.extractFileReferences(agentTask);
57
+ const consumedEdges = this.graph.getEdgesByType('consumed');
58
+ for (const [phaseName] of phaseOutputs) {
59
+ let totalScore = 1; // base score
60
+ // Find phase nodes matching this name
61
+ const phaseNodes = this.graph.getNodesByType('phase').filter((n) => n.label === phaseName || n.properties.name === phaseName);
62
+ for (const phaseNode of phaseNodes) {
63
+ // Accumulate per-node sub-score independently
64
+ let nodeScore = 0;
65
+ // Get agents spawned by this phase
66
+ const agents = this.graph.getNeighbors(phaseNode.id, 'spawned');
67
+ for (const agent of agents) {
68
+ // Get files this agent touched
69
+ const files = this.graph.getNeighbors(agent.id, 'touched_file');
70
+ for (const file of files) {
71
+ const filePath = file.label || file.properties.path || '';
72
+ if (taskFiles.some((tf) => filePath.includes(tf) || tf.includes(filePath))) {
73
+ nodeScore += 10; // strong signal: shared file
74
+ }
75
+ }
76
+ }
77
+ // Bonus if this phase's output was consumed by other agents
78
+ if (consumedEdges.some((e) => e.source === phaseNode.id)) {
79
+ nodeScore += 2;
80
+ }
81
+ // Time-decay: exponential decay based on phase node age (λ=0.05, half-life ~14 days)
82
+ if (phaseNode.created_at) {
83
+ const ageMs = Date.now() - new Date(phaseNode.created_at).getTime();
84
+ const ageDays = ageMs / (1000 * 60 * 60 * 24);
85
+ if (ageDays > 0) {
86
+ const decayFactor = Math.exp(-0.05 * ageDays);
87
+ nodeScore *= Math.max(decayFactor, 0.1); // floor at 10% to never fully zero out
88
+ }
89
+ }
90
+ totalScore += nodeScore;
91
+ }
92
+ scores.set(phaseName, totalScore);
93
+ }
94
+ return scores;
95
+ }
96
+ /**
97
+ * Extract file-like references from a task description.
98
+ * Matches patterns like "src/runtime/foo.ts", "test/bar.spec.js", "file.ext".
99
+ */
100
+ extractFileReferences(text) {
101
+ const patterns = [
102
+ /[\w\-./]+\.\w{1,4}/g, // file.ext or path/to/file.ext
103
+ /src\/[\w\-./]+/g, // src/path/to/thing
104
+ /tests?\/[\w\-./]+/g, // test/path or tests/path
105
+ ];
106
+ const refs = new Set();
107
+ for (const pattern of patterns) {
108
+ const matches = text.match(pattern);
109
+ if (matches) {
110
+ for (const m of matches)
111
+ refs.add(m);
112
+ }
113
+ }
114
+ return [...refs];
115
+ }
116
+ /**
117
+ * Render ranked phases into a context string, respecting the character budget.
118
+ */
119
+ renderContext(ranked, phaseOutputs, budget) {
120
+ const parts = [];
121
+ let totalChars = 0;
122
+ for (const [phaseName, score] of ranked) {
123
+ const outputs = phaseOutputs.get(phaseName);
124
+ if (!outputs || outputs.length === 0)
125
+ continue;
126
+ const section = `## Context from ${phaseName} (relevance: ${score.toFixed(0)}):\n${outputs.join('\n\n')}`;
127
+ if (totalChars + section.length > budget) {
128
+ const remaining = budget - totalChars;
129
+ if (remaining > 200) {
130
+ parts.push(section.slice(0, remaining) + '\n[...truncated]');
131
+ }
132
+ break;
133
+ }
134
+ parts.push(section);
135
+ totalChars += section.length;
136
+ }
137
+ return parts.join('\n\n');
138
+ }
139
+ /**
140
+ * Fallback: include all phase outputs within budget (mirrors existing behavior).
141
+ */
142
+ buildAllContext(phaseOutputs, budget) {
143
+ const parts = [];
144
+ let totalChars = 0;
145
+ for (const [phaseName, outputs] of phaseOutputs) {
146
+ if (outputs.length === 0)
147
+ continue;
148
+ const section = `## Context from ${phaseName}:\n${outputs.join('\n\n')}`;
149
+ if (totalChars + section.length > budget) {
150
+ const remaining = budget - totalChars;
151
+ if (remaining > 200) {
152
+ parts.push(section.slice(0, remaining) + '\n[...truncated]');
153
+ }
154
+ break;
155
+ }
156
+ parts.push(section);
157
+ totalChars += section.length;
158
+ }
159
+ return parts.join('\n\n');
160
+ }
161
+ }
162
+ //# sourceMappingURL=graph-context-router.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"graph-context-router.js","sourceRoot":"","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+ export interface DiscoveredTask {
3
+ title: string;
4
+ description: string;
5
+ priority: 'high' | 'medium' | 'low';
6
+ recommendedPattern: string;
7
+ estimatedCost: number;
8
+ evidence: string[];
9
+ affectedFiles: string[];
10
+ }
11
+ export interface FileRisk {
12
+ file: string;
13
+ failureRate: number;
14
+ errorCount: number;
15
+ coModifiedWith: string[];
16
+ lastTouched: string;
17
+ vulnerabilities: number;
18
+ totalTouches: number;
19
+ }
20
+ /**
21
+ * Mines the execution knowledge graph for actionable insights that
22
+ * suggest new work — high-failure-rate files, recurring errors,
23
+ * unresolved vulnerabilities, untested co-modification pairs, and
24
+ * architectural risk from high-centrality low-success files.
25
+ */
26
+ export declare class TaskDiscovery {
27
+ private graph;
28
+ constructor(graph: ExecutionGraph);
29
+ /**
30
+ * Mine the graph for all discoverable tasks.
31
+ * Returns tasks sorted by priority (high first).
32
+ */
33
+ discoverTasks(): DiscoveredTask[];
34
+ /**
35
+ * Get detailed risk profile for a specific file.
36
+ */
37
+ getFileRiskProfile(filePath: string): FileRisk;
38
+ /**
39
+ * Generate prioritized backlog from discovered tasks.
40
+ */
41
+ generateBacklog(maxItems?: number): DiscoveredTask[];
42
+ /**
43
+ * Files where >40% of agents that touched them failed → refactor task.
44
+ */
45
+ private findHighFailureRateFiles;
46
+ /**
47
+ * Files with 3+ error nodes → recurring error task.
48
+ */
49
+ private findRecurringErrors;
50
+ /**
51
+ * Error nodes with P0/P1 severity grouped by file.
52
+ * Clusters of 2+ high-severity errors → urgent task.
53
+ */
54
+ private findVulnerabilityClusters;
55
+ /**
56
+ * Co-modified file pairs that never appeared together in a test orchestration.
57
+ * High co-mod count but no joint testing → integration test task.
58
+ */
59
+ private findUntestedCoModPairs;
60
+ /**
61
+ * Files touched by many agents (high degree) but with low success rate.
62
+ * These represent architectural risk — central files that cause failures.
63
+ */
64
+ private findArchitecturalRisks;
65
+ /**
66
+ * Estimate cost for a task based on historical orchestrations with the same pattern.
67
+ * Falls back to a heuristic if no historical data.
68
+ */
69
+ private estimateCost;
70
+ }
71
+ //# sourceMappingURL=graph-discovery.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"graph-discovery.d.ts","sourceRoot":"","sources":["../../src/runtime/graph-discovery.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAK3D,MAAM,WAAW,cAAc;IAC7B,KAAK,EAAE,MAAM,CAAC;IACd,WAAW,EAAE,MAAM,CAAC;IACpB,QAAQ,EAAE,MAAM,GAAG,QAAQ,GAAG,KAAK,CAAC;IACpC,kBAAkB,EAAE,MAAM,CAAC;IAC3B,aAAa,EAAE,MAAM,CAAC;IACtB,QAAQ,EAAE,MAAM,EAAE,CAAC;IACnB,aAAa,EAAE,MAAM,EAAE,CAAC;CACzB;AAED,MAAM,WAAW,QAAQ;IACvB,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,UAAU,EAAE,MAAM,CAAC;IACnB,cAAc,EAAE,MAAM,EAAE,CAAC;IACzB,WAAW,EAAE,MAAM,CAAC;IACpB,eAAe,EAAE,MAAM,CAAC;IACxB,YAAY,EAAE,MAAM,CAAC;CACtB;AAYD;;;;;GAKG;AACH,qBAAa,aAAa;IACZ,OAAO,CAAC,KAAK;gBAAL,KAAK,EAAE,cAAc;IAEzC;;;OAGG;IACH,aAAa,IAAI,cAAc,EAAE;IAYjC;;OAEG;IACH,kBAAkB,CAAC,QAAQ,EAAE,MAAM,GAAG,QAAQ;IAmE9C;;OAEG;IACH,eAAe,CAAC,QAAQ,CAAC,EAAE,MAAM,GAAG,cAAc,EAAE;IAMpD;;OAEG;IACH,OAAO,CAAC,wBAAwB;IAoChC;;OAEG;IACH,OAAO,CAAC,mBAAmB;IAqC3B;;;OAGG;IACH,OAAO,CAAC,yBAAyB;IAwCjC;;;OAGG;IACH,OAAO,CAAC,sBAAsB;IAwF9B;;;OAGG;IACH,OAAO,CAAC,sBAAsB;IAuC9B;;;OA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