tr-plugin-meta-harness 0.3.0 → 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 +257 -11
  3. package/capability/BRICK.md +1 -1
  4. package/capability/index.mjs +154 -13
  5. package/cli.mjs +426 -41
  6. package/package.json +15 -3
  7. package/plugin.json +1457 -119
  8. package/skills/meta-harness/SKILL.md +63 -25
  9. package/src/adoption.mjs +102 -0
  10. package/src/agent-user.mjs +194 -0
  11. package/src/alerts.mjs +220 -14
  12. package/src/cascade.mjs +185 -0
  13. package/src/chat.mjs +80 -0
  14. package/src/codex-models.mjs +54 -0
  15. package/src/compat-harness.mjs +114 -0
  16. package/src/control.mjs +145 -0
  17. package/src/coordinator.mjs +267 -358
  18. package/src/dispatch-request.mjs +76 -0
  19. package/src/dispatch.mjs +119 -0
  20. package/src/documentation-authority.mjs +57 -0
  21. package/src/documentation.mjs +120 -32
  22. package/src/executor.mjs +101 -22
  23. package/src/gate-adapters/agy.mjs +155 -0
  24. package/src/gate-adapters/claude.mjs +303 -0
  25. package/src/gate-adapters/cline.mjs +111 -0
  26. package/src/gate-adapters/codex.mjs +164 -0
  27. package/src/gate-adapters/cursor.mjs +164 -0
  28. package/src/gate-adapters/devin.mjs +116 -0
  29. package/src/gate-adapters/dsh.mjs +284 -0
  30. package/src/gate-adapters/grok.mjs +112 -0
  31. package/src/gate-adapters/hermes.mjs +217 -0
  32. package/src/gate-adapters/hook-files.mjs +156 -0
  33. package/src/gate-adapters/index.mjs +131 -0
  34. package/src/gate-adapters/openclaw-plugin/gate-client.js +205 -0
  35. package/src/gate-adapters/openclaw-plugin/index.js +25 -0
  36. package/src/gate-adapters/openclaw-plugin/openclaw.plugin.json +9 -0
  37. package/src/gate-adapters/openclaw-plugin/package.json +15 -0
  38. package/src/gate-adapters/openclaw.mjs +288 -0
  39. package/src/gate-adapters/pi.mjs +146 -0
  40. package/src/gate.mjs +18 -0
  41. package/src/harness-updates.mjs +170 -0
  42. package/src/included-usage.mjs +344 -0
  43. package/src/jobs.mjs +135 -0
  44. package/src/json-reply.mjs +22 -0
  45. package/src/learner.mjs +97 -67
  46. package/src/maintenance.mjs +18 -0
  47. package/src/mcp-server.mjs +228 -0
  48. package/src/model-catalog.mjs +195 -0
  49. package/src/model-selection.mjs +67 -0
  50. package/src/paths.mjs +23 -0
  51. package/src/pool.mjs +69 -0
  52. package/src/process-manager.mjs +246 -0
  53. package/src/process-worker.mjs +18 -0
  54. package/src/reasoning.mjs +231 -0
  55. package/src/remote-operation.mjs +76 -0
  56. package/src/review.mjs +241 -0
  57. package/src/reviews.mjs +25 -0
  58. package/src/router-benchmark-corpus.mjs +16 -0
  59. package/src/router-benchmark.mjs +208 -0
  60. package/src/router.mjs +265 -346
  61. package/src/runtime.mjs +30 -8
  62. package/src/session/claude.mjs +358 -0
  63. package/src/session/codex.mjs +501 -0
  64. package/src/session/result.mjs +90 -0
  65. package/src/session/resume.mjs +393 -0
  66. package/src/session/run.mjs +258 -0
  67. package/src/session-jobs.mjs +77 -0
  68. package/src/setup.mjs +6 -3
  69. package/src/ssss-store.mjs +20 -0
  70. package/src/telemetry.mjs +267 -0
  71. package/src/termination.mjs +28 -0
  72. package/src/threads.mjs +150 -0
  73. package/src/usage-queue.mjs +137 -0
  74. package/src/verify-ssss.mjs +102 -0
  75. package/src/worker.mjs +955 -84
  76. package/src/worktree.mjs +244 -0
  77. package/ui/chunks/adapter-docs-freshness.md +16 -0
  78. package/ui/chunks/chat-handoff.md +26 -0
  79. package/ui/chunks/fleet-maintenance.md +21 -0
  80. package/ui/chunks/harness-inventory.md +21 -0
  81. package/ui/chunks/included-access.md +18 -0
  82. package/ui/chunks/included-usage-verification.md +15 -0
  83. package/ui/chunks/independent-review.md +17 -0
  84. package/ui/chunks/managed-execution.md +20 -0
  85. package/ui/chunks/official-documentation.md +18 -0
  86. package/ui/chunks/quota-recovery.md +21 -0
  87. package/ui/chunks/review-routing-decision.md +16 -0
  88. package/ui/chunks/route-work.md +18 -0
  89. package/ui/chunks/routing-evidence.md +18 -0
  90. package/ui/chunks/run-ledger.md +18 -0
  91. package/ui/chunks/session-controls.md +16 -0
  92. package/ui/home.js +198 -0
  93. package/ui/DESIGN.md +0 -32
  94. package/ui/card.js +0 -845
@@ -1,398 +1,307 @@
1
1
  /**
2
- * Meta Harness Multi-Agent Coordinator
3
- * Orchestrates role-specialized multi-agent execution pipelines:
4
- * - Pipeline: Architect -> Implementer -> Verifier (cross-model family, worktree-isolated)
5
- * - Council: Multi-model consensus voting
6
- * - Race: Speculative concurrent execution
7
- *
8
- * Works with any user's installed harness pool:
9
- * - Dynamically discovers installed harnesses and assigns distinct model families
10
- * for Architect, Implementer, and Verifier so confirmation bias is avoided.
11
- * - Supports plan generation (default safe inspection) and live execution (`execute: true`)
12
- * via `dispatchAgent` with real git worktree isolation for the Verifier stage.
2
+ * Multi-agent coordination.
3
+ * Pipeline: Explorer -> Architect -> Implementer -> Verifier. Writing happens only on a dedicated
4
+ * branch in its own worktree, and the Verifier inspects that exact commit from a different model
5
+ * family. Nothing merges into the operator's branch; the branch is the deliverable.
13
6
  */
