tr-plugin-meta-harness 0.0.0-stage → 0.5.26

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 (94) hide show
  1. package/DESIGN.md +86 -0
  2. package/README.md +310 -2
  3. package/capability/BRICK.md +59 -0
  4. package/capability/index.mjs +675 -0
  5. package/cli.mjs +524 -0
  6. package/package.json +32 -4
  7. package/plugin.json +1714 -0
  8. package/skills/meta-harness/SKILL.md +75 -0
  9. package/src/adapters/dsh.mjs +446 -0
  10. package/src/adoption.mjs +102 -0
  11. package/src/agent-user.mjs +194 -0
  12. package/src/alerts.mjs +229 -0
  13. package/src/cascade.mjs +185 -0
  14. package/src/chat.mjs +80 -0
  15. package/src/codex-models.mjs +54 -0
  16. package/src/compat-harness.mjs +114 -0
  17. package/src/control.mjs +145 -0
  18. package/src/coordinator.mjs +307 -0
  19. package/src/dispatch-request.mjs +76 -0
  20. package/src/dispatch.mjs +119 -0
  21. package/src/documentation-authority.mjs +57 -0
  22. package/src/documentation.mjs +240 -0
  23. package/src/executor.mjs +161 -0
  24. package/src/gate-adapters/agy.mjs +155 -0
  25. package/src/gate-adapters/claude.mjs +303 -0
  26. package/src/gate-adapters/cline.mjs +111 -0
  27. package/src/gate-adapters/codex.mjs +164 -0
  28. package/src/gate-adapters/cursor.mjs +164 -0
  29. package/src/gate-adapters/devin.mjs +116 -0
  30. package/src/gate-adapters/dsh.mjs +284 -0
  31. package/src/gate-adapters/grok.mjs +112 -0
  32. package/src/gate-adapters/hermes.mjs +217 -0
  33. package/src/gate-adapters/hook-files.mjs +156 -0
  34. package/src/gate-adapters/index.mjs +131 -0
  35. package/src/gate-adapters/openclaw-plugin/gate-client.js +205 -0
  36. package/src/gate-adapters/openclaw-plugin/index.js +25 -0
  37. package/src/gate-adapters/openclaw-plugin/openclaw.plugin.json +9 -0
  38. package/src/gate-adapters/openclaw-plugin/package.json +15 -0
  39. package/src/gate-adapters/openclaw.mjs +288 -0
  40. package/src/gate-adapters/pi.mjs +146 -0
  41. package/src/gate.mjs +18 -0
  42. package/src/harness-updates.mjs +170 -0
  43. package/src/included-usage.mjs +344 -0
  44. package/src/jobs.mjs +135 -0
  45. package/src/json-reply.mjs +22 -0
  46. package/src/learner.mjs +120 -0
  47. package/src/maintenance.mjs +18 -0
  48. package/src/mcp-server.mjs +228 -0
  49. package/src/model-catalog.mjs +195 -0
  50. package/src/model-selection.mjs +67 -0
  51. package/src/paths.mjs +23 -0
  52. package/src/pool.mjs +69 -0
  53. package/src/process-manager.mjs +246 -0
  54. package/src/process-worker.mjs +18 -0
  55. package/src/reasoning.mjs +231 -0
  56. package/src/remote-operation.mjs +76 -0
  57. package/src/review.mjs +241 -0
  58. package/src/reviews.mjs +25 -0
  59. package/src/router-benchmark-corpus.mjs +16 -0
  60. package/src/router-benchmark.mjs +208 -0
  61. package/src/router.mjs +334 -0
  62. package/src/runtime.mjs +58 -0
  63. package/src/session/claude.mjs +358 -0
  64. package/src/session/codex.mjs +501 -0
  65. package/src/session/result.mjs +90 -0
  66. package/src/session/resume.mjs +393 -0
  67. package/src/session/run.mjs +258 -0
  68. package/src/session-jobs.mjs +77 -0
  69. package/src/setup.mjs +38 -0
  70. package/src/ssss-store.mjs +20 -0
  71. package/src/telemetry.mjs +267 -0
  72. package/src/termination.mjs +28 -0
  73. package/src/threads.mjs +150 -0
  74. package/src/tracker.mjs +133 -0
  75. package/src/usage-queue.mjs +137 -0
  76. package/src/verify-ssss.mjs +102 -0
  77. package/src/worker.mjs +1104 -0
  78. package/src/worktree.mjs +244 -0
  79. package/ui/chunks/adapter-docs-freshness.md +16 -0
  80. package/ui/chunks/chat-handoff.md +26 -0
  81. package/ui/chunks/fleet-maintenance.md +21 -0
  82. package/ui/chunks/harness-inventory.md +21 -0
  83. package/ui/chunks/included-access.md +18 -0
  84. package/ui/chunks/included-usage-verification.md +15 -0
  85. package/ui/chunks/independent-review.md +17 -0
  86. package/ui/chunks/managed-execution.md +20 -0
  87. package/ui/chunks/official-documentation.md +18 -0
  88. package/ui/chunks/quota-recovery.md +21 -0
  89. package/ui/chunks/review-routing-decision.md +16 -0
  90. package/ui/chunks/route-work.md +18 -0
  91. package/ui/chunks/routing-evidence.md +18 -0
  92. package/ui/chunks/run-ledger.md +18 -0
  93. package/ui/chunks/session-controls.md +16 -0
  94. package/ui/home.js +198 -0
