tr-plugin-meta-harness 0.3.0 → 0.5.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/DESIGN.md +86 -0
  2. package/README.md +257 -11
  3. package/capability/BRICK.md +1 -1
  4. package/capability/index.mjs +154 -13
  5. package/cli.mjs +426 -41
  6. package/package.json +15 -3
  7. package/plugin.json +1457 -119
  8. package/skills/meta-harness/SKILL.md +63 -25
  9. package/src/adoption.mjs +102 -0
  10. package/src/agent-user.mjs +194 -0
  11. package/src/alerts.mjs +220 -14
  12. package/src/cascade.mjs +185 -0
  13. package/src/chat.mjs +80 -0
  14. package/src/codex-models.mjs +54 -0
  15. package/src/compat-harness.mjs +114 -0
  16. package/src/control.mjs +145 -0
  17. package/src/coordinator.mjs +267 -358
  18. package/src/dispatch-request.mjs +76 -0
  19. package/src/dispatch.mjs +119 -0
  20. package/src/documentation-authority.mjs +57 -0
  21. package/src/documentation.mjs +120 -32
  22. package/src/executor.mjs +101 -22
  23. package/src/gate-adapters/agy.mjs +155 -0
  24. package/src/gate-adapters/claude.mjs +303 -0
  25. package/src/gate-adapters/cline.mjs +111 -0
  26. package/src/gate-adapters/codex.mjs +164 -0
  27. package/src/gate-adapters/cursor.mjs +164 -0
  28. package/src/gate-adapters/devin.mjs +116 -0
  29. package/src/gate-adapters/dsh.mjs +284 -0
  30. package/src/gate-adapters/grok.mjs +112 -0
  31. package/src/gate-adapters/hermes.mjs +217 -0
  32. package/src/gate-adapters/hook-files.mjs +156 -0
  33. package/src/gate-adapters/index.mjs +131 -0
  34. package/src/gate-adapters/openclaw-plugin/gate-client.js +205 -0
  35. package/src/gate-adapters/openclaw-plugin/index.js +25 -0
  36. package/src/gate-adapters/openclaw-plugin/openclaw.plugin.json +9 -0
  37. package/src/gate-adapters/openclaw-plugin/package.json +15 -0
  38. package/src/gate-adapters/openclaw.mjs +288 -0
  39. package/src/gate-adapters/pi.mjs +146 -0
  40. package/src/gate.mjs +18 -0
  41. package/src/harness-updates.mjs +170 -0
  42. package/src/included-usage.mjs +344 -0
  43. package/src/jobs.mjs +135 -0
  44. package/src/json-reply.mjs +22 -0
  45. package/src/learner.mjs +97 -67
  46. package/src/maintenance.mjs +18 -0
  47. package/src/mcp-server.mjs +228 -0
  48. package/src/model-catalog.mjs +195 -0
  49. package/src/model-selection.mjs +67 -0
  50. package/src/paths.mjs +23 -0
  51. package/src/pool.mjs +69 -0
  52. package/src/process-manager.mjs +246 -0
  53. package/src/process-worker.mjs +18 -0
  54. package/src/reasoning.mjs +231 -0
  55. package/src/remote-operation.mjs +76 -0
  56. package/src/review.mjs +241 -0
  57. package/src/reviews.mjs +25 -0
  58. package/src/router-benchmark-corpus.mjs +16 -0
  59. package/src/router-benchmark.mjs +208 -0
  60. package/src/router.mjs +265 -346
  61. package/src/runtime.mjs +30 -8
  62. package/src/session/claude.mjs +358 -0
  63. package/src/session/codex.mjs +501 -0
  64. package/src/session/result.mjs +90 -0
  65. package/src/session/resume.mjs +393 -0
  66. package/src/session/run.mjs +258 -0
  67. package/src/session-jobs.mjs +77 -0
  68. package/src/setup.mjs +6 -3
  69. package/src/ssss-store.mjs +20 -0
  70. package/src/telemetry.mjs +267 -0
  71. package/src/termination.mjs +28 -0
  72. package/src/threads.mjs +150 -0
  73. package/src/usage-queue.mjs +137 -0
  74. package/src/verify-ssss.mjs +102 -0
  75. package/src/worker.mjs +955 -84
  76. package/src/worktree.mjs +244 -0
  77. package/ui/chunks/adapter-docs-freshness.md +16 -0
  78. package/ui/chunks/chat-handoff.md +26 -0
  79. package/ui/chunks/fleet-maintenance.md +21 -0
  80. package/ui/chunks/harness-inventory.md +21 -0
  81. package/ui/chunks/included-access.md +18 -0
  82. package/ui/chunks/included-usage-verification.md +15 -0
  83. package/ui/chunks/independent-review.md +17 -0
  84. package/ui/chunks/managed-execution.md +20 -0
  85. package/ui/chunks/official-documentation.md +18 -0
  86. package/ui/chunks/quota-recovery.md +21 -0
  87. package/ui/chunks/review-routing-decision.md +16 -0
  88. package/ui/chunks/route-work.md +18 -0
  89. package/ui/chunks/routing-evidence.md +18 -0
  90. package/ui/chunks/run-ledger.md +18 -0
  91. package/ui/chunks/session-controls.md +16 -0
  92. package/ui/home.js +198 -0
  93. package/ui/DESIGN.md +0 -32
  94. package/ui/card.js +0 -845
