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
@@ -0,0 +1,76 @@
1
+ import path from 'node:path';
2
+ import { sessionOptions } from './session/run.mjs';
3
+
4
+ const DEFAULT_PERMISSIONS = Object.freeze({ read: true, write: false, send: false, destructive: false });
5
+ export { DEFAULT_PERMISSIONS };
6
+
7
+ export function commandPermissions(value = DEFAULT_PERMISSIONS) {
8
+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('Command permissions must be boolean values');
9
+ for (const key of Object.keys(value)) {
10
+ if (!Object.hasOwn(DEFAULT_PERMISSIONS, key) || typeof value[key] !== 'boolean') throw new Error(`Invalid permission ${key}`);
11
+ }
12
+ return { ...DEFAULT_PERMISSIONS, ...value };
13
+ }
14
+
15
+ const PUBLIC_FIELDS = [
16
+ 'agent', 'cwd', 'prompt', 'permissions', 'node', 'allowUnknownAuth', 'timeoutMs',
17
+ 'model', 'tools', 'settingSources', 'allowedTools',
18
+ 'goal', 'maxTurns', 'maxTokens', 'maxBudgetUsd', 'resultSchema', 'approvalPolicy', 'questionTimeoutMs', 'effort', 'fallbackModel', 'name',
19
+ 'internalReasoning',
20
+ ];
21
+
22
+ /** The plugin host stops a foreground command after 10 minutes; a detached background job is not under that limit. */
23
+ export const FOREGROUND_TIMEOUT_MAX_MS = 540000;
24
+ export const BACKGROUND_TIMEOUT_MAX_MS = 5400000;
25
+
26
+ /**
27
+ * The deadline an attached run may use: the host passes its actual timer in TR_PLUGIN_TIMEOUT_MS
28
+ * (90 minutes for a terminal or background-task call), less a minute to finish and report.
29
+ * Without it, the conservative 9-minute limit applies.
30
+ */
31
+ export function attachedTimeoutMaxMs(env = process.env) {
32
+ const host = Number(env.TR_PLUGIN_TIMEOUT_MS);
33
+ if (!Number.isInteger(host) || host <= 60000) return FOREGROUND_TIMEOUT_MAX_MS;
34
+ return Math.min(BACKGROUND_TIMEOUT_MAX_MS, Math.max(FOREGROUND_TIMEOUT_MAX_MS, host - 60000));
35
+ }
36
+ /** A detached local job is coding work, not a probe: five minutes stopped real jobs mid-implementation. */
37
+ export const BACKGROUND_TIMEOUT_DEFAULT_MS = 3600000;
38
+ export const FOREGROUND_TIMEOUT_DEFAULT_MS = 300000;
39
+
40
+ export function defaultTimeoutMs({ background = false, local = true } = {}) {
41
+ return background && local ? BACKGROUND_TIMEOUT_DEFAULT_MS : FOREGROUND_TIMEOUT_DEFAULT_MS;
42
+ }
43
+
44
+ /** The deadline a resumed or forked job runs under: an explicit override, else the saved job's, else the default. */
45
+ export function continuationTimeoutMs({ override, saved, background = false } = {}) {
46
+ const timeoutMs = override ?? saved ?? defaultTimeoutMs({ background });
47
+ const max = background ? BACKGROUND_TIMEOUT_MAX_MS : attachedTimeoutMaxMs();
48
+ if (!Number.isInteger(timeoutMs) || timeoutMs < 1) throw new Error('--timeout-ms must be a whole number of milliseconds');
49
+ return Math.min(timeoutMs, max);
50
+ }
51
+
52
+ export function validateDispatchRequest(request, { background = false } = {}) {
53
+ if (!request || typeof request !== 'object' || Array.isArray(request)) throw new Error('Dispatch requires a JSON object');
54
+ if (Object.keys(request).some(key => !PUBLIC_FIELDS.includes(key))) throw new Error('Unsupported dispatch field; workspace context and containment are managed by Metaharness');
55
+ if (typeof request.agent !== 'string' || !/^[a-z][a-z0-9-]{0,63}$/.test(request.agent) ||
56
+ typeof request.cwd !== 'string' || !path.isAbsolute(request.cwd) || request.cwd.includes('\0') ||
57
+ typeof request.prompt !== 'string' || !request.prompt.trim() || Buffer.byteLength(request.prompt) > 65536) {
58
+ throw new Error('Dispatch requires an explicit agent, absolute workspace, and bounded nonempty prompt');
59
+ }
60
+ if (request.node !== undefined && (typeof request.node !== 'string' || !request.node.trim() || /[\0\r\n]/.test(request.node))) throw new Error('Invalid dispatch node');
61
+ if (request.allowUnknownAuth !== undefined && typeof request.allowUnknownAuth !== 'boolean') throw new Error('allowUnknownAuth must be a boolean');
62
+ // Only a local job gets the background limit: a remote node runs the attempt as its own foreground dispatch.
63
+ const local = request.node === undefined || request.node === 'local';
64
+ const timeoutMs = request.timeoutMs === undefined ? defaultTimeoutMs({ background, local }) : request.timeoutMs;
65
+ const max = background && local ? BACKGROUND_TIMEOUT_MAX_MS : local ? attachedTimeoutMaxMs() : FOREGROUND_TIMEOUT_MAX_MS;
66
+ if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > max) {
67
+ throw new Error(`Dispatch timeout must be 1..${FOREGROUND_TIMEOUT_MAX_MS} ms, or up to ${BACKGROUND_TIMEOUT_MAX_MS} ms for a local --background job`);
68
+ }
69
+ return { ...request, ...sessionOptions(request), permissions: commandPermissions(request.permissions), timeoutMs };
70
+ }
71
+
72
+ /** The installed destination starts from its own project context and decides containment itself. */
73
+ export function destinationDispatchRequest(request) {
74
+ const fields = PUBLIC_FIELDS.filter(key => key !== 'node' && request[key] !== undefined);
75
+ return validateDispatchRequest(Object.fromEntries(fields.map(key => [key, request[key]])));
76
+ }
@@ -0,0 +1,119 @@
1
+ /** One path for every agent run: contain it if needed, dispatch it, classify the outcome, write its receipt. */
2
+ import { executeOnNode } from './executor.mjs';
3
+ import { classifyFailure, INCLUDED_BILLING, READ_ONLY_ADAPTERS, cancellationResult } from './worker.mjs';
4
+ import { codexModelRefusal } from './codex-models.mjs';
5
+ import { recordRunReceipt } from './learner.mjs';
6
+ import { isGitRepo, createWorktree, removeWorktree, commitAll, deleteBranch, gitPointerProblem } from './worktree.mjs';
7
+ import { randomUUID } from 'node:crypto';
8
+ import { includedAdmission, openRouterAdmission, readIncludedPolicy } from './included-usage.mjs';
9
+ import { queueIncludedJob } from './usage-queue.mjs';
10
+ import { createModelValidator } from './model-selection.mjs';
11
+ import { enforceVelocityCircuitBreaker } from './alerts.mjs';
12
+
13
+ export async function dispatchWithReceipt(request, { dispatchFn, node = request.node || 'local', role, complexityScore, escalatedFrom,
14
+ record = recordRunReceipt, replay, retryId, manageWrites = false, validateModel, usagePolicy = readIncludedPolicy, admit = includedAdmission, admitOpenRouter = openRouterAdmission } = {}) {
15
+ const started = Date.now();
16
+ if (cancellationResult()) return cancellationResult();
17
+ try { await enforceVelocityCircuitBreaker({ kind: request.internalReasoning ? 'reasoning' : 'dispatch' }); } catch (error) {
18
+ return { ok: false, agent: request.agent, failureKind: 'circuit-breaker', error: error.message, launchPrevented: true, exitCode: null, durationMs: Date.now() - started };
19
+ }
20
+ if (request.agent === 'codex' && request.model === undefined && node === 'local') {
21
+ const refused = codexModelRefusal();
22
+ if (refused) return { ok: false, agent: request.agent, failureKind: 'model', error: refused, launchPrevented: true, exitCode: null, durationMs: Date.now() - started };
23
+ }
24
+ // A model this harness must not or cannot run is refused before launch; it says nothing about the harness, so no receipt.
25
+ if (request.model !== undefined) {
26
+ const check = (validateModel || createModelValidator({ local: node === 'local' }))(request.agent, request.model);
27
+ if (!check.ok) return { ok: false, agent: request.agent, failureKind: 'model', error: check.reason, modelCheck: check, launchPrevented: true, exitCode: null, durationMs: Date.now() - started };
28
+ }
29
+ // A harness that cannot be told not to write does read-only work in a checkout that is thrown away.
30
+ const contain = node === 'local' && request.permissions?.write !== true && !READ_ONLY_ADAPTERS.includes(request.agent) && request.isolated !== true && isGitRepo(request.cwd);
31
+ const ownWrites = manageWrites && node === 'local' && request.permissions?.write === true && isGitRepo(request.cwd);
32
+ let scratch = null, branch = null, result, billingMode = null, launchPrevented = false;
33
+ try {
34
+ let effective = request;
35
+ const policy = await usagePolicy();
36
+ const openRouter = Object.hasOwn(policy.openRouter ?? {}, request.agent);
37
+ const planOnly = request.includedPlanOnly === true;
38
+ if (planOnly && (!policy.enabled || node !== 'local' || openRouter)) {
39
+ result = { ok: false, failureKind: 'billing-policy', error: 'This reasoning task requires a verified local included plan.' };
40
+ launchPrevented = true;
41
+ } else if (policy.enabled && node === 'local') {
42
+ billingMode = openRouter ? 'openrouter' : 'included';
43
+ const admission = openRouter ? await admitOpenRouter(request.agent, policy) : await admit(request.agent, request.cwd, planOnly ? { ...policy, claude: undefined } : policy);
44
+ if (!admission.ok) {
45
+ result = { ...admission, agent: request.agent, exitCode: null };
46
+ launchPrevented = true;
47
+ } else effective = { ...request, [INCLUDED_BILLING]: { key: admission.key, claudePlan: admission.claudePlan, claudeToken: admission.claudeToken, openRouter: admission.openRouter, agy: admission.agy } };
48
+ }
49
+ result = cancellationResult() || result;
50
+ if (!result) {
51
+ if (contain || ownWrites) {
52
+ branch = ownWrites ? `meta-harness/dispatch-${randomUUID()}` : null;
53
+ scratch = createWorktree(request.cwd, { ...(branch ? { branch } : {}), prefix: ownWrites ? 'meta-harness-dispatch-' : 'meta-harness-readonly-' });
54
+ effective = { ...effective, ...(branch ? { branch } : {}), cwd: scratch, contextCwd: request.contextCwd || request.cwd, isolated: true };
55
+ }
56
+ result = dispatchFn ? await dispatchFn(effective) : await executeOnNode(node, { ...effective, operation: 'dispatch' });
57
+ if (cancellationResult()) result = { ...result, ...cancellationResult() };
58
+ if (contain) result = { ...result, readOnly: 'disposable-checkout' };
59
+ }
60
+ } catch (error) {
61
+ const message = String(error?.message || error);
62
+ result = { ok: false, error: message, agent: request.agent, ...(error?.code === 'NOT_READY' ? { failureKind: 'not-ready' } : classifyFailure(message)) };
63
+ } finally {
64
+ if (scratch) {
65
+ let keep = false;
66
+ try {
67
+ if (branch) {
68
+ const commit = commitAll(scratch, result?.cancelled ? 'meta-harness: unfinished cancelled dispatch' : 'meta-harness: dispatch changes');
69
+ if (commit) result = { ...result, branch, ...(result?.ok ? { commit } : { wip: commit }) };
70
+ else if (result?.sessionId) result = { ...result, branch };
71
+ else deleteBranch(request.cwd, branch);
72
+ }
73
+ } catch (error) {
74
+ // A refused commit must leave the checkout available for recovery, without running status there.
75
+ if (!gitPointerProblem(scratch)) throw error;
76
+ keep = true;
77
+ result = { ...result, ok: false, failureKind: 'security', error: String(error.message), branch, keptWorktree: scratch };
78
+ } finally { if (!keep) removeWorktree(request.cwd, scratch); }
79
+ if (!keep && branch && !result?.branch) deleteBranch(request.cwd, branch);
80
+ }
81
+ }
82
+ const durationMs = Date.now() - started;
83
+ if (result.execution?.receiptOwner === 'destination' && result.receiptId) return { ...result, durationMs };
84
+ if (result.execution?.remote && (result.queued || result.launchPrevented)) return { ...result, durationMs };
85
+ if (billingMode === 'included' && result.failureKind === 'quota') {
86
+ if (retryId) result = { ...result, needsReview: !launchPrevented && request.permissions?.write === true };
87
+ // Internal reasoning is an attempt within the caller's durable task.
88
+ else if (!request.internalReasoning) {
89
+ try {
90
+ const job = await queueIncludedJob(request, result, { role, replay, launchPrevented });
91
+ result = { ...result, queued: true, queueId: job.id, needsReview: job.needsReview };
92
+ } catch (error) {
93
+ result = { ...result, queueError: error.message };
94
+ }
95
+ }
96
+ }
97
+ if (launchPrevented) {
98
+ // A launch refused for quota is a quota wall too (A-124): record it, so routing sees the harness as
99
+ // exhausted until its reset and picks another included harness instead of choosing it again.
100
+ if (result.failureKind === 'quota') {
101
+ try { await record({ harness: request.agent, role, task: String(request.contextTask || request.prompt || '').slice(0, 200), success: false,
102
+ failureKind: 'quota', billingMode, error: result.error, resetsAt: result.resetsAt || null }); } catch { /* bookkeeping must not hide the refusal */ }
103
+ }
104
+ return { ...result, launchPrevented, durationMs };
105
+ }
106
+ // A finished run keeps its result: the worktree and any cost are real even when bookkeeping fails.
107
+ let receipt, receiptError;
108
+ try {
109
+ receipt = await record({
110
+ harness: request.agent, role, node, task: request.contextTask || request.prompt, complexityScore,
111
+ billingMode,
112
+ model: result.model ?? null, exitCode: result.exitCode ?? null, finishedReason: result.finishedReason ?? null,
113
+ tools: result.toolResults,
114
+ success: result.ok === true, durationMs, failureKind: result.ok ? null : result.failureKind || 'agent',
115
+ error: result.ok ? null : result.error, resetsAt: result.resetsAt, escalatedFrom,
116
+ });
117
+ } catch (error) { receiptError = String(error?.message || error); }
118
+ return { ...result, durationMs, ...(billingMode ? { billingMode } : {}), ...(receipt?.id ? { receiptId: receipt.id } : {}), ...(receiptError ? { receiptError } : {}) };
119
+ }
@@ -0,0 +1,57 @@
1
+ import os from 'node:os';
2
+ import { hostModule, readPeerMetaHarness } from './executor.mjs';
3
+ import { documentationStatus, ensureDocumentation, maintainDocumentation, readDocumentation, refreshDocumentation, searchDocumentation } from './documentation.mjs';
4
+ import { runProcess } from './worker.mjs';
5
+
6
+ const localCommands = {
7
+ 'docs-status': documentationStatus,
8
+ 'docs-ensure': ensureDocumentation,
9
+ 'docs-refresh': refreshDocumentation,
10
+ 'docs-search': searchDocumentation,
11
+ 'docs-read': readDocumentation,
12
+ maintenance: maintainDocumentation,
13
+ };
14
+
15
+ async function localMeshIdentity(load) {
16
+ // A peer's SSH session on the documentation owner does not have the owner's
17
+ // interactive Keychain. Public-cache reads only need the local mesh identity.
18
+ const { loadPluginModule } = await load('plugin-runtime');
19
+ const { resolveTailscaleBinary, STATUS_TIMEOUT_MS } = await loadPluginModule('mesh', 'tailscale-cli', { projectRoot: os.homedir() });
20
+ const result = await runProcess(resolveTailscaleBinary(), ['status', '--json'], { timeoutMs: STATUS_TIMEOUT_MS });
21
+ if (result.exitCode !== 0) return null;
22
+ const own = JSON.parse(result.stdout)?.Self;
23
+ return own ? { hostname: String(own.DNSName || own.HostName || '').replace(/\.$/, ''), ips: own.TailscaleIPs || [] } : null;
24
+ }
25
+
26
+ async function documentationAuthority(load, localIdentity, authorityOnly) {
27
+ if (!process.env.TR_PACKAGE_ROOT) return null;
28
+ const [{ getPlugin }, { readPluginRecord }] = await Promise.all([load('plugin-loader'), load('plugin-store')]);
29
+ const plugin = getPlugin('meta-harness', os.homedir()) || getPlugin('cli-agents', os.homedir());
30
+ const record = plugin?.valid ? readPluginRecord(plugin) : null;
31
+ const selected = (record?.task_nodes ?? record?.frontmatter?.task_nodes)?.maintenance;
32
+ if (!selected) return null;
33
+ const self = await localIdentity(load);
34
+ if (self?.hostname === selected || self?.ips?.includes(selected)) return { node: { ...self, self: true } };
35
+ if (authorityOnly) throw new Error(`This node cannot verify itself as the documentation authority ${selected}`);
36
+ const mesh = await load('mesh');
37
+ const node = mesh.findMeshNode(selected);
38
+ if (!node) throw new Error(`The configured documentation authority ${selected} is not recorded in the mesh`);
39
+ return { mesh, node };
40
+ }
41
+
42
+ export async function runDocumentationCommand(operation, options = {}, { load = hostModule, localIdentity = localMeshIdentity, peer = readPeerMetaHarness, commands = localCommands, authorityOnly = process.env.TR_METAHARNESS_DOCS_AUTHORITY_ONLY === '1' } = {}) {
43
+ const authority = await documentationAuthority(load, localIdentity, authorityOnly);
44
+ if (!authority) {
45
+ if (authorityOnly) throw new Error('The destination has no configured documentation authority');
46
+ return commands[operation](options);
47
+ }
48
+ const { node, mesh } = authority;
49
+ const sourceNode = node.hostname || node.ip;
50
+ if (node.self) return { ...await commands[operation](options), sourceNode };
51
+ const command = operation === 'maintenance' ? 'docs-ensure' : operation;
52
+ const args = [command];
53
+ for (const key of ['agent', 'url', 'query']) if (options[key] !== undefined) args.push(`--${key}`, options[key]);
54
+ const refreshing = command === 'docs-refresh' || command === 'docs-ensure';
55
+ const output = await peer(node, args, { mesh, timeoutMs: refreshing ? 90_000 : 30_000, env: ['TR_METAHARNESS_DOCS_AUTHORITY_ONLY=1'] });
56
+ return { ...output, sourceNode, remote: true };
57
+ }
@@ -3,33 +3,64 @@ import fs from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import os from 'node:os';
5
5
  import crypto from 'node:crypto';