@@ -0,0 +1,675 @@
1
+ /**
2
+ * Metaharness Capability Brick
3
+ * Zero-dependency, host-free pure ES module for agent routing,
4
+ * complexity classification, adapter discovery, gate cascades, and SSSS receipts.
5
+ * Works identically in any standalone app, edge device, workstation, or cloud environment.
6
+ */
7
+
8
+ export const ADAPTER_CATALOG = {
9
+ agy: {
10
+ id: 'agy',
11
+ name: 'Google Antigravity CLI',
12
+ bin: 'agy',
13
+ family: 'google',
14
+ tier: 'frontier',
15
+ billingModel: 'subscription',
16
+ speed: 'fast',
17
+ costScore: 6,
18
+ qualityScore: 9.2,
19
+ contextLimit: 1048576,
20
+ modalities: ['text', 'code', 'image', 'audio', 'video'],
21
+ features: ['subagents', 'mcp', 'headless', 'worktrees', 'live_api'],
22
+ flags: { prompt: '-p', nonInteractive: '--mode accept-edits', planMode: '--mode plan', output: '--output-format json' }
23
+ },
24
+ claude: {
25
+ id: 'claude',
26
+ name: 'Anthropic Claude Code',
27
+ bin: 'claude',
28
+ family: 'anthropic',
29
+ tier: 'frontier',
30
+ billingModel: 'subscription',
31
+ speed: 'balanced',
32
+ costScore: 8,
33
+ qualityScore: 9.5,
34
+ contextLimit: 200000,
35
+ modalities: ['text', 'code'],
36
+ features: ['subagents', 'mcp', 'headless', 'compact', 'plan_mode'],
37
+ flags: { prompt: '-p', nonInteractive: '--permission-mode bypassPermissions', planMode: '--permission-mode plan', output: '--output-format json' }
38
+ },
39
+ codex: {
40
+ id: 'codex',
41
+ name: 'OpenAI Codex CLI',
42
+ bin: 'codex',
43
+ family: 'openai',
44
+ tier: 'frontier',
45
+ billingModel: 'subscription',
46
+ speed: 'balanced',
47
+ costScore: 8,
48
+ qualityScore: 9.3,
49
+ contextLimit: 128000,
50
+ modalities: ['text', 'code'],
51
+ features: ['mcp', 'headless', 'streaming'],
52
+ flags: { prompt: 'exec', nonInteractive: '--sandbox danger-full-access', planMode: '--sandbox read-only', output: '--json' }
53
+ },
54
+ grok: {
55
+ id: 'grok',
56
+ name: 'xAI Grok CLI',
57
+ bin: 'grok',
58
+ family: 'xai',
59
+ tier: 'frontier',
60
+ billingModel: 'subscription',
61
+ speed: 'fast',
62
+ costScore: 6,
63
+ qualityScore: 8.8,
64
+ contextLimit: 131072,
65
+ modalities: ['text', 'code', 'image'],
66
+ features: ['headless', 'search_live'],
67
+ flags: { prompt: '-p', nonInteractive: '--yes', output: '--output-format json' }
68
+ },
69
+ ollama: {
70
+ id: 'ollama',
71
+ name: 'Ollama Local Runtime',
72
+ bin: 'ollama',
73
+ family: 'local-open-weights',
74
+ tier: 'local',
75
+ billingModel: 'local',
76
+ speed: 'ultra-fast',
77
+ costScore: 0,
78
+ qualityScore: 7.5,
79
+ contextLimit: 32768,
80
+ modalities: ['text', 'code'],
81
+ features: ['offline', 'zero_cost', 'pipe_stdin', 'gpu_accelerated'],
82
+ flags: { prompt: 'run', nonInteractive: '', output: '' }
83
+ },
84
+ hermes: {
85
+ id: 'hermes',
86
+ name: 'Hermes Agent Runtime',
87
+ bin: 'hermes',
88
+ family: 'nous-open-weights',
89
+ tier: 'budget',
90
+ billingModel: 'metered',
91
+ speed: 'fast',
92
+ costScore: 3,
93
+ qualityScore: 8.2,
94
+ contextLimit: 65536,
95
+ modalities: ['text', 'code'],
96
+ features: ['gateway', 'mesh_dispatch', 'tool_calling'],
97
+ flags: { prompt: 'chat', nonInteractive: '--oneshot', output: '--format stream-json' }
98
+ },
99
+ dsh: {
100
+ id: 'dsh',
101
+ name: 'DeepSeek Harness',
102
+ bin: 'dsh',
103
+ family: 'deepseek',
104
+ tier: 'budget',
105
+ billingModel: 'metered',
106
+ speed: 'balanced',
107
+ costScore: 2,
108
+ qualityScore: 8.9,
109
+ contextLimit: 65536,
110
+ modalities: ['text', 'code'],
111
+ features: ['cost_efficient', 'deep_reasoning', 'mesh_routing'],
112
+ flags: { prompt: '-', nonInteractive: '--profile headless', output: '--json' }
113
+ },
114
+ openclaw: {
115
+ id: 'openclaw',
116
+ name: 'OpenClaw Multi-Agent Gateway',
117
+ bin: 'openclaw',
118
+ family: 'multi-provider',
119
+ tier: 'specialized',
120
+ billingModel: 'metered',
121
+ speed: 'balanced',
122
+ costScore: 5,
123
+ qualityScore: 8.4,
124
+ contextLimit: 65536,
125
+ modalities: ['text', 'code'],
126
+ features: ['multi_channel', 'skill_orchestration'],
127
+ flags: { prompt: 'agent', nonInteractive: '--message', output: '--json' }
128
+ },
129
+ aider: {
130
+ id: 'aider',
131
+ name: 'Aider Pair Programmer',
132
+ bin: 'aider',
133
+ family: 'multi-provider',
134
+ tier: 'budget',
135
+ billingModel: 'metered',
136
+ speed: 'balanced',
137
+ costScore: 4,
138
+ qualityScore: 8.7,
139
+ contextLimit: 128000,
140
+ modalities: ['text', 'code'],
141
+ features: ['git_repo_map', 'lint_auto_fix'],
142
+ flags: { prompt: '--message', nonInteractive: '--yes', output: '' }
143
+ },
144
+ goose: {
145
+ id: 'goose',
146
+ name: 'Block Goose Developer Agent',
147
+ bin: 'goose',
148
+ family: 'multi-provider',
149
+ tier: 'specialized',
150
+ billingModel: 'metered',
151
+ speed: 'balanced',
152
+ costScore: 5,
153
+ qualityScore: 8.3,
154
+ contextLimit: 65536,
155
+ modalities: ['text', 'code'],
156
+ features: ['mcp', 'tool_calling'],
157
+ flags: { prompt: 'run', nonInteractive: '--text', output: '' }
158
+ },
159
+ openhands: {
160
+ id: 'openhands',
161
+ name: 'OpenHands Autonomous SWE',
162
+ bin: 'openhands',
163
+ family: 'multi-provider',
164
+ tier: 'frontier',
165
+ billingModel: 'metered',
166
+ speed: 'deliberate',
167
+ costScore: 7,
168
+ qualityScore: 9.0,
169
+ contextLimit: 128000,
170
+ modalities: ['text', 'code'],
171
+ features: ['sandboxed_docker', 'swe_bench_optimized'],
172
+ flags: { prompt: '-t', nonInteractive: '--headless', output: '--json' }
173
+ },
174
+ cline: {
175
+ id: 'cline',
176
+ name: 'Cline Autonomous CLI',
177
+ bin: 'cline',
178
+ family: 'multi-provider',
179
+ tier: 'specialized',
180
+ billingModel: 'metered',
181
+ speed: 'balanced',
182
+ costScore: 5,
183
+ qualityScore: 8.5,
184
+ contextLimit: 128000,
185
+ modalities: ['text', 'code'],
186
+ features: ['mcp', 'terminal_integration'],
187
+ flags: { prompt: 'task', nonInteractive: '-y', output: '--json' }
188
+ },
189
+ muse: {
190
+ id: 'muse',
191
+ name: 'Meta Muse Code',
192
+ bin: 'muse',
193
+ family: 'meta',
194
+ tier: 'specialized',
195
+ billingModel: 'subscription',
196
+ speed: 'fast',
197
+ costScore: 4,
198
+ qualityScore: 8.4,
199
+ contextLimit: 128000,
200
+ modalities: ['text', 'code'],
201
+ features: ['headless', 'jsonl_events'],
202
+ flags: { prompt: 'exec', nonInteractive: '--json', output: '--json' }
203
+ },
204
+ pi: {
205
+ id: 'pi',
206
+ name: 'Pi Coding Agent',
207
+ bin: 'pi',
208
+ family: 'multi-provider',
209
+ tier: 'budget',
210
+ billingModel: 'metered',
211
+ speed: 'fast',
212
+ costScore: 3,
213
+ qualityScore: 8.3,
214
+ contextLimit: 128000,
215
+ modalities: ['text', 'code'],
216
+ features: ['minimal_tools', 'headless_json'],
217
+ flags: { prompt: '--print', nonInteractive: '--mode json', output: '--mode json' }
218
+ }
219
+ };
220
+
221
+ /**
222
+ * Validate custom or dynamically loaded adapter manifest
223
+ */
224
+ export function validateAdapterManifest(adapter) {
225
+ if (!adapter || typeof adapter !== 'object') {
226
+ return { valid: false, errors: ['Adapter manifest must be an object'] };
227
+ }
228
+ const errors = [];
229
+ if (!adapter.name || typeof adapter.name !== 'string') errors.push('Missing string field: name');
230
+ const bin = adapter.bin || adapter.binary;
231
+ if (!bin || typeof bin !== 'string') errors.push('Missing string field: bin (or binary)');
232
+ if (typeof adapter.costScore !== 'number') errors.push('Missing numeric field: costScore');
233
+ if (typeof adapter.qualityScore !== 'number') errors.push('Missing numeric field: qualityScore');
234
+
235
+ return {
236
+ valid: errors.length === 0,
237
+ errors
238
+ };
239
+ }
240
+
241
+ /**
242
+ * Deterministic Complexity Classifier (Jev RouteLLM heuristic)
243
+ * Scores prompt on: multi-file keywords, architectural decisions,
244
+ * security boundaries, math/crypto, and instruction surface length.
245
+ */
246
+ export function classifyTaskComplexity(taskDescription, options = {}) {
247
+ const text = String(taskDescription || '').toLowerCase();
248
+ let score = 0;
249
+ const factors = [];
250
+
251
+ if (/refactor|architect|redesign|migrate|framework|unif/.test(text)) {
252
+ score += 35;
253
+ factors.push('architectural-scope');
254
+ }
255
+ if (/auth|crypto|fido2|passkey|secret|credential|token|sandbox|isolation/.test(text)) {
256
+ score += 30;
257
+ factors.push('security-sensitive');
258
+ }
259
+ if (/multi-file|across (all|every)|entire (repo|fleet)|worktree|every (mesh )?(node|machine|host|repo)|(all|several|multiple) (repos|repositories|nodes|machines)|\bmesh\b|\bfleet\b/.test(text)) {
260
+ score += 25;
261
+ factors.push('broad-blast-radius');
262
+ }
263
+ if (/\bproduction\b|\bdeploy|roll ?out|\bdroplet\b|\bcore\b|\bmigration\b|\brelease\b/.test(text)) {
264
+ score += 15;
265
+ factors.push('production-or-core');
266
+ }
267
+ if (/benchmark|telemetry|concurrency|race condition|memory leak/.test(text)) {
268
+ score += 20;
269
+ factors.push('complex-debugging');
270
+ }
271
+ // Several distinct pieces of work (comma or semicolon separated clauses, phases) are not one edit.
272
+ const clauses = text.split(/[,;]|\band then\b|\bthen\b|\bplus\b/).filter(part => part.trim().split(/\s+/).length >= 3).length;
273
+ if (clauses >= 4 || /phases? \d+ (and|&) \d+/.test(text)) {
274
+ score += 15;
275
+ factors.push('multi-part-work');
276
+ }
277
+ // An easy-sounding word ("rename", "readme") lowers the score only when nothing else carries risk:
278
+ // a rename across repositories or a credential change is not a typo fix.
279
+ if (/typo|rename|docstring|comment|formatting|readme|lint fix/.test(text) && factors.length === 0) {
280
+ score -= 30;
281
+ factors.push('low-complexity-edit');
282
+ }
283
+
284
+ const words = text.trim() ? text.trim().split(/\s+/).length : 0;
285
+ if (words > 120) {
286
+ score += 20;
287
+ factors.push('long-instruction-surface');
288
+ } else if (words < 15) {
289
+ score -= 10;
290
+ factors.push('terse-instruction');
291
+ }
292
+
293
+ if (options.preferLocal) {
294
+ score -= 40;
295
+ factors.push('prefer-local-override');
296
+ }
297
+ if (options.preferFrontier) {
298
+ score += 50;
299
+ factors.push('prefer-frontier-override');
300
+ }
301
+
302
+ const bounded = Math.max(0, Math.min(100, 50 + score));
303
+ let tier = 'budget';
304
+ if (bounded >= 70) {
305
+ tier = 'frontier';
306
+ } else if (bounded <= 35) {
307
+ tier = 'local';
308
+ }
309
+
310
+ return {
311
+ score: bounded,
312
+ tier,
313
+ factors,
314
+ isFrontierRecommended: tier === 'frontier',
315
+ isLocalRecommended: tier === 'local'
316
+ };
317
+ }
318
+
319
+ /**
320
+ * Resolve normalized adapter specification from string ID or object
321
+ */
322
+ function resolveAdapterEntry(h, catalog = ADAPTER_CATALOG) {
323
+ if (typeof h === 'string') {
324
+ return catalog[h] || {
325
+ id: h,
326
+ bin: h,
327
+ name: h,
328
+ family: 'custom',
329
+ tier: 'budget',
330
+ qualityScore: 6.0,
331
+ costScore: 4.0
332
+ };
333
+ }
334
+ const id = h.id || h.bin || h.binary || 'custom';
335
+ const base = catalog[id] || {};
336
+ return {
337
+ ...base,
338
+ ...h,
339
+ id,
340
+ bin: h.bin || h.binary || base.bin || id,
341
+ name: h.name || base.name || id,
342
+ family: h.family || base.family || 'custom',
343
+ tier: h.tier || base.tier || 'budget',
344
+ qualityScore: typeof h.qualityScore === 'number' ? h.qualityScore : (base.qualityScore ?? 6.0),
345
+ costScore: typeof h.costScore === 'number' ? h.costScore : (base.costScore ?? 4.0)
346
+ };
347
+ }
348
+
349
+ /**
350
+ * Select optimal harness based on complexity score, actual installed availability,
351
+ * quota headroom, and optional empirical scorecard pass rates.
352
+ */
353
+ export function selectOptimalHarness(taskDescription, availableHarnesses = [], quotaStatus = {}, options = {}) {
354
+ const catalog = options.catalog || ADAPTER_CATALOG;
355
+ const empiricalScorecard = options.empiricalScorecard || {};
356
+ const base = classifyTaskComplexity(taskDescription, options);
357
+ // A caller with a better classifier (such as a typed decision) may supply the tier.
358
+ const complexity = options.tierOverride ? { ...base, tier: options.tierOverride } : base;
359
+
360
+ const pool = availableHarnesses.length > 0
361
+ ? availableHarnesses.map(h => resolveAdapterEntry(h, catalog))
362
+ : Object.values(catalog);
363
+
364
+ // Filter out harnesses that are explicitly reported as exhausted or rate-limited (>95% measured usage)
365
+ // or local models when host memory is critically low
366
+ const viable = pool.filter(h => {
367
+ const q = quotaStatus[h.id] || quotaStatus[h.bin];
368
+ if (!q) return true;
369
+ if (q.status === 'exhausted' || q.status === 'unavailable' || q.status === 'low-ram') return false;
370
+ if (typeof q.usagePercent === 'number' && q.usagePercent >= 95) return false;
371
+ return true;
372
+ });
373
+
374
+ const candidates = viable;
375
+ const isFrontier = complexity.tier === 'frontier';
376
+ const isLocal = complexity.tier === 'local';
377
+
378
+ const ranked = candidates.map(h => {
379
+ let rawUtility = 0;
380
+ if (isFrontier) {
381
+ rawUtility = (h.qualityScore * 2.0) - (h.costScore * 0.2);
382
+ if (h.tier === 'frontier') rawUtility += 5.0;
383
+ } else if (isLocal) {
384
+ rawUtility = (10 - h.costScore) * 2.0 + (h.tier === 'local' ? 5.0 : 0);
385
+ } else {
386
+ rawUtility = (h.qualityScore * 1.0) - (h.costScore * 0.8);
387
+ if (h.tier === 'budget') rawUtility += 3.0;
388
+ }
389
+
390
+ // Penalize harnesses that are installed but currently unauthenticated so ready harnesses rank first
391
+ const q = quotaStatus[h.id] || quotaStatus[h.bin];
392
+ if (q && q.status === 'needs_auth') {
393
+ rawUtility -= 6.0;
394
+ }
395
+ // No login probe exists for this harness, so it ranks below one verified as signed in
396
+ if (q && q.status === 'unverified') {
397
+ rawUtility -= 1.0;
398
+ }
399
+
400
+ // Factor in empirical local pass rate if at least 2 runs recorded
401
+ const emp = empiricalScorecard[h.id] || empiricalScorecard[h.bin];
402
+ if (emp && emp.total >= 2 && typeof emp.passRate === 'number') {
403
+ const bonus = ((emp.passRate - 75) / 25) * 2.0; // -6.0 to +2.0 adjustment
404
+ rawUtility += bonus;
405
+ }
406
+
407
+ return {
408
+ harness: h.id || h.bin,
409
+ name: h.name,
410
+ family: h.family || 'custom',
411
+ tier: h.tier,
412
+ utility: parseFloat(rawUtility.toFixed(3)),
413
+ complexityMatched: h.tier === complexity.tier
414
+ };
415
+ }).sort((a, b) => b.utility - a.utility);
416
+
417
+ return {
418
+ selected: ranked[0]?.harness || null,
419
+ complexity,
420
+ candidates: ranked
421
+ };
422
+ }
423
+
424
+ /**
425
+ * Pure deterministic envelope builder for preflight and execution context
426
+ */
427
+ export function buildBootstrapEnvelope(task, options = {}) {
428
+ const timestamp = options.timestamp || new Date().toISOString();
429
+ const normalizedTask = String(task || '').trim();
430
+ const harness = options.harness || 'unknown';
431
+ return {
432
+ id: options.id || `envelope-${harness}-${Buffer.from(normalizedTask.slice(0, 48)).toString('hex').slice(0, 12) || 'task'}`,
433
+ task: normalizedTask,
434
+ action: options.action || 'read,edit,test',
435
+ ready: options.ready !== false,
436
+ harness,
437
+ timestamp,
438
+ contextCapsule: {
439
+ requiredRules: options.requiredRules || [],
440
+ plugins: options.plugins || [],
441
+ budget: options.budget || 17000
442
+ },
443
+ verificationReceipt: {
444
+ preflightPassed: options.preflightPassed !== false,
445
+ ackTime: timestamp
446
+ }
447
+ };
448
+ }
449
+
450
+ /**
451
+ * Evaluate deterministic code quality gate cascade (FrugalGPT concept).
452
+ * Escalates to a higher tier (or cross-family frontier model) from the caller's
453
+ * actual available pool rather than assuming hardcoded binaries.
454
+ */
455
+ export function evaluateGateCascade(currentHarness, gateResults = {}, availableHarnesses = []) {
456
+ const { testsPassed = true, linterPassed = true, typecheckPassed = true } = gateResults;
457
+ const passedAll = testsPassed && linterPassed && typecheckPassed;
458
+
459
+ if (passedAll) {
460
+ return {
461
+ escalationRequired: false,
462
+ recommendedHarness: currentHarness,
463
+ reason: 'All deterministic gates passed.'
464
+ };
465
+ }
466
+
467
+ const pool = availableHarnesses.length > 0
468
+ ? availableHarnesses.map(h => resolveAdapterEntry(h))
469
+ : Object.values(ADAPTER_CATALOG);
470
+
471
+ const currentSpec = resolveAdapterEntry(currentHarness);
472
+ const currentTier = currentSpec.tier || 'budget';
473
+ const currentFamily = currentSpec.family || 'unknown';
474
+
475
+ const byUtility = (list) => [...list].sort((a, b) => (b.qualityScore - a.qualityScore) || (a.costScore - b.costScore));
476
+
477
+ let nextSpec = null;
478
+ let reason = 'Gate failures detected; escalating to higher-capability harness.';
479
+
480
+ if (currentTier === 'local') {
481
+ const budgetPool = byUtility(pool.filter(h => h.tier === 'budget' && h.id !== currentSpec.id));
482
+ const frontierPool = byUtility(pool.filter(h => h.tier === 'frontier' && h.id !== currentSpec.id));
483
+ nextSpec = budgetPool[0] || frontierPool[0] || byUtility(pool.filter(h => h.id !== currentSpec.id))[0];
484
+ reason = `Local tier (${currentSpec.id}) failed quality gates; escalating to ${nextSpec?.tier || 'next'} tier (${nextSpec?.id || currentSpec.id}).`;
485
+ } else if (currentTier === 'budget' || currentTier === 'specialized') {
486
+ const frontierPool = byUtility(pool.filter(h => h.tier === 'frontier' && h.id !== currentSpec.id));
487
+ nextSpec = frontierPool[0] || byUtility(pool.filter(h => h.id !== currentSpec.id))[0];
488
+ reason = `${currentTier} tier (${currentSpec.id}) failed quality gates; escalating to frontier harness (${nextSpec?.id || currentSpec.id}).`;
489
+ } else {
490
+ // Already frontier: pick a frontier harness from a DIFFERENT model family to break confirmation bias
491
+ const crossFamilyFrontier = byUtility(pool.filter(h => h.tier === 'frontier' && h.id !== currentSpec.id && h.family !== currentFamily));
492
+ const anyOtherFrontier = byUtility(pool.filter(h => h.tier === 'frontier' && h.id !== currentSpec.id));
493
+ nextSpec = crossFamilyFrontier[0] || anyOtherFrontier[0] || byUtility(pool.filter(h => h.id !== currentSpec.id))[0];
494
+ reason = `Primary frontier harness (${currentSpec.id}) failed gates; cross-auditing with distinct model family (${nextSpec?.id || currentSpec.id}).`;
495
+ }
496
+
497
+ return {
498
+ escalationRequired: true,
499
+ previousHarness: currentSpec.id,
500
+ recommendedHarness: nextSpec?.id || currentSpec.id,
501
+ reason,
502
+ failures: {
503
+ tests: !testsPassed,
504
+ linter: !linterPassed,
505
+ typecheck: !typecheckPassed
506
+ }
507
+ };
508
+ }
509
+
510
+ /**
511
+ * Compute empirical scorecard from ledger runs
512
+ */
513
+ export function computeEmpiricalScorecard(historyRuns = []) {
514
+ const summary = {};
515
+ for (const run of historyRuns) {
516
+ // Quota walls, sign-in gaps and process failures say nothing about the harness's work.
517
+ if (['quota', 'auth', 'process', 'not-ready'].includes(run.failureKind)) continue;
518
+ const h = run.harness || 'unknown';
519
+ if (!summary[h]) {
520
+ summary[h] = { total: 0, passed: 0, failed: 0, totalDurationMs: 0, passRate: 0, avgDurationMs: 0 };
521
+ }
522
+ summary[h].total += 1;
523
+ if (run.success) {
524
+ summary[h].passed += 1;
525
+ } else {
526
+ summary[h].failed += 1;
527
+ }
528
+ summary[h].totalDurationMs += (run.durationMs || 0);
529
+ }
530
+
531
+ for (const h of Object.keys(summary)) {
532
+ const item = summary[h];
533
+ item.passRate = item.total > 0 ? parseFloat(((item.passed / item.total) * 100).toFixed(1)) : 0;
534
+ item.avgDurationMs = item.total > 0 ? Math.round(item.totalDurationMs / item.total) : 0;
535
+ }
536
+
537
+ return summary;
538
+ }
539
+
540
+ /**
541
+ * Synthesize raw subagent output through a strict "One-Way Valve" filter.
542
+ * Compresses verbose exploratory dumps, file trees, and search outputs into
543
+ * a dense, structured context digest bounded by maxChars (default 2000 chars, ~500 tokens).
544
+ * Prevents downstream context rot across multi-step orchestration.
545
+ */
546
+ export function synthesizeOneWayValve(rawOutput, options = {}) {
547
+ const maxChars = options.maxChars || 2000;
548
+ const text = String(rawOutput || '').trim();
549
+ if (!text) return 'No findings reported.';
550
+
551
+ // Extract file paths, line references, and key findings
552
+ const fileLines = text.split('\n');
553
+ const filesFound = new Set();
554
+ const keyObservations = [];
555
+
556
+ for (const line of fileLines) {
557
+ const trimmed = line.trim();
558
+ if (!trimmed) continue;
559
+ // Match potential file paths: e.g. src/foo.js, /path/to/file.mjs:42
560
+ const pathMatch = trimmed.match(/(?:[a-zA-Z0-9_-]+\/)+[a-zA-Z0-9._-]+\.[a-zA-Z0-9]+/);
561
+ if (pathMatch) {
562
+ filesFound.add(pathMatch[0]);
563
+ }
564
+ if (/^(found|note|warning|error|exports|function|class|symbol|defined|status|schema|todo|fixme)/i.test(trimmed) || trimmed.startsWith('- ') || trimmed.startsWith('* ')) {
565
+ if (keyObservations.length < 15) {
566
+ keyObservations.push(trimmed.replace(/^[-*]\s*/, ''));
567
+ }
568
+ }
569
+ }
570
+
571
+ const parts = [];
572
+ if (filesFound.size > 0) {
573
+ parts.push(`Relevant Files: ${Array.from(filesFound).slice(0, 10).join(', ')}`);
574
+ }
575
+ if (keyObservations.length > 0) {
576
+ parts.push(`Key Findings:\n- ${keyObservations.join('\n- ')}`);
577
+ }
578
+
579
+ let digest = parts.join('\n\n');
580
+ if (!digest || digest.length < 50) {
581
+ digest = text.length > maxChars ? `${text.slice(0, maxChars - 20)}... [truncated]` : text;
582
+ } else if (digest.length > maxChars) {
583
+ digest = `${digest.slice(0, maxChars - 20)}... [truncated]`;
584
+ }
585
+
586
+ return digest;
587
+ }
588
+
589
+ /**
590
+ * Decompose a multi-step task into specialized subagent stages:
591
+ * 1. Explorer (read-only codebase sweep, zero-cost / local preference)
592
+ * 2. Architect (modular design & file contracts, frontier preference)
593
+ * 3. Implementer (code authoring & unit test generation)
594
+ * 4. Verifier (adversarial code audit in isolated worktree, distinct model family)
595
+ */
596
+ export function decomposeTask(taskDescription, options = {}) {
597
+ const task = String(taskDescription || '').trim();
598
+ if (!task) throw new Error('Task description is required for decomposition');
599
+
600
+ const complexity = classifyTaskComplexity(task, options);
601
+ const catalog = options.catalog || ADAPTER_CATALOG;
602
+ const available = options.availableHarnesses?.length ? options.availableHarnesses : Object.keys(catalog);
603
+ const entry = id => catalog[id] || {};
604
+ const byQuality = [...available].sort((a, b) => (entry(b).qualityScore ?? 0) - (entry(a).qualityScore ?? 0));
605
+ const byCost = [...available].sort((a, b) => (entry(a).costScore ?? 99) - (entry(b).costScore ?? 99));
606
+
607
+ // Explorer takes the cheapest harness, Architect the strongest
608
+ const explorerHarness = byCost[0] || null;
609
+ const architectHarness = byQuality[0] || null;
610
+ const implementerHarness = byQuality.find(id => id !== architectHarness && id !== explorerHarness) || architectHarness;
611
+
612
+ // Verifier must come from a different model family. Without one, it stays null rather than grading its own work.
613
+ const verifierHarness = byQuality.find(id => entry(id).family && entry(id).family !== entry(implementerHarness).family) || null;
614
+ const tierOf = id => entry(id).tier || null;
615
+
616
+ return {
617
+ task,
618
+ complexity,
619
+ crossFamilyVerification: Boolean(verifierHarness),
620
+ stages: [
621
+ {
622
+ id: 'stage-1-explore',
623
+ role: 'Explorer',
624
+ preferredHarness: explorerHarness,
625
+ tier: tierOf(explorerHarness),
626
+ permissions: { read: true, write: false },
627
+ objective: 'Sweep workspace, locate relevant files, inspect interfaces, and read official documentation without context bloat.',
628
+ valveFilter: true
629
+ },
630
+ {
631
+ id: 'stage-2-architect',
632
+ role: 'Architect',
633
+ preferredHarness: architectHarness,
634
+ tier: tierOf(architectHarness),
635
+ permissions: { read: true, write: false },
636
+ objective: 'Synthesize Explorer digest into modular architectural blueprint, interface contracts, and verification gates.'
637
+ },
638
+ {
639
+ id: 'stage-3-implement',
640
+ role: 'Implementer',
641
+ preferredHarness: implementerHarness,
642
+ tier: tierOf(implementerHarness),
643
+ permissions: { read: true, write: true },
644
+ objective: 'Author production implementation files and test cases strictly following the Architectural blueprint.'
645
+ },
646
+ {
647
+ id: 'stage-4-verify',
648
+ role: 'Verifier',
649
+ preferredHarness: verifierHarness,
650
+ tier: tierOf(verifierHarness),
651
+ worktreeIsolated: true,
652
+ permissions: { read: true, write: false },
653
+ objective: 'Adversarial code review and quality gate verification executed in an isolated Git worktree with a distinct model family.'
654
+ }
655
+ ]
656
+ };
657
+ }
658
+
659
+ /**
660
+ * Metaharness Brick Factory
661
+ */
662
+ export function createMetaHarness(customAdapters = {}) {
663
+ const mergedAdapters = { ...ADAPTER_CATALOG, ...customAdapters };
664
+ return {
665
+ catalog: mergedAdapters,
666
+ validateAdapter: (adapter) => validateAdapterManifest(adapter),
667
+ classify: (task, opts) => classifyTaskComplexity(task, opts),
668
+ select: (task, available, quotas, opts) => selectOptimalHarness(task, available, quotas, { ...opts, catalog: mergedAdapters }),
669
+ buildEnvelope: (task, opts) => buildBootstrapEnvelope(task, opts),
670
+ evaluateCascade: (harness, gates, available) => evaluateGateCascade(harness, gates, available),
671
+ scorecard: (runs) => computeEmpiricalScorecard(runs),
672
+ decompose: (task, opts) => decomposeTask(task, { ...opts, catalog: mergedAdapters }),
673
+ valve: (raw, opts) => synthesizeOneWayValve(raw, opts)
674
+ };
675
+ }