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,284 @@
1
+ /**
2
+ * DeepSeek Harness (DSH) PreToolUse hook adapter.
3
+ * Migrates legacy tr-first.sh / tr-wrapper.sh into managed preflight gate.
4
+ */
5
+ import { execFileSync } from 'node:child_process';
6
+ import fs from 'node:fs';
7
+ import path from 'node:path';
8
+ import os from 'node:os';
9
+
10
+ import { gateCommandWithPath, hasGate, mergeGate, readJsonFile, readJsonQuietly, writeJsonFile } from './hook-files.mjs';
11
+
12
+ const ACK_COMMAND = 'total-recall tr-preflight --ack --task "<task>" --action read,edit,test';
13
+
14
+ /**
15
+ * DSH homes in use by processes running now. A development build of the desktop app sets its own.
16
+ * The flags have no dash: on macOS a dashed -e means all processes and hides the environment.
17
+ */
18
+ function runningHomes() {
19
+ try {
20
+ const out = execFileSync('ps', ['axeww', '-o', 'command='], { encoding: 'utf8', maxBuffer: 64 * 1024 * 1024, stdio: ['ignore', 'pipe', 'ignore'], timeout: 3000 });
21
+ return [...new Set([...out.matchAll(/\bDSH_HOME=(\/[^\s]+)/g)].map((match) => match[1]))];
22
+ } catch { return []; }
23
+ }
24
+
25
+ /** The account's own home from the user database. `$HOME`, which os.homedir() follows, is also set by a sandbox. */
26
+ const accountHome = () => { try { return os.userInfo().homedir; } catch { return null; } };
27
+
28
+ /**
29
+ * Every DSH home to cover. DSH's default is ~/.dsh. A home set in the environment or in use by a
30
+ * running process is also covered, and remembered so it stays covered when it is not running.
31
+ * Only the real home folder looks at running processes, so an install into a temporary one
32
+ * cannot touch them. Removal never looks: every home it covered is remembered, and a sandboxed
33
+ * HOME passes the check above, so a test could otherwise strip a real home's gate.
34
+ */
35
+ function dshHomes(home, env, { scanProcesses = true } = {}) {
36
+ const record = path.join(home, '.dsh', 'hooks', 'other-homes.json');
37
+ const remembered = readJsonQuietly(record);
38
+ const others = new Set(Array.isArray(remembered) ? remembered : []);
39
+ if (env.DSH_HOME) others.add(path.resolve(env.DSH_HOME));
40
+ // The process list can hold any text, so a running process only counts if it names a real home.
41
+ if (scanProcesses && home === accountHome()) for (const dir of runningHomes()) if (fs.existsSync(path.join(dir, 'profiles'))) others.add(dir);
42
+ others.delete(path.join(home, '.dsh'));
43
+ const present = [...others].filter((dir) => fs.existsSync(dir));
44
+ return { record, others: present, all: [path.join(home, '.dsh'), ...present] };
45
+ }
46
+
47
+ /**
48
+ * The hook bridge's entry file. A profile cannot always resolve the package by name: a
49
+ * development build carries it only as a dev dependency, and the failure is a warning that
50
+ * leaves no gate. So the mount names the file. The desktop app keeps its runtime beside its
51
+ * home, and the command-line install carries the package inside its own folder.
52
+ */
53
+ function findBridge(dshHome, env) {
54
+ const roots = [path.join(path.dirname(dshHome), 'project', 'node_modules')];
55
+ for (const dir of String(env.PATH || '').split(path.delimiter)) {
56
+ if (!dir) continue;
57
+ try {
58
+ const packageRoot = path.dirname(path.dirname(fs.realpathSync(path.join(dir, 'dsh'))));
59
+ roots.push(path.join(packageRoot, 'node_modules'));
60
+ break;
61
+ } catch { /* not in this folder */ }
62
+ }
63
+ for (const root of roots) {
64
+ const entry = path.join(root, '@deepseek-ai', 'dsh-hooks-claude-code', 'lib', 'index.js');
65
+ if (fs.existsSync(entry)) return fs.realpathSync(entry);
66
+ }
67
+ return null;
68
+ }
69
+
70
+ const MOUNT = /(?:^|\n)# Runs the Total Recall gate in every profile\.\n- insert:\n - id: hooks-claude-code\n name: '[^'\n]*'\n config:\n configPath: [^\n]*\n/;
71
+
72
+ /**
73
+ * DSH runs hooks only through a bridge plugin that something mounts. The home patch applies to
74
+ * every profile and nothing regenerates it, unlike a profile's own patch, which can be generated.
75
+ */
76
+ function mountBridge(dshHome, hooksPath, entry, dryRun) {
77
+ const file = path.join(dshHome, 'cordis.patch.yml');
78
+ const text = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '';
79
+ const row = `# Runs the Total Recall gate in every profile.\n- insert:\n - id: hooks-claude-code\n name: '${entry}'\n config:\n configPath: ${hooksPath}\n`;
80
+ if (text.includes(row)) return [];
81
+ const rest = text.replace(MOUNT, '').replace(/\n*$/, '');
82
+ if (!dryRun) {
83
+ fs.mkdirSync(dshHome, { recursive: true });
84
+ fs.writeFileSync(file, rest ? `${rest}\n\n${row}` : row);
85
+ }
86
+ return [`hook bridge in ${file}`];
87
+ }
88
+
89
+ /** A mount an earlier release put in a profile's patch would mount the bridge twice. */
90
+ function removeProfileMount(dshHome, dryRun) {
91
+ const removed = [];
92
+ const root = path.join(dshHome, 'profiles');
93
+ let names = [];
94
+ try { names = fs.readdirSync(root); } catch { return removed; }
95
+ const row = /\n*# Runs the Total Recall gate in this profile\.\n- insert:\n - id: hooks-claude-code\n name: '@deepseek-ai\/dsh-hooks-claude-code'\n config:\n configPath: [^\n]*\n/;
96
+ for (const name of names) {
97
+ const file = path.join(root, name, 'cordis.patch.yml');
98
+ if (!fs.existsSync(file)) continue;
99
+ const text = fs.readFileSync(file, 'utf8');
100
+ if (!row.test(text)) continue;
101
+ if (!dryRun) fs.writeFileSync(file, text.replace(row, '\n'));
102
+ removed.push(`bridge mount in the ${name} profile`);
103
+ }
104
+ return removed;
105
+ }
106
+
107
+ /**
108
+ * DSH's PreToolUse hook can only block, but PostToolUse can attach context. A warning raised
109
+ * before a tool is held here under the call's id and handed over after it runs.
110
+ */
111
+ /**
112
+ * DSH's tool names, as it offers them to the model. A tool missing here counts as a working
113
+ * tool, so a read would need a receipt, including the read that earns the receipt.
114
+ */
115
+ const TOOL_CLASSES = {
116
+ bash: 'shell', Bash: 'shell', shell: 'shell',
117
+ read: 'read', Read: 'read', read_image: 'read', glob: 'read', Glob: 'read', grep: 'read', Grep: 'read',
118
+ edit: 'write', Edit: 'write', write: 'write', Write: 'write',
119
+ web_fetch: 'web', web_search: 'web',
120
+ subagent: 'agent', subagent_fork: 'agent', send_message: 'agent', list_agents: 'agent', interrupt_agent: 'agent', workflow: 'agent',
121
+ ask_user_question: 'meta', create_goal: 'meta', get_goal: 'meta', update_goal: 'meta', todo_write: 'meta', exit_plan_mode: 'meta',
122
+ skill: 'meta', working_directory: 'meta', job_list: 'meta', job_output: 'meta',
123
+ };
124
+
125
+ const notePath = (id) => path.join(os.tmpdir(), `tr-preflight-${os.userInfo().uid}`, 'dsh-notes', String(id).replace(/[^\w-]/g, '_'));
126
+
127
+ // DSH runs hooks in its sandbox, which refuses writes to the home folder. A note that cannot be
128
+ // held is lost, and that must never affect the tool call.
129
+ function holdNote(id, text) {
130
+ if (!id) return;
131
+ try {
132
+ const file = notePath(id);
133
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
134
+ fs.writeFileSync(file, text, { mode: 0o600 });
135
+ } catch { /* the warning is lost, the call still runs */ }
136
+ }
137
+
138
+ function takeNote(id) {
139
+ if (!id) return null;
140
+ const file = notePath(id);
141
+ try {
142
+ const text = fs.readFileSync(file, 'utf8');
143
+ fs.rmSync(file);
144
+ return text;
145
+ } catch { return null; }
146
+ }
147
+
148
+ export const dshAdapter = {
149
+ id: 'dsh',
150
+ level: 'enforced',
151
+ warnings: {
152
+ delivery: 'documented',
153
+ via: 'additionalContext on PostToolUse, after the tool runs',
154
+ source: 'deepseek-harness/packages/experimental/hooks-claude-code/README.md',
155
+ afterTool: true,
156
+ },
157
+ source: {
158
+ note: 'DeepSeek Harness hook configuration in ~/.dsh/hooks/hooks.json',
159
+ retrieved: '2026-11-04'
160
+ },
161
+ limits: [
162
+ 'Claude-compatible PreToolUse contract: exit code 2 blocks execution',
163
+ 'Repository sweep checks enforce Total Recall consult requirement'
164
+ ],
165
+
166
+ parse(input = {}) {
167
+ const event = input.hook_event_name || input.event || 'PreToolUse';
168
+ const toolName = input.tool_name || input.toolName || '';
169
+ const toolInput = input.tool_input || input.toolInput || {};
170
+ const cwd = input.cwd || process.cwd();
171
+
172
+ const tool = TOOL_CLASSES[toolName] || 'other';
173
+ let command;
174
+ let filePath;
175
+
176
+ if (tool === 'shell') command = toolInput.command || toolInput.cmd || '';
177
+ else if (tool === 'write' || tool === 'read') filePath = toolInput.file_path || toolInput.path || '';
178
+
179
+ return {
180
+ event,
181
+ tool,
182
+ command,
183
+ path: filePath,
184
+ cwd,
185
+ raw: input
186
+ };
187
+ },
188
+
189
+ emit(decision, event, cwd = process.cwd()) {
190
+ if (decision?.decision === 'allow') {
191
+ return { stdout: '', exitCode: 0 };
192
+ }
193
+
194
+ const reason = decision?.reason || `TR-PREFLIGHT gate: action denied. Run: ${decision?.fix || ACK_COMMAND}`;
195
+ const payload = {
196
+ decision: 'deny',
197
+ permissionDecision: 'deny',
198
+ reason,
199
+ fix: decision?.fix || ACK_COMMAND
200
+ };
201
+ return { stdout: `${JSON.stringify(payload)}\n`, exitCode: 2 };
202
+ },
203
+
204
+ async run({ stdin, decideWith }) {
205
+ const parsed = this.parse(stdin);
206
+ if (parsed.event === 'PostToolUse') {
207
+ const note = takeNote(stdin?.tool_use_id);
208
+ if (!note) return { stdout: '', exitCode: 0 };
209
+ const payload = { hookSpecificOutput: { hookEventName: 'PostToolUse', additionalContext: note } };
210
+ return { stdout: `${JSON.stringify(payload)}\n`, exitCode: 0 };
211
+ }
212
+ const decision = decideWith({
213
+ tool: parsed.tool,
214
+ command: parsed.command,
215
+ path: parsed.path,
216
+ cwd: parsed.cwd
217
+ });
218
+ if (decision?.decision === 'allow' && decision.warning) holdNote(stdin?.tool_use_id, decision.warning);
219
+ return this.emit(decision, parsed.event, parsed.cwd);
220
+ },
221
+
222
+ install({ home = os.homedir(), env = process.env, dryRun = false, remove = false, off = false } = {}) {
223
+ const homes = dshHomes(home, env, { scanProcesses: !(remove || off) });
224
+ const added = [];
225
+ const removed = [];
226
+ const command = gateCommandWithPath('dsh', env);
227
+ let settings = null;
228
+ const unmounted = [];
229
+ for (const dshHome of homes.all) {
230
+ const hooksPath = path.join(dshHome, 'hooks', 'hooks.json');
231
+ settings = settings || hooksPath;
232
+ const config = readJsonFile(hooksPath, { hooks: {} });
233
+ config.hooks = config.hooks || {};
234
+ const options = { remove: remove || off, command };
235
+ const before = mergeGate(config.hooks.PreToolUse, 'dsh', options);
236
+ const after = mergeGate(config.hooks.PostToolUse, 'dsh', options);
237
+ config.hooks.PreToolUse = before.groups;
238
+ config.hooks.PostToolUse = after.groups;
239
+ if (!dryRun && (before.added.length || before.removed.length || after.added.length || after.removed.length)) writeJsonFile(hooksPath, config);
240
+ added.push(...before.added, ...after.added.map(() => 'managed PostToolUse note delivery'));
241
+ removed.push(...before.removed, ...after.removed);
242
+ removed.push(...removeProfileMount(dshHome, dryRun));
243
+ if (remove || off) {
244
+ const patch = path.join(dshHome, 'cordis.patch.yml');
245
+ if (fs.existsSync(patch) && MOUNT.test(fs.readFileSync(patch, 'utf8'))) {
246
+ const rest = fs.readFileSync(patch, 'utf8').replace(MOUNT, '');
247
+ // DSH refuses to start on a patch file that is not a list, and an empty one is not.
248
+ if (!dryRun) { if (rest.trim()) fs.writeFileSync(patch, rest); else fs.rmSync(patch); }
249
+ removed.push(`hook bridge in ${patch}`);
250
+ }
251
+ continue;
252
+ }
253
+ const entry = findBridge(dshHome, env);
254
+ if (entry) added.push(...mountBridge(dshHome, hooksPath, entry, dryRun));
255
+ else unmounted.push(dshHome);
256
+ }
257
+ if (!dryRun && homes.others.length) writeJsonFile(homes.record, homes.others);
258
+ return {
259
+ settings,
260
+ added,
261
+ removed,
262
+ ...(unmounted.length ? { unsupported: `The DSH hook bridge package was not found for ${unmounted.join(', ')}, so the gate will not run there.` } : {})
263
+ };
264
+ },
265
+
266
+ verify({ home = os.homedir(), env = process.env } = {}) {
267
+ const installed = dshHomes(home, env).all.every((dshHome) => {
268
+ const hooks = readJsonQuietly(path.join(dshHome, 'hooks', 'hooks.json')).hooks;
269
+ const patch = path.join(dshHome, 'cordis.patch.yml');
270
+ return hasGate(hooks?.PreToolUse, 'dsh') && hasGate(hooks?.PostToolUse, 'dsh')
271
+ && fs.existsSync(patch) && MOUNT.test(fs.readFileSync(patch, 'utf8'));
272
+ });
273
+ const out = this.emit({ decision: 'deny', reason: 'receipt missing', fix: ACK_COMMAND }, 'PreToolUse', '/nonexistent-directory-without-receipt');
274
+ return {
275
+ installed,
276
+ exercised: out.exitCode === 2 && out.stdout.includes('"decision":"deny"'),
277
+ level: this.level,
278
+ native: out.stdout.trim()
279
+ };
280
+ }
281
+
282
+ };
283
+
284
+ export default dshAdapter;
@@ -0,0 +1,112 @@
1
+ /**
2
+ * xAI Grok Build CLI hook adapter.
3
+ * Official doc: https://docs.x.ai/build/features/hooks
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
+ export const grokAdapter = {
14
+ id: 'grok',
15
+ level: 'enforced (unverified live)',
16
+ warnings: {
17
+ delivery: 'none',
18
+ via: null,
19
+ source: 'https://docs.x.ai/build/features/hooks',
20
+ why: 'Exit 0 allows, and only a deny carries text.',
21
+ },
22
+ source: {
23
+ url: 'https://docs.x.ai/build/features/hooks',
24
+ retrieved: '2026-11-04',
25
+ note: 'Grok Build hooks in ~/.grok/hooks/ or .grok/hooks/'
26
+ },
27
+ limits: [
28
+ 'Timeouts, crashes and malformed outputs fail open in Grok Build',
29
+ 'Project-level hooks require trust in ~/.grok/trusted_folders.toml'
30
+ ],
31
+
32
+ parse(input = {}) {
33
+ const event = input.hookEventName || input.event || 'PreToolUse';
34
+ const toolName = input.toolName || input.tool_name || input.tool || '';
35
+ const toolInput = input.toolInput || input.tool_input || input.input || {};
36
+ const cwd = input.cwd || input.workspaceRoot || process.cwd();
37
+
38
+ let tool = 'other';
39
+ let command;
40
+ let filePath;
41
+
42
+ if (toolName === 'Bash' || toolName === 'exec' || toolName === 'shell') {
43
+ tool = 'shell';
44
+ command = toolInput.command || toolInput.cmd || '';
45
+ } else if (/^(Edit|Write)$/.test(toolName)) {
46
+ tool = 'write';
47
+ filePath = toolInput.file_path || toolInput.path || '';
48
+ } else if (/^(Read|Glob|Grep)$/.test(toolName)) {
49
+ tool = 'read';
50
+ filePath = toolInput.file_path || toolInput.path || '';
51
+ }
52
+
53
+ return {
54
+ event,
55
+ tool,
56
+ command,
57
+ path: filePath,
58
+ cwd,
59
+ raw: input
60
+ };
61
+ },
62
+
63
+ emit(decision, event, cwd = process.cwd()) {
64
+ if (decision?.decision === 'allow') {
65
+ const payload = { decision: 'allow' };
66
+ return { stdout: `${JSON.stringify(payload)}\n`, exitCode: 0 };
67
+ }
68
+
69
+ const reason = decision?.reason || `TR-PREFLIGHT gate: action denied. Run: ${decision?.fix || ACK_COMMAND}`;
70
+ const payload = {
71
+ decision: 'deny',
72
+ reason,
73
+ fix: decision?.fix || ACK_COMMAND
74
+ };
75
+ return { stdout: `${JSON.stringify(payload)}\n`, exitCode: 2 };
76
+ },
77
+
78
+ async run({ stdin, decideWith }) {
79
+ const parsed = this.parse(stdin);
80
+ const decision = decideWith({
81
+ tool: parsed.tool,
82
+ command: parsed.command,
83
+ path: parsed.path,
84
+ cwd: parsed.cwd
85
+ });
86
+ return this.emit(decision, parsed.event, parsed.cwd);
87
+ },
88
+
89
+ install({ home = os.homedir(), dryRun = false, remove = false, off = false } = {}) {
90
+ const hooksPath = path.join(home, '.grok', 'hooks', 'total-recall-preflight.json');
91
+ const config = readJsonFile(hooksPath, { hooks: {} });
92
+ config.hooks = config.hooks || {};
93
+ // Grok's matcher is a regular expression and optional, so leave it off to match every tool.
94
+ const { groups, added, removed } = mergeGate(config.hooks.PreToolUse, 'grok', { remove: remove || off, matcher: null });
95
+ config.hooks.PreToolUse = groups;
96
+ if (!dryRun && (added.length || removed.length)) writeJsonFile(hooksPath, config);
97
+ return { settings: hooksPath, added, removed };
98
+ },
99
+
100
+ verify({ home = os.homedir() } = {}) {
101
+ const installed = hasGate(readJsonQuietly(path.join(home, '.grok', 'hooks', 'total-recall-preflight.json')).hooks?.PreToolUse, 'grok');
102
+ const out = this.emit({ decision: 'deny', reason: 'receipt missing', fix: ACK_COMMAND }, 'PreToolUse', '/nonexistent-directory-without-receipt');
103
+ return {
104
+ installed,
105
+ exercised: out.exitCode === 2 && out.stdout.includes('"decision":"deny"'),
106
+ level: this.level,
107
+ native: out.stdout.trim()
108
+ };
109
+ }
110
+ };
111
+
112
+ export default grokAdapter;
@@ -0,0 +1,217 @@
1
+ /**
2
+ * Hermes Agent Runtime hook adapter.
3
+ * Official doc: https://hermes-agent.nousresearch.com/docs/user-guide/features/hooks
4
+ */
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ import os from 'node:os';
8
+
9
+ import { gateBinary, gateLauncherScript, writeGateLauncher, removeDeadGateFile, LAUNCHER_HOOK_TIMEOUT_SECONDS } from './hook-files.mjs';
10
+
11
+ const ACK_COMMAND = 'total-recall tr-preflight --ack --task "<task>" --action read,edit,test';
12
+
13
+ const GATE = 'preflight gate --harness hermes';
14
+ const HOOK_TIMEOUT_SECONDS = LAUNCHER_HOOK_TIMEOUT_SECONDS;
15
+ /**
16
+ * The gate arguments as they may appear in config.yaml. Another tool that rewrites the file can
17
+ * wrap a long string at 80 columns: core's lesson hooks did, and split this text over two lines,
18
+ * so the adapter no longer saw its own entry and added another on every install.
19
+ */
20
+ const spaced = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&').replace(/ +/g, '[\\s\\\\]+');
21
+ const GATE_RE = new RegExp(spaced(GATE));
22
+ const ENTRY = (command) => ` - matcher: ".*"
23
+ command: "${command}"
24
+ timeout: ${HOOK_TIMEOUT_SECONDS}
25
+ fail_closed: true
26
+ `;
27
+ const ENTRY_LINES = new RegExp(` - matcher: ".*"\\n command: "[^"\\n]*${GATE}"\\n timeout: \\d+\\n fail_closed: true\\n`);
28
+
29
+ /**
30
+ * The launcher sits outside the Total Recall package and is named like the command, so the hook
31
+ * line still reads `total-recall preflight gate --harness hermes` to everything that looks for it.
32
+ */
33
+ export const launcherPath = (home = os.homedir()) => path.join(home, '.hermes', 'agent-hooks', 'total-recall');
34
+
35
+ /** What the hook runs: the shared launcher, answering in Hermes's own block shape. */
36
+ export const launcherScript = (cli) => gateLauncherScript(cli, (message) => ({ action: 'block', message }));
37
+
38
+ /** The hook line: the launcher, then the gate arguments it passes on. */
39
+ const hookCommand = (home) => `${launcherPath(home)} ${GATE}`;
40
+
41
+ /** Hermes reads shell hooks from config.yaml, so the gate goes there, beside any others. */
42
+ function withGate(text, command) {
43
+ const entry = ENTRY(command);
44
+ if (/^ pre_tool_call:[ \t]*\n/m.test(text)) return text.replace(/^ pre_tool_call:[ \t]*\n/m, (line) => `${line}${entry}`);
45
+ if (/^hooks:[ \t]*\n/m.test(text)) return text.replace(/^hooks:[ \t]*\n/m, (line) => `${line} pre_tool_call:\n${entry}`);
46
+ if (/^hooks:/m.test(text)) throw new Error('config.yaml sets hooks: on one line; expand it before installing the gate');
47
+ return `${text.replace(/\n*$/, text ? '\n' : '')}\nhooks:\n pre_tool_call:\n${entry}`;
48
+ }
49
+
50
+ /**
51
+ * Remove every hook list item whose command runs the gate. Other tools rewrite config.yaml (the
52
+ * lesson hooks re-serialize it), so the item is found by indentation, not by its exact text: the
53
+ * item runs from its `- ` line to the next line indented no deeper than that dash.
54
+ */
55
+ export function withoutGate(text) {
56
+ if (!GATE_RE.test(text)) return text;
57
+ const exact = text.replace(ENTRY_LINES, '');
58
+ if (!GATE_RE.test(exact)) return exact;
59
+ let lines = text.split('\n');
60
+ const indent = (line) => line.match(/^ */)[0].length;
61
+ for (let guard = 0; guard < 50; guard++) {
62
+ // The line the gate text starts on; a wrapped entry continues on the next one.
63
+ const found = GATE_RE.exec(lines.join('\n'));
64
+ if (!found) break;
65
+ const hit = lines.join('\n').slice(0, found.index).split('\n').length - 1;
66
+ let start = hit;
67
+ while (start >= 0 && !/^ *- /.test(lines[start])) start--;
68
+ if (start < 0 || indent(lines[start]) > indent(lines[hit])) break;
69
+ const dash = indent(lines[start]);
70
+ let end = start + 1;
71
+ while (end < lines.length && (lines[end].trim() === '' || indent(lines[end]) > dash)) end++;
72
+ while (end > start + 1 && lines[end - 1].trim() === '') end--;
73
+ lines = [...lines.slice(0, start), ...lines.slice(end)];
74
+ }
75
+ return lines.join('\n');
76
+ }
77
+
78
+ export const hermesAdapter = {
79
+ id: 'hermes',
80
+ level: 'enforced',
81
+ warnings: {
82
+ delivery: 'none',
83
+ via: null,
84
+ source: 'https://hermes-agent.nousresearch.com/docs/user-guide/features/hooks',
85
+ why: 'pre_tool_call has no text field that lets the tool run. pre_llm_call adds context for the next turn, and is a different hook.',
86
+ },
87
+ source: {
88
+ url: 'https://hermes-agent.nousresearch.com/docs/user-guide/features/hooks',
89
+ retrieved: '2026-11-04',
90
+ note: 'Hermes shell & plugin hooks in ~/.hermes/config.yaml'
91
+ },
92
+ limits: [
93
+ 'Hermes plugin callbacks fail closed on timeout',
94
+ 'Pre-tool hook returns {"action":"block","message":...} with exit 2',
95
+ 'Hermes reports a missing hook command only as "command not found", so the hook runs a launcher outside the Total Recall package'
96
+ ],
97
+
98
+ parse(input = {}) {
99
+ const event = input.event || input.hook_event_name || 'pre_tool_call';
100
+ const toolName = input.tool_name || input.tool || '';
101
+ const toolInput = input.tool_input || input.params || input.args || {};
102
+ const cwd = input.cwd || process.cwd();
103
+
104
+ let tool = 'other';
105
+ let command;
106
+ let filePath;
107
+
108
+ if (toolName === 'terminal' || toolName === 'Bash' || toolName === 'shell' || toolName === 'exec') {
109
+ tool = 'shell';
110
+ command = toolInput.command || toolInput.cmd || '';
111
+ } else if (toolName === 'write_file' || toolName === 'patch' || toolName === 'Edit' || toolName === 'Write') {
112
+ tool = 'write';
113
+ filePath = toolInput.path || toolInput.file_path || '';
114
+ } else if (toolName === 'read_file' || toolName === 'search_files' || toolName === 'session_search' || toolName === 'Read') {
115
+ tool = 'read';
116
+ filePath = toolInput.path || toolInput.file_path || '';
117
+ } else if (toolName === 'delegate_task') {
118
+ tool = 'agent';
119
+ } else if (/^(web_search|web_extract|x_search)$/.test(toolName)) {
120
+ tool = 'web';
121
+ } else if (/^(clarify|todo)$/.test(toolName)) {
122
+ tool = 'meta';
123
+ }
124
+
125
+ return {
126
+ event,
127
+ tool,
128
+ command,
129
+ path: filePath,
130
+ cwd,
131
+ raw: input
132
+ };
133
+ },
134
+
135
+ emit(decision, event, cwd = process.cwd()) {
136
+ if (decision?.decision === 'allow') {
137
+ const payload = { action: 'allow' };
138
+ return { stdout: `${JSON.stringify(payload)}\n`, exitCode: 0 };
139
+ }
140
+
141
+ const reason = decision?.reason || `TR-PREFLIGHT gate: action denied. Run: ${decision?.fix || ACK_COMMAND}`;
142
+ const payload = {
143
+ action: 'block',
144
+ message: reason,
145
+ fix: decision?.fix || ACK_COMMAND
146
+ };
147
+ return { stdout: `${JSON.stringify(payload)}\n`, exitCode: 2 };
148
+ },
149
+
150
+ async run({ stdin, decideWith }) {
151
+ const parsed = this.parse(stdin);
152
+ const decision = decideWith({
153
+ tool: parsed.tool,
154
+ command: parsed.command,
155
+ path: parsed.path,
156
+ cwd: parsed.cwd
157
+ });
158
+ return this.emit(decision, parsed.event, parsed.cwd);
159
+ },
160
+
161
+ install({ home = os.homedir(), dryRun = false, remove = false, off = false, env = process.env } = {}) {
162
+ const hermesDir = path.join(home, '.hermes');
163
+ const configPath = path.join(hermesDir, 'config.yaml');
164
+ const launcher = launcherPath(home);
165
+ const removed = removeDeadGateFile(path.join(hermesDir, 'hooks.json'), 'hermes', { dryRun });
166
+ const added = [];
167
+ const text = fs.existsSync(configPath) ? fs.readFileSync(configPath, 'utf8') : '';
168
+ const present = GATE_RE.test(text);
169
+ if (remove || off) {
170
+ if (present) {
171
+ const next = withoutGate(text);
172
+ if (GATE_RE.test(next)) throw new Error(`could not remove the gate from ${configPath}; remove the pre_tool_call entry that runs "${GATE}" by hand`);
173
+ if (!dryRun) fs.writeFileSync(configPath, next);
174
+ removed.push('managed pre_tool_call gate');
175
+ }
176
+ // Only after the hook line is gone: a line left pointing at a deleted launcher blocks every call.
177
+ if (fs.existsSync(launcher)) {
178
+ if (!dryRun) fs.rmSync(launcher);
179
+ removed.push('gate launcher');
180
+ }
181
+ return { settings: configPath, added, removed };
182
+ }
183
+ // The launcher goes in before the hook line that names it, and is rewritten when it differs.
184
+ const wrote = writeGateLauncher(launcher, launcherScript(gateBinary('hermes', env)), { dryRun });
185
+ if (wrote) added.push(wrote);
186
+ const command = hookCommand(home);
187
+ const wired = new RegExp(spaced(command)).test(text);
188
+ if (!wired) {
189
+ // An entry that runs the command directly is replaced: it is the one an update breaks.
190
+ const base = present ? withoutGate(text) : text;
191
+ if (GATE_RE.test(base)) throw new Error(`could not replace the gate in ${configPath}; remove the pre_tool_call entry that runs "${GATE}" by hand`);
192
+ if (!dryRun) {
193
+ fs.mkdirSync(hermesDir, { recursive: true });
194
+ if (text) fs.copyFileSync(configPath, `${configPath}.bak-total-recall`);
195
+ fs.writeFileSync(configPath, withGate(base, command));
196
+ }
197
+ added.push(present ? 'managed pre_tool_call gate (now runs through the launcher)' : 'managed pre_tool_call gate');
198
+ }
199
+ return { settings: configPath, added, removed, note: 'Hermes asks to approve a new hook on first use, unless hooks_auto_accept is on. A running gateway keeps the hooks it started with until it restarts.' };
200
+ },
201
+
202
+ verify({ home = os.homedir() } = {}) {
203
+ const configPath = path.join(home, '.hermes', 'config.yaml');
204
+ const text = fs.existsSync(configPath) ? fs.readFileSync(configPath, 'utf8') : '';
205
+ // A hook line that names a launcher which is not there blocks every call, so it is not installed.
206
+ const installed = GATE_RE.test(text) && (!text.includes(launcherPath(home)) || fs.existsSync(launcherPath(home)));
207
+ const out = this.emit({ decision: 'deny', reason: 'receipt missing', fix: ACK_COMMAND }, 'pre_tool_call', '/nonexistent-directory-without-receipt');
208
+ return {
209
+ installed,
210
+ exercised: out.exitCode === 2 && out.stdout.includes('"action":"block"'),
211
+ level: this.level,
212
+ native: out.stdout.trim()
213
+ };
214
+ }
215
+ };
216
+
217
+ export default hermesAdapter;