6
+ import { execFile } from 'node:child_process';
7
+ import { promisify } from 'node:util';
8
+ import { agentEnvironment, loadCustomAdapters } from './worker.mjs';
9
+
10
+ const exec = promisify(execFile);
6
11
 
7
12
  export const DOC_SOURCES = [
8
13
  { id: 'claude', index: 'https://code.claude.com/docs/llms.txt', prefix: 'https://code.claude.com/docs/', catalog:true },
9
14
  { id: 'codex', index: 'https://developers.openai.com/codex/llms.txt', prefix: 'https://learn.chatgpt.com/docs/', catalog:true },
10
15
  { id: 'agy', index: 'https://antigravity.google/docs/cli/reference', prefix: 'https://antigravity.google/docs/' },
11
- { id: 'cursor', index: 'https://cursor.com/llms.txt', prefix: 'https://cursor.com/docs', catalog:true },
16
+ // cursor.com/docs and cursor.com/docs/llms.txt answer 308 to the Agents Window documentation on docs.grok.com (checked 2026-12-01).
17
+ { id: 'cursor', index: 'https://docs.grok.com/build/agents-window/llms.txt', prefix: 'https://docs.grok.com/build/agents-window/', catalog:true },
12
18
  { id: 'dsh', repo: 'deepseek-ai/deepseek-harness', branch: 'master', directories: ['docs/', 'apps/cli/', 'packages/boot/'], index: 'https://raw.githubusercontent.com/deepseek-ai/deepseek-harness/master/apps/cli/README.md' },
13
- { id: 'grok', index: 'https://docs.x.ai/llms.txt', prefix: 'https://docs.x.ai/build/', catalog:true },
19
+ // xAI moved its documentation: docs.x.ai answers 301 to docs.grok.com (checked 2026-12-01).
20
+ { id: 'grok', index: 'https://docs.grok.com/llms.txt', prefix: 'https://docs.grok.com/build/', catalog:true },
14
21
  { id: 'muse', index: 'https://dev.meta.ai/docs/muse-code', prefix: 'https://dev.meta.ai/docs/muse-code' },
15
22
  { id: 'pi', repo: 'badlogic/pi-mono', branch: 'main', directories: ['packages/coding-agent/docs/'], index: 'https://raw.githubusercontent.com/badlogic/pi-mono/main/packages/coding-agent/README.md' },
16
23
  { id: 'hermes', repo: 'NousResearch/hermes-agent', branch: 'main', directories: ['website/docs/'], index: 'https://raw.githubusercontent.com/NousResearch/hermes-agent/main/website/docs/reference/cli-commands.md' },
24
+ { id: 'devin', index: 'https://docs.devin.ai/llms.txt', prefix: 'https://docs.devin.ai/', catalog:true },
25
+ { id: 'windsurf', index: 'https://docs.windsurf.com/llms.txt', prefix: 'https://docs.windsurf.com/', catalog:true },
26
+ { id: 'cline', index: 'https://docs.cline.bot/llms.txt', prefix: 'https://docs.cline.bot/', catalog:true },
27
+ { id: 'openclaw', index: 'https://docs.openclaw.ai/llms.txt', prefix: 'https://docs.openclaw.ai/', catalog:true },
28
+ { id: 'aider', index: 'https://aider.chat/docs/', prefix: 'https://aider.chat/docs/' },
29
+ { id: 'goose', index: 'https://goose-docs.ai/llms.txt', prefix: 'https://goose-docs.ai/', catalog:true },
30
+ { id: 'openhands', index: 'https://docs.openhands.dev/llms.txt', prefix: 'https://docs.openhands.dev/', catalog:true },
31
+ { id: 'replit', index: 'https://docs.replit.com/llms.txt', prefix: 'https://docs.replit.com/', catalog:true },
32
+ { id: 'lovable', index: 'https://docs.lovable.dev/llms.txt', prefix: 'https://docs.lovable.dev/', catalog:true },
33
+ { id: 'ollama', index: 'https://docs.ollama.com/llms.txt', prefix: 'https://docs.ollama.com/', catalog:true },
17
34
  ];