package/src/executor.mjs CHANGED
@@ -1,9 +1,14 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { pathToFileURL } from 'node:url';
4
- import { runWorker, runProcess, getActiveAdapters } from './worker.mjs';
4
+ import { runWorker, runProcess, getActiveAdapters, notReady, agentEnvironment } from './worker.mjs';
5
+ import { dispatchWithReceipt } from './dispatch.mjs';
6
+ import { commandPermissions, destinationDispatchRequest } from './dispatch-request.mjs';
7
+ import { readIncludedPolicy } from './included-usage.mjs';
5
8
 
6
- async function hostModule(name) {
9
+ export { DEFAULT_PERMISSIONS, commandPermissions } from './dispatch-request.mjs';
10
+
11
+ export async function hostModule(name) {
7
12
  const selected = process.env.TR_PACKAGE_ROOT;
8
13
  if (!selected || !path.isAbsolute(selected)) throw new Error('Verified native Total Recall host required');
9
14
  const root = fs.realpathSync(selected);
@@ -11,13 +16,6 @@ async function hostModule(name) {
11
16
  return import(pathToFileURL(path.join(root, 'src/core', `${name}.mjs`)).href);
12
17
  }
13
18
 
14
- export const DEFAULT_PERMISSIONS = Object.freeze({ read: true, write: false, send: false, destructive: false });
15
- export function commandPermissions(value = DEFAULT_PERMISSIONS) {
16
- if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('Command permissions must be boolean values');
17
- for (const key of Object.keys(value)) if (!Object.hasOwn(DEFAULT_PERMISSIONS, key) || typeof value[key] !== 'boolean') throw new Error(`Invalid permission ${key}`);
18
- return { ...DEFAULT_PERMISSIONS, ...value };
19
- }
20
-
21
19
  export async function listTargets() {
22
20
  try {
23
21
  const mesh = await hostModule('mesh');
@@ -26,40 +24,118 @@ export async function listTargets() {
26
24
  nodes: nodes.length > 0 ? nodes : [{ id: 'local', name: 'Local Host', online: true, self: true, accessConfigured: true }],
27
25
  adapters: getActiveAdapters().map(({ id, name, docs, custom }) => ({ id, name, docs, custom: Boolean(custom) }))
28
26
  };
29
- } catch {
27
+ } catch (error) {
30
28
  return {
31
29
  nodes: [{ id: 'local', name: 'Local Host', online: true, self: true, accessConfigured: true }],
32
- adapters: getActiveAdapters().map(({ id, name, docs, custom }) => ({ id, name, docs, custom: Boolean(custom) }))
30
+ adapters: getActiveAdapters().map(({ id, name, docs, custom }) => ({ id, name, docs, custom: Boolean(custom) })),
31
+ meshError: String(error?.message || error).slice(0, 400),
33
32
  };
34
33
  }
35
34
  }
36
35
 
37
36
  export function workerProgram(request) {
38
- const source = fs.readFileSync(new URL('./worker.mjs', import.meta.url), 'utf8');
39
- return source + '\nrunWorker(' + JSON.stringify(request) + ').then(result=>console.log(JSON.stringify(result))).catch(()=>{console.error("Selected agent worker failed");process.exitCode=1;});\n';
37
+ // Materialize a portable module graph. The stdin launcher imports only Node
38
+ // built-ins. Relative imports resolve inside this owned bundle on the node.
39
+ const names = ['worker.mjs', 'control.mjs', 'jobs.mjs', 'paths.mjs', 'mcp-server.mjs', 'agent-user.mjs', 'worktree.mjs', 'ssss-store.mjs',
40
+ ...fs.readdirSync(new URL('./session/', import.meta.url)).filter(name => name.endsWith('.mjs')).map(name => `session/${name}`)];
41
+ const files = Object.fromEntries(names.map(name => [name, fs.readFileSync(new URL(name, import.meta.url), 'utf8')]));
42
+ return `import fs from 'node:fs';
43
+ import os from 'node:os';
44
+ import path from 'node:path';
45
+ import { pathToFileURL } from 'node:url';
46
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'metaharness-worker-'));
47
+ try {
48
+ for (const [name, source] of Object.entries(${JSON.stringify(files)})) {
49
+ const file = path.join(directory, name);
50
+ fs.mkdirSync(path.dirname(file), { recursive: true });
51
+ fs.writeFileSync(file, source, { mode: 0o600 });
52
+ }
53
+ const { runWorker } = await import(pathToFileURL(path.join(directory, 'worker.mjs')).href);
54
+ console.log(JSON.stringify(await runWorker(${JSON.stringify(request)})));
55
+ } catch (error) { console.error(String(error?.message || 'Selected agent worker failed')); process.exitCode = 1; }
56
+ finally { fs.rmSync(directory, { recursive: true, force: true }); }
57
+ `;
58
+
59
+ }
60
+
61
+ function destinationDispatchResult(result, node, request) {
62
+ let payload;
63
+ try { payload = JSON.parse(result.output); } catch { /* No structured result from the installed owner. */ }
64
+ if (!payload || typeof payload.ok !== 'boolean' || (payload.ok && !result.ok)) {
65
+ throw notReady(`Installed Metaharness on ${node} returned no valid dispatch outcome (exit ${result.exitCode ?? 'unknown'})`);
66
+ }
67
+ return { ...payload, execution: { node, workspace: request.cwd, remote: true,
68
+ ...(typeof payload.receiptId === 'string' ? { receiptOwner: 'destination' } : {}) } };
40
69
  }
41
70
 
42
71
  export async function executeOnNode(node, request, { worker = runWorker, processRunner = runProcess, mesh, access } = {}) {
43
72
  if (!node || node === 'local') return worker(request);
44
- mesh ||= await hostModule('mesh'); access ||= await hostModule('mesh-access');
73
+ mesh ||= await hostModule('mesh');
45
74
  const target = mesh.findMeshNode(node);
46
75
  if (!target) throw new Error('Selected mesh node is not recorded');
47
- if (target.self) return worker(request);
76
+ if (target.self && request.operation !== 'dispatch') return worker(request);
77
+ // Route simple dispatch through the installed owner, just like a routed, coordinated or managed job.
78
+ const dispatch = request.operation === 'dispatch';
79
+ let transport = request;
80
+ if (dispatch) {
81
+ const input = JSON.stringify(destinationDispatchRequest(request));
82
+ if (Buffer.byteLength(input) > 65536) throw new Error('Remote dispatch request is too large');
83
+ // The transport outlives the attempt it carries by a minute, so the destination reports its own timeout (A-101).
84
+ transport = { operation: 'direct', cwd: request.cwd, argv: ['total-recall', 'meta-harness', 'dispatch', '--stdin', '--json'], input,
85
+ timeoutMs: Number.isInteger(request.timeoutMs) && request.timeoutMs > 0 ? request.timeoutMs + 60_000 : 600000 };
86
+ }
87
+ const managed = dispatch || (transport.argv?.[1] === 'meta-harness' &&
88
+ ['route', 'coordinate', 'review', 'process', 'run-command', 'usage-retry'].includes(transport.argv[2]));
89
+ if (managed && (await readIncludedPolicy()).enabled) transport = { ...transport, requireIncluded: true };
90
+ if (target.self) {
91
+ const result = destinationDispatchResult(await worker(transport), 'local', request);
92
+ result.execution.remote = false;
93
+ return result;
94
+ }
48
95
  if (target.online === false) throw new Error('Selected mesh node is offline');
96
+ access ||= await hostModule('mesh-access');
49
97
  const resolved = access.resolveNodeAccess(target);
50
98
  const args = access.buildSshArgs(resolved, { command: 'export PATH="$HOME/.local/bin:/opt/homebrew/bin:/usr/local/bin:$PATH"; exec node --input-type=module', extraOptions: ['BatchMode=yes', 'ConnectTimeout=10'] });
51
99
  if (!args) throw new Error('Selected mesh node has no verified SSH access');
52
- const result = await processRunner('ssh', args, { input: workerProgram(request), timeoutMs: request.operation === 'inspect' ? 120000 : 330000 });
53
- if (result.reason || result.exitCode !== 0) throw new Error('Selected mesh worker failed; verify node access, workspace and agent installation');
54
- try { return JSON.parse(result.stdout); } catch { throw new Error('Selected mesh worker returned invalid data'); }
100
+ const result = await processRunner('ssh', args, { input: workerProgram(transport), timeoutMs: transport.operation === 'inspect' ? 120000 : (transport.timeoutMs || 900000) + 30000, maxBytes: 17 * 1024 * 1024, env: { ...agentEnvironment(), ...(process.env.SSH_AUTH_SOCK ? { SSH_AUTH_SOCK: process.env.SSH_AUTH_SOCK } : {}) } });
101
+ if (result.reason || result.exitCode !== 0) throw notReady(`Worker on ${node} failed: ${String(result.stderr || result.reason || 'verify node access, workspace and agent installation').trim().slice(0, 400)}`);
102
+ let payload;
103
+ try { payload = JSON.parse(result.stdout); } catch { throw new Error('Selected mesh worker returned invalid data'); }
104
+ return dispatch ? destinationDispatchResult(payload, target.hostname || node, request) : payload;
55
105
  }
56
106
 
57
107
  export async function inspectNode(node = 'local', dependencies) {
58
- return executeOnNode(node, { operation: 'inspect' }, dependencies);
108
+ let inspectOptions;
109
+ if (!node || node === 'local') {
110
+ try {
111
+ const policy = await readIncludedPolicy();
112
+ const openRouterAgents = Object.keys(policy.openRouter || {});
113
+ inspectOptions = { openRouterAgents };
114
+ if (policy.claudeToken?.keyName && policy.claudeToken?.fingerprint) {
115
+ const { readClaudeToken } = await import('./included-usage.mjs');
116
+ const token = await readClaudeToken(policy.claudeToken.keyName);
117
+ if (token) inspectOptions.claudeToken = token;
118
+ }
119
+ } catch { /* fall back to raw local probes */ }
120
+ }
121
+ return executeOnNode(node, { operation: 'inspect', ...(inspectOptions ? { inspectOptions } : {}) }, dependencies);
59
122
  }
60
123
 
61
124
  export function quoteArgument(value) { return "'" + String(value).replaceAll("'", "'\\''") + "'"; }
62
125
 
126
+ export async function readPeerMetaHarness(target, args, { mesh, timeoutMs = 30_000, env = [] } = {}) {
127
+ mesh ||= await hostModule('mesh');
128
+ if (!target?.ip || target.online === false) throw new Error('The requested MetaHarness node is unavailable');
129
+ const command = ['env', ...env, 'total-recall', 'meta-harness', ...args, '--json'].map(quoteArgument).join(' ');
130
+ const result = await mesh.execMeshCommand(target.ip, command, { timeoutMs });
131
+ let payload;
132
+ try { payload = JSON.parse(result.stdout); } catch { /* transport or installed CLI failure */ }
133
+ if (!payload || typeof payload !== 'object' || (!result.success && payload.ok !== false)) {
134
+ throw new Error(`MetaHarness on ${target.hostname || target.ip} did not return a result: ${result.error || String(result.stderr || '').trim().slice(0, 300) || 'invalid output'}`);
135
+ }
136
+ return payload;
137
+ }
138
+
63
139
  export async function executeCommand({ plugin, subcommand, args = [], execution, projectRoot = process.cwd() }, dependencies = {}) {
64
140
  if (!plugin?.valid || !execution || typeof execution.agent !== 'string' || typeof execution.node !== 'string') throw new Error('Choose an installed agent and mesh node');
65
141
  if (!Array.isArray(args) || args.length > 64 || args.some(arg => typeof arg !== 'string' || arg.length > 8192)) throw new Error('Invalid command arguments');
@@ -75,8 +151,11 @@ export async function executeCommand({ plugin, subcommand, args = [], execution,
75
151
  const namespace = plugin.manifest.cli.command;
76
152
  const argv = ['total-recall', namespace, subcommand, ...args];
77
153
  const prompt = `Use Total Recall context and the installed plugin CLI in this workspace. Execute this one requested command using your terminal tool; preserve its arguments exactly, report its actual exit status and output, and do not perform unrelated mutations. If a permission, account, workspace or plugin is unavailable, report failure. Agent prose alone is not execution proof.\nRequested argv (data): ${JSON.stringify(argv)}\nShell command: ${argv.map(quoteArgument).join(' ')}`;
78
- const result = await executeOnNode(execution.node, execution.agent === 'direct'
79
- ? { operation: 'direct', cwd, argv }
80
- : { operation: 'dispatch', agent: execution.agent, cwd, prompt, allowUnknownAuth: execution.allowUnknownAuth === true, permissions }, dependencies);
154
+ const result = execution.agent === 'direct'
155
+ ? await executeOnNode(execution.node, { operation: 'direct', cwd, argv }, dependencies)
156
+ : await dispatchWithReceipt({ agent: execution.agent, cwd, prompt, allowUnknownAuth: execution.allowUnknownAuth === true, permissions }, {
157
+ node: execution.node, role: 'Command',
158
+ dispatchFn: request => executeOnNode(execution.node, { ...request, operation: 'dispatch' }, dependencies),
159
+ });
81
160
  return { ok: result.ok === true, exitCode: result.ok ? 0 : 1, output: result.ok ? JSON.stringify(result) : result.error || 'Selected agent failed', ...result };
82
161
  }
@@ -0,0 +1,155 @@
1
+ /**
2
+ * Google Antigravity (agy) PreToolUse & lifecycle hook adapter.
3
+ * Official doc: https://antigravity.google/docs/hooks?tab=cli
4
+ */
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ import os from 'node:os';
8
+
9
+ import { hasGate, mergeGate, readJsonFile, readJsonQuietly, writeJsonFile } from './hook-files.mjs';
10
+
11
+ const ACK_COMMAND = 'total-recall tr-preflight --ack --task "<task>" --action read,edit,test';
12
+
13
+ const HOOK_NAME = 'total-recall-preflight';
14
+
15
+ export const agyAdapter = {
16
+ id: 'agy',
17
+ aliases: ['antigravity'],
18
+ level: 'enforced',
19
+ warnings: {
20
+ delivery: 'documented',
21
+ via: 'reason',
22
+ source: 'agy-customizations/docs/hooks.md, bundled with the CLI',
23
+ },
24
+ source: {
25
+ url: 'https://antigravity.google/docs/hooks?tab=cli',
26
+ retrieved: '2026-11-04',
27
+ note: 'Antigravity CLI hooks in ~/.gemini/config/hooks.json or .agents/hooks.json'
28
+ },
29
+ readablePaths: [
30
+ /\/\.gemini\/antigravity\/brain\/[^/]+\/\.system_generated\/tasks\/[^/]+\.log$/,
31
+ /\/\.gemini\/antigravity\/brain\/[^/]+\/\.system_generated\/steps\/[^/]+\/output\.txt$/
32
+ ],
33
+ limits: [
34
+ 'Hooks receive camelCase toolCall fields: toolCall.name and toolCall.args',
35
+ 'PreToolUse blocks execution with decision: "deny" and exit code 2'
36
+ ],
37
+
38
+ parse(input = {}) {
39
+ const event = input.event || input.hookEventName || 'PreToolUse';
40
+ const toolCall = input.toolCall || {};
41
+ const name = toolCall.name || input.toolName || input.tool_name || '';
42
+ const args = toolCall.args || input.toolArgs || input.tool_input || {};
43
+ const cwd = input.cwd || input.workspacePaths?.[0] || process.cwd();
44
+
45
+ let tool = 'other';
46
+ let command;
47
+ let filePath;
48
+
49
+ if (name === 'run_command' || name === 'Bash') {
50
+ tool = 'shell';
51
+ command = args.CommandLine || args.command || '';
52
+ } else if (name === 'read_file' || name === 'view_file' || /^(Read|Glob|Grep)$/.test(name)) {
53
+ tool = 'read';
54
+ filePath = args.Path || args.file_path || args.path || '';
55
+ } else if (name === 'write_file' || name === 'edit_file' || /^(Edit|Write)$/.test(name)) {
56
+ tool = 'write';
57
+ filePath = args.Path || args.file_path || args.path || '';
58
+ } else if (name === 'search_web' || /^(WebFetch|WebSearch)$/.test(name)) {
59
+ tool = 'web';
60
+ } else if (/^(ask_question|show_message|manage_task)$/.test(name)) {
61
+ tool = 'meta';
62
+ } else if (/^(invoke_subagent|send_message|manage_subagents)$/.test(name)) {
63
+ tool = 'agent';
64
+ }
65
+
66
+ return {
67
+ event,
68
+ tool,
69
+ command,
70
+ path: filePath,
71
+ cwd,
72
+ raw: input
73
+ };
74
+ },
75
+
76
+ emit(decision, event, cwd = process.cwd()) {
77
+ if (decision?.decision === 'allow') {
78
+ // `allow` means automatic approval here, and the gate must not approve commands or edits.
79
+ // `ask` leaves the user's normal prompt and "Always Allow" choices in charge. A run Meta
80
+ // Harness started has already chosen its permission mode, and reads need no approval.
81
+ const answer = process.env.TR_META_HARNESS_RUN || decision.readOnly ? 'allow' : 'ask';
82
+ const payload = decision.warning ? { decision: answer, reason: decision.warning } : { decision: answer };
83
+ return { stdout: `${JSON.stringify(payload)}\n`, exitCode: 0 };
84
+ }
85
+
86
+ const reason = decision?.reason || `TR-PREFLIGHT gate: action denied. Run: ${decision?.fix || ACK_COMMAND}`;
87
+ const payload = {
88
+ decision: 'deny',
89
+ reason,
90
+ fix: decision?.fix || ACK_COMMAND
91
+ };
92
+ return { stdout: `${JSON.stringify(payload)}\n`, exitCode: 2 };
93
+ },
94
+
95
+ async run({ stdin, decideWith }) {
96
+ const parsed = this.parse(stdin);
97
+ const decision = decideWith({
98
+ tool: parsed.tool,
99
+ command: parsed.command,
100
+ path: parsed.path,
101
+ cwd: parsed.cwd
102
+ });
103
+ return this.emit({ ...decision, readOnly: ['read', 'search', 'web', 'meta', 'ui', 'agent'].includes(parsed.tool) }, parsed.event, parsed.cwd);
104
+ },
105
+
106
+ install({ home = os.homedir(), dryRun = false, remove = false, off = false } = {}) {
107
+ const hooksPath = path.join(home, '.gemini', 'config', 'hooks.json');
108
+ const config = readJsonFile(hooksPath, {});
109
+ // Top-level keys are hook names. Earlier installs wrote a hook called "hooks" with entries
110
+ // Antigravity skips.
111
+ const stale = mergeGate(config.hooks?.PreToolUse, 'agy', { remove: true });
112
+ const removed = stale.removed;
113
+ if (config.hooks) {
114
+ config.hooks.PreToolUse = stale.groups;
115
+ if (!config.hooks.PreToolUse.length) delete config.hooks.PreToolUse;
116
+ if (!Object.keys(config.hooks).length) delete config.hooks;
117
+ }
118
+ const current = config[HOOK_NAME]?.PreToolUse;
119
+ const { groups, added, removed: gone } = mergeGate(current, 'agy', { remove: remove || off });
120
+ removed.push(...gone);
121
+ const lifecycle = [
122
+ ['SessionStart', 'total-recall preflight session-start --harness agy'],
123
+ ];
124
+ const nextHook = groups.length ? { ...(config[HOOK_NAME] || {}), PreToolUse: groups } : {};
125
+ delete nextHook.PreInvocation;
126
+ for (const [event, cmd] of lifecycle) {
127
+ const existing = Array.isArray(config[HOOK_NAME]?.[event]) ? config[HOOK_NAME][event] : [];
128
+ const kept = existing.filter((h) => !String(h?.command || '').includes('total-recall preflight '));
129
+ if (remove || off) {
130
+ if (kept.length !== existing.length) removed.push(cmd);
131
+ if (kept.length) nextHook[event] = kept;
132
+ } else {
133
+ if (!existing.some((h) => h?.command === cmd)) added.push(cmd);
134
+ nextHook[event] = [...kept, { type: 'command', command: cmd, timeout: 10 }];
135
+ }
136
+ }
137
+ if (Object.keys(nextHook).length) config[HOOK_NAME] = nextHook;
138
+ else delete config[HOOK_NAME];
139
+ if (!dryRun && (added.length || removed.length)) writeJsonFile(hooksPath, config);
140
+ return { settings: hooksPath, added, removed };
141
+ },
142
+
143
+ verify({ home = os.homedir() } = {}) {
144
+ const installed = hasGate(readJsonQuietly(path.join(home, '.gemini', 'config', 'hooks.json'))[HOOK_NAME]?.PreToolUse, 'agy');
145
+ const out = this.emit({ decision: 'deny', reason: 'receipt missing', fix: ACK_COMMAND }, 'PreToolUse', '/nonexistent-directory-without-receipt');
146
+ return {
147
+ installed,
148
+ exercised: out.exitCode === 2 && out.stdout.includes('"decision":"deny"'),
149
+ level: this.level,
150
+ native: out.stdout.trim()
151
+ };
152
+ }
153
+ };
154
+
155
+ export default agyAdapter;
@@ -0,0 +1,303 @@
1
+ /**
2
+ * Claude Code PreToolUse & UserPromptSubmit adapter.
3
+ * Official doc: https://docs.anthropic.com/en/docs/agents-and-tools/claude-code/overview
4
+ */
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ import os from 'node:os';
8
+
9
+ const ACK_COMMAND = 'total-recall tr-preflight --ack --task "<task>" --action read,edit,test';
10
+
11
+ export const claudeAdapter = {
12
+ id: 'claude',
13
+ level: 'enforced',
14
+ warnings: {
15
+ delivery: 'documented',
16
+ via: 'hookSpecificOutput.additionalContext',
17
+ source: 'https://code.claude.com/docs/en/hooks.md',
18
+ },
19
+ source: {
20
+ url: 'https://docs.anthropic.com/en/docs/agents-and-tools/claude-code/overview',
21
+ retrieved: '2026-11-04',
22
+ note: 'Claude Code hook configuration in settings.json with PreToolUse and UserPromptSubmit'
23
+ },
24
+ readablePaths: [
25
+ /\/\.claude\/projects\/[^/]+\/[^/]+\/tool-results\/[^/]+$/
26
+ ],
27
+ limits: [
28
+ 'UserPromptSubmit hook is advisory-only per ENFORCE-R1 and never blocks turn',
29
+ 'PreToolUse blocks tool executions with exit 2 or permissionDecision: "deny"'
30
+ ],
31
+
32
+ /**
33
+ * Parse Claude Code native hook JSON from stdin into normalized shape:
34
+ * { event, tool, command, path, cwd }
35
+ */
36
+ parse(input = {}) {
37
+ const event = input.hook_event_name || (input.tool_name ? 'PreToolUse' : 'UserPromptSubmit');
38
+ const toolName = input.tool_name || '';
39
+ const cwd = input.cwd || process.cwd();
40
+ const toolInput = input.tool_input || {};
41
+
42
+ let tool = 'other';
43
+ let command;
44
+ let filePath;
45
+
46
+ if (toolName === 'Bash') {
47
+ tool = 'shell';
48
+ command = toolInput.command || '';
49
+ } else if (/^(Read|Glob|Grep)$/.test(toolName)) {
50
+ tool = 'read';
51
+ filePath = toolInput.file_path || toolInput.path || toolInput.pattern || '';
52
+ } else if (/^(Edit|Write|MultiEdit|NotebookEdit)$/.test(toolName)) {
53
+ tool = 'write';
54
+ filePath = toolInput.file_path || toolInput.notebook_path || '';
55
+ } else if (/^(WebFetch|WebSearch)$/.test(toolName)) {
56
+ tool = 'web';
57
+ } else if (/^mcp__ccd_turn__/.test(toolName)) {
58
+ tool = 'ui';
59
+ } else if (/^mcp__ccd_(session|session_mgmt)__/.test(toolName)) {
60
+ tool = 'agent';
61
+ } else if (/^mcp__/.test(toolName)) {
62
+ tool = 'mcp';
63
+ } else if (/^(Agent|Task|SendMessage|ListAgents)$/.test(toolName)) {
64
+ tool = 'agent';
65
+ } else if (/^(ToolSearch|Skill|AskUserQuestion|TodoWrite|ExitPlanMode|EnterPlanMode)$/.test(toolName)) {
66
+ tool = 'meta';
67
+ }
68
+
69
+ return {
70
+ event,
71
+ tool,
72
+ command,
73
+ path: filePath,
74
+ cwd,
75
+ raw: input
76
+ };
77
+ },
78
+
79
+ /**
80
+ * Emit Claude Code native response: { stdout, exitCode }
81
+ */
82
+ emit(decision, event, cwd = process.cwd()) {
83
+ if (event === 'UserPromptSubmit') {
84
+ // ENFORCE-R1: Prompt hooks never block
85
+ if (decision?.decision === 'deny') {
86
+ const payload = {
87
+ hookSpecificOutput: {
88
+ hookEventName: 'UserPromptSubmit',
89
+ additionalContext: `TR-PREFLIGHT FAILED for ${cwd}: ${decision.reason || 'check failed'}. Run this on its own, with nothing piped, chained or redirected, and read everything it prints: ${decision.fix || ACK_COMMAND}`
90
+ }
91
+ };
92
+ return { stdout: `${JSON.stringify(payload)}\n`, exitCode: 0 };
93
+ }
94
+ return { stdout: '', exitCode: 0 };
95
+ }
96
+
97
+ // PreToolUse. permissionDecision stays unset: a warning must not approve the call.
98
+ if (decision?.decision === 'allow') {
99
+ if (decision.warning) {
100
+ const payload = { hookSpecificOutput: { hookEventName: 'PreToolUse', additionalContext: decision.warning } };
101
+ return { stdout: `${JSON.stringify(payload)}\n`, exitCode: 0 };
102
+ }
103
+ return { stdout: '', exitCode: 0 };
104
+ }
105
+
106
+ // Denied
107
+ const payload = {
108
+ hookSpecificOutput: {
109
+ hookEventName: 'PreToolUse',
110
+ permissionDecision: 'deny',
111
+ permissionDecisionReason: decision?.reason || `TR-PREFLIGHT gate: action denied. Run: ${decision?.fix || ACK_COMMAND}`
112
+ }
113
+ };
114
+ return { stdout: `${JSON.stringify(payload)}\n`, exitCode: 2 };
115
+ },
116
+
117
+ /**
118
+ * Run the gate pipeline for Claude Code
119
+ */
120
+ async run({ stdin, decideWith }) {
121
+ const parsed = this.parse(stdin);
122
+ const decision = decideWith({
123
+ tool: parsed.tool,
124
+ command: parsed.command,
125
+ path: parsed.path,
126
+ cwd: parsed.cwd
127
+ });
128
+ return this.emit(decision, parsed.event, parsed.cwd);
129
+ },
130
+
131
+ /**
132
+ * Install Claude Code managed hooks in settings.json, removing the stopgap
133
+ */
134
+ install({ home = os.homedir(), dryRun = false, remove = false, off = false } = {}) {
135
+ const isRemove = remove || off;
136
+ const claudeDir = path.join(home, '.claude');
137
+ const settingsPath = path.join(claudeDir, 'settings.json');
138
+ const stopgapPath = path.join(claudeDir, 'hooks', 'total-recall-preflight.mjs');
139
+ const added = [];
140
+ const removed = [];
141
+
142
+ let settings = {};
143
+ if (fs.existsSync(settingsPath)) {
144
+ try {
145
+ settings = JSON.parse(fs.readFileSync(settingsPath, 'utf8') || '{}');
146
+ } catch (err) {
147
+ throw new Error(`${settingsPath} is not valid JSON; fix it before installing hooks: ${err.message}`);
148
+ }
149
+ }
150
+
151
+ const hooks = settings.hooks || (settings.hooks = {});
152
+
153
+ if (isRemove) {
154
+ for (const event of ['PreToolUse', 'UserPromptSubmit', 'SessionStart', 'PostToolUse']) {
155
+ if (Array.isArray(hooks[event])) {
156
+ const beforeLen = hooks[event].length;
157
+ hooks[event] = hooks[event].filter(entry => {
158
+ const subHooks = entry.hooks || [];
159
+ return !subHooks.some(h => String(h.command || '').includes('preflight') || String(h.command || '').includes('total-recall-preflight'));
160
+ });
161
+ if (hooks[event].length < beforeLen) {
162
+ removed.push(`managed ${event} hook entry`);
163
+ }
164
+ }
165
+ }
166
+ if (!dryRun && (removed.length || fs.existsSync(settingsPath))) {
167
+ fs.writeFileSync(settingsPath, `${JSON.stringify(settings, null, 2)}\n`);
168
+ }
169
+ return { settings: settingsPath, added: [], removed };
170
+ }
171
+
172
+ // 1. Remove stopgap references if present
173
+ for (const event of ['PreToolUse', 'UserPromptSubmit', 'SessionStart', 'PostToolUse']) {
174
+ if (Array.isArray(hooks[event])) {
175
+ const beforeLen = hooks[event].length;
176
+ hooks[event] = hooks[event].filter(entry => {
177
+ const subHooks = entry.hooks || [];
178
+ return !subHooks.some(h => String(h.command || '').includes('total-recall-preflight.mjs'));
179
+ });
180
+ if (hooks[event].length < beforeLen) {
181
+ removed.push(`stopgap ${event} hook entry`);
182
+ }
183
+ }
184
+ }
185
+
186
+ // Remove stopgap file on disk if not dryRun
187
+ if (!dryRun && fs.existsSync(stopgapPath)) {
188
+ try {
189
+ fs.unlinkSync(stopgapPath);
190
+ removed.push('total-recall-preflight.mjs file');
191
+ } catch { /* ignore */ }
192
+ }
193
+
194
+ // 2. Add managed preflight gate entries
195
+ const gateCommand = 'total-recall preflight gate --harness claude';
196
+ const remindCommand = 'total-recall preflight remind';
197
+
198
+ // PreToolUse: match all tools
199
+ hooks.PreToolUse = hooks.PreToolUse || [];
200
+ const hasPreTool = hooks.PreToolUse.some(e =>
201
+ (e.hooks || []).some(h => String(h.command || '').includes('preflight gate --harness claude'))
202
+ );
203
+ if (!hasPreTool) {
204
+ hooks.PreToolUse.push({
205
+ matcher: '*',
206
+ hooks: [{
207
+ type: 'command',
208
+ command: gateCommand,
209
+ timeout: 5
210
+ }]
211
+ });
212
+ added.push('managed PreToolUse gate');
213
+ }
214
+
215
+ // UserPromptSubmit: advisory reminder
216
+ hooks.UserPromptSubmit = hooks.UserPromptSubmit || [];
217
+ const hasPrompt = hooks.UserPromptSubmit.some(e =>
218
+ (e.hooks || []).some(h => String(h.command || '').includes('preflight remind'))
219
+ );
220
+ if (!hasPrompt) {
221
+ hooks.UserPromptSubmit.push({
222
+ hooks: [{
223
+ type: 'command',
224
+ command: remindCommand,
225
+ timeout: 5
226
+ }]
227
+ });
228
+ added.push('managed UserPromptSubmit reminder');
229
+ }
230
+
231
+ // SessionStart: a compacted or cleared session no longer has its capsule, so the next ack prints it
232
+ hooks.SessionStart = hooks.SessionStart || [];
233
+ const hasSessionStart = hooks.SessionStart.some(e =>
234
+ (e.hooks || []).some(h => String(h.command || '').includes('preflight session-start'))
235
+ );
236
+ if (!hasSessionStart) {
237
+ hooks.SessionStart.push({
238
+ matcher: 'compact|clear',
239
+ hooks: [{
240
+ type: 'command',
241
+ command: 'total-recall preflight session-start',
242
+ timeout: 5
243
+ }]
244
+ });
245
+ added.push('managed SessionStart capsule reset');
246
+ }
247
+
248
+ if (!dryRun && (added.length || removed.length)) {
249
+ fs.mkdirSync(claudeDir, { recursive: true });
250
+ if (fs.existsSync(settingsPath)) {
251
+ fs.copyFileSync(settingsPath, `${settingsPath}.bak-total-recall`);
252
+ }
253
+ fs.writeFileSync(settingsPath, `${JSON.stringify(settings, null, 2)}\n`);
254
+ }
255
+
256
+ return { settings: settingsPath, added, removed };
257
+ },
258
+
259
+ /**
260
+ * Verify installed hook with a synthetic denied tool call
261
+ */
262
+ verify({ home = os.homedir() } = {}) {
263
+ const settingsPath = path.join(home, '.claude', 'settings.json');
264
+ if (!fs.existsSync(settingsPath)) {
265
+ return { installed: false, exercised: false, reason: 'settings.json not found' };
266
+ }
267
+ let settings;
268
+ try {
269
+ settings = JSON.parse(fs.readFileSync(settingsPath, 'utf8') || '{}');
270
+ } catch {
271
+ return { installed: false, exercised: false, reason: 'settings.json is unparseable' };
272
+ }
273
+ const preHooks = settings.hooks?.PreToolUse || [];
274
+ const installed = preHooks.some(e =>
275
+ (e.hooks || []).some(h => String(h.command || '').includes('preflight gate --harness claude'))
276
+ );
277
+
278
+ // Exercise with synthetic denied payload
279
+ const syntheticDeniedCall = {
280
+ hook_event_name: 'PreToolUse',
281
+ tool_name: 'Bash',
282
+ tool_input: { command: 'git status' },
283
+ cwd: '/nonexistent-directory-without-receipt'
284
+ };
285
+
286
+ const out = this.emit(
287
+ { decision: 'deny', reason: 'receipt missing', fix: ACK_COMMAND },
288
+ 'PreToolUse',
289
+ syntheticDeniedCall.cwd
290
+ );
291
+
292
+ const exercised = out.exitCode === 2 && out.stdout.includes('"permissionDecision":"deny"');
293
+
294
+ return {
295
+ installed,
296
+ exercised,
297
+ level: 'enforced',
298
+ native: out.stdout.trim()
299
+ };
300
+ }
301
+ };
302
+
303
+ export default claudeAdapter;