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.
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 +117 -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
package/cli.mjs CHANGED
@@ -1,51 +1,334 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
+ import { spawn } from 'node:child_process';
3
4
  import { pathToFileURL } from 'node:url';
4
- import { ADAPTERS, inspectAgents, getActiveAdapters, getCustomAdaptersDirs, loadCustomAdapters } from './src/worker.mjs';
5
- import { inspectNode, listTargets, executeCommand, executeOnNode } from './src/executor.mjs';
6
- import { DOC_SOURCES, documentationStatus, refreshDocumentation, ensureDocumentation, maintainDocumentation, readDocumentation, searchDocumentation } from './src/documentation.mjs';
7
- import { manageRuntime } from './src/runtime.mjs';
5
+ import { configDir } from './src/paths.mjs';
6
+ import { inspectAgents, getActiveAdapters, getCustomAdaptersDirs, loadCustomAdapters, validateCustomAdapter, adapterPath } from './src/worker.mjs';
7
+ import { inspectNode, listTargets, executeCommand, executeOnNode, hostModule, readPeerMetaHarness } from './src/executor.mjs';
8
+ import { DOC_SOURCES } from './src/documentation.mjs';
9
+ import { runDocumentationCommand } from './src/documentation-authority.mjs';
10
+ import { manageRuntime, validateRuntimeOperation } from './src/runtime.mjs';
11
+ import { validateDispatchRequest } from './src/dispatch-request.mjs';
8
12
  import { setupIntegrations } from './src/setup.mjs';
13
+ import { maintainIntegrations } from './src/maintenance.mjs';
9
14
  import { inspectUpstreamFleet, getAgentChangelog } from './src/tracker.mjs';
10
15
  import { inspectQuotas, getBenchmarks, routeTask } from './src/router.mjs';
11
16
  import { coordinateTask } from './src/coordinator.mjs';
12
- import { recordRunReceipt, learnFromHistory } from './src/learner.mjs';
17
+ import { executeRoutedTask } from './src/cascade.mjs';
18
+ import { dispatchWithReceipt } from './src/dispatch.mjs';
19
+ import { resolvePool } from './src/pool.mjs';
20
+ import { checkAlerts, notifyAlert, priorityCacheProjects } from './src/alerts.mjs';
21
+ import { learnFromHistory, voidReceipts } from './src/learner.mjs';
22
+ import { decomposeTask } from './capability/index.mjs';
23
+ import { listThreads, getThread, createThread, updateThread, closeThread, deleteThread, cleanupFixtureThreads } from './src/threads.mjs';
24
+ import { readReviews } from './src/reviews.mjs';
25
+ import { executeCodeReview } from './src/review.mjs';
26
+ import { stopOnTermination, finishCancellation } from './src/termination.mjs';
27
+ import { cancellationResult } from './src/worker.mjs';
28
+ import { startJob, newJobId, cancelJob, resolveJob } from './src/jobs.mjs';
29
+ import { appendCommand, waitingRequests } from './src/control.mjs';
30
+ import { sessionOptions } from './src/session/run.mjs';
31
+ import { continueJob } from './src/session-jobs.mjs';
13
32
 