35
+ function sourcesFor(agent) {
36
+ const sources = new Map(DOC_SOURCES.map(source => [source.id, source]));
37
+ for (const adapter of loadCustomAdapters()) if (adapter.docs) {
38
+ const url = new URL(adapter.docs);
39
+ sources.set(adapter.id, { id: adapter.id, index: url.href, prefix: new URL('.', url).href, origin: url.hostname });
40
+ }
41
+ const selected = agent ? [sources.get(agent)].filter(Boolean) : [...sources.values()];
42
+ if (!selected.length) throw new Error('Unknown documentation adapter or missing declared documentation URL');
43
+ return selected;
44
+ }
18
45
  const hash = value => crypto.createHash('sha256').update(value).digest('hex');
19
46
  const TTL = 24 * 60 * 60 * 1000;
20
47
  function pageFile(directory,id,file){if(!/^[a-f0-9]{64}-[a-f0-9]{64}\.txt$/.test(file || ''))throw new Error('Invalid cached documentation filename');return path.join(directory,id,file);}
21
48
  function atomic(file, value) { fs.mkdirSync(path.dirname(file), { recursive: true }); const temp = `${file}.${process.pid}.tmp`; fs.writeFileSync(temp, value, { mode: 0o600 }); fs.renameSync(temp, file); }