14
-
15
- import fs from 'node:fs';
16
- import path from 'node:path';
17
- import os from 'node:os';
18
- import { spawnSync } from 'node:child_process';
19
- import { ADAPTER_CATALOG, classifyTaskComplexity } from '../capability/index.mjs';
20
- import { inspectAgents, dispatchAgent, getActiveAdapters } from './worker.mjs';
21
- import { notifyAlert } from './alerts.mjs';
22
7
  import { recordRunReceipt } from './learner.mjs';
8
+ import { classifyTaskComplexity, synthesizeOneWayValve } from '../capability/index.mjs';
9
+ import { notifyAlert } from './alerts.mjs';
10
+ import { dispatchWithReceipt } from './dispatch.mjs';
11
+ import { queueIncludedJob } from './usage-queue.mjs';
12
+ import { resolvePool, localExecutionNode } from './pool.mjs';
13
+ import { createThread, appendThreadTurn, updateThread } from './threads.mjs';
14
+ import { executeCodeReview } from './review.mjs';
15
+ import { isGitRepo, isDirty, headCommit, createWorktree, removeWorktree, commitAll, diffBetween, linkDependencies, deleteBranch } from './worktree.mjs';
16
+ import { lastJsonWith } from './json-reply.mjs';
17
+ import { runQualityGate } from './gate.mjs';
18
+ import { forwardRemoteOperation } from './remote-operation.mjs';
19
+ import { cancellationResult } from './worker.mjs';
20
+ import { sessionOptions } from './session/run.mjs';
21
+ import { createModelValidator, filterPoolByModel } from './model-selection.mjs';
23
22
 