14
- export async function run(argv = []) {
33
+ import { chatTarget, setChatDefault } from './src/chat.mjs';
34
+
35
+ const VALUE_FLAGS = ['--result-schema-json', '--goal', '--max-turns', '--max-budget-usd', '--max-tokens', '--result-schema', '--at', '--node', '--mode', '--orchestrator', '--branch', '--reviewer', '--thread', '--status', '--platform', '--agent', '--url', '--query', '--tier', '--threshold', '--author', '--explorer', '--architect', '--implementer', '--verifier', '--title', '--summary', '--cwd', '--tools', '--setting-sources', '--model', '--name', '--tail', '--timeout-ms', '--void', '--reason', '--approvals', '--question-timeout-ms', '--brains'];
36
+ VALUE_FLAGS.push('--k', '--repeats', '--catalog-samples', '--corpus', '--baseline', '--min-recall', '--min-mrr', '--max-p95-ms', '--max-recall-drop', '--core-root');
37
+ VALUE_FLAGS.push('--enable', '--disable', '--max-usage-percent');
38
+ const BOOLEAN_VALUES = ['true', 'false'];
39
+
40
+ /** A boolean flag is on when present, unless an explicit `false` follows it (`--background false`). */
41
+ export function flagOn(args, name) {
42
+ const index = args.indexOf(name);
43
+ return index >= 0 && args[index + 1] !== 'false';
44
+ }
45
+
46
+ /** Removes a boolean flag and its optional explicit value. */
47
+ export function withoutFlag(args, name) {
48
+ return args.filter((arg, index) => arg !== name && !(BOOLEAN_VALUES.includes(arg) && args[index - 1] === name));
49
+ }
50
+
51
+ export function parseArguments(args) {
52
+ const positional = [];
53
+ for (let index = 1; index < args.length; index += 1) {
54
+ if (VALUE_FLAGS.includes(args[index])) { index += 1; continue; }
55
+ if (args[index].startsWith('--')) {
56
+ // A boolean flag may carry an explicit true/false; it is the flag's value, never a positional.
57
+ if (BOOLEAN_VALUES.includes(args[index + 1])) index += 1;
58
+ continue;
59
+ }
60
+ positional.push(args[index]);
61
+ }
62
+ const value = name => {
63
+ const index = args.indexOf(name);
64
+ if (index < 0) return undefined;
65
+ if (!args[index + 1] || args[index + 1].startsWith('--')) throw new Error(`${name} requires a value`);
66
+ return args[index + 1];
67
+ };
68
+ return { positional, value, has: name => flagOn(args, name) };
69
+ }
70
+
71
+ const TASK_OPERATIONS = ['dispatch', 'fork', 'resume'];
72
+ const PLAN_OPERATIONS = ['route', 'coordinate', 'orchestrate'];
73
+
74
+ function taskMode(args) {
75
+ const [operation] = args;
76
+ const executePlan = PLAN_OPERATIONS.includes(operation) && args.includes('--execute');
77
+ const executes = TASK_OPERATIONS.includes(operation) || executePlan;
78
+ return { executes, detached: executes && flagOn(args, '--background') };
79
+ }
80
+
81
+ export async function run(argv = [], { backgroundJobId } = {}) {
82
+ // MCP owns stdin/stdout for its whole lifetime. The CLI result wrapper must stay out of that stream.
83
+ if (argv[3] === 'mcp' && !argv.includes('--help') && !argv.includes('-h')) {
84
+ try { await runOperation(argv); }
85
+ catch (error) { console.error(`Metaharness MCP: ${error.message}`); process.exitCode = 1; }
86
+ return;
87
+ }
88
+ stopOnTermination();
89
+ let job, result;
90
+ const previousJob = process.env.TR_METAHARNESS_JOB;
91
+ try {
92
+ const args = argv.slice(3), operation = args[0];
93
+ const { executes, detached } = taskMode(args);
94
+ if (executes && !detached && !args.includes('--help') && !args.includes('-h')) {
95
+ job = startJob(operation, backgroundJobId ? { id: backgroundJobId } : {});
96
+ process.env.TR_METAHARNESS_JOB = job.job;
97
+ }
98
+ result = await runOperation(argv, { background: Boolean(backgroundJobId) });
99
+ }
100
+ catch (error) {
101
+ const message = String(error?.message || error);
102
+ result = { ok: false, error: message };
103
+ if (!argv.includes('--json')) console.error(`meta-harness: ${message}`);
104
+ process.exitCode = 1;
105
+ }
106
+ result = finishCancellation(result);
107
+ if (result !== undefined) {
108
+ if (job) {
109
+ if (result.execution?.remote && result.job) result.execution = { ...result.execution, remoteJob: result.job };
110
+ result = { ...result, job: job.job };
111
+ }
112
+ job?.finish(result);
113
+ if (!backgroundJobId) console.log(JSON.stringify(result));
114
+ }
115
+ if (previousJob === undefined) delete process.env.TR_METAHARNESS_JOB;
116
+ else process.env.TR_METAHARNESS_JOB = previousJob;
117
+ }
118
+
119
+ /** Explicitly detached jobs report through the job log and thread. */
120
+ async function detachRun(argv) {
121
+ const directory = path.join(configDir(), 'jobs');
122
+ fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
123
+ const id = newJobId();
124
+ const log = path.join(directory, `${id}.log`);
125
+ const output = fs.openSync(log, 'a', 0o600);
126
+ const entry = new URL('./cli.mjs', import.meta.url).href;
127
+ const input = argv[3] === 'dispatch' ? fs.readFileSync(0, 'utf8') : null;
128
+ const child = spawn(process.execPath, ['--input-type=module', '-e', `import(${JSON.stringify(entry)}).then(m=>m.run(${JSON.stringify([...withoutFlag(argv, '--background'),...(argv.includes('--execute') && !argv.includes('--wait') ? ['--wait'] : [])])}, {backgroundJobId:${JSON.stringify(id)}}))`], { cwd: process.cwd(), detached: true, stdio: [input === null ? 'ignore' : 'pipe', output, output], env: process.env });
129
+ if (input !== null) { child.stdin.on('error', () => {}); child.stdin.end(input); }
130
+ try {
131
+ await new Promise((resolve, reject) => { child.once('spawn', resolve); child.once('error', reject); });
132
+ const deadline = Date.now() + 10_000;
133
+ while (!fs.statSync(log).size) {
134
+ if (child.exitCode !== null || Date.now() > deadline) {
135
+ child.kill('SIGTERM');
136
+ throw new Error(`The background job did not record its PID. Log: ${log}`);
137
+ }
138
+ await new Promise(resolve => setTimeout(resolve, 20));
139
+ }
140
+ child.unref();
141
+ } finally { fs.closeSync(output); }
142
+ return { ok: true, background: true, job: id, pid: child.pid, log, follow: `The final JSON result is written to ${log}; a pipeline also records a thread.` };
143
+ }
144
+
145
+ async function runOperation(argv, { background = false } = {}) {
15
146
  const args = argv.slice(3); const operation = args[0] || 'status';
147
+ const { positional, value, has } = parseArguments(args);
148
+ const remoteTimeout = () => {
149
+ const raw = value('--timeout-ms');
150
+ if (raw === undefined) return {};
151
+ const timeoutMs = Number(raw);
152
+ if (!Number.isInteger(timeoutMs)) throw new Error('--timeout-ms must be a whole number of milliseconds');
153
+ return { timeoutMs };
154
+ };
16
155
  // Help anywhere in the arguments prints usage; it must never run an operation.
17
156
  if (operation === 'help' || args.some(arg => arg === '--help' || arg === '-h')) {
18
157
  const manifest=JSON.parse(fs.readFileSync(new URL('./plugin.json',import.meta.url),'utf8'));
19
- console.log('Usage: total-recall cli-agents <operation> [options]\nEvery agent receives Total Recall bootstrap before dispatch. Runtime syntax: runtime <agent> <native-command...> [--node ID].\n');
20
- for(const command of manifest.cli.subcommands)console.log(` ${command.name} ${(command.args || []).map(arg=>arg.flag?`${arg.flag} <${arg.name}>`:`<${arg.name}>`).join(' ')} — ${command.description}`);
158
+ console.log('Usage: total-recall meta-harness <operation> [options] (alias: cli-agents)\nEvery agent receives Total Recall bootstrap before dispatch. Runtime syntax: runtime <agent> <maintenance-command...> [--node ID].\n');
159
+ for(const command of manifest.cli.subcommands)console.log(` ${command.name} ${(command.args || []).map(arg=>arg.flag?(arg.type==='boolean'?`[${arg.flag}]`:`${arg.flag} <${arg.name}>`):`<${arg.name}>`).join(' ')} — ${command.description}`);
21
160
  return;
22
161
  }
162
+ if (taskMode(args).detached) return detachRun(argv);
163
+ const controls = () => sessionOptions({ cwd: value('--cwd') || process.cwd(),
164
+ ...(value('--result-schema-json') !== undefined ? { resultSchema: JSON.parse(value('--result-schema-json')) } : {}),
165
+ ...Object.fromEntries([['goal', '--goal'], ['maxTurns', '--max-turns'], ['maxBudgetUsd', '--max-budget-usd'], ['maxTokens', '--max-tokens'],
166
+ ['resultSchema', '--result-schema'], ['approvalPolicy', '--approvals'], ['questionTimeoutMs', '--question-timeout-ms']]
167
+ .filter(([, flag]) => value(flag) !== undefined).map(([key, flag]) => [key, ['maxTurns', 'maxBudgetUsd', 'maxTokens', 'questionTimeoutMs'].includes(key) ? Number(value(flag)) : value(flag)])) });
168
+ const modelOption = () => (value('--model') === undefined ? {} : { model: value('--model') });
23
169
  let result;
24
- if (operation === 'status') result = {...await inspectAgents(),documentation:documentationStatus()};
170
+ if (operation === 'router-benchmark') {
171
+ const allowed = new Set(['--json', '--save', '--allow-catalog-change', '--core-root', ...['--k', '--repeats', '--catalog-samples', '--corpus', '--baseline', '--min-recall', '--min-mrr', '--max-p95-ms', '--max-recall-drop', '--cwd']]);
172
+ for (const arg of args.slice(1)) if (arg.startsWith('--') && !allowed.has(arg)) throw new Error(`Unsupported router-benchmark flag: ${arg}`);
173
+ if (positional.length) throw new Error('router-benchmark takes flags only');
174
+ const { runRouterBenchmark } = await import('./src/router-benchmark.mjs');
175
+ const numeric = Object.fromEntries([['k', '--k'], ['repeats', '--repeats'], ['catalogSamples', '--catalog-samples'], ['minRecall', '--min-recall'], ['minMrr', '--min-mrr'], ['maxP95Ms', '--max-p95-ms'], ['maxRecallDrop', '--max-recall-drop']].filter(([, flag]) => value(flag) !== undefined).map(([key, flag]) => [key, Number(value(flag))]));
176
+ const json = flag => value(flag) === undefined ? undefined : JSON.parse(fs.readFileSync(value(flag), 'utf8'));
177
+ result = await runRouterBenchmark({ ...numeric, coreRoot: value('--core-root'), allowCatalogChange: has('--allow-catalog-change'), corpus: json('--corpus'), baseline: json('--baseline'), projectRoot: value('--cwd') || process.cwd(), save: has('--save') });
178
+ if (!result.ok) process.exitCode = 1;
179
+ }
180
+ else if (operation === 'status') result = {
181
+ ...await inspectNode(value('--node') || 'local'),
182
+ documentation: await runDocumentationCommand('docs-status').catch(error => ({ ok: false, error: error.message })),
183
+ };
25
184
  else if (operation === 'catalog') result = { adapters: getActiveAdapters(), permissions: ['read', 'write', 'send', 'destructive'] };
185
+ else if (operation === 'chat-target') result = chatTarget(value('--brains'));
186
+ else if (operation === 'chat-default') result = setChatDefault(positional[0], value('--url'));
187
+ else if (operation === 'reasoning-config') {
188
+ const allowed = new Set(['--json', '--agent', '--model', '--max-usage-percent', '--enable', '--disable']);
189
+ for (const arg of args.slice(1)) if (arg.startsWith('--') && !allowed.has(arg)) throw new Error(`Unsupported reasoning-config flag: ${arg}`);
190
+ if (positional.length) throw new Error('reasoning-config takes flags only');
191
+ const { reasoningConfig } = await import('./src/reasoning.mjs');
192
+ const percent = value('--max-usage-percent');
193
+ result = await reasoningConfig({ agent: value('--agent'), model: value('--model'), enable: value('--enable'), disable: value('--disable'),
194
+ maxUsagePercent: percent === undefined ? undefined : Number(percent) });
195
+ }
26
196
  else if (operation === 'nodes') result = await listTargets();
27
- else if (operation === 'quota') {
28
- const index = args.indexOf('--node');
29
- result = await inspectQuotas({ node: index >= 0 ? args[index + 1] : 'local' });
197
+ else if (operation === 'adoption') {
198
+ const node = value('--node');
199
+ if (node && has('--all')) throw new Error('Choose either --node or --all');
200
+ const { inspectLocalAdoption, inspectFleetAdoption } = await import('./src/adoption.mjs');
201
+ result = has('--all') || (node && node !== 'local') ? await inspectFleetAdoption({ node }) : await inspectLocalAdoption();
202
+ if (!result.ok) process.exitCode = 1;
203
+ }
204
+ else if (operation === 'quota') result = await inspectQuotas({ node: value('--node') || 'local' });
205
+ else if (operation === 'openrouter-bind') {
206
+ const { bindOpenRouter } = await import('./src/included-usage.mjs');
207
+ result = await bindOpenRouter(positional[0], positional[1], value('--model'));
208
+ }
209
+ else if (['included-status', 'included-enforce', 'included-bind-claude', 'included-bind-claude-plan', 'included-bind-claude-token', 'included-bind-agy'].includes(operation)) {
210
+ const usage = await import('./src/included-usage.mjs');
211
+ if (operation === 'included-status') result = await usage.includedUsageStatus({ probe: has('--probe') });
212
+ else if (operation === 'included-bind-agy') result = await usage.bindAgyPlan();
213
+ else if (operation === 'included-enforce') result = await usage.enforceIncludedUsage();
214
+ else if (operation === 'included-bind-claude-token') result = await usage.bindClaudeToken({ keyName: value('--key') || 'CLAUDE_CODE_OAUTH_TOKEN' });
215
+ else {
216
+ if (!has('--stdin')) throw new Error('Pass verified Claude billing evidence as JSON on stdin.');
217
+ const input = fs.readFileSync(0, 'utf8');
218
+ if (Buffer.byteLength(input) > 4096) throw new Error('Claude billing evidence is too large.');
219
+ const evidence = JSON.parse(input);
220
+ result = await (operation === 'included-bind-claude-plan' ? usage.bindClaudeMaxPlan : usage.bindClaudeIncludedKey)(evidence);
221
+ }
222
+ }
223
+ else if (operation === 'agent-user') {
224
+ const users = await import('./src/agent-user.mjs');
225
+ if (has('--clear')) result = await users.writeAgentUser(null);
226
+ else if (positional[0]) {
227
+ if (users.agentUserRequired()) users.resolveAgentAccount(positional[0]);
228
+ result = await users.writeAgentUser(positional[0]);
229
+ }
230
+ else result = { user: await users.readAgentUser(), required: users.agentUserRequired() };
30
231
  }
31
- else if (operation === 'benchmarks') result = getBenchmarks();
232
+ else if (['usage-queue', 'usage-retry', 'usage-cancel', 'usage-reconcile'].includes(operation)) {
233
+ const queue = await import('./src/usage-queue.mjs');
234
+ if (operation === 'usage-queue') result = { ok: true, jobs: await queue.listIncludedJobs() };
235
+ else if (operation === 'usage-reconcile') result = await queue.archiveUnreplayableReasoning({ apply: has('--apply') });
236
+ else if (!positional[0]) throw new Error('Choose a queued job ID.');
237
+ else if (operation === 'usage-cancel') result = { ok: true, job: await queue.cancelIncludedJob(positional[0]) };
238
+ else result = await queue.retryIncludedJob(positional[0]);
239
+ if (!result.ok) process.exitCode = 1;
240
+ }
241
+ else if (operation === 'benchmarks') result = await getBenchmarks();
32
242
  else if (operation === 'route') {
33
- const includeUninstalled = args.includes('--include-uninstalled');
34
- const preferLocal = args.includes('--prefer-local');
35
- const preferFrontier = args.includes('--prefer-frontier');
36
- const task = args.slice(1).filter(a => !a.startsWith('--')).join(' ');
243
+ const task = positional.join(' ');
37
244
  if (!task) throw new Error('route requires a task description');
38
- result = await routeTask(task, { includeUninstalled, preferLocal, preferFrontier });
245
+ const options = { ...controls(), jev: has('--jev'), preferLocal: has('--prefer-local'), preferFrontier: has('--prefer-frontier'), node: value('--node'), cwd: value('--cwd'), allowUnknownAuth: has('--allow-unknown-auth'), ...modelOption(), ...remoteTimeout() };
246
+ const agent = value('--agent');
247
+ if (agent !== undefined) options.agent = agent;
248
+ result = has('--execute') ? await executeRoutedTask(task, { ...options, gate: has('--gate'), gateOptions: { tier: value('--tier') || 'fast' } }) : await routeTask(task, options);
249
+ if (!result.ok) process.exitCode = 1;
250
+ }
251
+ else if (operation === 'decompose') {
252
+ const task = positional.join(' ');
253
+ if (!task) throw new Error('decompose requires a task description');
254
+ const pool = await resolvePool({ allowUnknownAuth: has('--allow-unknown-auth') });
255
+ result = { ...decomposeTask(task, { availableHarnesses: pool.ready.map(h => h.id) }), excluded: pool.excluded };
256
+ }
257
+ else if (operation === 'coordinate' || operation === 'orchestrate') {
258
+ const task = positional.join(' ');
259
+ if (!task) throw new Error(`${operation} requires a task description`);
260
+ result = await coordinateTask(task, {
261
+ ...controls(), mode: value('--mode') || 'pipeline', execute: has('--execute'), orchestrator: value('--orchestrator'), explorer: value('--explorer'), architect: value('--architect'), implementer: value('--implementer'), verifier: value('--verifier'),
262
+ branch: value('--branch'), subagents: !has('--no-subagents'), autoReview: has('--auto-review'), gate: has('--gate'), gateOptions: { tier: value('--tier') || 'fast' }, allowSameFamily: has('--allow-same-family'), reviewer: value('--reviewer'),
263
+ node: value('--node') || 'local', cwd: value('--cwd'), allowUnknownAuth: has('--allow-unknown-auth'), ...modelOption(), ...remoteTimeout(),
264
+ });
265
+ if (!result.ok) process.exitCode = 1;
266
+ }
267
+ else if (operation === 'threads') {
268
+ const sub = args[1] || 'list';
269
+ if (sub === 'list') {
270
+ const statusIdx = args.indexOf('--status');
271
+ const platformIdx = args.indexOf('--platform');
272
+ result = listThreads({
273
+ status: statusIdx >= 0 ? args[statusIdx + 1] : undefined,
274
+ platform: platformIdx >= 0 ? args[platformIdx + 1] : undefined
275
+ });
276
+ } else if (sub === 'cleanup-fixtures') {
277
+ result = cleanupFixtureThreads({ dryRun: has('--dry-run') });
278
+ } else if (sub === 'show' || sub === 'get') {
279
+ const id = args[2];
280
+ if (!id) throw new Error('threads show requires a thread id');
281
+ result = getThread(id);
282
+ if (!result) throw new Error(`Thread not found: ${id}`);
283
+ } else if (sub === 'create') {
284
+ const title = value('--title') || positional.slice(1).join(' ');
285
+ result = createThread({
286
+ title: title || 'New Agent Thread',
287
+ platform: value('--platform') || 'universal',
288
+ branch: value('--branch') || null
289
+ });
290
+ } else if (sub === 'update') {
291
+ const id = positional[1];
292
+ if (!id) throw new Error('threads update requires a thread id');
293
+ const patch = Object.fromEntries(['title', 'status', 'platform', 'branch', 'summary'].map(key => [key, value(`--${key}`)]).filter(([, entry]) => entry !== undefined));
294
+ if (!Object.keys(patch).length) throw new Error('threads update requires at least one field');
295
+ result = updateThread(id, patch);
296
+ } else if (sub === 'close') {
297
+ const id = args[2];
298
+ if (!id) throw new Error('threads close requires a thread id');
299
+ result = closeThread(id);
300
+ } else if (sub === 'delete') {
301
+ const id = args[2];
302
+ if (!id) throw new Error('threads delete requires a thread id');
303
+ result = { ok: deleteThread(id) };
304
+ } else {
305
+ throw new Error(`Unsupported threads operation: ${sub}`);
306
+ }
307
+ }
308
+ else if (operation === 'reviews') result = { ok: true, reviews: readReviews() };
309
+ else if (operation === 'review') {
310
+ result = await executeCodeReview({ target: positional[0] || null, reviewer: value('--reviewer'), author: value('--author'), threadId: value('--thread'), staged: has('--staged'), node: value('--node') || 'local', cwd: value('--cwd'), allowUnknownAuth: has('--allow-unknown-auth'), ...remoteTimeout() });
311
+ if (!result.ok) process.exitCode = 1;
312
+ }
313
+ else if (operation === 'learn') {
314
+ if (has('--emit')) throw new Error('learn --emit was removed. Routing reads run receipts directly.');
315
+ result = value('--void') !== undefined
316
+ ? await voidReceipts({ ids: String(value('--void')).split(',').map(id => id.trim()).filter(Boolean), reason: value('--reason') })
317
+ : await learnFromHistory();
318
+ if (!result.ok) process.exitCode = 1;
319
+ }
320
+ else if (operation === 'priority-cache') {
321
+ result = await priorityCacheProjects({ add: value('--add'), remove: value('--remove') });
39
322
  }
40
- else if (operation === 'coordinate') {
41
- const modeIdx = args.indexOf('--mode');
42
- const mode = modeIdx >= 0 ? args[modeIdx + 1] : 'pipeline';
43
- const execute = args.includes('--execute');
44
- const task = args.slice(1).filter(a => !a.startsWith('--') && a !== mode).join(' ');
45
- if (!task) throw new Error('coordinate requires a task description');
46
- result = await coordinateTask(task, { mode, execute });
323
+ else if (operation === 'alerts') {
324
+ const sub = positional[0] || 'check';
325
+ if (sub === 'check') {
326
+ const { quotas } = await inspectQuotas({});
327
+ result = await checkAlerts({ quotas, threshold: Number(value('--threshold')) || 85, dryRun: has('--dry-run') });
328
+ } else if (sub === 'test') result = await notifyAlert({ title: 'Metaharness: test alert', message: 'Alert delivery check.', dryRun: has('--dry-run') });
329
+ else throw new Error(`Unsupported alerts operation: ${sub}`);
330
+ if (!result.ok) process.exitCode = 1;
47
331
  }
48
- else if (operation === 'learn') result = learnFromHistory();
49
332
  else if (operation === 'upstream') result = await inspectUpstreamFleet(getActiveAdapters());
50
333
  else if (operation === 'changelog') result = getAgentChangelog(args[1] || 'agy');
51
334
  else if (operation === 'adapter') {
@@ -61,11 +344,11 @@ export async function run(argv = []) {
61
344
  } catch {
62
345
  throw new Error('Invalid adapter JSON specification');
63
346
  }
64
- if (!spec.id || !spec.binary) throw new Error('Adapter specification must define id and binary');
347
+ spec = validateCustomAdapter(spec);
65
348
  const dirs = getCustomAdaptersDirs();
66
349
  fs.mkdirSync(dirs[0], { recursive: true });
67
- const dest = path.join(dirs[0], `${spec.id}.json`);
68
- fs.writeFileSync(dest, JSON.stringify(spec, null, 2), 'utf8');
350
+ const dest = adapterPath(dirs[0], spec.id);
351
+ fs.writeFileSync(dest, JSON.stringify(spec, null, 2), { encoding: 'utf8', mode: 0o600, flag: 'wx' });
69
352
  result = { ok: true, added: spec.id, path: dest };
70
353
  } else if (sub === 'remove') {
71
354
  const id = args[2];
@@ -73,19 +356,21 @@ export async function run(argv = []) {
73
356
  const dirs = getCustomAdaptersDirs();
74
357
  let removed = false;
75
358
  for (const d of dirs) {
76
- const dest = path.join(d, `${id}.json`);
359
+ const dest = adapterPath(d, id);
77
360
  if (fs.existsSync(dest)) {
78
361
  fs.unlinkSync(dest);
79
362
  removed = true;
80
363
  }
81
364
  }
82
365
  result = { ok: removed, removed: id };
83
- }
366
+ if (!removed) process.exitCode = 1;
367
+ } else throw new Error(`Unsupported adapter operation: ${sub}`);
84
368
  }
85
369
  else if(operation==='docs-sources')result={sources:DOC_SOURCES};
86
370
  else if(operation==='docs-read' || operation==='docs-search') {
87
371
  const option=name=>{const i=args.indexOf(name);if(i<0)return undefined;if(!args[i+1] || args[i+1].startsWith('--'))throw new Error(`${name} requires a value`);return args[i+1];};
88
- result=operation==='docs-read'?readDocumentation({agent:option('--agent'),url:option('--url')}):searchDocumentation({agent:option('--agent'),query:option('--query')});
372
+ result = await runDocumentationCommand(operation, { agent: option('--agent'), url: option('--url'), query: option('--query') });
373
+ if (result.ok === false) process.exitCode = 1;
89
374
  }
90
375
  else if(operation==='setup') {
91
376
  const index=args.indexOf('--node');
@@ -97,23 +382,122 @@ export async function run(argv = []) {
97
382
  if (selected>=0 && (!args[selected+1] || args[selected+1].startsWith('-'))) throw new Error('--agent requires an adapter identifier');
98
383
  const options = selected>=0 ? {agent:args[selected+1]} : {};
99
384
  if(operation==='maintenance') {
100
- const setup=await setupIntegrations();
101
- result={...await maintainDocumentation(options),setup};
102
- } else result = operation==='docs-status' ? documentationStatus(options) : operation==='docs-ensure' ? await ensureDocumentation(options) : await refreshDocumentation(options);
385
+ if (has('--models')) {
386
+ const { syncModelCatalog } = await import('./src/model-catalog.mjs');
387
+ result = await syncModelCatalog();
388
+ } else if (has('--harnesses')) {
389
+ const { updateHarnesses } = await import('./src/harness-updates.mjs');
390
+ result = await updateHarnesses({ only: options.agent || null, dryRun: has('--dry-run') });
391
+ } else {
392
+ result=await maintainIntegrations(options);
393
+ }
394
+ } else result = await runDocumentationCommand(operation, options);
103
395
  if(!result.ok)process.exitCode=1;
104
396
  }
105
397
  else if (operation === 'runtime') {
106
398
  const runtimeArgs=args.slice(1).filter(arg=>arg!=='--json'), agent=runtimeArgs.shift();
107
399
  const index=runtimeArgs.indexOf('--node'); let node='local';
108
400
  if(index>=0){node=runtimeArgs[index+1];if(!node || node.startsWith('-'))throw new Error('--node requires an identifier');runtimeArgs.splice(index,2);}
109
- result = node==='local' ? await manageRuntime(agent,runtimeArgs) : await executeOnNode(node,{operation:'direct',cwd:process.cwd(),argv:['total-recall','cli-agents','runtime',agent,...runtimeArgs,'--json']});
401
+ const command = validateRuntimeOperation(agent, runtimeArgs);
402
+ result = node==='local' ? await manageRuntime(agent,command) : await executeOnNode(node,{operation:'direct',useHome:true,argv:['total-recall','meta-harness','runtime',agent,...command,'--json']});
110
403
  if(!result.ok)process.exitCode=1;
111
404
  }
405
+ else if (operation === 'process') {
406
+ const processes = await import('./src/process-manager.mjs');
407
+ const [action = 'list', target, ...task] = positional;
408
+ if (action === 'list') result = { ok: true, agents: processes.listAgents() };
409
+ else if (action === 'status') {
410
+ result = processes.listAgents().find(record => record.id === target || String(record.pid) === target);
411
+ if (!result) throw new Error('Managed process not found');
412
+ } else if (action === 'spawn') {
413
+ if (!target || !task.length) throw new Error('process spawn requires a harness and task');
414
+ result = await processes.spawnAgent(target, task.join(' '), {
415
+ node: value('--node') || 'local', cwd: value('--cwd'), name: value('--name'),
416
+ tools: value('--tools'), settingSources: value('--setting-sources'), model: value('--model'),
417
+ detach: !has('--no-detach'), write: !has('--read-only'), allowUnknownAuth: has('--allow-unknown-auth'),
418
+ });
419
+ if (result.status === 'failed') process.exitCode = 1;
420
+ } else if (action === 'kill') {
421
+ if (!target) throw new Error('process kill requires a managed process id');
422
+ result = await processes.killAgent(target);
423
+ } else if (action === 'logs') {
424
+ if (!target) throw new Error('process logs requires a managed process id');
425
+ result = { ok: true, logs: await processes.getAgentLogs(target, Number(value('--tail') || 50)) };
426
+ } else throw new Error(`Unsupported process operation: ${action}`);
427
+ }
428
+ else if (operation === 'fork' || operation === 'resume') {
429
+ if (positional.length !== (operation === 'fork' ? 1 : 2)) throw new Error(`${operation} requires a job${operation === 'resume' ? ' and quoted text' : ''}.`);
430
+ const deadline = value('--timeout-ms');
431
+ if (deadline !== undefined && !/^\d+$/.test(deadline)) throw new Error('--timeout-ms must be a whole number of milliseconds');
432
+ result = await continueJob(positional[0], operation === 'fork' ? 'Continue from this session.' : positional[1], { fork: operation === 'fork', atTurn: value('--at'),
433
+ ...(deadline !== undefined ? { deadlineMs: Number(deadline) } : {}), background });
434
+ if (!result.ok) process.exitCode = 1;
435
+ }
436
+ else if (operation === 'cancel') {
437
+ result = await cancelJob(positional[0]);
438
+ }
439
+ else if (['reply', 'approve', 'interrupt', 'goal'].includes(operation)) {
440
+ if (!positional[0]) throw new Error(`${operation} requires a job ID.`);
441
+ if (positional.length !== (operation === 'approve' ? 3 : operation === 'interrupt' ? 1 : 2)) {
442
+ throw new Error(`${operation}: supply a job${operation === 'approve' ? ', request ID, and allow or deny' : operation === 'interrupt' ? '' : ' and quoted text'}.`);
443
+ }
444
+ result = await appendCommand(positional[0], { type: operation,
445
+ ...(operation === 'approve' ? { requestId: positional[1], value: positional[2] } : operation === 'interrupt' ? {} : { text: positional[1] }) },
446
+ { local: has('--local-delivery') });
447
+ }
448
+ else if (operation === 'mcp') {
449
+ const { runMcpServer, QUESTION_TIMEOUT_MS } = await import('./src/mcp-server.mjs');
450
+ await runMcpServer({ approvalPolicy: value('--approvals') || 'auto',
451
+ questionTimeoutMs: value('--question-timeout-ms') === undefined ? QUESTION_TIMEOUT_MS : Number(value('--question-timeout-ms')) });
452
+ return;
453
+ }
454
+ else if (operation === 'watch') {
455
+ // A-107: a dispatched agent's live status and latest events, by log path or job prefix.
456
+ const target = positional[0];
457
+ const selectedNode = value('--node');
458
+ if (selectedNode && selectedNode !== 'local') {
459
+ const mesh = await hostModule('mesh');
460
+ const peer = mesh.findMeshNode(selectedNode);
461
+ if (!peer) throw new Error('Selected mesh node is not recorded');
462
+ if (!peer.self) {
463
+ if (!/^[a-z0-9-]{3,120}$/.test(target || '')) throw new Error('Remote watch requires a job ID');
464
+ const tail = value('--tail');
465
+ result = { ...await readPeerMetaHarness(peer, ['watch', target, ...(tail ? ['--tail', tail] : [])], { mesh }), node: peer.hostname };
466
+ if (result.ok === false) process.exitCode = 1;
467
+ return result;
468
+ }
469
+ }
470
+ const jobs = path.join(configDir(), 'jobs');
471
+ let file = target && target.endsWith('.events.jsonl') ? path.resolve(target) : null;
472
+ if (target && !file) {
473
+ try {
474
+ const job = resolveJob(target);
475
+ const canonical = path.join(jobs, `${job.id}.events.jsonl`);
476
+ if (fs.existsSync(canonical)) file = canonical;
477
+ } catch (error) {
478
+ if (!error.message.startsWith('No job log matches')) throw error;
479
+ }
480
+ }
481
+ if (!file) {
482
+ const names = fs.existsSync(jobs) ? fs.readdirSync(jobs).filter(name => name.endsWith('.events.jsonl') && (!target || name.startsWith(target))) : [];
483
+ const newest = names.map(name => ({ name, at: fs.statSync(path.join(jobs, name)).mtimeMs })).sort((a, b) => b.at - a.at)[0];
484
+ if (!newest) throw new Error(target ? `No job log matches ${target}` : 'No dispatched job has a live log yet');
485
+ file = path.join(jobs, newest.name);
486
+ }
487
+ const { readProgress } = await import('./src/worker.mjs');
488
+ result = { ok: true, file, ...readProgress(file, Number(value('--tail') || 20)), waiting: waitingRequests(file) };
489
+ }
112
490
  else if(operation==='dispatch') {
113
- if(!args.includes('--stdin'))throw new Error('Task requests must arrive through stdin');
491
+ if(!args.includes('--stdin'))throw new Error('Task requests must arrive through stdin: pass --stdin with JSON {agent, cwd, prompt}');
114
492
  const input=fs.readFileSync(0,'utf8');if(Buffer.byteLength(input)>65536)throw new Error('Task request too large');
115
- const request=JSON.parse(input);
116
- result=await executeOnNode(request.node || 'local',{...request,operation:'dispatch'});
493
+ const body=JSON.parse(input);
494
+ if(value('--model')!==undefined && body?.model!==undefined && body.model!==value('--model'))throw new Error('--model and the request model differ; give the model once');
495
+ const request=validateDispatchRequest({...body,...controls(),...modelOption()},{background});
496
+ // A-107: a local dispatch streams its agent's events to a live log, announced before it starts.
497
+ const progressFile=(request.node||'local')==='local'?path.join(configDir(),'jobs',`${process.env.TR_METAHARNESS_JOB || `dispatch-${Date.now().toString(36)}-${request.agent}`}.events.jsonl`):undefined;
498
+ const edits=request.permissions?.write===true?'kept on a branch':'discarded; pass permissions {"read":true,"write":true}, or use route --execute, to keep them';
499
+ if(progressFile)console.error(JSON.stringify({progress:progressFile,agent:request.agent,edits}));
500
+ result=await dispatchWithReceipt(progressFile?{...request,progressFile}:request,{node:request.node || 'local',role:'Dispatch',manageWrites:true});
117
501
  if(!result.ok)process.exitCode=1;
118
502
  }
119
503
  else if (operation === 'inspect') {
@@ -133,7 +517,8 @@ export async function run(argv = []) {
133
517
  const plugin = getPlugin(request.pluginId, request.projectRoot || process.cwd());
134
518
  result = await executeCommand({ ...request, plugin });
135
519
  if (!result.ok) process.exitCode = 1;
136
- } else throw new Error('Unknown CLI-agents operation');
137
- console.log(JSON.stringify(result));
520
+ } else throw new Error(`Unknown operation: ${operation}`);
521
+ if (cancellationResult()) process.exitCode = cancellationResult().exitCode;
522
+ return result;
138
523
  }
139
524
  export default run;
package/package.json CHANGED
@@ -1,15 +1,18 @@
1
1
  {
2
2
  "name": "tr-plugin-meta-harness",
3
- "version": "0.3.0",
4
- "description": "Total Recall Meta Harness plugin",
3
+ "version": "0.5.27",
4
+ "description": "Total Recall Metaharness plugin",
5
5
  "type": "module",
6
6
  "scripts": {
7
- "test": "node --test test/*.test.mjs"
7
+ "test": "node --import ./test/isolate.mjs --test test/*.test.mjs",
8
+ "ssss": "ssss",
9
+ "ssss:validate": "node src/verify-ssss.mjs --target ."
8
10
  },
9
11
  "files": [
10
12
  "cli.mjs",
11
13
  "plugin.json",
12
14
  "README.md",
15
+ "DESIGN.md",
13
16
  "src/",
14
17
  "!src/**/*.spec.mjs",
15
18
  "ui/",
@@ -18,5 +21,14 @@
18
21
  ],
19
22
  "publishConfig": {
20
23
  "access": "public"
24
+ },
25
+ "dependencies": {
26
+ "@gregiteen/ssss-cli": "0.14.6"
27
+ },
28
+ "devDependencies": {
29
+ "total-recall-brain": "3.52.14"
30
+ },
31
+ "overrides": {
32
+ "@ssss/cli": "npm:@gregiteen/ssss-cli@0.14.6"
21
33
  }
22
34
  }