22
49
  export function documentationDirectory() {
23
50
  const brain = process.env.TR_SECRETS_BRAIN || path.join(process.env.AGENT_DIR || path.join(os.homedir(), '.agent'), 'skills/total-recall');
24
- return path.join(brain, 'memory-derived/cli-agents/docs');
51
+ const directory = path.join(brain, 'memory-derived/meta-harness/docs');
52
+ // Keep the downloaded pages when the old directory name is still on disk.
53
+ const legacy = path.join(brain, 'memory-derived/cli-agents/docs');
54
+ if (!fs.existsSync(directory) && fs.existsSync(legacy)) { fs.mkdirSync(path.dirname(directory), { recursive: true }); fs.renameSync(legacy, directory); }
55
+ return directory;
25
56
  }
26
57
  function metadata(directory, id) { try { return JSON.parse(fs.readFileSync(path.join(directory,id,'index.json'),'utf8')); } catch { return null; } }
27
58
  export function documentationStatus({ directory = documentationDirectory(), agent, now = Date.now() } = {}) {
28
- const sources = agent ? DOC_SOURCES.filter(source => source.id === agent) : DOC_SOURCES;
59
+ const sources = sourcesFor(agent);
29
60
  if (!sources.length) throw new Error('Unknown documentation adapter');
30
61
  const agents = sources.map(source => {
31
62
  const saved = metadata(directory,source.id);
32
- const complete = saved?.complete === true && saved.pages?.length > 0 && saved.pages.every(page => {
63
+ const complete = saved?.complete === true && saved.pages?.some(page => page.url === source.index) && saved.pages.every(page => {
33
64
  try { return hash(fs.readFileSync(pageFile(directory,source.id,page.file))) === page.sha256; } catch { return false; }
34
65
  });
35
66
  const age=now-Date.parse(saved?.checkedAt);
@@ -38,16 +69,17 @@ export function documentationStatus({ directory = documentationDirectory(), agen
38
69
  });
39
70
  return { ok:agents.every(row=>row.fresh), directory, agents };
40
71
  }
41
- async function download(url, fetchImpl) {
42
- const allowed = new Set(['code.claude.com','claude.com','platform.claude.com','docs.anthropic.com','anthropic.com','developers.openai.com','openai.com','help.openai.com','learn.chatgpt.com','chatgpt.com','antigravity.google','cursor.com','docs.x.ai','dev.meta.ai','raw.githubusercontent.com','api.github.com']);
72
+ async function download(url, fetchImpl, declaredOrigin) {
73
+ const allowed = new Set(['code.claude.com','claude.com','platform.claude.com','docs.anthropic.com','anthropic.com','developers.openai.com','openai.com','help.openai.com','learn.chatgpt.com','chatgpt.com','antigravity.google','cursor.com','docs.x.ai','docs.grok.com','dev.meta.ai','docs.devin.ai','docs.windsurf.com','windsurf.com','docs.cline.bot','docs.openclaw.ai','aider.chat','docs.replit.com','docs.lovable.dev','docs.ollama.com','goose-docs.ai','block.github.io','docs.openhands.dev','raw.githubusercontent.com','api.github.com']);
43
74
  let target = new URL(url);
75
+ if (declaredOrigin) allowed.add(declaredOrigin);
44
76
  for(let redirects=0;redirects<5;redirects++) {
45
77
  if(target.protocol!=='https:' || target.username || target.password || !allowed.has(target.hostname)) throw new Error(`Unapproved official documentation origin: ${target.hostname}`);
46
- const response=await fetchImpl(target,{redirect:'manual',signal:AbortSignal.timeout(20000),headers:{'User-Agent':'Total-Recall-CLI-Agents-Docs','Accept':'*/*'}});
78
+ const response=await fetchImpl(target,{redirect:'manual',signal:AbortSignal.timeout(20000),headers:{'User-Agent':'Total-Recall-Metaharness-Docs','Accept':'*/*'}});
47
79
  if(response.status>=300 && response.status<400){target=new URL(response.headers.get('location'),target);continue;}
48
80
  // Some entries advertise Markdown exports which no longer exist while the
49
81
  // same official HTML document remains available. Fetch that representation.
50
- if(response.status===404 && ['cursor.com','docs.x.ai'].includes(target.hostname) && target.pathname.endsWith('.md')){target.pathname=target.pathname.slice(0,-3);continue;}
82
+ if(response.status===404 && ['cursor.com','docs.x.ai','docs.grok.com'].includes(target.hostname) && target.pathname.endsWith('.md')){target.pathname=target.pathname.slice(0,-3);continue;}
51
83
  if(!response.ok)throw new Error(`Documentation HTTP ${response.status}: ${target.origin}${target.pathname}`);
52
84
  const chunks=[];let size=0;
53
85
  for await(const chunk of response.body){size+=chunk.byteLength;if(size>8*1024*1024){throw new Error('Documentation page exceeds download budget');}chunks.push(chunk);}
@@ -63,47 +95,96 @@ function links(text,base,prefix) {
63
95
  for(const match of text.matchAll(/\]\(([^\s)]+)(?:\s+[^)]*)?\)/g)){try{values.push(new URL(match[1],base).href);}catch{}}
64
96
  for(const match of text.matchAll(/href=["']([^"']+)["']/g)) {try{values.push(new URL(match[1],base).href);}catch{}}
65
97
  return [...new Set(values.map(value=>{try{const url=new URL(value);url.hash='';url.search='';url.pathname=url.pathname.replace(/\/{2,}/g,'/').replace(/\/$/,'') || '/';return url.href;}catch{return '';}}))]
66
- .filter(url=>url.startsWith(prefix) && !/\.(png|jpg|jpeg|svg|gif|css|js|woff2?|ico|pdf)$/i.test(url));
98
+ .filter(url=>url.startsWith(prefix) && !/%3[CE]|[<>"'`\s]/i.test(url) && !/\.(png|jpg|jpeg|svg|gif|css|js|woff2?|ico|pdf|json|ya?ml|xml|zip|gz|tgz|lock)$/i.test(url));
99
+ }
100
+ async function gitDocumentationPaths(source) {
101
+ const checkout = fs.mkdtempSync(path.join(os.tmpdir(), 'meta-harness-doc-tree-'));
102
+ const options = {
103
+ cwd: checkout, timeout: 30000, maxBuffer: 4 * 1024 * 1024,
104
+ env: { ...agentEnvironment(), GIT_TERMINAL_PROMPT: '0', GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: os.devNull },
105
+ };
106
+ try {
107
+ await exec('git', ['-c', 'http.followRedirects=false', 'clone', '--quiet', '--filter=blob:none',
108
+ '--depth=1', '--single-branch', '--branch', source.branch, '--no-checkout',
109
+ '--', `https://github.com/${source.repo}.git`, checkout], options);
110
+ const { stdout } = await exec('git', ['ls-tree', '-r', '-z', 'HEAD', '--', ...source.directories], options);
111
+ return stdout.split('\0').flatMap(entry => {
112
+ const match = /^100(?:644|755) blob [a-f0-9]+\t([\s\S]+)$/.exec(entry);
113
+ return match ? [match[1]] : [];
114
+ });
115
+ } catch {
116
+ throw new Error(`Could not read the official documentation tree through Git for ${source.repo}`);
117
+ } finally { fs.rmSync(checkout, { recursive: true, force: true }); }
67
118
  }
68
- export async function refreshDocumentation({ directory = documentationDirectory(), agent, fetchImpl = fetch, now = () => new Date(), maxPages = 1500 } = {}) {
69
- const sources=agent?DOC_SOURCES.filter(source=>source.id===agent):DOC_SOURCES;
119
+
120
+ export async function refreshDocumentation({ directory = documentationDirectory(), agent, fetchImpl = fetch, now = () => new Date(), maxPages = 1500, readGitPaths = gitDocumentationPaths } = {}) {
121
+ const sources=sourcesFor(agent);
70
122
  if(!sources.length)throw new Error('Unknown documentation adapter');
71
123
  const reports=[];
72
124
  for(const source of sources) {
73
- const previous=metadata(directory,source.id), pages=[], queue=[source.index], seen=new Set(), queued=new Set(queue), errors=[];
74
- const enqueue=url=>{if(!queued.has(url)){queued.add(url);queue.push(url);}};
125
+ const previous=metadata(directory,source.id), pages=[], queue=[source.index], seen=new Set(), queued=new Set(queue), errors=[], discovered=new Set(), skipped=[];
126
+ // `found` marks a link taken from HTML navigation. The vendor's catalog, the index and the repository tree are authoritative; a link found by scraping is not.
127
+ const enqueue=(url,found=false)=>{if(!queued.has(url)){queued.add(url);queue.push(url);if(found)discovered.add(url);}};
128
+ let treeSource;
75
129
  try {
76
130
  if(source.repo) {
77
- const tree=JSON.parse(await download(`https://api.github.com/repos/${source.repo}/git/trees/${source.branch}?recursive=1`,fetchImpl));
78
- if(tree.truncated)throw new Error('Official repository documentation tree is truncated');
79
- for(const entry of tree.tree || [])if(entry.type==='blob' && /\.(md|mdx)$/i.test(entry.path) && source.directories.some(dir=>entry.path.startsWith(dir)))enqueue(`https://raw.githubusercontent.com/${source.repo}/${source.branch}/${entry.path}`);
131
+ let paths;
132
+ try {
133
+ const tree = JSON.parse(await download(`https://api.github.com/repos/${source.repo}/git/trees/${source.branch}?recursive=1`, fetchImpl));
134
+ if (tree.truncated) throw new Error('Official repository documentation tree is truncated');
135
+ if (!Array.isArray(tree.tree)) throw new Error('Invalid official repository documentation tree');
136
+ paths = tree.tree.filter(entry => entry.type === 'blob').map(entry => entry.path);
137
+ treeSource = 'github-rest';
138
+ } catch (error) {
139
+ if (!/^Documentation HTTP (403|429):|^Official repository documentation tree is truncated$/.test(error.message)) throw error;
140
+ paths = await readGitPaths(source);
141
+ treeSource = 'github-git';
142
+ }
143
+ for (const file of paths) {
144
+ if (!/\.(md|mdx)$/i.test(file) || !source.directories.some(dir => file.startsWith(dir))) continue;
145
+ const encoded = file.split('/').map(encodeURIComponent).join('/');
146
+ enqueue(`https://raw.githubusercontent.com/${source.repo}/${source.branch}/${encoded}`);
147
+ }
148
+ if (queue.length === 1) throw new Error('Official repository documentation tree contains no additional pages');
80
149
  }
81
150
  // Bounded batches; follow the official index/navigation to cover agent features.
82
151
  while(queue.length) {
83
152
  const batch=[];
84
153
  while(queue.length && batch.length<4){const url=queue.shift();if(!seen.has(url)){seen.add(url);batch.push(url);}}
85
154
  if(seen.size>maxPages)throw new Error('Official documentation exceeds configured page budget');
86
- const downloads=await Promise.allSettled(batch.map(async url=>({url,text:await download(url,fetchImpl)})));
155
+ const downloads=await Promise.allSettled(batch.map(async url=>({url,text:await download(url,fetchImpl,source.origin)})));
87
156
  for(let index=0;index<downloads.length;index++) {
88
- const result=downloads[index];if(result.status==='rejected'){errors.push({url:batch[index],error:result.reason.message});continue;}
157
+ const result=downloads[index];
158
+ if(result.status==='rejected'){
159
+ const message=result.reason.message;
160
+ // A scraped link that is gone (404 or 410) is a stale or illustrative link, such as a placeholder in a code sample. It is reported as skipped and does not fail the refresh. Anything else, and anything the vendor itself lists, stays a failure.
161
+ if(discovered.has(batch[index]) && /HTTP (404|410)\b/.test(message)){skipped.push({url:batch[index],error:message});continue;}
162
+ // A page that redirects off the approved origins (for example a trust-center portal) is an external link, not documentation. It is never followed, and it is reported. The index itself redirecting away still fails the refresh.
163
+ if(batch[index]!==source.index && /^Unapproved official documentation origin/.test(message)){skipped.push({url:batch[index],error:message});continue;}
164
+ errors.push({url:batch[index],error:message});continue;
165
+ }
89
166
  const {url,text}=result.value;
90
167
  const sha256=hash(text),file=`${hash(url)}-${sha256}.txt`;
91
168
  atomic(path.join(directory,source.id,file),text);
92
169
  pages.push({url,file,sha256,bytes:Buffer.byteLength(text)});
93
170
  // A published llms index is the authoritative documentation catalog.
94
171
  // HTML navigation also contains unrelated and obsolete marketing links.
95
- if(source.prefix && (!source.catalog || url.endsWith('llms.txt')))for(const link of links(text,url,source.prefix))enqueue(link);
172
+ if(source.prefix && (!source.catalog || url.endsWith('llms.txt')))for(const link of links(text,url,source.prefix))enqueue(link,!url.endsWith('llms.txt'));
96
173
  }
97
174
  }
98
175
  const checkedAt=now().toISOString();
176
+ // An index that moved can answer with a different vendor's catalog and "succeed" with almost nothing
177
+ // (2026-12-01: 417 pages became 1). A collapse to under a quarter of the last complete set is a failure, and the last set is kept.
178
+ const before=previous?.complete?previous.pages?.length || 0:0;
179
+ if(!errors.length && before>=20 && pages.length*4<before)errors.push({url:source.index,error:`Documentation collapsed from ${before} pages to ${pages.length}; the official index may have moved`});
99
180
  if(errors.length){
100
181
  const error=`${errors.length} official document(s) failed: ${errors[0].error}`;
101
182
  const preserved=previous?.complete?previous:{id:source.id,complete:false,pages};
102
- atomic(path.join(directory,source.id,'index.json'),JSON.stringify({...preserved,lastAttempt:checkedAt,error,failedCount:errors.length,failures:errors},null,2));
103
- reports.push({id:source.id,ok:false,error,pages:preserved.pages?.length || 0,downloadedPages:pages.length,failedCount:errors.length,failures:errors});continue;
183
+ atomic(path.join(directory,source.id,'index.json'),JSON.stringify({...preserved,lastAttempt:checkedAt,error,failedCount:errors.length,failures:errors,...(skipped.length?{skipped}:{})},null,2));
184
+ reports.push({id:source.id,ok:false,error,pages:preserved.pages?.length || 0,downloadedPages:pages.length,failedCount:errors.length,failures:errors,...(skipped.length?{skippedCount:skipped.length,skipped}:{})});continue;
104
185
  }
105
- atomic(path.join(directory,source.id,'index.json'),JSON.stringify({id:source.id,complete:true,checkedAt,lastAttempt:checkedAt,pages},null,2));
106
- reports.push({id:source.id,ok:true,pages:pages.length});
186
+ atomic(path.join(directory,source.id,'index.json'),JSON.stringify({id:source.id,complete:true,checkedAt,lastAttempt:checkedAt,pages,...(skipped.length?{skipped}:{})},null,2));
187
+ reports.push({id:source.id,ok:true,pages:pages.length,...(treeSource?{treeSource}:{}),...(skipped.length?{skippedCount:skipped.length,skipped}:{})});
107
188
  } catch(error) {
108
189
  atomic(path.join(directory,source.id,'index.json'),JSON.stringify({...previous,id:source.id,lastAttempt:now().toISOString(),error:error.message},null,2));
109
190
  reports.push({id:source.id,ok:false,error:error.message,pages:previous?.pages?.length || 0});
@@ -121,15 +202,19 @@ export async function ensureDocumentation(options={}) {
121
202
 
122
203
  export async function maintainDocumentation(options={}) {
123
204
  const status=documentationStatus(options);
124
- const next=status.agents.filter(row=>!row.fresh).sort((a,b)=>String(a.lastAttempt || '').localeCompare(String(b.lastAttempt || '')))[0];
125
- if(!next)return {...status,scope:'all-agent-documentation-current'};
126
- const refreshed=await refreshDocumentation({...options,agent:next.id});
205
+ const pending=status.agents.filter(row=>!row.fresh).sort((a,b)=>String(a.lastAttempt || '').localeCompare(String(b.lastAttempt || '')));
206
+ const reports=[];
207
+ // Missing documentation for one harness must not prevent attempts for the others.
208
+ for(const row of pending) {
209
+ try { reports.push(...(await refreshDocumentation({...options,agent:row.id})).agents); }
210
+ catch(error) { reports.push({id:row.id,ok:false,error:error.message}); }
211
+ }
127
212
  const current=documentationStatus(options);
128
- return {...refreshed,scope:'one-stale-agent-refreshed',coverage_complete:current.ok,pending:current.agents.filter(row=>!row.fresh).map(row=>row.id)};
213
+ return {...current,ok:current.ok && reports.every(row=>row.ok),scope:'all-agent-documentation',refresh:reports,coverage_complete:current.ok,pending:current.agents.filter(row=>!row.fresh).map(row=>row.id)};
129
214
  }
130
215
 
131
216
  export function readDocumentation({agent,url,directory=documentationDirectory()}) {
132
- if(!DOC_SOURCES.some(source=>source.id===agent))throw new Error('Unknown documentation adapter');
217
+ sourcesFor(agent);
133
218
  const index=metadata(directory,agent);
134
219
  if(!url)return {agent,pages:index?.pages?.map(page=>({url:page.url,sha256:page.sha256,bytes:page.bytes})) || []};
135
220
  const page=index?.pages?.find(page=>page.url===url);
@@ -141,10 +226,13 @@ export function readDocumentation({agent,url,directory=documentationDirectory()}
141
226
 
142
227
  export function searchDocumentation({agent,query,directory=documentationDirectory()}) {
143
228
  if(typeof query!=='string' || !query.trim())throw new Error('Documentation query required');
144
- const sources=agent?DOC_SOURCES.filter(source=>source.id===agent):DOC_SOURCES;
145
- const matches=[];
229
+ const sources=sourcesFor(agent);
230
+ const matches=[],phrase=query.trim().toLowerCase(),terms=phrase.split(/\s+/).filter(Boolean);
146
231
  for(const source of sources)for(const page of metadata(directory,source.id)?.pages || []) {
147
- const doc=readDocumentation({agent:source.id,url:page.url,directory});const index=doc.content.toLowerCase().indexOf(query.toLowerCase());
232
+ const doc=readDocumentation({agent:source.id,url:page.url,directory});const text=doc.content.toLowerCase();
233
+ // The exact phrase wins. Otherwise a page matches when it contains every term, in any order, so a query of two words is not limited to pages where they happen to be adjacent.
234
+ let index=text.indexOf(phrase);
235
+ if(index<0 && terms.length>1 && terms.every(term=>text.includes(term)))index=Math.min(...terms.map(term=>text.indexOf(term)));
148
236
  if(index>=0)matches.push({agent:source.id,url:page.url,excerpt:doc.content.slice(Math.max(0,index-120),index+600)});
149
237
  if(matches.length>=30)return {matches,truncated:true};
150
238
  }