24
- /**
25
- * Resolve installed or available harnesses with their model family metadata
26
- */
27
- async function resolvePool(options = {}) {
28
- const active = getActiveAdapters();
29
- let installedIds = [];
30
- if (Array.isArray(options.availableHarnesses) && options.availableHarnesses.length > 0) {
31
- installedIds = options.availableHarnesses;
32
- } else {
33
- try {
34
- const inspected = await inspectAgents({ env: process.env });
35
- installedIds = (inspected.agents || []).filter(a => a.installed).map(a => a.id);
36
- } catch {}
37
- }
38
-
39
- const candidateIds = installedIds.length > 0 ? installedIds : active.map(a => a.id);
40
- return candidateIds.map(id => {
41
- const cap = ADAPTER_CATALOG[id] || {};
42
- const workerSpec = active.find(a => a.id === id) || {};
43
- return {
44
- id,
45
- name: cap.name || workerSpec.name || id,
46
- family: cap.family || 'custom',
47
- tier: cap.tier || 'budget',
48
- qualityScore: cap.qualityScore ?? 7.5,
49
- costScore: cap.costScore ?? 4
50
- };
51
- });
23
+ const OPEN_THREADS = new Set();
24
+ const MAX_BLUEPRINT = 20000;
25
+ /** Implementation is the long stage: a 15-minute session fallback stopped real implementers mid-change (2026-12-01). */
26
+ export const IMPLEMENTER_TIMEOUT_MS = 3600000;
27
+ export const STAGE_TIMEOUT_MS = 900000;
28
+ export function stageTimeoutMs(role, override) {
29
+ if (override !== undefined) return override;
30
+ return role === 'Implementer' ? IMPLEMENTER_TIMEOUT_MS : STAGE_TIMEOUT_MS;
31
+ }
32
+ /** A stopped pipeline must not leave its thread reading as active. */
33
+ export function failOpenThreads(summary = 'The run was stopped before it finished.') {
34
+ for (const id of OPEN_THREADS) { try { updateThread(id, { status: 'failed', summary }); } catch { /* the thread store reports its own failure */ } }
35
+ OPEN_THREADS.clear();
52
36
  }
53
37
 
54
- /**
55
- * Select three role-specialized harnesses preferring distinct model families
56
- */
57
38
  export function assignPipelineRoles(pool = [], options = {}) {
58
39
  const sorted = [...pool].sort((a, b) => b.qualityScore - a.qualityScore);
59
- const findById = (id) => sorted.find(h => h.id === id) || (ADAPTER_CATALOG[id] ? { id, ...ADAPTER_CATALOG[id] } : { id, name: id, family: 'custom' });
60
-
61
- const architect = options.architect
62
- ? findById(options.architect)
63
- : (sorted[0] || findById('claude'));
64
-
65
- const implementer = options.implementer
66
- ? findById(options.implementer)
67
- : (sorted.find(h => h.id !== architect.id) || sorted[0] || findById('agy'));
68
-
69
- // Verifier must use a distinct model family from Implementer whenever more than 1 family is available
70
- const verifier = options.verifier
71
- ? findById(options.verifier)
72
- : (sorted.find(h => h.family !== implementer.family && h.id !== implementer.id)
73
- || sorted.find(h => h.id !== implementer.id)
74
- || implementer);
75
-
76
- return {
77
- architect,
78
- implementer,
79
- verifier,
80
- heterogeneousFamilies: verifier.family !== implementer.family || pool.length <= 1
40
+ const findById = id => {
41
+ const harness = sorted.find(h => h.id === id);
42
+ if (!harness) throw new Error(`Selected harness ${id} is not ready for this task`);
43
+ return harness;
81
44
  };
82
- }
45
+ // The session's own harness leads only when it can take work; TR_ACTIVE_HARNESS is advisory.
46
+ const active = process.env.TR_ACTIVE_HARNESS;
47
+ const orchestrator = options.orchestrator ? findById(options.orchestrator) : sorted.find(h => h.id === active) || sorted[0] || null;
48
+ if (!orchestrator) return { orchestrator: null, explorer: null, architect: null, implementer: null, verifier: null, heterogeneousFamilies: false };
83
49
 
84
- /**
85
- * Coordinate a task across specialized roles and model families
86
- */
87
- export async function coordinateTask(taskDescription, options = {}) {
88
- const mode = options.mode || 'pipeline';
89
- const task = String(taskDescription || '').trim();
90
- if (!task) throw new Error('Task description is required for coordination');
91
-
92
- const pool = await resolvePool(options);
93
-
94
- if (mode === 'pipeline') {
95
- return await runSpecializedPipeline(task, pool, options);
96
- } else if (mode === 'council') {
97
- return await runCouncilCoordination(task, pool, options);
98
- } else if (mode === 'race') {
99
- return await runRaceCoordination(task, pool, options);
100
- } else {
101
- throw new Error(`Unsupported coordination mode: ${mode}`);
102
- }
50
+ const byCost = [...pool].sort((a, b) => a.costScore - b.costScore);
51
+ const explorer = options.explorer ? findById(options.explorer) : byCost.find(h => h.id !== orchestrator.id) || orchestrator;
52
+ const architect = options.architect ? findById(options.architect) : orchestrator;
53
+ // A requested model is the Implementer's: only a harness that can run it writes the code.
54
+ const compatible = options.modelCompatible;
55
+ const writers = compatible ? sorted.filter(h => compatible.includes(h.id)) : sorted;
56
+ const implementer = options.implementer ? findById(options.implementer) : writers.find(h => h.id !== explorer.id && h.id !== architect.id) || writers.find(h => h.id !== architect.id) || (compatible ? writers[0] || null : architect);
57
+ if (compatible && implementer && !compatible.includes(implementer.id)) throw new Error(`Selected implementer ${implementer.id} cannot run model ${options.model}`);
58
+ if (!implementer) return { orchestrator, explorer, architect, implementer: null, verifier: null, heterogeneousFamilies: false };
59
+ const verifier = options.verifier ? findById(options.verifier) : sorted.find(h => h.family !== implementer.family) || null;
60
+ return { orchestrator, explorer, architect, implementer, verifier, heterogeneousFamilies: Boolean(verifier) && verifier.family !== implementer.family };
103
61
  }
104
62
 
105
- /**
106
- * Create a temporary detached git worktree if inside a git repository
107
- */
108
- function createVerifierWorktree(cwd) {
109
- try {
110
- const check = spawnSync('git', ['rev-parse', '--is-inside-work-tree'], { cwd, encoding: 'utf8', timeout: 3000 });
111
- if (check.status !== 0) return null;
112
- const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'meta-harness-verify-'));
113
- const add = spawnSync('git', ['worktree', 'add', '--detach', tmpDir], { cwd, encoding: 'utf8', timeout: 10000 });
114
- if (add.status !== 0) {
115
- fs.rmSync(tmpDir, { recursive: true, force: true });
116
- return null;
117
- }
118
- return tmpDir;
119
- } catch {
120
- return null;
121
- }
63
+ /** The agent must state a verdict. Silence or an unreadable answer is not a pass. */
64
+ export function parseVerification(response) {
65
+ const parsed = lastJsonWith(response, 'verdict');
66
+ const verdict = String(parsed?.verdict).toUpperCase();
67
+ if (['PASS', 'FAIL'].includes(verdict)) return { parsed: true, verdict, findings: Array.isArray(parsed.findings) ? parsed.findings : [] };
68
+ return { parsed: false, verdict: 'UNREADABLE', findings: [] };
69
+ }
70
+ export function parseVote(response) {
71
+ const parsed = lastJsonWith(response, 'vote');
72
+ const vote = String(parsed?.vote).toUpperCase();
73
+ return ['APPROVE', 'REJECT'].includes(vote) ? { vote, reason: parsed.reason || null } : { vote: 'ABSTAIN', reason: null };
122
74
  }
123
75
 
124
- function removeVerifierWorktree(cwd, worktreeDir) {
125
- if (!worktreeDir) return;
126
- try {
127
- spawnSync('git', ['worktree', 'remove', '--force', worktreeDir], { cwd, encoding: 'utf8', timeout: 5000 });
128
- } catch {}
129
- try {
130
- fs.rmSync(worktreeDir, { recursive: true, force: true });
131
- } catch {}
76
+ const stageOf = (role, harness, permissions, action, extra = {}) => ({ role, harness: harness?.id || null, harnessName: harness?.name || null, modelFamily: harness?.family || null, permissions, action, status: 'planned', output: null, ...extra });
77
+ const READ = { read: true, write: false };
78
+ const WRITE = { read: true, write: true };
79
+
80
+ function buildStages(roles, withSubagents) {
81
+ const stages = [];
82
+ if (withSubagents) stages.push(stageOf('Explorer', roles.explorer, READ, 'Find the relevant files, symbols and interfaces.', { contextDigest: null }));
83
+ stages.push(stageOf('Architect', roles.architect, READ, 'Produce the blueprint, file list and verification steps.'));
84
+ stages.push(stageOf('Implementer', roles.implementer, WRITE, 'Write the code and tests on a dedicated branch in its own worktree.'));
85
+ stages.push(stageOf('Verifier', roles.verifier, READ, 'Audit the implementation commit from a different model family.', { worktreeIsolated: true, passed: null }));
86
+ return stages;
132
87
  }
133
88
 
134
- /**
135
- * Architect -> Implementer -> Verifier Pipeline
136
- * Enforces heterogeneous model families to eliminate confirmation bias.
137
- */
138
- async function runSpecializedPipeline(task, pool, options = {}) {
139
- const startTime = Date.now();
89
+ async function runPipeline(task, poolInfo, options) {
90
+ const started = Date.now();
91
+ const pool = poolInfo.ready;
140
92
  const roles = assignPipelineRoles(pool, options);
141
- const executeLive = options.execute === true;
142
93
  const cwd = options.cwd || process.cwd();
143
- const dispatchFn = options.dispatchFn || dispatchAgent;
94
+ const execute = options.execute === true;
95
+ const withSubagents = options.subagents !== false;
96
+ const stages = roles.orchestrator ? buildStages(roles, withSubagents) : [];
97
+ if (options.model !== undefined) for (const item of stages) if (item.role === 'Implementer') item.model = options.model;
98
+ const base = { mode: 'pipeline', task, ...modelFields(options), orchestrator: roles.orchestrator?.id || null, executedLive: execute, excluded: poolInfo.excluded, heterogeneousFamiliesVerified: roles.heterogeneousFamilies, stages };
99
+
100
+ if (!execute) {
101
+ const blockers = [];
102
+ if (!roles.orchestrator) blockers.push('No harness can take work right now.');
103
+ else if (!roles.implementer) blockers.push(`No harness that can take work can run model ${options.model}.`);
104
+ else if (!roles.heterogeneousFamilies) blockers.push('Only one model family is available, so no independent Verifier exists.');
105
+ return { ...base, ok: blockers.length === 0, threadId: null, blockers };
106
+ }
107
+ if (!roles.orchestrator) throw new Error(`No harness can take work right now: ${poolInfo.excluded.map(e => `${e.harness} (${e.reason})`).join(', ') || 'none installed'}`);
108
+ if (!roles.implementer) throw new Error(`No harness that can take work can run model ${options.model}`);
109
+ if (!roles.heterogeneousFamilies && options.allowSameFamily !== true) throw new Error('Refusing to run: only one model family is available, so no independent Verifier exists. Pass --allow-same-family to accept self-review.');
110
+ if (!isGitRepo(cwd)) throw new Error('A pipeline writes on its own branch, so it must run inside a git repository');
111
+
112
+ const verifier = roles.verifier || roles.implementer;
144
113
  const complexity = classifyTaskComplexity(task);
114
+ // Validate the repository before creating lifecycle state: an unborn repository has no usable base.
115
+ const baseCommit = headCommit(cwd);
116
+ const warnings = isDirty(cwd) ? ['The working tree has uncommitted changes; the branch starts from the last commit and does not include them.'] : [];
117
+ const thread = createThread({ title: task.slice(0, 80), task, platform: roles.orchestrator.id, model: roles.orchestrator.name, status: 'active' });
118
+ OPEN_THREADS.add(thread.id);
119
+ const branch = options.branch || `meta-harness/${thread.id}`;
120
+ const run = async (stage, harness, prompt, { workdir = cwd, permissions, role = stage.role } = {}) => {
121
+ stage.status = 'running';
122
+ const result = await dispatchWithReceipt({ agent: harness.id, node: 'local', cwd: workdir, contextCwd: cwd, contextTask: task, prompt,
123
+ ...sessionOptions({ ...options, cwd }), timeoutMs: stageTimeoutMs(stage.role, options.timeoutMs), goal: stage.role === 'Implementer' ? options.goal || task.slice(0, 4000) : prompt.slice(0, 4000),
124
+ ...(stage.role === 'Implementer' && options.model !== undefined ? { model: options.model } : {}),
125
+ permissions: permissions || stage.permissions, allowUnknownAuth: options.allowUnknownAuth === true }, { dispatchFn: options.dispatchFn, role, complexityScore: complexity.score });
126
+ stage.status = result.cancelled ? 'cancelled' : result.ok ? 'completed' : result.queued ? 'queued' : 'failed';
127
+ stage.output = result.response || result.error || null;
128
+ for (const key of ['goalCheck', 'structured', 'sessionId', 'progressFile', 'usage']) if (result[key] !== undefined) stage[key] = result[key];
129
+ stage.failureKind = result.ok ? undefined : result.failureKind;
130
+ if (result.queueId) stage.queueId = result.queueId;
131
+ appendThreadTurn(thread.id, { role: role.toLowerCase(), agent: harness.id, content: stage.output || '' });
132
+ return result;
133
+ };
145
134
 
146
- const stages = [
147
- {
148
- role: 'Architect',
149
- harness: roles.architect.id,
150
- harnessName: roles.architect.name,
151
- modelFamily: roles.architect.family,
152
- permissions: { read: true, write: false },
153
- status: executeLive ? 'pending' : 'planned',
154
- action: 'Analyze requirements, design modular contracts, and formulate verification plan.',
155
- output: null
156
- },
157
- {
158
- role: 'Implementer',
159
- harness: roles.implementer.id,
160
- harnessName: roles.implementer.name,
161
- modelFamily: roles.implementer.family,
162
- permissions: { read: true, write: true },
163
- status: executeLive ? 'pending' : 'planned',
164
- action: 'Author implementation files and unit tests following Architectural blueprint.',
165
- output: null
166
- },
167
- {
168
- role: 'Verifier',
169
- harness: roles.verifier.id,
170
- harnessName: roles.verifier.name,
171
- modelFamily: roles.verifier.family,
172
- permissions: { read: true, write: false },
173
- worktreeIsolated: true,
174
- status: executeLive ? 'pending' : 'planned',
175
- action: 'Execute deterministic test gates, audit diffs, and verify invariant compliance in isolated worktree.',
176
- passed: executeLive ? null : true,
177
- output: null
135
+ let ok = true, commit = null, implementerDir = null, gate = null, wip = false;
136
+ const stage = role => stages.find(item => item.role === role);
137
+ try {
138
+ let digest = '';
139
+ if (withSubagents) {
140
+ const explorer = await run(stage('Explorer'), roles.explorer, `[ROLE: EXPLORER]\nDo not change any file. Find the files, symbols and interfaces relevant to this task:\n${task}`);
141
+ if (!explorer.ok) { ok = false; return finish(); }
142
+ digest = synthesizeOneWayValve(explorer.response, { maxChars: 2000 });
143
+ stage('Explorer').contextDigest = digest;
178
144
  }
179
- ];
145
+ const architect = await run(stage('Architect'), roles.architect, `[ROLE: ARCHITECT]\nDo not change any file. Task:\n${task}\n\nExplorer digest:\n${digest || 'None.'}\n\nProduce a concise blueprint, the files to change, and how to verify the result.`);
146
+ if (!architect.ok) { ok = false; return finish(); }
147
+ const blueprint = architect.response.length > MAX_BLUEPRINT ? `${architect.response.slice(0, MAX_BLUEPRINT)}\n[Blueprint shortened to ${MAX_BLUEPRINT} characters.]` : architect.response;
180
148
 
181
- let allSucceeded = true;
149
+ implementerDir = createWorktree(cwd, { branch });
150
+ const implementer = await run(stage('Implementer'), roles.implementer, `[ROLE: IMPLEMENTER]\nWork only in this checkout. Implement the task and its tests. Do not commit; the harness commits your changes.\nTask:\n${task}\n\nBlueprint:\n${blueprint}`, { workdir: implementerDir });
151
+ if (!implementer.ok) {
152
+ // A failed stage after real edits (a goal check, a timeout) must not discard them: keep them on the branch.
153
+ ok = false;
154
+ commit = commitAll(implementerDir, `meta-harness: unfinished implementer work (${implementer.failureKind || 'failed'})\n\n${task.slice(0, 200)}`) || null;
155
+ wip = Boolean(commit);
156
+ return finish();
157
+ }
158
+ commit = commitAll(implementerDir, `meta-harness: ${task.slice(0, 60)}\n\nImplementer: ${roles.implementer.id}`);
159
+ if (!commit) commit = baseCommit;
160
+ stage('Implementer').commit = commit;
161
+ updateThread(thread.id, { branch, worktreePath: null });
182
162
 
183
- if (executeLive) {
184
- // Stage 1: Architect (Read-Only Plan)
185
- const archStart = Date.now();
186
- const archRes = await dispatchFn({
187
- agent: roles.architect.id,
188
- cwd,
189
- prompt: `[ROLE: ARCHITECT]\nProduce a concise architectural blueprint, file list, and verification steps for:\n${task}`,
190
- permissions: { read: true, write: false },
191
- allowUnknownAuth: options.allowUnknownAuth === true
192
- });
193
- stages[0].status = archRes.ok ? 'completed' : 'failed';
194
- stages[0].output = archRes.response || archRes.error || null;
195
- recordRunReceipt({
196
- harness: roles.architect.id,
197
- task: `[Architect] ${task}`,
198
- complexityScore: complexity.score,
199
- success: Boolean(archRes.ok),
200
- durationMs: Date.now() - archStart
201
- });
163
+ if (options.gate) {
164
+ linkDependencies(cwd, implementerDir);
165
+ gate = await (options.gateFn || runQualityGate)(implementerDir, options.gateOptions);
166
+ if (cancellationResult()) { ok = false; return finish(); }
167
+ if (!gate.passed) { ok = false; stage('Verifier').status = 'skipped'; stage('Verifier').output = `Quality gate did not pass: ${gate.summary}`; return finish(); }
168
+ }
202
169
 
203
- if (!archRes.ok) {
204
- allSucceeded = false;
205
- } else {
206
- // Stage 2: Implementer
207
- const implStart = Date.now();
208
- const implRes = await dispatchFn({
209
- agent: roles.implementer.id,
210
- cwd,
211
- prompt: `[ROLE: IMPLEMENTER]\nFollow this Architect blueprint:\n${archRes.response}\n\nImplement the requested task:\n${task}`,
212
- permissions: { read: true, write: true },
213
- allowUnknownAuth: options.allowUnknownAuth === true
214
- });
215
- stages[1].status = implRes.ok ? 'completed' : 'failed';
216
- stages[1].output = implRes.response || implRes.error || null;
217
- recordRunReceipt({
218
- harness: roles.implementer.id,
219
- task: `[Implementer] ${task}`,
220
- complexityScore: complexity.score,
221
- success: Boolean(implRes.ok),
222
- durationMs: Date.now() - implStart
223
- });
170
+ const diff = diffBetween(cwd, baseCommit, commit);
171
+ const verifyDir = createWorktree(cwd, { ref: commit, prefix: 'meta-harness-verify-' });
172
+ try {
173
+ const verification = await run(stage('Verifier'), verifier, `[ROLE: INDEPENDENT VERIFIER]\nYou did not write this code. Do not change any file. Run the checks you can and audit commit ${commit} for this task:\n${task}\n\nBlueprint:\n${blueprint}\n\nDiff${diff.length > 30000 ? ' (first 30000 characters; read the rest from this checkout)' : ''}:\n${diff.slice(0, 30000)}\n\nEnd your reply with exactly one JSON object: {"verdict":"PASS"|"FAIL","findings":["..."]}`, { workdir: verifyDir });
174
+ const parsed = verification.ok ? parseVerification(verification.response) : { parsed: false, verdict: 'NOT_RUN', findings: [] };
175
+ Object.assign(stage('Verifier'), { commit, verdict: parsed.verdict, findings: parsed.findings, passed: parsed.verdict === 'PASS' });
176
+ if (parsed.verdict !== 'PASS') { ok = false; return finish(); }
177
+ } finally { removeWorktree(cwd, verifyDir); }
224
178
 
225
- if (!implRes.ok) {
226
- allSucceeded = false;
227
- } else {
228
- // Stage 3: Verifier (Isolated git worktree when available)
229
- const verifyStart = Date.now();
230
- const worktreeDir = createVerifierWorktree(cwd);
231
- const verifyCwd = worktreeDir || cwd;
232
- try {
233
- const verRes = await dispatchFn({
234
- agent: roles.verifier.id,
235
- cwd: verifyCwd,
236
- prompt: `[ROLE: INDEPENDENT VERIFIER]\nAudit the implementation and run verification checks for:\n${task}\n\nArchitect Blueprint:\n${archRes.response}\n\nImplementer Summary:\n${implRes.response}`,
237
- permissions: { read: true, write: false },
238
- allowUnknownAuth: options.allowUnknownAuth === true
239
- });
240
- stages[2].status = verRes.ok ? 'completed' : 'failed';
241
- stages[2].passed = Boolean(verRes.ok);
242
- stages[2].output = verRes.response || verRes.error || null;
243
- stages[2].worktreePath = worktreeDir || null;
244
- recordRunReceipt({
245
- harness: roles.verifier.id,
246
- task: `[Verifier] ${task}`,
247
- complexityScore: complexity.score,
248
- success: Boolean(verRes.ok),
249
- durationMs: Date.now() - verifyStart
250
- });
251
- if (!verRes.ok) allSucceeded = false;
252
- } finally {
253
- removeVerifierWorktree(cwd, worktreeDir);
254
- }
255
- }
179
+ if (options.autoReview) {
180
+ const review = await executeCodeReview({ cwd, author: roles.implementer.id, threadId: thread.id, task, target: `${baseCommit}...${commit}`, dispatchFn: options.dispatchFn, reviewer: options.reviewer, allowUnknownAuth: options.allowUnknownAuth === true, availableHarnesses: options.availableHarnesses });
181
+ stages.push({ role: 'Reviewer', harness: review.review?.reviewer || null, status: review.ok ? 'completed' : 'failed', verdict: review.review?.verdict || null, riskScore: review.review?.riskScore ?? null, output: review.review?.summary || review.error || null });
182
+ if (!review.ok || review.review?.verdict !== 'APPROVE') ok = false;
256
183
  }
257
- } else {
258
- stages[0].output = `Planned Architect stage (${roles.architect.name}) for: ${task.slice(0, 80)}`;
259
- stages[1].output = `Planned Implementer stage (${roles.implementer.name}) following Architect blueprint.`;
260
- stages[2].output = `Planned cross-family Verifier stage (${roles.verifier.name}, family: ${roles.verifier.family}) in isolated git worktree.`;
184
+ return finish();
185
+ } catch (error) {
186
+ // An infrastructure failure (git, a refused commit) must still close the thread and report.
187
+ ok = false;
188
+ const current = stages.find(item => ['running', 'planned'].includes(item.status));
189
+ if (current) Object.assign(current, { status: 'failed', failureKind: 'process', output: String(error.message) });
190
+ return finish();
191
+ } finally {
192
+ removeWorktree(cwd, implementerDir);
193
+ if (implementerDir && !wip && (!commit || (!ok && !cancellationResult()))) deleteBranch(cwd, branch);
261
194
  }
262
195
 
263
- const durationMs = Date.now() - startTime;
264
- const result = {
265
- ok: allSucceeded,
266
- mode: 'pipeline',
267
- executedLive: executeLive,
268
- task,
269
- stages,
270
- durationMs,
271
- heterogeneousFamiliesVerified: roles.heterogeneousFamilies
272
- };
273
-
274
- if (executeLive) {
275
- await notifyAlert({
276
- title: allSucceeded ? 'Meta Harness: Pipeline Completed' : 'Meta Harness: Pipeline Failed',
277
- message: `Multi-agent pipeline ${allSucceeded ? 'succeeded' : 'failed'} for task: ${task.slice(0, 60)}`,
278
- severity: allSucceeded ? 'info' : 'warning'
279
- });
196
+ function finish() {
197
+ const cancelled = cancellationResult();
198
+ if (cancelled) {
199
+ ok = false;
200
+ if (implementerDir) commit = commitAll(implementerDir, 'meta-harness: unfinished pipeline from a cancelled job') || commit;
201
+ }
202
+ return (async () => {
203
+ for (const item of stages) if (item.status === 'planned') item.status = 'skipped';
204
+ OPEN_THREADS.delete(thread.id);
205
+ const kept = (ok || cancelled || wip) && commit;
206
+ updateThread(thread.id, { status: ok ? 'completed' : 'failed', branch: kept ? branch : null, commit, baseCommit });
207
+ const alert = cancelled ? null : await notifyAlert({ title: ok ? 'Metaharness: pipeline passed' : 'Metaharness: pipeline failed', message: `${task.slice(0, 80)}${commit ? ` (branch ${branch})` : ''}`, severity: ok ? 'info' : 'warning' });
208
+ const limited = stages.find(item => item.failureKind === 'limit');
209
+ return { ...base, ok, ...cancelled, ...(limited ? { failureKind: 'limit', error: limited.output } : {}), goalCheck: stage('Implementer')?.goalCheck, structured: stage('Implementer')?.structured,
210
+ sessionId: stage('Implementer')?.sessionId, progressFile: stage('Implementer')?.progressFile,
211
+ threadId: thread.id, branch: kept ? branch : null, commit, baseCommit, ...(wip ? { wip: true } : {}), gate, warnings, durationMs: Date.now() - started, alert };
212
+ })();
280
213
  }
281
-
282
- return result;
283
214
  }
284
215
 
285
- /**
286
- * Council Consensus (Multi-model deliberation across available harnesses)
287
- */
288
- async function runCouncilCoordination(task, pool, options = {}) {
289
- const councilHarnesses = options.harnesses
290
- || pool.slice(0, 3).map(h => h.id);
291
- const executeLive = options.execute === true;
216
+ async function runCouncil(task, poolInfo, options) {
217
+ // One seat per model family, strongest first, so the seats can actually disagree.
218
+ const families = new Set();
219
+ const seats = options.harnesses || [...poolInfo.ready].sort((a, b) => b.qualityScore - a.qualityScore).filter(h => !families.has(h.family) && families.add(h.family)).slice(0, 3).map(h => h.id);
220
+ if (options.execute !== true) return { ok: seats.length > 0, mode: 'council', task, ...modelFields(options), executedLive: false, consensus: 'planned', excluded: poolInfo.excluded, votes: seats.map(harness => ({ harness, status: 'planned' })) };
221
+ if (!seats.length) throw new Error('No harness can take work right now');
292
222
  const cwd = options.cwd || process.cwd();
293
- const dispatchFn = options.dispatchFn || dispatchAgent;
223
+ const votes = await Promise.all(seats.map(async harness => {
224
+ const result = await dispatchWithReceipt({ agent: harness, node: 'local', cwd, contextTask: task, ...sessionOptions({ ...options, cwd }), ...(options.model !== undefined ? { model: options.model } : {}), prompt: `[ROLE: COUNCIL MEMBER]\nDo not change any file. Assess this proposal, with its trade-offs and risks:\n${task}\n\nEnd your reply with exactly one JSON object: {"vote":"APPROVE"|"REJECT","reason":"..."}`, permissions: READ, allowUnknownAuth: options.allowUnknownAuth === true }, { dispatchFn: options.dispatchFn, role: 'Council' });
225
+ return { harness, ok: result.ok === true, failureKind: result.failureKind, ...(result.ok ? parseVote(result.response) : { vote: 'ABSTAIN', reason: null, error: result.error }),
226
+ ...(result.queueId ? { queueId: result.queueId } : {}), feedback: result.response || null };
227
+ }));
228
+ const count = vote => votes.filter(item => item.vote === vote).length;
229
+ const majority = votes.length / 2;
230
+ const consensus = count('APPROVE') > majority ? 'approved' : count('REJECT') > majority ? 'rejected' : 'no-consensus';
231
+ const limited = votes.some(item => item.failureKind === 'limit');
232
+ return { ok: !limited && votes.some(item => item.ok), ...(limited ? { failureKind: 'limit' } : {}), ...cancellationResult(), mode: 'council', task, ...modelFields(options), executedLive: true, consensus, excluded: poolInfo.excluded, votes };
233
+ }
294
234
 
295
- if (executeLive) {
296
- const dispatches = await Promise.all(councilHarnesses.map(async (h) => {
297
- try {
298
- const res = await dispatchFn({
299
- agent: h,
300
- cwd,
301
- prompt: `[COUNCIL DELIBERATION]\nProvide your independent engineering assessment and recommendation for:\n${task}`,
302
- permissions: { read: true, write: false },
303
- allowUnknownAuth: options.allowUnknownAuth === true
304
- });
305
- return {
306
- harness: h,
307
- ok: Boolean(res.ok),
308
- recommendation: res.ok ? 'completed' : 'failed',
309
- response: res.response || res.error || null
310
- };
311
- } catch (err) {
312
- return {
313
- harness: h,
314
- ok: false,
315
- recommendation: 'error',
316
- response: err.message
317
- };
235
+ async function runRace(task, poolInfo, options) {
236
+ const seats = options.candidates || [...poolInfo.ready].sort((a, b) => b.qualityScore - a.qualityScore).slice(0, 2).map(h => h.id);
237
+ if (options.execute !== true) return { ok: seats.length > 1, mode: 'race', task, ...modelFields(options), executedLive: false, excluded: poolInfo.excluded, candidates: seats.map(harness => ({ harness, status: 'planned' })) };
238
+ if (seats.length < 2) throw new Error('A race needs at least two harnesses that can take work');
239
+ if (!options.gate) return { ok: false, mode: 'race', task, executedLive: false, verification: 'unverified', gateApplied: false, error: 'A race requires a deterministic quality gate before any candidate can win.' };
240
+ const cwd = options.cwd || process.cwd();
241
+ if (!isGitRepo(cwd)) throw new Error('A race writes on separate branches, so it must run inside a git repository');
242
+ const id = `race-${Date.now().toString(36)}`;
243
+ const entries = await Promise.all(seats.map(async harness => {
244
+ const branch = `meta-harness/${id}-${harness}`;
245
+ let directory;
246
+ let keep = false;
247
+ try {
248
+ const started = Date.now();
249
+ directory = createWorktree(cwd, { branch });
250
+ const result = await dispatchWithReceipt({ agent: harness, node: 'local', cwd: directory, contextCwd: cwd, contextTask: task, ...sessionOptions({ ...options, cwd }), goal: options.goal || task.slice(0, 4000), ...(options.model !== undefined ? { model: options.model } : {}), prompt: `[ROLE: IMPLEMENTER]\nWork only in this checkout. Implement the task and its tests. Do not commit.\nTask:\n${task}`, permissions: WRITE, allowUnknownAuth: options.allowUnknownAuth === true }, { dispatchFn: options.dispatchFn, role: 'Race' });
251
+ const commit = result.ok || result.cancelled ? commitAll(directory, `meta-harness race: ${task.slice(0, 60)}\n\nAgent: ${harness}`) : null;
252
+ if (result.cancelled) {
253
+ keep = Boolean(commit);
254
+ return { ...result, harness, branch: keep ? branch : null, wip: commit };
318
255
  }
319
- }));
320
-
321
- const passedCount = dispatches.filter(d => d.ok).length;
322
- return {
323
- ok: passedCount > 0,
324
- mode: 'council',
325
- executedLive: true,
326
- task,
327
- council: councilHarnesses,
328
- consensus: passedCount === councilHarnesses.length ? 'unanimous' : (passedCount > 0 ? 'majority' : 'failed'),
329
- votes: dispatches
330
- };
331
- }
332
-
333
- const votes = councilHarnesses.map(h => ({
334
- harness: h,
335
- status: 'planned',
336
- recommendation: 'ready',
337
- reasoning: `Scheduled independent read-only deliberation on ${h}.`
256
+ if (result.ok && options.gate) linkDependencies(cwd, directory);
257
+ const gate = result.ok ? await (options.gateFn || runQualityGate)(directory, options.gateOptions) : null;
258
+ if (cancellationResult()) {
259
+ keep = Boolean(commit);
260
+ return { ...cancellationResult(), harness, branch: keep ? branch : null, commit };
261
+ }
262
+ keep = result.ok === true && gate?.passed === true;
263
+ return { harness, branch: keep ? branch : null, commit: keep ? commit : null, ok: keep, gate, goalCheck: result.goalCheck, structured: result.structured, failureKind: result.failureKind, completedAt: Date.now(), durationMs: Date.now() - started, error: result.ok ? keep ? undefined : 'The quality gate failed' : result.error,
264
+ ...(result.queueId ? { queueId: result.queueId } : {}) };
265
+ } catch (error) {
266
+ return { harness, branch: null, commit: null, ok: false, gate: null, durationMs: null, error: String(error.message) };
267
+ } finally {
268
+ removeWorktree(cwd, directory);
269
+ if (!keep) deleteBranch(cwd, branch);
270
+ }
338
271
  }));
339
-
340
- return {
341
- ok: true,
342
- mode: 'council',
343
- executedLive: false,
344
- task,
345
- council: councilHarnesses,
346
- consensus: 'planned',
347
- votes
348
- };
272
+ const finishers = entries.filter(entry => entry.ok).sort((a, b) => a.completedAt - b.completedAt);
273
+ const limited = entries.some(item => item.failureKind === 'limit');
274
+ return { ok: !limited && finishers.length > 0, ...(limited ? { failureKind: 'limit' } : {}), ...cancellationResult(), mode: 'race', task, ...modelFields(options), executedLive: true, gateApplied: true, verification: !limited && finishers.length ? 'passed' : 'failed', winner: limited ? null : finishers[0]?.harness || null, excluded: poolInfo.excluded, candidates: entries };
349
275
  }
350
276
 
351
- /**
352
- * Speculative Concurrent Race
353
- */
354
- async function runRaceCoordination(task, pool, options = {}) {
355
- const contenders = options.harnesses
356
- || pool.slice(0, 2).map(h => h.id);
357
- const executeLive = options.execute === true;
358
- const cwd = options.cwd || process.cwd();
359
- const dispatchFn = options.dispatchFn || dispatchAgent;
277
+ const modelFields = options => options.model !== undefined ? { model: options.model, modelSelection: options.modelSelection } : {};
360
278
 
361
- if (executeLive) {
362
- const results = await Promise.all(contenders.map(async (h) => {
363
- const start = Date.now();
364
- try {
365
- const res = await dispatchFn({
366
- agent: h,
367
- cwd,
368
- prompt: task,
369
- permissions: { read: true, write: false },
370
- allowUnknownAuth: options.allowUnknownAuth === true
371
- });
372
- return { harness: h, ok: Boolean(res.ok), durationMs: Date.now() - start, response: res.response || null };
373
- } catch (err) {
374
- return { harness: h, ok: false, durationMs: Date.now() - start, error: err.message };
375
- }
376
- }));
377
- const winners = results.filter(r => r.ok).sort((a, b) => a.durationMs - b.durationMs);
378
- return {
379
- ok: winners.length > 0,
380
- mode: 'race',
381
- executedLive: true,
382
- task,
383
- contenders,
384
- winner: winners[0]?.harness || null,
385
- results
386
- };
279
+ export async function coordinateTask(taskDescription, options = {}) {
280
+ if (cancellationResult()) return cancellationResult();
281
+ const task = String(taskDescription || '').trim();
282
+ if (!task) throw new Error('Task description is required for coordination');
283
+ const remote = await forwardRemoteOperation('coordinate', task, options);
284
+ if (remote) return remote;
285
+ const mode = options.mode || 'pipeline';
286
+ if (!['pipeline', 'orchestrate', 'council', 'race'].includes(mode)) throw new Error(`Unsupported coordination mode: ${mode}`);
287
+ localExecutionNode(options);
288
+ let poolInfo = await resolvePool(options);
289
+ if (options.model !== undefined) {
290
+ // Council and race seats all run the model, so their pool narrows. A pipeline keeps every harness
291
+ // for its other roles and gives the Implementer role to one that can run the model.
292
+ const filtered = filterPoolByModel(poolInfo, options.model, options.modelValidator || createModelValidator());
293
+ options = { ...options, modelSelection: filtered.selection, modelCompatible: filtered.selection.compatible };
294
+ if (mode === 'council' || mode === 'race') poolInfo = filtered.pool;
387
295
  }
388
-
389
- return {
390
- ok: true,
391
- mode: 'race',
392
- executedLive: false,
393
- task,
394
- contenders,
395
- winner: contenders[0] || null,
396
- reason: 'Planned concurrent race across selected contenders.'
397
- };
296
+ const wall = poolInfo.excluded.find(item => item.failureKind === 'quota');
297
+ const minimum = mode === 'race' || ((mode === 'pipeline' || mode === 'orchestrate') && options.allowSameFamily !== true) ? 2 : 1;
298
+ if (options.execute === true && wall && poolInfo.ready.length < minimum) {
299
+ const blocked = { ok: false, failureKind: 'quota', error: 'Coordination is waiting for included usage.', resetsAt: wall.resetsAt };
300
+ const job = await queueIncludedJob({ agent: wall.harness, cwd: options.cwd || process.cwd(), prompt: task }, blocked,
301
+ { role: 'Coordinate', launchPrevented: true });
302
+ return { ...blocked, mode, executedLive: false, queued: true, queueId: job.id, needsReview: job.needsReview };
303
+ }
304
+ if (mode === 'council') return runCouncil(task, poolInfo, options);
305
+ if (mode === 'race') return runRace(task, poolInfo, options);
306
+ return runPipeline(task, poolInfo, options);
398
307
  }