tr-plugin-meta-harness 0.3.0 → 0.5.27
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.
- package/DESIGN.md +86 -0
- package/README.md +257 -11
- package/capability/BRICK.md +1 -1
- package/capability/index.mjs +154 -13
- package/cli.mjs +426 -41
- package/package.json +15 -3
- package/plugin.json +1457 -119
- package/skills/meta-harness/SKILL.md +63 -25
- package/src/adoption.mjs +102 -0
- package/src/agent-user.mjs +194 -0
- package/src/alerts.mjs +220 -14
- package/src/cascade.mjs +185 -0
- package/src/chat.mjs +80 -0
- package/src/codex-models.mjs +54 -0
- package/src/compat-harness.mjs +117 -0
- package/src/control.mjs +145 -0
- package/src/coordinator.mjs +267 -358
- package/src/dispatch-request.mjs +76 -0
- package/src/dispatch.mjs +119 -0
- package/src/documentation-authority.mjs +57 -0
- package/src/documentation.mjs +120 -32
- package/src/executor.mjs +101 -22
- package/src/gate-adapters/agy.mjs +155 -0
- package/src/gate-adapters/claude.mjs +303 -0
- package/src/gate-adapters/cline.mjs +111 -0
- package/src/gate-adapters/codex.mjs +164 -0
- package/src/gate-adapters/cursor.mjs +164 -0
- package/src/gate-adapters/devin.mjs +116 -0
- package/src/gate-adapters/dsh.mjs +284 -0
- package/src/gate-adapters/grok.mjs +112 -0
- package/src/gate-adapters/hermes.mjs +217 -0
- package/src/gate-adapters/hook-files.mjs +156 -0
- package/src/gate-adapters/index.mjs +131 -0
- package/src/gate-adapters/openclaw-plugin/gate-client.js +205 -0
- package/src/gate-adapters/openclaw-plugin/index.js +25 -0
- package/src/gate-adapters/openclaw-plugin/openclaw.plugin.json +9 -0
- package/src/gate-adapters/openclaw-plugin/package.json +15 -0
- package/src/gate-adapters/openclaw.mjs +288 -0
- package/src/gate-adapters/pi.mjs +146 -0
- package/src/gate.mjs +18 -0
- package/src/harness-updates.mjs +170 -0
- package/src/included-usage.mjs +344 -0
- package/src/jobs.mjs +135 -0
- package/src/json-reply.mjs +22 -0
- package/src/learner.mjs +97 -67
- package/src/maintenance.mjs +18 -0
- package/src/mcp-server.mjs +228 -0
- package/src/model-catalog.mjs +195 -0
- package/src/model-selection.mjs +67 -0
- package/src/paths.mjs +23 -0
- package/src/pool.mjs +69 -0
- package/src/process-manager.mjs +246 -0
- package/src/process-worker.mjs +18 -0
- package/src/reasoning.mjs +231 -0
- package/src/remote-operation.mjs +76 -0
- package/src/review.mjs +241 -0
- package/src/reviews.mjs +25 -0
- package/src/router-benchmark-corpus.mjs +16 -0
- package/src/router-benchmark.mjs +208 -0
- package/src/router.mjs +265 -346
- package/src/runtime.mjs +30 -8
- package/src/session/claude.mjs +358 -0
- package/src/session/codex.mjs +501 -0
- package/src/session/result.mjs +90 -0
- package/src/session/resume.mjs +393 -0
- package/src/session/run.mjs +258 -0
- package/src/session-jobs.mjs +77 -0
- package/src/setup.mjs +6 -3
- package/src/ssss-store.mjs +20 -0
- package/src/telemetry.mjs +267 -0
- package/src/termination.mjs +28 -0
- package/src/threads.mjs +150 -0
- package/src/usage-queue.mjs +137 -0
- package/src/verify-ssss.mjs +102 -0
- package/src/worker.mjs +955 -84
- package/src/worktree.mjs +244 -0
- package/ui/chunks/adapter-docs-freshness.md +16 -0
- package/ui/chunks/chat-handoff.md +26 -0
- package/ui/chunks/fleet-maintenance.md +21 -0
- package/ui/chunks/harness-inventory.md +21 -0
- package/ui/chunks/included-access.md +18 -0
- package/ui/chunks/included-usage-verification.md +15 -0
- package/ui/chunks/independent-review.md +17 -0
- package/ui/chunks/managed-execution.md +20 -0
- package/ui/chunks/official-documentation.md +18 -0
- package/ui/chunks/quota-recovery.md +21 -0
- package/ui/chunks/review-routing-decision.md +16 -0
- package/ui/chunks/route-work.md +18 -0
- package/ui/chunks/routing-evidence.md +18 -0
- package/ui/chunks/run-ledger.md +18 -0
- package/ui/chunks/session-controls.md +16 -0
- package/ui/home.js +198 -0
- package/ui/DESIGN.md +0 -32
- package/ui/card.js +0 -845
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
/** Headless reasoning belongs to Metaharness, including config, readiness and receipts. */
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { brainDir } from './paths.mjs';
|
|
5
|
+
import { getActiveAdapters, inspectAgents } from './worker.mjs';
|
|
6
|
+
import { dispatchTask } from './compat-harness.mjs';
|
|
7
|
+
import { INTERNAL_JOB_MARKER } from './session/run.mjs';
|
|
8
|
+
import { readCodexRateLimits } from './telemetry.mjs';
|
|
9
|
+
import { enforceVelocityCircuitBreaker } from './alerts.mjs';
|
|
10
|
+
import { readIncludedPolicy } from './included-usage.mjs';
|
|
11
|
+
|
|
12
|
+
// One reasoning generation is bounded; the reasoning config may lower or raise it.
|
|
13
|
+
const DEFAULT_REASONING_MAX_TOKENS = 64000;
|
|
14
|
+
// How long a held reasoning caller waits before asking again.
|
|
15
|
+
export const REASONING_HOLD_MS = 30 * 60_000;
|
|
16
|
+
export const REASONING_CONFIG_HINT = 'Set one with: total-recall meta-harness reasoning-config --agent <harness> [--model <model>] [--max-usage-percent <1-100>]';
|
|
17
|
+
|
|
18
|
+
export function reasoningConfigPath(options = {}) {
|
|
19
|
+
return path.join(options.brainDir || brainDir(options.env || process.env), 'config', 'meta-harness', 'reasoning.json');
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function readConfig(file) {
|
|
23
|
+
if (!fs.existsSync(file)) return {};
|
|
24
|
+
let value;
|
|
25
|
+
try { value = JSON.parse(fs.readFileSync(file, 'utf8')); }
|
|
26
|
+
catch (error) { throw new Error(`Invalid reasoning configuration: ${error.message}`); }
|
|
27
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('Reasoning configuration must be an object');
|
|
28
|
+
return value;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function loadRuntimeConfig(_legacyPath, options = {}) {
|
|
32
|
+
const env = options.env || process.env, argv = options.argv || process.argv;
|
|
33
|
+
const root = options.brainDir || brainDir(env);
|
|
34
|
+
const config = readConfig(options.reasoningFile || path.join(root, 'config', 'meta-harness', 'reasoning.json'));
|
|
35
|
+
const brain = readConfig(path.join(root, 'config', 'brain.json'));
|
|
36
|
+
const adapters = getActiveAdapters();
|
|
37
|
+
// Background reasoning runs only where the operator chose. Adapter order is never a default:
|
|
38
|
+
// it once sent every background review to the first adapter's most expensive model.
|
|
39
|
+
let agents = [];
|
|
40
|
+
if (config.agents !== undefined) {
|
|
41
|
+
if (!Array.isArray(config.agents)) throw new Error('Reasoning agents must be an array');
|
|
42
|
+
agents = config.agents.filter(agent => agent.enabled !== false).map((agent, index) => {
|
|
43
|
+
const adapter = adapters.find(item => item.id === agent.name || item.id === agent.id);
|
|
44
|
+
if (!adapter) throw new Error(`Unknown reasoning harness ${agent.name || agent.id}`);
|
|
45
|
+
if (agent.flags !== undefined || (agent.binary && agent.binary !== adapter.binary)) throw new Error('Native flags belong to the adapter registry');
|
|
46
|
+
return { name: adapter.id, binary: adapter.binary, enabled: true, priority: agent.priority ?? index + 1, model: agent.model || null };
|
|
47
|
+
}).sort((a, b) => a.priority - b.priority);
|
|
48
|
+
}
|
|
49
|
+
let preferred = argv.find(value => value.startsWith('--agent='))?.slice(8) || env.TR_CLI_AGENT || config.preferredAgent || brain.preferred_agent;
|
|
50
|
+
if (!preferred) {
|
|
51
|
+
for (const file of [options.instructionsFile, options.surfaceDir && path.join(options.surfaceDir, 'AGENTS.md')].filter(Boolean)) {
|
|
52
|
+
if (!fs.existsSync(file)) continue;
|
|
53
|
+
const text = fs.readFileSync(file, 'utf8');
|
|
54
|
+
preferred = (text.match(/preferred\s+CLI\s+agent\s+is\s+([a-zA-Z0-9_-]+)/i) || text.match(/preferred_cli_agent:\s*([a-zA-Z0-9_-]+)/i))?.[1]?.toLowerCase();
|
|
55
|
+
if (preferred) break;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
if (preferred) {
|
|
59
|
+
let selected = agents.find(agent => agent.name === preferred);
|
|
60
|
+
if (!selected && config.agents !== undefined) throw new Error(`Preferred reasoning harness ${preferred} is not configured`);
|
|
61
|
+
if (!selected) {
|
|
62
|
+
// An explicit preference with no reasoning file is still an operator choice.
|
|
63
|
+
const adapter = adapters.find(item => item.id === preferred);
|
|
64
|
+
if (!adapter) throw new Error(`Unknown reasoning harness ${preferred}`);
|
|
65
|
+
selected = { name: adapter.id, binary: adapter.binary, enabled: true, priority: 0, model: null };
|
|
66
|
+
agents.push(selected);
|
|
67
|
+
}
|
|
68
|
+
selected.priority = 0;
|
|
69
|
+
agents.sort((a, b) => a.priority - b.priority);
|
|
70
|
+
}
|
|
71
|
+
if (env.TR_CLI_MODEL && agents.length) agents[0].model = env.TR_CLI_MODEL;
|
|
72
|
+
const maxTokens = config.maxTokens ?? DEFAULT_REASONING_MAX_TOKENS;
|
|
73
|
+
if (!Number.isSafeInteger(maxTokens) || maxTokens < 1) throw new Error('Reasoning maxTokens must be a positive integer');
|
|
74
|
+
const maxUsagePercent = config.maxUsagePercent ?? null;
|
|
75
|
+
if (maxUsagePercent !== null && (typeof maxUsagePercent !== 'number' || !(maxUsagePercent > 0 && maxUsagePercent <= 100))) {
|
|
76
|
+
throw new Error('Reasoning maxUsagePercent must be a number above 0 and at most 100');
|
|
77
|
+
}
|
|
78
|
+
const timeout = Number(env.TR_CLI_TIMEOUT || config.timeout || 300);
|
|
79
|
+
if (!Number.isFinite(timeout) || timeout <= 0) throw new Error('Reasoning timeout must be positive');
|
|
80
|
+
return { agents, timeout, maxTokens, maxUsagePercent, maxRetries: config.maxRetries ?? 0, embedding: config.embedding || options.embedding,
|
|
81
|
+
allowUnknownAuth: config.allowUnknownAuth === true, preferredAgent: preferred || null };
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Show or change which harness and model run background reasoning (lesson reviews and other
|
|
86
|
+
* internal jobs). `agent` becomes the primary and is enabled; `enable`/`disable` keep an option
|
|
87
|
+
* listed without running it. Models are checked with the model owner before they are saved.
|
|
88
|
+
*/
|
|
89
|
+
export async function reasoningConfig({ agent, model, maxUsagePercent, enable, disable } = {}, options = {}) {
|
|
90
|
+
const env = options.env || process.env;
|
|
91
|
+
const file = reasoningConfigPath(options);
|
|
92
|
+
const raw = readConfig(file);
|
|
93
|
+
const changing = [agent, model, maxUsagePercent, enable, disable].some(value => value !== undefined);
|
|
94
|
+
if (changing) {
|
|
95
|
+
if (env.TR_META_HARNESS_RUN) throw new Error('Only the operator may change the background reasoning configuration.');
|
|
96
|
+
const adapters = getActiveAdapters();
|
|
97
|
+
const known = id => {
|
|
98
|
+
if (!adapters.some(item => item.id === id)) throw new Error(`Unknown reasoning harness ${id}`);
|
|
99
|
+
return id;
|
|
100
|
+
};
|
|
101
|
+
const agents = Array.isArray(raw.agents) ? raw.agents.map(item => ({ ...item })) : [];
|
|
102
|
+
const entry = id => agents.find(item => (item.name || item.id) === id) || (agents.push({ name: id }), agents.at(-1));
|
|
103
|
+
if (agent !== undefined) {
|
|
104
|
+
const primary = entry(known(agent));
|
|
105
|
+
primary.enabled = true;
|
|
106
|
+
agents.splice(agents.indexOf(primary), 1);
|
|
107
|
+
agents.unshift(primary);
|
|
108
|
+
}
|
|
109
|
+
for (const id of [enable].filter(Boolean)) entry(known(id)).enabled = true;
|
|
110
|
+
for (const id of [disable].filter(Boolean)) entry(known(id)).enabled = false;
|
|
111
|
+
if (model !== undefined) {
|
|
112
|
+
const target = agent !== undefined ? agents[0] : agents.find(item => item.enabled !== false);
|
|
113
|
+
if (!target) throw new Error('Choose a harness with --agent before setting a model');
|
|
114
|
+
const check = (options.validateModel || (await import('./model-selection.mjs')).createModelValidator())(target.name, model);
|
|
115
|
+
if (!check.ok) throw new Error(check.reason || `${target.name} cannot run ${model}`);
|
|
116
|
+
target.model = model;
|
|
117
|
+
}
|
|
118
|
+
agents.forEach((item, index) => { item.priority = index + 1; });
|
|
119
|
+
const next = { ...raw, agents };
|
|
120
|
+
if (maxUsagePercent !== undefined) next.maxUsagePercent = Number(maxUsagePercent);
|
|
121
|
+
// Validate the whole file before it replaces the old one.
|
|
122
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
123
|
+
const temp = `${file}.${process.pid}.tmp`;
|
|
124
|
+
fs.writeFileSync(temp, JSON.stringify(next, null, 2) + '\n');
|
|
125
|
+
try {
|
|
126
|
+
loadRuntimeConfig(undefined, { ...options, brainDir: path.dirname(path.dirname(path.dirname(file))), reasoningFile: temp, argv: [] });
|
|
127
|
+
fs.renameSync(temp, file);
|
|
128
|
+
} catch (error) { fs.rmSync(temp, { force: true }); throw error; }
|
|
129
|
+
}
|
|
130
|
+
const saved = readConfig(file);
|
|
131
|
+
const effective = loadRuntimeConfig(undefined, { ...options, argv: [] });
|
|
132
|
+
return { ok: true, path: file, configured: effective.agents.length > 0, config: saved,
|
|
133
|
+
order: effective.agents.map(item => ({ harness: item.name, model: item.model || null })),
|
|
134
|
+
maxUsagePercent: effective.maxUsagePercent, holdMinutes: REASONING_HOLD_MS / 60_000,
|
|
135
|
+
...(effective.agents.length ? {} : { note: `Background reasoning is refused until a harness is configured. ${REASONING_CONFIG_HINT}` }) };
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export async function checkRuntimeHealth(config, { inspect = inspectAgents } = {}) {
|
|
139
|
+
const desired = (config?.agents || loadRuntimeConfig().agents).filter(agent => agent.enabled !== false);
|
|
140
|
+
const report = await inspect({ ids: desired.map(agent => agent.name) });
|
|
141
|
+
const available = desired.flatMap(agent => {
|
|
142
|
+
const observed = report.agents.find(item => item.id === agent.name);
|
|
143
|
+
return observed?.installed && observed.authenticated === true && observed.versionVerified && !observed.blockedBy
|
|
144
|
+
? [{ name: agent.name, binary: agent.binary, priority: agent.priority }] : [];
|
|
145
|
+
});
|
|
146
|
+
return { status: available.length ? 'healthy' : 'degraded', available, primary: available[0]?.name || null,
|
|
147
|
+
...(available.length ? {} : { reason: 'No configured harness has verified login and runtime readiness' }) };
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
export async function callLocalRuntime(prompt, system, config, dependencies = {}) {
|
|
151
|
+
if (typeof prompt !== 'string' || !prompt.trim()) throw new Error('A nonempty reasoning task is required');
|
|
152
|
+
try {
|
|
153
|
+
await (dependencies.enforceBreaker || enforceVelocityCircuitBreaker)({ kind: 'reasoning' });
|
|
154
|
+
} catch (error) {
|
|
155
|
+
if (error?.code !== 'CIRCUIT_BREAKER_TRIPPED') throw error;
|
|
156
|
+
throw Object.assign(new Error(error.message, { cause: error }), {
|
|
157
|
+
code: 'REASONING_DEFERRED', retryAfterMs: REASONING_HOLD_MS,
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
config ||= loadRuntimeConfig();
|
|
161
|
+
const text = `${INTERNAL_JOB_MARKER}\n${system ? `${system}\n\n---\n\n${prompt}` : prompt}`;
|
|
162
|
+
const agents = (config.agents || []).filter(agent => agent.enabled !== false).sort((a, b) => a.priority - b.priority);
|
|
163
|
+
if (!agents.length) throw new Error(`No background reasoning harness is configured. ${REASONING_CONFIG_HINT}`);
|
|
164
|
+
const { resolvePool } = await import('./pool.mjs');
|
|
165
|
+
const pool = await (dependencies.resolvePool || resolvePool)({ allowUnknownAuth: config.allowUnknownAuth === true,
|
|
166
|
+
model: agents.find(agent => agent.name === 'codex')?.model });
|
|
167
|
+
// An operator OpenRouter binding admits a metered harness explicitly; dispatch bills it through that binding.
|
|
168
|
+
const policy = await (dependencies.readPolicy || readIncludedPolicy)();
|
|
169
|
+
const bound = id => Object.hasOwn(policy?.openRouter ?? {}, id);
|
|
170
|
+
const includedPlanOnly = config.includedPlanOnly === true;
|
|
171
|
+
const candidates = agents.filter(agent => includedPlanOnly
|
|
172
|
+
? !bound(agent.name) && pool.ready.some(ready => ready.id === agent.name)
|
|
173
|
+
: pool.ready.some(ready => ready.id === agent.name) || bound(agent.name));
|
|
174
|
+
const failures = [], held = [], delays = [];
|
|
175
|
+
const hold = (message, resetsAt) => {
|
|
176
|
+
held.push(message);
|
|
177
|
+
const reset = Date.parse(resetsAt);
|
|
178
|
+
delays.push(Number.isFinite(reset) && reset > Date.now() ? Math.max(60_000, reset - Date.now()) : REASONING_HOLD_MS);
|
|
179
|
+
};
|
|
180
|
+
const excluded = (pool.excluded || []).filter(item => agents.some(agent => agent.name === item.harness));
|
|
181
|
+
for (const item of excluded) {
|
|
182
|
+
if (item.failureKind === 'quota' && !bound(item.harness)) hold(`${item.harness}: ${item.reason}`, item.resetsAt);
|
|
183
|
+
}
|
|
184
|
+
if (!candidates.length && !held.length) throw new Error(`No configured CLI agent is ready: ${excluded.map(item => `${item.harness}: ${item.reason}`).join('; ') || 'no verified runtime'}`);
|
|
185
|
+
for (const agent of candidates) {
|
|
186
|
+
if (agent.name === 'codex' && config.maxUsagePercent) {
|
|
187
|
+
const limits = (dependencies.readCodexRateLimits || readCodexRateLimits)();
|
|
188
|
+
const windows = [limits?.primary, limits?.secondary].filter(Boolean);
|
|
189
|
+
// No live reading means no measured usage; the Codex wall still stops a run at 100%.
|
|
190
|
+
const used = windows.length ? Math.max(...windows.map(window => window.used_percent)) : null;
|
|
191
|
+
if (used !== null && used >= config.maxUsagePercent) {
|
|
192
|
+
hold(`codex usage is ${used}%, at or above the ${config.maxUsagePercent}% background reasoning threshold`);
|
|
193
|
+
continue;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
const result = await (dependencies.dispatch || dispatchTask)(agent.name, text, {
|
|
197
|
+
cwd: config.cwd || process.cwd(), node: config.node || 'local', timeoutMs: (config.timeout || 300) * 1000,
|
|
198
|
+
model: agent.model || undefined, write: false, role: 'Reasoning', allowUnknownAuth: config.allowUnknownAuth === true,
|
|
199
|
+
internalReasoning: true, includedPlanOnly, maxTurns: 1, maxTokens: config.maxTokens ?? DEFAULT_REASONING_MAX_TOKENS,
|
|
200
|
+
});
|
|
201
|
+
if (result.ok === true || result.success === true) return result.response || '';
|
|
202
|
+
if (result.failureKind === 'quota' || result.failureKind === 'circuit-breaker') {
|
|
203
|
+
hold(`${agent.name}: ${result.error || result.failureKind}`, result.resetsAt);
|
|
204
|
+
continue;
|
|
205
|
+
}
|
|
206
|
+
if (result.queued || result.queueError || result.failureKind === 'billing-policy') {
|
|
207
|
+
const error = new Error(result.queued ? `Included usage exhausted. Queued as ${result.queueId}.` : result.queueError || result.error);
|
|
208
|
+
error.queueId = result.queueId;
|
|
209
|
+
throw error;
|
|
210
|
+
}
|
|
211
|
+
failures.push(`${agent.name}: ${result.error || 'dispatch failed'}`);
|
|
212
|
+
}
|
|
213
|
+
if (held.length && !failures.length) {
|
|
214
|
+
throw Object.assign(new Error(`Background reasoning held: ${held.join('; ')}`), { code: 'REASONING_DEFERRED', retryAfterMs: Math.min(...delays) });
|
|
215
|
+
}
|
|
216
|
+
throw new Error(`All CLI agents failed (${[...held, ...failures].join('; ')})`);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** A caller that forbids paid API use must opt into this separate runtime operation. */
|
|
220
|
+
export function callIncludedPlanRuntime(prompt, system, config, dependencies) {
|
|
221
|
+
return callLocalRuntime(prompt, system, {
|
|
222
|
+
...(config || loadRuntimeConfig()), includedPlanOnly: true, node: 'local', allowUnknownAuth: false,
|
|
223
|
+
}, dependencies);
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
export async function callLocalRuntimeRaw(messages, config, _tools, dependencies) {
|
|
227
|
+
if (!Array.isArray(messages)) throw new Error('Reasoning messages must be an array');
|
|
228
|
+
const system = messages.filter(message => message.role === 'system').map(message => message.content).join('\n');
|
|
229
|
+
const user = messages.filter(message => message.role !== 'system').map(message => message.content).join('\n');
|
|
230
|
+
return { role: 'assistant', content: await callLocalRuntime(user, system, config, dependencies) };
|
|
231
|
+
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/** Forward a complete owning-plugin job through the existing verified mesh executor. */
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { executeOnNode } from './executor.mjs';
|
|
4
|
+
import { isLocalExecutionNode } from './pool.mjs';
|
|
5
|
+
|
|
6
|
+
const BOOLEAN_FLAGS = {
|
|
7
|
+
execute: '--execute', gate: '--gate', jev: '--jev', preferLocal: '--prefer-local', preferFrontier: '--prefer-frontier',
|
|
8
|
+
autoReview: '--auto-review', allowSameFamily: '--allow-same-family', allowUnknownAuth: '--allow-unknown-auth', staged: '--staged',
|
|
9
|
+
};
|
|
10
|
+
const VALUE_FLAGS = {
|
|
11
|
+
mode: '--mode', orchestrator: '--orchestrator', explorer: '--explorer', architect: '--architect', implementer: '--implementer',
|
|
12
|
+
goal: '--goal', maxTurns: '--max-turns', maxBudgetUsd: '--max-budget-usd', maxTokens: '--max-tokens', approvalPolicy: '--approvals', questionTimeoutMs: '--question-timeout-ms', resultSchema: '--result-schema',
|
|
13
|
+
verifier: '--verifier', reviewer: '--reviewer', author: '--author', threadId: '--thread', branch: '--branch', model: '--model',
|
|
14
|
+
};
|
|
15
|
+
const OPERATION_KEYS = {
|
|
16
|
+
route: ['execute', 'gate', 'jev', 'preferLocal', 'preferFrontier', 'allowUnknownAuth', 'model'],
|
|
17
|
+
coordinate: ['execute', 'gate', 'autoReview', 'allowSameFamily', 'allowUnknownAuth', 'mode', 'orchestrator', 'explorer', 'architect', 'implementer', 'verifier', 'reviewer', 'branch', 'model'],
|
|
18
|
+
review: ['staged', 'allowUnknownAuth', 'reviewer', 'author', 'threadId'],
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
export async function forwardRemoteOperation(operation, task, options = {}) {
|
|
22
|
+
if (!options.node || isLocalExecutionNode(options.node)) return null;
|
|
23
|
+
if (!Object.hasOwn(OPERATION_KEYS, operation)) throw new Error('Unsupported remote operation');
|
|
24
|
+
if (typeof options.node !== 'string' || /[\0\r\n]/.test(options.node)) throw new Error('Explicit recorded mesh node required');
|
|
25
|
+
if (typeof options.cwd !== 'string' || !path.isAbsolute(options.cwd) || options.cwd.includes('\0')) throw new Error('Remote execution requires an explicit absolute workspace (--cwd) on the selected node');
|
|
26
|
+
// A job runs several agents, so its budget is the maximum, not one agent's.
|
|
27
|
+
const timeoutMs = options.timeoutMs ?? 3600000;
|
|
28
|
+
if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 3600000) throw new Error('Remote operation timeout must be between 1 ms and one hour');
|
|
29
|
+
|
|
30
|
+
const argv = ['total-recall', 'meta-harness', operation];
|
|
31
|
+
if (operation === 'review') {
|
|
32
|
+
if (options.target) argv.push(String(options.target));
|
|
33
|
+
} else {
|
|
34
|
+
if (typeof task !== 'string' || !task.trim()) throw new Error('Remote operation requires a task description');
|
|
35
|
+
argv.push(task);
|
|
36
|
+
}
|
|
37
|
+
const controls = ['route', 'coordinate'].includes(operation) ? ['goal', 'maxTurns', 'maxBudgetUsd', 'maxTokens', 'approvalPolicy', 'questionTimeoutMs', 'resultSchema'] : [];
|
|
38
|
+
for (const key of [...OPERATION_KEYS[operation], ...controls]) {
|
|
39
|
+
if (BOOLEAN_FLAGS[key]) { if (options[key] === true) argv.push(BOOLEAN_FLAGS[key]); }
|
|
40
|
+
else if (options[key] !== undefined && options[key] !== null) {
|
|
41
|
+
if (['maxTurns', 'maxBudgetUsd', 'maxTokens', 'questionTimeoutMs'].includes(key)) { argv.push(VALUE_FLAGS[key], String(options[key])); continue; }
|
|
42
|
+
if (key === 'resultSchema' && typeof options[key] !== 'string') { argv.push('--result-schema-json', JSON.stringify(options[key])); continue; }
|
|
43
|
+
if (typeof options[key] !== 'string' || !options[key] || /\0/.test(options[key])) throw new Error(`Invalid remote ${key}`);
|
|
44
|
+
argv.push(VALUE_FLAGS[key], options[key]);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
if (operation === 'coordinate' && options.subagents === false) argv.push('--no-subagents');
|
|
48
|
+
if (['route', 'coordinate'].includes(operation) && options.gateOptions?.tier) argv.push('--tier', options.gateOptions.tier);
|
|
49
|
+
// Older peers detach executed plans unless explicitly told to wait.
|
|
50
|
+
if (operation !== 'review' && options.execute === true) argv.push('--wait');
|
|
51
|
+
// Force destination-local execution so a forwarded job cannot recursively forward itself.
|
|
52
|
+
argv.push('--cwd', options.cwd, '--node', 'local', '--json');
|
|
53
|
+
const execution = { node: options.node, workspace: options.cwd, remote: true, operation };
|
|
54
|
+
let transport;
|
|
55
|
+
try {
|
|
56
|
+
transport = await (options.executeOnNodeFn || executeOnNode)(options.node, { operation: 'direct', cwd: options.cwd, argv, timeoutMs });
|
|
57
|
+
} catch (error) {
|
|
58
|
+
return { ok: false, execution, failureKind: 'transport', error: `Remote ${operation} transport failed: ${error.message}. The job may still be running on ${options.node}; check its branches and threads before starting it again.` };
|
|
59
|
+
}
|
|
60
|
+
let payload;
|
|
61
|
+
try {
|
|
62
|
+
payload = JSON.parse(transport.output || '');
|
|
63
|
+
if (!payload || typeof payload !== 'object' || Array.isArray(payload) || typeof payload.ok !== 'boolean' || payload.background === true) throw new Error('Missing operation outcome');
|
|
64
|
+
} catch {
|
|
65
|
+
return { ok: false, execution, failureKind: 'transport', transportExitCode: transport.exitCode ?? null,
|
|
66
|
+
error: transport.error || 'Remote operation returned no valid structured result' };
|
|
67
|
+
}
|
|
68
|
+
const result = { ...payload, ok: transport.ok === true && payload.ok === true, execution, transportExitCode: transport.exitCode ?? null,
|
|
69
|
+
...(!transport.ok && !payload.failureKind ? { failureKind: 'transport' } : {}) };
|
|
70
|
+
if (!result.ok && !result.error) result.error = transport.error || `Remote ${operation} failed`;
|
|
71
|
+
if (result.ok && payload.branch) result.deliverable = { node: options.node, workspace: options.cwd, branch: payload.branch, commit: payload.commit ?? null };
|
|
72
|
+
const threadId = payload.threadId || options.threadId;
|
|
73
|
+
if (threadId) result.threadRef = { node: options.node, workspace: options.cwd, id: threadId };
|
|
74
|
+
if (payload.review) result.review = { ...payload.review, node: options.node, workspace: options.cwd, ...(threadId ? { threadId } : {}) };
|
|
75
|
+
return result;
|
|
76
|
+
}
|
package/src/review.mjs
ADDED
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Metaharness Universal Cross-Model Adversarial Code Review Engine
|
|
3
|
+
*
|
|
4
|
+
* Runs automated code reviews across integrated agent platforms (claude, codex, agy,
|
|
5
|
+
* grok, dsh, hermes, etc.).
|
|
6
|
+
*
|
|
7
|
+
* Golden Rule: The Reviewer MUST belong to a distinct model family from the Author / Implementer
|
|
8
|
+
* to eliminate self-confirmation bias.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { spawnSync } from 'node:child_process';
|
|
12
|
+
import fs from 'node:fs';
|
|
13
|
+
import path from 'node:path';
|
|
14
|
+
import { ADAPTER_CATALOG } from '../capability/index.mjs';
|
|
15
|
+
import { appendThreadTurn, updateThread } from './threads.mjs';
|
|
16
|
+
import { notifyAlert } from './alerts.mjs';
|
|
17
|
+
import { dispatchWithReceipt } from './dispatch.mjs';
|
|
18
|
+
import { resolvePool, localExecutionNode } from './pool.mjs';
|
|
19
|
+
import { lastJsonWith } from './json-reply.mjs';
|
|
20
|
+
import { createWorktree, removeWorktree, commitAll, headCommit } from './worktree.mjs';
|
|
21
|
+
import { forwardRemoteOperation } from './remote-operation.mjs';
|
|
22
|
+
import { recordReview } from './reviews.mjs';
|
|
23
|
+
|
|
24
|
+
const MAX_DIFF = 30000;
|
|
25
|
+
// Generated surfaces say nothing a reviewer can act on, and they crowd out the source.
|
|
26
|
+
const GENERATED = ['.cursorrules', '.cursor', 'openwiki', 'package-lock.json', 'AGENTS.md', 'CLAUDE.md', 'GEMINI.md', 'INSTRUCTIONS.md'].map(item => `:!${item}`);
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Read exactly what was asked for: an explicit target, the staged changes, or by default the
|
|
30
|
+
* branch against the default branch and then the uncommitted changes. An explicitly requested
|
|
31
|
+
* selection that turns out empty stays empty.
|
|
32
|
+
*/
|
|
33
|
+
export function extractGitDiff(options = {}) {
|
|
34
|
+
const cwd = options.cwd || process.cwd();
|
|
35
|
+
const run = args => spawnSync('git', args, { cwd, encoding: 'utf8', timeout: 15000, maxBuffer: 64 * 1024 * 1024 });
|
|
36
|
+
const read = (args, extra = []) => run(['diff', ...(extra.length ? extra : ['--binary']), ...args, '--', '.', ...GENERATED]);
|
|
37
|
+
const ref = value => {
|
|
38
|
+
const result = run(['rev-parse', '--verify', `${value}^{commit}`]);
|
|
39
|
+
if (result.status !== 0) throw new Error(String(result.stderr || 'Invalid review reference').trim());
|
|
40
|
+
return result.stdout.trim();
|
|
41
|
+
};
|
|
42
|
+
const done = (args, diff, target, snapshot) => {
|
|
43
|
+
const stat = read(args, ['--stat']).stdout || '';
|
|
44
|
+
const untracked = snapshot.mode === 'working' ? run(['ls-files', '-o', '--exclude-standard', '-z', '--', '.', ...GENERATED]).stdout || '' : '';
|
|
45
|
+
return { ok: true, diff, target, stat: stat.trim(), untracked: untracked.split('\0').filter(Boolean), snapshot };
|
|
46
|
+
};
|
|
47
|
+
const explicit = options.staged === true ? ['--staged'] : (options.target || options.branch) ? [options.target || options.branch] : null;
|
|
48
|
+
try {
|
|
49
|
+
if (explicit) {
|
|
50
|
+
if (explicit[0] !== '--staged' && explicit[0].startsWith('-')) throw new Error('Review targets must be Git references, not options');
|
|
51
|
+
const result = read(explicit);
|
|
52
|
+
if (result.status !== 0) return { ok: false, error: String(result.stderr || 'git diff failed').trim(), diff: '' };
|
|
53
|
+
let snapshot;
|
|
54
|
+
if (options.staged === true) snapshot = { mode: 'staged', ref: ref('HEAD') };
|
|
55
|
+
else if (explicit[0].includes('..')) snapshot = { mode: 'commit', ref: ref(explicit[0].split(/\.{2,3}/).at(-1) || 'HEAD') };
|
|
56
|
+
else snapshot = { mode: 'working', ref: ref(explicit[0]) };
|
|
57
|
+
return done(explicit, result.stdout.trim(), explicit.join(' '), snapshot);
|
|
58
|
+
}
|
|
59
|
+
const mergeBase = run(['merge-base', getDefaultBranch(cwd), 'HEAD']);
|
|
60
|
+
const base = mergeBase.status === 0 ? mergeBase.stdout.trim() : ref('HEAD');
|
|
61
|
+
const working = read([base]);
|
|
62
|
+
if (working.status !== 0) return { ok: false, error: String(working.stderr || 'git diff failed').trim(), diff: '' };
|
|
63
|
+
return done([base], working.stdout.trim(), 'working tree', { mode: 'working', ref: base });
|
|
64
|
+
} catch (error) {
|
|
65
|
+
return { ok: false, error: error.message, diff: '' };
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function getDefaultBranch(cwd) {
|
|
70
|
+
try {
|
|
71
|
+
const res = spawnSync('git', ['symbolic-ref', 'refs/remotes/origin/HEAD'], { cwd, encoding: 'utf8', timeout: 3000 });
|
|
72
|
+
if (res.status === 0 && res.stdout.includes('/')) {
|
|
73
|
+
return res.stdout.trim();
|
|
74
|
+
}
|
|
75
|
+
} catch {}
|
|
76
|
+
return 'main';
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Pin the selected diff in a disposable commit, so reviewers never read unrelated current files. */
|
|
80
|
+
function reviewSnapshot(cwd, selection) {
|
|
81
|
+
const directory = createWorktree(cwd, { ref: selection.snapshot.ref, prefix: 'meta-harness-review-' });
|
|
82
|
+
try {
|
|
83
|
+
if (selection.snapshot.mode !== 'commit') {
|
|
84
|
+
if (selection.diff) {
|
|
85
|
+
const patch = spawnSync('git', ['apply', '--index', '--binary', '-'], { cwd: directory, input: `${selection.diff}\n`, encoding: 'utf8', timeout: 15000 });
|
|
86
|
+
if (patch.status !== 0) throw new Error(`Could not pin the selected review diff: ${String(patch.stderr || patch.error).trim()}`);
|
|
87
|
+
}
|
|
88
|
+
for (const file of selection.untracked) {
|
|
89
|
+
const source = path.resolve(cwd, file), destination = path.resolve(directory, file);
|
|
90
|
+
if (!source.startsWith(`${path.resolve(cwd)}${path.sep}`) || !destination.startsWith(`${directory}${path.sep}`) || !fs.lstatSync(source).isFile()) throw new Error(`Unsafe untracked review file: ${file}`);
|
|
91
|
+
fs.mkdirSync(path.dirname(destination), { recursive: true });
|
|
92
|
+
fs.copyFileSync(source, destination);
|
|
93
|
+
}
|
|
94
|
+
commitAll(directory, 'meta-harness: pin selected review snapshot');
|
|
95
|
+
}
|
|
96
|
+
return { directory, commit: headCommit(directory) };
|
|
97
|
+
} catch (error) { removeWorktree(cwd, directory); throw error; }
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Assign an adversarial reviewer from an alternative model family
|
|
102
|
+
*/
|
|
103
|
+
export function selectAdversarialReviewer(authorHarness, availablePool = [], options = {}) {
|
|
104
|
+
const authorFamily = ADAPTER_CATALOG[authorHarness]?.family || null;
|
|
105
|
+
|
|
106
|
+
// Filter pool for distinct family
|
|
107
|
+
const distinctFamilyCandidates = availablePool.filter(h => {
|
|
108
|
+
const spec = ADAPTER_CATALOG[h.id] || h;
|
|
109
|
+
return spec.family && spec.family !== authorFamily && h.id !== authorHarness;
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
if (distinctFamilyCandidates.length > 0) {
|
|
113
|
+
// Prefer higher quality frontier reviewers
|
|
114
|
+
distinctFamilyCandidates.sort((a, b) => (b.qualityScore || 8) - (a.qualityScore || 8));
|
|
115
|
+
return distinctFamilyCandidates[0];
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// Nobody independent is available when every remaining harness shares the author's family.
|
|
119
|
+
return null;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Construct structured adversarial review prompt
|
|
124
|
+
*/
|
|
125
|
+
export function buildReviewPrompt(diff, context = {}) {
|
|
126
|
+
const task = context.task ? `Context / Task:\n${context.task}\n\n` : '';
|
|
127
|
+
const branch = context.branch ? `Branch: ${context.branch}\n` : '';
|
|
128
|
+
|
|
129
|
+
return `[ROLE: ADVERSARIAL CODE REVIEWER]
|
|
130
|
+
You are an independent, highly critical senior security and architecture engineer performing an adversarial code review.
|
|
131
|
+
You did NOT write this code. Do not rubber-stamp. Look for vulnerabilities, silent failures, regressions, anti-patterns, and test coverage gaps.
|
|
132
|
+
|
|
133
|
+
${task}${branch}${context.evidence ? `Job evidence (recorded by Metaharness, not by the author):\n${JSON.stringify(context.evidence, null, 2).slice(0, 8000)}\n\n` : ''}${context.stat ? `Files changed:\n${context.stat}\n\n` : ''}${context.untracked?.length ? `New untracked files, not in the diff; read them too:\n${context.untracked.slice(0, 100).join('\n')}\n\n` : ''}${diff.length > MAX_DIFF ? `This diff is cut at ${MAX_DIFF} of ${diff.length} characters. Read the remainder from the repository and say so if you could not.\n` : ''}GIT DIFF TO REVIEW:
|
|
134
|
+
\`\`\`diff
|
|
135
|
+
${diff.slice(0, MAX_DIFF)}
|
|
136
|
+
\`\`\`
|
|
137
|
+
|
|
138
|
+
Judge the diff. Use the job evidence for claims about how the job ran (questions asked, replies, the goal check, the gate). A claim you cannot verify from the diff or the evidence is a "suggestion" marked unverified in its issue text; it is never "critical" or blocking. Mark a finding "critical" only for a defect in the diff itself.
|
|
139
|
+
|
|
140
|
+
Evaluate the diff against these strict criteria:
|
|
141
|
+
1. Security & Blast Radius (privilege escalation, token leakage, unhandled exceptions)
|
|
142
|
+
2. Invariant & Rule Adherence (does it break existing contracts or introduce silent side effects?)
|
|
143
|
+
3. Determinism & Test Coverage (are edge cases covered by automated tests?)
|
|
144
|
+
4. Architecture & Code Hygiene (readability, dead code, performance pitfalls)
|
|
145
|
+
|
|
146
|
+
Output your review in the following exact JSON format:
|
|
147
|
+
{
|
|
148
|
+
"verdict": "APPROVE" | "REQUEST_CHANGES" | "NEEDS_DISCUSSION",
|
|
149
|
+
"riskScore": <1-10, where 1 is trivial/clean and 10 is critical vulnerability>,
|
|
150
|
+
"summary": "<Concise 2-3 sentence executive summary>",
|
|
151
|
+
"findings": [
|
|
152
|
+
{
|
|
153
|
+
"severity": "critical" | "warning" | "suggestion",
|
|
154
|
+
"file": "<filename>",
|
|
155
|
+
"line": "<line number or approximate>",
|
|
156
|
+
"issue": "<concise description>",
|
|
157
|
+
"suggestedFix": "<concrete recommendation>"
|
|
158
|
+
}
|
|
159
|
+
],
|
|
160
|
+
"invariantsChecked": ["<list of rules or invariants verified>"]
|
|
161
|
+
}`;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** Only a stated verdict counts. Anything else needs a human, and says so. */
|
|
165
|
+
export function parseReviewVerdict(response) {
|
|
166
|
+
const text = String(response || '').trim();
|
|
167
|
+
const parsed = lastJsonWith(text, 'verdict');
|
|
168
|
+
if (parsed && ['APPROVE', 'REQUEST_CHANGES', 'NEEDS_DISCUSSION'].includes(parsed.verdict)) return { ...parsed, parsed: true, findings: Array.isArray(parsed.findings) ? parsed.findings : [] };
|
|
169
|
+
return { verdict: 'NEEDS_DISCUSSION', parsed: false, riskScore: null, summary: text.slice(0, 300) || 'The reviewer returned nothing readable.', findings: [] };
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
export function reviewBlocksPush(result) {
|
|
173
|
+
if (result?.ok !== true) return true;
|
|
174
|
+
if (result.verdict === 'NO_DIFF') return false;
|
|
175
|
+
const review = result.review;
|
|
176
|
+
// R45.8: only blocking findings stop the push; other findings go to the job result.
|
|
177
|
+
// An unreadable review cannot clear a push, so it blocks.
|
|
178
|
+
return !review || review.parsed === false ||
|
|
179
|
+
review.findings?.some(f => f.blocking === true || ['blocking', 'critical'].includes(f.severity)) === true;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
export async function executeCodeReview(options = {}) {
|
|
183
|
+
const remote = await forwardRemoteOperation('review', null, options);
|
|
184
|
+
if (remote) return remote;
|
|
185
|
+
localExecutionNode(options);
|
|
186
|
+
const selection = { workspace: options.cwd || process.cwd(), target: options.target || (options.staged ? '--staged' : 'working tree'), reviewer: options.reviewer || null };
|
|
187
|
+
let result;
|
|
188
|
+
try { result = await executeLocalReview(options, selection); }
|
|
189
|
+
catch (error) {
|
|
190
|
+
// Preserve the existing CLI error contract, but retain failed attempts too.
|
|
191
|
+
try { recordReview({ ok: false, error: error.message }, selection); }
|
|
192
|
+
catch (storeError) { throw new Error(`${error.message}; review store failed: ${storeError.message}`); }
|
|
193
|
+
throw error;
|
|
194
|
+
}
|
|
195
|
+
try { return { ...result, reviewId: recordReview(result, selection).id }; }
|
|
196
|
+
catch (error) { return { ...result, ok: false, reviewStoreError: error.message }; }
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
async function executeLocalReview(options, selection) {
|
|
200
|
+
const cwd = options.cwd || process.cwd();
|
|
201
|
+
const author = options.author || null;
|
|
202
|
+
const diffResult = extractGitDiff({ cwd, target: options.target, staged: options.staged });
|
|
203
|
+
if (!diffResult.ok) throw new Error(`Failed to read the diff: ${diffResult.error}`);
|
|
204
|
+
Object.assign(selection, { diff: diffResult.diff, untracked: diffResult.untracked, target: diffResult.target, commit: headCommit(cwd) });
|
|
205
|
+
if (!diffResult.diff && !diffResult.untracked?.length) return { ok: true, verdict: 'NO_DIFF', target: diffResult.target, summary: `Nothing to review for ${diffResult.target}.` };
|
|
206
|
+
|
|
207
|
+
const { ready, excluded } = await resolvePool(options);
|
|
208
|
+
const reviewer = options.reviewer ? ready.find(h => h.id === options.reviewer) : selectAdversarialReviewer(author, ready);
|
|
209
|
+
if (!reviewer) throw new Error(`No independent reviewer can take work right now: ${excluded.map(e => `${e.harness} (${e.reason})`).join(', ') || 'no other harness available'}`);
|
|
210
|
+
|
|
211
|
+
const authorFamily = ADAPTER_CATALOG[author]?.family || null;
|
|
212
|
+
const reviewerFamily = ADAPTER_CATALOG[reviewer.id]?.family || reviewer.family || null;
|
|
213
|
+
if (author && (reviewer.id === author || (authorFamily && authorFamily === reviewerFamily))) throw new Error(`${reviewer.id} shares a model family with the author ${author}, so it cannot review this independently`);
|
|
214
|
+
const independence = author ? 'verified' : 'unverified: the author was not named';
|
|
215
|
+
selection.reviewer = reviewer.id;
|
|
216
|
+
const truncated = diffResult.diff.length > MAX_DIFF;
|
|
217
|
+
const snapshot = reviewSnapshot(cwd, diffResult);
|
|
218
|
+
selection.commit = snapshot.commit;
|
|
219
|
+
let result;
|
|
220
|
+
try { result = await dispatchWithReceipt({
|
|
221
|
+
agent: reviewer.id, node: 'local', cwd: snapshot.directory, contextCwd: cwd, contextTask: options.task || `Review the code changes in ${diffResult.target}`,
|
|
222
|
+
prompt: buildReviewPrompt(diffResult.diff, { task: options.task, evidence: options.evidence, branch: options.branch || diffResult.target, stat: diffResult.stat, untracked: diffResult.untracked }),
|
|
223
|
+
permissions: { read: true, write: false }, allowUnknownAuth: options.allowUnknownAuth === true,
|
|
224
|
+
...(reviewer.id === 'codex' ? { reviewTarget: { type: 'custom', instructions: buildReviewPrompt(diffResult.diff, { task: options.task, evidence: options.evidence, branch: diffResult.target }) } } : {}),
|
|
225
|
+
}, { dispatchFn: options.dispatchFn, role: 'Reviewer' }); }
|
|
226
|
+
finally { removeWorktree(cwd, snapshot.directory); }
|
|
227
|
+
if (!result.ok) return { ok: false, target: diffResult.target, reviewer: reviewer.id, error: result.error, failureKind: result.failureKind, excluded };
|
|
228
|
+
|
|
229
|
+
const review = { ...parseReviewVerdict(result.response), reviewer: reviewer.id, reviewerName: reviewer.name || reviewer.id, author, target: diffResult.target, snapshotCommit: snapshot.commit, truncated, independence, node: 'local', workspace: cwd, ...(options.threadId ? { threadId: options.threadId } : {}), timestamp: new Date().toISOString() };
|
|
230
|
+
let threadError;
|
|
231
|
+
if (options.threadId) {
|
|
232
|
+
try {
|
|
233
|
+
appendThreadTurn(options.threadId, { role: 'reviewer', agent: reviewer.id, content: `[Code review by ${review.reviewerName}]\nVerdict: ${review.verdict}\nRisk: ${review.riskScore ?? 'not stated'}/10\n${review.summary || ''}` });
|
|
234
|
+
updateThread(options.threadId, { review, status: review.verdict === 'APPROVE' ? 'approved' : 'review_pending' });
|
|
235
|
+
} catch (error) { threadError = error.message; }
|
|
236
|
+
}
|
|
237
|
+
if (review.verdict === 'REQUEST_CHANGES' || review.riskScore >= 7) {
|
|
238
|
+
await notifyAlert({ title: `Code review: changes requested by ${review.reviewerName}`, message: `Risk ${review.riskScore ?? 'not stated'}/10 on ${diffResult.target}: ${String(review.summary || '').slice(0, 120)}`, severity: 'warning' });
|
|
239
|
+
}
|
|
240
|
+
return { ok: true, review, ...(threadError ? { threadError } : {}) };
|
|
241
|
+
}
|
package/src/reviews.mjs
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/** Review results are append-only SSSS records, independent of thread lifetime. */
|
|
2
|
+
import crypto from 'node:crypto';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { threadsFile } from './paths.mjs';
|
|
5
|
+
import { PluginStateStore } from './ssss-store.mjs';
|
|
6
|
+
|
|
7
|
+
const store = () => new PluginStateStore(path.join(path.dirname(threadsFile()), 'meta-harness-reviews.jsonl'), 'meta-harness');
|
|
8
|
+
const dispositions = { APPROVE: 'approved', REQUEST_CHANGES: 'changes_requested', NEEDS_DISCUSSION: 'needs_discussion', NO_DIFF: 'no_diff', FAILED: 'failed' };
|
|
9
|
+
|
|
10
|
+
export function readReviews() { return store().read([]); }
|
|
11
|
+
export function recordReview(result, selection = {}) {
|
|
12
|
+
const review = result.review;
|
|
13
|
+
const verdict = review?.verdict || result.verdict || 'FAILED';
|
|
14
|
+
if (!dispositions[verdict]) throw new Error('Invalid review verdict');
|
|
15
|
+
const entry = {
|
|
16
|
+
id: `review-${crypto.randomUUID()}`, timestamp: new Date().toISOString(),
|
|
17
|
+
workspace: selection.workspace, target: review?.target || result.target || selection.target || null,
|
|
18
|
+
commit: review?.snapshotCommit || selection.commit || null,
|
|
19
|
+
diff: selection.diff || '', untracked: selection.untracked || [],
|
|
20
|
+
reviewer: review?.reviewer || result.reviewer || selection.reviewer || null,
|
|
21
|
+
verdict, disposition: dispositions[verdict], result,
|
|
22
|
+
};
|
|
23
|
+
store().append(entry);
|
|
24
|
+
return entry;
|
|
25
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/** Human-authored labels. Never derived from a router response. */
|
|
2
|
+
export const ROUTER_CORPUS = {
|
|
3
|
+
schemaVersion: 1, id: 'metaharness-router-efficiency', version: '1.1.0',
|
|
4
|
+
cases: [
|
|
5
|
+
{ id: 'credentials', intent: 'Inspect encrypted auth credentials', groups: [['plugin:auth:status', 'plugin:auth:secret']], kind: 'ambiguous' },
|
|
6
|
+
{ id: 'models', intent: 'List live AI models with their pricing', groups: [['plugin:ai-models:models']], kind: 'semantic' },
|
|
7
|
+
{ id: 'quota', intent: 'Show coding harness quotas and readiness', groups: [['plugin:meta-harness:quota']], kind: 'semantic' },
|
|
8
|
+
{ id: 'catalog', intent: 'Discover all installed plugin operations', groups: [['core:plugin', 'plugin:composable-cli:library']], kind: 'ambiguous' },
|
|
9
|
+
{ id: 'two-steps', intent: 'List live AI model prices then inspect coding harness quota', groups: [['plugin:ai-models:models'], ['plugin:meta-harness:quota']], kind: 'multi-step' },
|
|
10
|
+
{ id: 'absent', intent: 'Teleport a physical bicycle to Mars', groups: [], kind: 'unavailable' },
|
|
11
|
+
{ id: 'underspecified', intent: 'Do the thing', groups: [], kind: 'ambiguous' },
|
|
12
|
+
{ id: 'frontier', layer: 'harness', intent: 'Audit authentication security architecture across all modules', expected: ['codex', 'claude'], scenario: 'ready', kind: 'frontier' },
|
|
13
|
+
{ id: 'inactive', layer: 'harness', intent: 'Audit authentication security architecture', expected: [], scenario: 'inactive', kind: 'inactive' },
|
|
14
|
+
{ id: 'quota-wall', layer: 'harness', intent: 'Audit authentication security architecture', expected: [], scenario: 'quota', kind: 'quota' },
|
|
15
|
+
].map(c => ({ layer: 'capability', surface: 'cli', provenance: 'independent:operator-task-and-declared-contracts', ...c })),
|
|
16
|
+
};
|