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
@@ -0,0 +1,288 @@
1
+ /**
2
+ * OpenClaw hook adapter. OpenClaw runs hooks only from plugin code, so this adapter installs the
3
+ * small plugin in ./openclaw-plugin/, which asks `preflight gate --harness openclaw` about each call.
4
+ * Official docs: https://docs.openclaw.ai/plugins/hooks/tool-policy
5
+ * and https://docs.openclaw.ai/plugins/building-plugins
6
+ */
7
+ import { spawnSync } from 'node:child_process';
8
+ import fs from 'node:fs';
9
+ import os from 'node:os';
10
+ import path from 'node:path';
11
+ import { fileURLToPath } from 'node:url';
12
+
13
+ import { removeDeadGateFile } from './hook-files.mjs';
14
+
15
+ const ACK_COMMAND = 'total-recall tr-preflight --ack --task "<task>" --action read,edit,test';
16
+
17
+ const PLUGIN_ID = 'total-recall-gate';
18
+ const PLUGIN_SOURCE = path.join(path.dirname(fileURLToPath(import.meta.url)), 'openclaw-plugin');
19
+ const PLUGIN_FILES = ['package.json', 'openclaw.plugin.json', 'index.js', 'gate-client.js'];
20
+ /** The first version whose hook, session and middleware contract this was tested against. */
21
+ const MIN_VERSION = [2026, 11, 1];
22
+
23
+ const DEAD_FILE = (home) => path.join(home, '.openclaw', 'hooks.json');
24
+
25
+ /**
26
+ * Every tool in the catalog of OpenClaw 2026.11.1, so the report's "unrecognized" list means
27
+ * something. `mcp` covers external actions with no class of their own; `decide` treats it as
28
+ * `other`. `process` only controls an `exec` the gate already passed. `message` is how the agent
29
+ * talks to its operator. `dispatch_action` runs a tool found by `tool_search`, and OpenClaw wraps
30
+ * that tool with the same hook, so the real call is checked under its real name. Gating the
31
+ * dispatcher too would stop an agent reaching `exec` that way from ever acknowledging.
32
+ */
33
+ const TOOLS_BY_CLASS = {
34
+ shell: ['exec', 'code_execution', 'terminal'],
35
+ read: ['ls', 'read', 'memory_get', 'personal_instructions', 'sessions_history', 'skills_read', 'view_image', 'pdf', 'transcripts', 'github_identity_status'],
36
+ write: ['write', 'edit', 'apply_patch', 'skill_workshop'],
37
+ search: ['memory_search', 'sessions_search', 'skills_search'],
38
+ web: ['web_search', 'web_fetch', 'x_search', 'browser'],
39
+ agent: ['sessions_spawn', 'sessions_send', 'sessions_yield', 'subagents', 'agents_wait'],
40
+ meta: ['tool_search', 'tool_describe', 'dispatch_action', 'tool_call', 'structured_output', 'process', 'session_status', 'sessions', 'sessions_list', 'conversations_list', 'presence', 'agents_list', 'get_goal', 'create_goal', 'update_goal', 'progress_card', 'heartbeat_respond', 'suggest_task', 'dismiss_task', 'decision_evaluate', 'theme'],
41
+ ui: ['message', 'ask_user', 'tts', 'show_widget'],
42
+ mcp: ['conversations_send', 'conversations_turn', 'gateway', 'plugins', 'automations', 'cron', 'nodes', 'computer', 'mobile_ui', 'screen', 'canvas', 'dashboard', 'portal', 'secrets', 'image_generate', 'music_generate', 'video_generate', 'github_publish'],
43
+ };
44
+ const CLASS_OF = new Map(Object.entries(TOOLS_BY_CLASS).flatMap(([cls, names]) => names.map((name) => [name, cls])));
45
+
46
+ function locate(home, env) {
47
+ const stateDir = env.OPENCLAW_STATE_DIR || path.join(home, '.openclaw');
48
+ return {
49
+ stateDir,
50
+ configPath: env.OPENCLAW_CONFIG_PATH || path.join(stateDir, 'openclaw.json'),
51
+ dir: path.join(stateDir, PLUGIN_ID),
52
+ };
53
+ }
54
+
55
+ const defaultRun = (args, env) => spawnSync('openclaw', args, { env, encoding: 'utf8', timeout: 60000 });
56
+
57
+ /** Every OpenClaw command runs against this state folder, so a test home never reaches the live one. */
58
+ function openclawEnv(home, env, place) {
59
+ return { ...env, HOME: home, OPENCLAW_STATE_DIR: place.stateDir, OPENCLAW_CONFIG_PATH: place.configPath };
60
+ }
61
+
62
+ /** Only the machine's own gateway may be told to reload. A test folder would still reach it over the default port. */
63
+ function isLiveState(home, env) {
64
+ return home === os.homedir() && !env.OPENCLAW_STATE_DIR && !env.OPENCLAW_CONFIG_PATH;
65
+ }
66
+
67
+ function realPath(file) {
68
+ try { return fs.realpathSync(file); } catch { return path.resolve(file); }
69
+ }
70
+
71
+ /** @returns {{ ok: true } | { ok: false, why: string }} */
72
+ function checkApp(run, env) {
73
+ const out = run(['--version'], env);
74
+ if (out?.error || out?.status !== 0) return { ok: false, why: 'No OpenClaw app runs here.' };
75
+ const version = /\b(\d{4})\.(\d+)\.(\d+)\b/.exec(`${out.stdout || ''}`);
76
+ if (!version) return { ok: false, why: 'The openclaw command here reports no version, so it is not the OpenClaw app.' };
77
+ const parts = version.slice(1).map(Number);
78
+ for (let i = 0; i < MIN_VERSION.length; i += 1) {
79
+ if (parts[i] > MIN_VERSION[i]) return { ok: true };
80
+ if (parts[i] < MIN_VERSION[i]) {
81
+ return { ok: false, why: `OpenClaw ${version[0]} is older than ${MIN_VERSION.join('.')}, the first version this gate was tested against. Update OpenClaw, then run: total-recall preflight install --harness openclaw` };
82
+ }
83
+ }
84
+ return { ok: true };
85
+ }
86
+
87
+ function findOnPath(name, env) {
88
+ for (const dir of String(env.PATH || '').split(path.delimiter)) {
89
+ const candidate = path.join(dir || '.', name);
90
+ try {
91
+ fs.accessSync(candidate, fs.constants.X_OK);
92
+ return candidate;
93
+ } catch { /* keep looking */ }
94
+ }
95
+ return null;
96
+ }
97
+
98
+ /**
99
+ * This machine's paths for the plugin. A gateway starts with its own PATH, which can put another
100
+ * Node first, so the gate runs on the Node found here. Stable PATH folders survive a Node upgrade;
101
+ * `process.execPath` would not.
102
+ */
103
+ function gateSettings(env) {
104
+ const command = findOnPath('total-recall', env);
105
+ const node = findOnPath('node', env);
106
+ return {
107
+ command: command || 'total-recall',
108
+ path: node ? [path.dirname(node)] : [],
109
+ package: command ? path.resolve(path.dirname(realPath(command)), '..') : null,
110
+ tools: {
111
+ open: ['meta', 'ui', 'read', 'search'].flatMap((cls) => TOOLS_BY_CLASS[cls]),
112
+ shell: TOOLS_BY_CLASS.shell,
113
+ write: TOOLS_BY_CLASS.write,
114
+ },
115
+ };
116
+ }
117
+
118
+ function wantedFiles(env) {
119
+ const files = new Map(PLUGIN_FILES.map((name) => [name, fs.readFileSync(path.join(PLUGIN_SOURCE, name), 'utf8')]));
120
+ files.set('gate.json', `${JSON.stringify(gateSettings(env), null, 2)}\n`);
121
+ return files;
122
+ }
123
+
124
+ function readText(file) {
125
+ try { return fs.readFileSync(file, 'utf8'); } catch { return null; }
126
+ }
127
+
128
+ /** Replaced in one step: the gateway may load this folder at any moment. */
129
+ function writeAtomically(file, text) {
130
+ const temporary = `${file}.${process.pid}.tmp`;
131
+ fs.writeFileSync(temporary, text);
132
+ fs.renameSync(temporary, file);
133
+ }
134
+
135
+ /** A disabled plugin counts as absent, because the gate has no off switch. An unreadable config does too. */
136
+ function isRegistered(configPath, dir) {
137
+ let config;
138
+ try { config = JSON.parse(fs.readFileSync(configPath, 'utf8')); } catch { return false; }
139
+ const wanted = realPath(dir);
140
+ const paths = config?.plugins?.load?.paths;
141
+ return Array.isArray(paths)
142
+ && paths.some((entry) => realPath(entry) === wanted)
143
+ && config?.plugins?.entries?.[PLUGIN_ID]?.enabled !== false;
144
+ }
145
+
146
+ function failure(out, doing) {
147
+ const detail = `${out?.stderr || ''} ${out?.stdout || ''}`.trim().split('\n').filter(Boolean).at(-1) || out?.error?.message || `exit ${out?.status}`;
148
+ return new Error(`OpenClaw could not ${doing}: ${detail.slice(0, 300)}`);
149
+ }
150
+
151
+ /** A running gateway reads a new plugin when told to. A gateway that is down reads it when it starts. */
152
+ function applyToGateway(run, env) {
153
+ const out = run(['plugins', 'reload', PLUGIN_ID, '--accept-capabilities', '--json'], env);
154
+ return out?.status === 0
155
+ ? 'Loaded into the running gateway.'
156
+ : 'Takes effect when the gateway next starts: total-recall openclaw gateway restart';
157
+ }
158
+
159
+ function removePlugin({ home, env, dryRun, run, place, removed }) {
160
+ const present = fs.existsSync(place.dir);
161
+ const registered = isRegistered(place.configPath, place.dir);
162
+ if (!present && !registered) return { settings: null, added: [], removed };
163
+ if (dryRun) return { settings: place.dir, added: [], removed: [...removed, 'managed before_tool_call plugin'] };
164
+ const cliEnv = openclawEnv(home, env, place);
165
+ let note;
166
+ if (registered) {
167
+ const out = run(['plugins', 'uninstall', PLUGIN_ID, '--force'], cliEnv);
168
+ if (out?.status !== 0) note = `OpenClaw still lists the plugin (${failure(out, 'remove it').message}). Run: openclaw plugins uninstall ${PLUGIN_ID}`;
169
+ }
170
+ fs.rmSync(place.dir, { recursive: true, force: true });
171
+ if (!note && isLiveState(home, env)) note = 'Restart the gateway to unload it: total-recall openclaw gateway restart';
172
+ return { settings: place.dir, added: [], removed: [...removed, 'managed before_tool_call plugin'], ...(note ? { note } : {}) };
173
+ }
174
+
175
+ export const openclawAdapter = {
176
+ id: 'openclaw',
177
+ level: 'enforced',
178
+ warnings: {
179
+ delivery: 'documented',
180
+ via: 'tool-result middleware, from the installed plugin',
181
+ source: 'https://docs.openclaw.ai/plugins/building-plugins',
182
+ },
183
+ source: {
184
+ url: 'https://docs.openclaw.ai/plugins/hooks/tool-policy',
185
+ retrieved: '2026-11-06',
186
+ note: 'A before_tool_call hook and tool-result middleware in an installed plugin. Tool names, context fields and the install contract were read from OpenClaw 2026.11.1, and proved by real agent turns through its gateway.',
187
+ },
188
+ limits: [
189
+ 'OpenClaw blocks a call when a before_tool_call hook throws or runs out of time, so the plugin holds the repair exceptions itself',
190
+ 'Returns { block: true, blockReason } on deny',
191
+ 'An operator can always run `openclaw plugins disable total-recall-gate`; the next install or update turns it back on',
192
+ ],
193
+
194
+ parse(input = {}) {
195
+ const toolName = input.toolName || input.tool_name || '';
196
+ const params = input.params || {};
197
+ const base = input.cwd || process.cwd();
198
+ const tool = input.toolKind === 'code_mode_exec' ? 'shell' : (CLASS_OF.get(toolName) || 'other');
199
+ const workdir = typeof params.workdir === 'string' && params.workdir.trim()
200
+ ? params.workdir.replace(/^~(?=$|\/)/, os.homedir())
201
+ : null;
202
+ return {
203
+ event: input.event || 'before_tool_call',
204
+ tool,
205
+ command: tool === 'shell' && typeof params.command === 'string' ? params.command : undefined,
206
+ path: params.path || params.file_path || params.filePath || input.derivedPaths?.[0] || undefined,
207
+ cwd: tool === 'shell' && workdir ? path.resolve(base, workdir) : base,
208
+ raw: input,
209
+ };
210
+ },
211
+
212
+ emit(decision, event, cwd = process.cwd()) {
213
+ if (decision?.decision === 'allow') {
214
+ const payload = decision.warning ? { block: false, warning: decision.warning } : { block: false };
215
+ return { stdout: `${JSON.stringify(payload)}\n`, exitCode: 0 };
216
+ }
217
+
218
+ const reason = decision?.reason || `TR-PREFLIGHT gate: action denied. Run: ${decision?.fix || ACK_COMMAND}`;
219
+ const payload = {
220
+ block: true,
221
+ blockReason: reason,
222
+ fix: decision?.fix || ACK_COMMAND,
223
+ };
224
+ return { stdout: `${JSON.stringify(payload)}\n`, exitCode: 2 };
225
+ },
226
+
227
+ async run({ stdin, decideWith }) {
228
+ const parsed = this.parse(stdin);
229
+ const decision = decideWith({
230
+ tool: parsed.tool,
231
+ command: parsed.command,
232
+ path: parsed.path,
233
+ cwd: parsed.cwd,
234
+ });
235
+ return this.emit(decision, parsed.event, parsed.cwd);
236
+ },
237
+
238
+ install({ home = os.homedir(), env = process.env, dryRun = false, remove = false, off = false, run = defaultRun } = {}) {
239
+ const place = locate(home, env);
240
+ const removed = removeDeadGateFile(DEAD_FILE(home), 'openclaw', { dryRun });
241
+ if (remove || off) return removePlugin({ home, env, dryRun, run, place, removed });
242
+
243
+ const cliEnv = openclawEnv(home, env, place);
244
+ const app = checkApp(run, cliEnv);
245
+ if (!app.ok) return { settings: null, added: [], removed, unsupported: app.why };
246
+
247
+ const files = wantedFiles(env);
248
+ const changed = [...files].filter(([name, text]) => readText(path.join(place.dir, name)) !== text);
249
+ const registered = isRegistered(place.configPath, place.dir);
250
+ if (!changed.length && registered) return { settings: place.dir, added: [], removed };
251
+ const added = ['managed before_tool_call plugin'];
252
+ if (dryRun) return { settings: place.dir, added, removed };
253
+
254
+ fs.mkdirSync(place.dir, { recursive: true });
255
+ for (const [name, text] of changed) writeAtomically(path.join(place.dir, name), text);
256
+ if (!registered) {
257
+ // Consent is given here because this is the owner's own plugin, from the owner's own installer.
258
+ const out = run(['plugins', 'install', place.dir, '--link', '--force', '--accept-capabilities'], cliEnv);
259
+ if (out?.status !== 0) throw failure(out, 'install the gate plugin');
260
+ }
261
+ const note = isLiveState(home, env) ? applyToGateway(run, cliEnv) : null;
262
+ return { settings: place.dir, added, removed, ...(note ? { note } : {}) };
263
+ },
264
+
265
+ verify({ home = os.homedir(), env = process.env, run = defaultRun } = {}) {
266
+ const place = locate(home, env);
267
+ const out = this.emit({ decision: 'deny', reason: 'receipt missing', fix: ACK_COMMAND }, 'before_tool_call', '/nonexistent-directory-without-receipt');
268
+ const exercised = out.exitCode === 2 && out.stdout.includes('"block":true');
269
+ const base = { exercised, level: this.level, native: out.stdout.trim() };
270
+ if (!isRegistered(place.configPath, place.dir) || !fs.existsSync(path.join(place.dir, 'gate.json'))) {
271
+ return { ...base, installed: false, note: 'The gate plugin is not installed. Run: total-recall preflight install --harness openclaw' };
272
+ }
273
+ const inspected = run(['plugins', 'inspect', PLUGIN_ID, '--runtime', '--json'], openclawEnv(home, env, place));
274
+ let report = null;
275
+ try {
276
+ const text = String(inspected?.stdout || '');
277
+ report = JSON.parse(text.slice(text.indexOf('{')));
278
+ } catch { /* reported below */ }
279
+ const loaded = report?.plugin?.status === 'loaded' && (report?.typedHooks || []).some((hook) => hook?.name === 'before_tool_call');
280
+ return {
281
+ ...base,
282
+ installed: loaded,
283
+ ...(loaded ? {} : { note: `OpenClaw did not load the gate plugin: ${report?.plugin?.error || failure(inspected, 'inspect it').message}` }),
284
+ };
285
+ },
286
+ };
287
+
288
+ export default openclawAdapter;
@@ -0,0 +1,146 @@
1
+ /**
2
+ * Pi Coding Agent extension hook adapter.
3
+ * Official doc: https://raw.githubusercontent.com/badlogic/pi-mono/main/packages/coding-agent/docs/extensions.md
4
+ */
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ import os from 'node:os';
8
+
9
+ import { removeDeadGateFile } from './hook-files.mjs';
10
+
11
+ const ACK_COMMAND = 'total-recall tr-preflight --ack --task "<task>" --action read,edit,test';
12
+
13
+ /**
14
+ * Pi loads extensions as modules, so the gate is a small one that asks Total Recall. Text
15
+ * after a tool_call cannot carry a warning, so it goes through pi.sendMessage. Anything that
16
+ * goes wrong blocks, as the gate does in every harness.
17
+ */
18
+ export const PI_EXTENSION = `// Total Recall preflight gate. Written by \`total-recall preflight install\`.
19
+ import { spawnSync } from 'node:child_process';
20
+
21
+ export default function totalRecallGate(pi) {
22
+ pi.on('tool_call', async (event, ctx) => {
23
+ const input = JSON.stringify({ event: 'tool_call', toolName: event.toolName, input: event.input, cwd: ctx.cwd, sessionId: ctx.sessionManager?.getSessionId?.() });
24
+ const result = spawnSync('total-recall', ['preflight', 'gate', '--harness', 'pi'], { input, encoding: 'utf8', timeout: 10000 });
25
+ let answer = {};
26
+ try { answer = JSON.parse(result.stdout || '{}'); } catch { /* handled below */ }
27
+ if (result.status === 0 && !answer.block) {
28
+ if (answer.warning) pi.sendMessage({ customType: 'total-recall-note', content: answer.warning, display: true }, { deliverAs: 'steer' });
29
+ return undefined;
30
+ }
31
+ return { block: true, reason: answer.reason || result.stderr || 'The Total Recall gate could not run.' };
32
+ });
33
+ }
34
+ `;
35
+
36
+ export const piAdapter = {
37
+ id: 'pi',
38
+ level: 'enforced (unverified live)',
39
+ warnings: {
40
+ delivery: 'documented',
41
+ via: 'pi.sendMessage, from the installed extension',
42
+ source: 'https://raw.githubusercontent.com/badlogic/pi-mono/main/packages/coding-agent/docs/extensions.md',
43
+ },
44
+ source: {
45
+ url: 'https://raw.githubusercontent.com/badlogic/pi-mono/main/packages/coding-agent/docs/extensions.md',
46
+ retrieved: '2026-11-04',
47
+ note: 'Pi Coding Agent tool_call extensions in ~/.pi/agent/extensions/'
48
+ },
49
+ limits: [
50
+ 'Pi loaded extensions must fail closed explicitly',
51
+ 'Returns { block: true, reason } on denied calls'
52
+ ],
53
+
54
+ parse(input = {}) {
55
+ const event = input.event || 'tool_call';
56
+ const toolName = input.toolName || input.tool || '';
57
+ const toolInput = input.input || input.params || {};
58
+ const cwd = input.cwd || process.cwd();
59
+
60
+ let tool = 'other';
61
+ let command;
62
+ let filePath;
63
+
64
+ if (toolName === 'bash' || toolName === 'execute' || toolName === 'Bash' || toolName === 'shell') {
65
+ tool = 'shell';
66
+ command = toolInput.command || toolInput.cmd || '';
67
+ } else if (toolName === 'edit' || toolName === 'write' || toolName === 'patch') {
68
+ tool = 'write';
69
+ filePath = toolInput.path || toolInput.file || '';
70
+ } else if (/^(read|grep|find|ls)$/.test(toolName)) {
71
+ tool = 'read';
72
+ filePath = toolInput.path || toolInput.file || '';
73
+ }
74
+
75
+ return {
76
+ event,
77
+ tool,
78
+ command,
79
+ path: filePath,
80
+ cwd,
81
+ raw: input
82
+ };
83
+ },
84
+
85
+ emit(decision, event, cwd = process.cwd()) {
86
+ if (decision?.decision === 'allow') {
87
+ const payload = decision.warning ? { block: false, warning: decision.warning } : { block: false };
88
+ return { stdout: `${JSON.stringify(payload)}\n`, exitCode: 0 };
89
+ }
90
+
91
+ const reason = decision?.reason || `TR-PREFLIGHT gate: action denied. Run: ${decision?.fix || ACK_COMMAND}`;
92
+ const payload = {
93
+ block: true,
94
+ reason,
95
+ fix: decision?.fix || ACK_COMMAND
96
+ };
97
+ return { stdout: `${JSON.stringify(payload)}\n`, exitCode: 2 };
98
+ },
99
+
100
+ async run({ stdin, decideWith }) {
101
+ const parsed = this.parse(stdin);
102
+ const decision = decideWith({
103
+ tool: parsed.tool,
104
+ command: parsed.command,
105
+ path: parsed.path,
106
+ cwd: parsed.cwd
107
+ });
108
+ return this.emit(decision, parsed.event, parsed.cwd);
109
+ },
110
+
111
+ install({ home = os.homedir(), dryRun = false, remove = false, off = false } = {}) {
112
+ const piDir = path.join(home, '.pi', 'agent', 'extensions');
113
+ const extensionPath = path.join(piDir, 'total-recall-preflight.ts');
114
+ const removed = removeDeadGateFile(path.join(piDir, 'total-recall-preflight.json'), 'pi', { dryRun });
115
+ const added = [];
116
+ if (remove || off) {
117
+ if (fs.existsSync(extensionPath)) {
118
+ if (!dryRun) fs.rmSync(extensionPath);
119
+ removed.push('managed tool_call extension');
120
+ }
121
+ return { settings: extensionPath, added, removed };
122
+ }
123
+ const current = fs.existsSync(extensionPath) ? fs.readFileSync(extensionPath, 'utf8') : null;
124
+ if (current !== PI_EXTENSION) {
125
+ if (!dryRun) {
126
+ fs.mkdirSync(piDir, { recursive: true });
127
+ fs.writeFileSync(extensionPath, PI_EXTENSION);
128
+ }
129
+ added.push('managed tool_call extension');
130
+ }
131
+ return { settings: extensionPath, added, removed };
132
+ },
133
+
134
+ verify({ home = os.homedir() } = {}) {
135
+ const installed = fs.existsSync(path.join(home, '.pi', 'agent', 'extensions', 'total-recall-preflight.ts'));
136
+ const out = this.emit({ decision: 'deny', reason: 'receipt missing', fix: ACK_COMMAND }, 'tool_call', '/nonexistent-directory-without-receipt');
137
+ return {
138
+ installed,
139
+ exercised: out.exitCode === 2 && out.stdout.includes('"block":true'),
140
+ level: this.level,
141
+ native: out.stdout.trim()
142
+ };
143
+ }
144
+ };
145
+
146
+ export default piAdapter;
package/src/gate.mjs ADDED
@@ -0,0 +1,18 @@
1
+ /** Run the repository's own quality gates through the code-quality plugin. No configured gate is not a pass. */
2
+ import { runProcess } from './worker.mjs';
3
+
4
+ const run = async (binary, args, { cwd, timeoutMs }) => {
5
+ // Asynchronous, so a gate never stalls another agent in the same run, and stoppable with the run.
6
+ const result = await runProcess(binary, args, { cwd, timeoutMs, env: process.env, maxBytes: 16 * 1024 * 1024 });
7
+ return { status: result.exitCode, stdout: result.stdout, stderr: result.stderr, error: result.reason ? new Error(result.reason) : undefined };
8
+ };
9
+
10
+ export async function runQualityGate(directory, { tier = 'fast', runner = run, timeoutMs = 600000 } = {}) {
11
+ const result = await runner(process.env.TOTAL_RECALL_BIN || 'total-recall', ['code-quality-check', '--tier', tier, '--json'], { cwd: directory, timeoutMs });
12
+ const output = `${result.stdout || ''}\n${result.stderr || ''}`.trim();
13
+ if (result.error || result.status === null) return { status: 'unavailable', passed: false, tier, summary: `The gate did not run: ${result.error?.message || 'terminated'}` };
14
+ let report = null;
15
+ try { report = JSON.parse(result.stdout); } catch { /* a text report */ }
16
+ if (/No code-quality state|No checks at tier/.test(output)) return { status: 'unconfigured', passed: false, tier, summary: String(report?.error || output).slice(0, 500) };
17
+ return { status: result.status === 0 ? 'passed' : 'failed', passed: result.status === 0, tier, summary: output.slice(-2000), report };
18
+ }
@@ -0,0 +1,170 @@
1
+ /**
2
+ * Keep each harness on this machine current, with the harness's own update command.
3
+ *
4
+ * Nothing updated a harness before this: the upstream report compared versions for three of
5
+ * them and changed nothing, and it reported Hermes as current because it had no way to ask.
6
+ * A Hermes install sat a release behind until a person noticed.
7
+ *
8
+ * Every command here was read from the installed binary's own `--help` on 2026-11-16, never
9
+ * guessed. A harness owns what an update does to its own services: `hermes update` drains and
10
+ * restarts its gateway itself. DSH documents no update command and is an npm package, so it is
11
+ * moved with npm, in the prefix it is already installed in, and only forward.
12
+ */
13
+ import fs from 'node:fs';
14
+ import os from 'node:os';
15
+ import path from 'node:path';
16
+ import { findBinary, runProcess, agentEnvironment } from './worker.mjs';
17
+
18
+ export const HARNESS_UPDATERS = Object.freeze({
19
+ claude: { binary: 'claude', update: ['update'] },
20
+ codex: { binary: 'codex', update: ['update'] },
21
+ agy: { binary: 'agy', update: ['update'] },
22
+ grok: { binary: 'grok', update: ['update'] },
23
+ cursor: { binary: 'cursor-agent', update: ['update'] },
24
+ // Hermes restarts its gateway on every update run, so it is asked first whether one is waiting.
25
+ hermes: { binary: 'hermes', check: ['update', '--check'], pending: /Run `hermes update`/, update: ['update', '--yes'] },
26
+ // These three rewrite the files a running copy has loaded, so they wait until none is running.
27
+ pi: { binary: 'pi', update: ['update', '--self'], idleOnly: true },
28
+ cline: { binary: 'cline', update: ['update'], idleOnly: true },
29
+ openclaw: { binary: 'openclaw', update: ['update', '--yes'], idleOnly: true },
30
+ dsh: { binary: 'dsh', npm: '@deepseek-ai/dsh', idleOnly: true },
31
+ });
32
+
33
+ /** Under the ten minutes a plugin task may run, so the report is written before the runner stops it. */
34
+ export const UPDATE_BUDGET_MS = 9 * 60_000;
35
+ const CHECK_TIMEOUT_MS = 60_000;
36
+ const VERSION_TIMEOUT_MS = 15_000;
37
+
38
+ const firstLine = (text) => String(text || '').split(/\r?\n/).map((line) => line.trim()).find(Boolean) || null;
39
+ const tail = (result) => `${result.reason ? `${result.reason}: ` : ''}${String(result.stderr || result.stdout || '').trim().slice(-400)}`.trim() || `exit ${result.exitCode}`;
40
+ const failedRun = (result) => Boolean(result.reason) || result.exitCode !== 0;
41
+ /**
42
+ * What identifies the installed build in a version line: its version numbers and commit ids.
43
+ * The words around them can change without a new build: after its first run here, Grok's updater
44
+ * added "[stable]" to the same version, which read as an update when whole lines were compared.
45
+ */
46
+ export const buildOf = (line) => (String(line || '').match(/\b\d+(?:\.\d+)+(?:-[0-9A-Za-z.]+)?\b|\b[0-9a-f]{7,40}\b/g) || [String(line || '')]).join(' ');
47
+ const real = (file) => { try { return fs.realpathSync(file); } catch { return file; } };
48
+
49
+ /** Order two versions. A release sorts after its own pre-releases; pre-release parts compare in turn. */
50
+ export function compareVersions(a, b) {
51
+ const parse = (value) => {
52
+ const match = /(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?/.exec(String(value || ''));
53
+ return match ? { core: match.slice(1, 4).map(Number), pre: match[4] ? match[4].split('.') : null } : null;
54
+ };
55
+ const left = parse(a), right = parse(b);
56
+ if (!left || !right) return null;
57
+ for (let i = 0; i < 3; i++) if (left.core[i] !== right.core[i]) return left.core[i] < right.core[i] ? -1 : 1;
58
+ if (!left.pre || !right.pre) return left.pre ? -1 : right.pre ? 1 : 0;
59
+ for (let i = 0; i < Math.max(left.pre.length, right.pre.length); i++) {
60
+ const x = left.pre[i], y = right.pre[i];
61
+ if (x === undefined || y === undefined) return x === undefined ? -1 : 1;
62
+ if (x === y) continue;
63
+ const numeric = /^\d+$/.test(x) && /^\d+$/.test(y);
64
+ return (numeric ? Number(x) < Number(y) : x < y) ? -1 : 1;
65
+ }
66
+ return 0;
67
+ }
68
+
69
+ /** The npm prefix a global package is installed under, from its binary: `<prefix>/lib/node_modules/<package>/…`. */
70
+ export function npmPrefixOf(binary, name) {
71
+ const parts = real(binary).split(path.sep);
72
+ const tree = parts.lastIndexOf('node_modules');
73
+ const expected = name.split('/');
74
+ if (tree < 1 || parts[tree - 1] !== 'lib' || expected.some((part, i) => parts[tree + 1 + i] !== part)) return null;
75
+ return { prefix: parts.slice(0, tree - 1).join(path.sep) || path.sep, packageDir: parts.slice(0, tree + 1 + expected.length).join(path.sep) };
76
+ }
77
+
78
+ /** Command lines of every other process on this machine, for telling whether a harness is in use. */
79
+ async function otherCommandLines(run) {
80
+ const listed = await run('ps', ['-axo', 'pid=,command='], { timeoutMs: 15_000, env: agentEnvironment() });
81
+ if (failedRun(listed)) throw new Error(`could not list processes: ${tail(listed)}`);
82
+ return listed.stdout.split('\n').map((line) => /^\s*(\d+)\s+(.*)$/.exec(line)).filter(Boolean)
83
+ .filter((match) => Number(match[1]) !== process.pid && Number(match[1]) !== process.ppid).map((match) => match[2]);
84
+ }
85
+
86
+ /** A running copy of this harness: a process started from its binary, or from the files behind it. */
87
+ function runningCopy(lines, binary, directories = []) {
88
+ const files = [...new Set([binary, real(binary)])];
89
+ return lines.find((line) => files.some((file) => ` ${line} `.includes(` ${file} `))
90
+ || directories.some((directory) => line.includes(`${directory}${path.sep}`))) || null;
91
+ }
92
+
93
+ /**
94
+ * Update every listed harness that is installed, one at a time. A harness that fails is
95
+ * reported and the rest still run. Never throws.
96
+ * @param {{ only?: string, dryRun?: boolean, env?: object, run?: Function, find?: Function, gates?: Function, processes?: Function, now?: () => number, budgetMs?: number }} [options]
97
+ */
98
+ export async function updateHarnesses({ only = null, dryRun = false, env = process.env, run = runProcess, find = findBinary,
99
+ gates = async (id) => (await import('./gate-adapters/index.mjs')).install(id), processes = () => otherCommandLines(run),
100
+ now = Date.now, budgetMs = UPDATE_BUDGET_MS } = {}) {
101
+ if (only && !HARNESS_UPDATERS[only]) {
102
+ return { ok: false, rows: [{ harness: only, status: 'unsupported', detail: 'No update command is recorded for this harness, so it is not updated here.' }] };
103
+ }
104
+ const started = now();
105
+ const options = (timeoutMs) => ({ cwd: os.homedir(), env: agentEnvironment(env), timeoutMs });
106
+ const rows = [];
107
+ for (const [harness, spec] of Object.entries(HARNESS_UPDATERS)) {
108
+ if (only && harness !== only) continue;
109
+ const row = { harness };
110
+ rows.push(row);
111
+ try {
112
+ const binary = find(spec.binary, env);
113
+ if (!binary) { row.status = 'not-present'; continue; }
114
+ const left = budgetMs - (now() - started);
115
+ if (left < CHECK_TIMEOUT_MS) { row.status = 'not-run'; row.detail = 'The time allowed for one run was used up by the harnesses before this one.'; continue; }
116
+ // A runtime pinned in a versioned folder belongs to whatever installed it there.
117
+ if (real(binary).split(path.sep).includes('tr-harness-runtimes')) {
118
+ row.status = 'managed';
119
+ row.detail = 'Installed as a pinned runtime, which its installer moves. An update from inside it would leave the pin wrong.';
120
+ continue;
121
+ }
122
+ // Some harnesses print their version on stderr.
123
+ const version = async () => { const shown = await run(binary, ['--version'], options(VERSION_TIMEOUT_MS)); return firstLine(shown.stdout) || firstLine(shown.stderr); };
124
+ row.before = await version();
125
+
126
+ let command = spec.update ? [binary, spec.update] : null;
127
+ let packageDir = null;
128
+ if (spec.npm) {
129
+ const installed = npmPrefixOf(binary, spec.npm);
130
+ if (!installed) { row.status = 'unsupported'; row.detail = `Not an npm global install of ${spec.npm}, so npm is not used to move it.`; continue; }
131
+ packageDir = installed.packageDir;
132
+ const npm = find('npm', env);
133
+ if (!npm) { row.status = 'failed'; row.detail = 'npm is not on PATH.'; continue; }
134
+ const asked = await run(npm, ['view', spec.npm, 'dist-tags.latest'], options(CHECK_TIMEOUT_MS));
135
+ if (failedRun(asked)) { row.status = 'failed'; row.detail = `check: ${tail(asked)}`; continue; }
136
+ const latest = firstLine(asked.stdout);
137
+ const order = compareVersions(row.before, latest);
138
+ if (order === null) { row.status = 'failed'; row.detail = `check: could not compare ${row.before} with ${latest}.`; continue; }
139
+ // Only forward: a `latest` tag behind the installed pre-release must never downgrade it.
140
+ if (order >= 0) { row.status = 'current'; continue; }
141
+ row.pending = latest;
142
+ command = [npm, ['install', '-g', '--prefix', installed.prefix, `${spec.npm}@${latest}`]];
143
+ }
144
+ if (spec.check) {
145
+ const checked = await run(binary, spec.check, options(CHECK_TIMEOUT_MS));
146
+ if (failedRun(checked)) { row.status = 'failed'; row.detail = `check: ${tail(checked)}`; continue; }
147
+ if (!spec.pending.test(`${checked.stdout}\n${checked.stderr}`)) { row.status = 'current'; continue; }
148
+ row.pending = firstLine(String(checked.stdout).split(/\r?\n/).filter((line) => /available/i.test(line)).join('\n'));
149
+ }
150
+ if (spec.idleOnly) {
151
+ const busy = runningCopy(await processes(), binary, packageDir ? [packageDir] : []);
152
+ if (busy) { row.status = 'busy'; row.detail = `In use (${busy.slice(0, 120)}), so it was left alone. The next run tries again.`; continue; }
153
+ }
154
+ if (dryRun) { row.status = row.pending ? 'would-update' : 'would-run'; continue; }
155
+ const updated = await run(command[0], command[1], options(budgetMs - (now() - started)));
156
+ row.after = await version();
157
+ if (failedRun(updated)) { row.status = 'failed'; row.detail = tail(updated); continue; }
158
+ row.status = row.after && buildOf(row.after) !== buildOf(row.before) ? 'updated' : 'current';
159
+ if (row.status === 'updated') {
160
+ // A new release can rewrite the file its hooks live in, so the gate is put back at once.
161
+ try { await gates(harness); row.gate = 'reinstalled'; }
162
+ catch (error) { row.gate = `not reinstalled: ${error.message}`; row.status = 'failed'; row.detail = 'Updated, but the Total Recall gate could not be put back.'; }
163
+ }
164
+ } catch (error) {
165
+ row.status = 'failed';
166
+ row.detail = error.message;
167
+ }
168
+ }
169
+ return { ok: rows.every((row) => !['failed', 'not-run'].includes(row.status)), rows };
170
+ }