@mindmux/cli 0.0.0-stage → 0.1.1
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.
- package/LICENSE +201 -0
- package/README.md +58 -2
- package/bin/mindmux.mjs +3 -0
- package/bin/mmx.mjs +6 -0
- package/docs/README.md +14 -0
- package/docs/agents.md +61 -0
- package/docs/brain.md +54 -0
- package/docs/cloud.md +29 -0
- package/docs/development.md +24 -0
- package/docs/installation.md +86 -0
- package/docs/setup.md +116 -0
- package/package.json +40 -4
- package/src/brain-index.mjs +31 -0
- package/src/brain.mjs +117 -0
- package/src/clean.mjs +119 -0
- package/src/cli.mjs +254 -0
- package/src/cloud.mjs +164 -0
- package/src/codex-hooks.mjs +15 -0
- package/src/doctor.mjs +95 -0
- package/src/hooks.mjs +106 -0
- package/src/host-config.mjs +108 -0
- package/src/integrations.mjs +100 -0
- package/src/mcp-server.mjs +114 -0
- package/src/menu.mjs +49 -0
- package/src/prompts.mjs +31 -0
- package/src/recall.mjs +64 -0
- package/src/review.mjs +166 -0
- package/src/setup.mjs +297 -0
- package/src/status.mjs +65 -0
- package/src/storage.mjs +76 -0
package/src/cli.mjs
ADDED
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
import { parseArgs } from 'node:util';
|
|
2
|
+
import { resolve, join, basename } from 'node:path';
|
|
3
|
+
import { existsSync, rmSync, realpathSync } from 'node:fs';
|
|
4
|
+
import { binding, projectRoot, preferences, mergePreferences, ignoreRuntime, readJson, writeJson, homeDir, serverUrl, DEFAULT_SERVER } from './storage.mjs';
|
|
5
|
+
import { localCommand, withBrain } from './brain.mjs';
|
|
6
|
+
import { withCloud, login, credentialPath } from './cloud.mjs';
|
|
7
|
+
import { connect } from './integrations.mjs';
|
|
8
|
+
import { runHook } from './hooks.mjs';
|
|
9
|
+
import { recall } from './recall.mjs';
|
|
10
|
+
import { reviewedWrite, finishReview } from './review.mjs';
|
|
11
|
+
|
|
12
|
+
const HELP = `mmx — project Brain operations and agent integrations (v0.1.1)
|
|
13
|
+
|
|
14
|
+
Setup:
|
|
15
|
+
mmx setup [--agent claude-code,codex] login, choose Brain, install MCP + rules/hooks
|
|
16
|
+
mmx setup --local --agent codex --yes local Brain without Cloud login
|
|
17
|
+
mmx setup --json return detailed setup results as JSON
|
|
18
|
+
mmx status [--online] [--json] show configuration and observed activity
|
|
19
|
+
mmx switch [--brain-id ID | --local] choose another Brain; keep login and data
|
|
20
|
+
mmx clean [--keep-login] [--yes] reset local setup and data; keep Cloud data
|
|
21
|
+
mmx remove [--agent NAME] remove setup entries; keep data and login
|
|
22
|
+
mmx init --local initialize/reuse a local Brain
|
|
23
|
+
mmx login [--server URL] [--no-open] OAuth PKCE browser login
|
|
24
|
+
mmx logout [--server URL] remove this CLI's saved credentials
|
|
25
|
+
mmx brain bind --brain-id ID [--server URL]
|
|
26
|
+
mmx brain bind --local explicitly choose the local Brain
|
|
27
|
+
mmx project create --workspace-id ID --name NAME --confirm
|
|
28
|
+
mmx connect --agent cursor|claude-code|codex
|
|
29
|
+
mmx disconnect --agent NAME remove only owned integration entries
|
|
30
|
+
mmx doctor [--online] [--json] diagnose configuration and connectivity
|
|
31
|
+
mmx doctor --fix [--yes] review and apply managed configuration repair
|
|
32
|
+
|
|
33
|
+
Brain (JSON output, automatically uses the selected local/cloud Brain):
|
|
34
|
+
mmx brain status | list | roots
|
|
35
|
+
mmx brain read ID | read-root SLUG
|
|
36
|
+
mmx brain index | reindex
|
|
37
|
+
mmx brain search QUERY | recall QUERY
|
|
38
|
+
cat decision.md | mmx brain create --id ID --title TITLE --category decision [--status draft] [--source TEXT]
|
|
39
|
+
cat decision.md | mmx brain update ID --expected-version VERSION --summary WHY [--source TEXT]
|
|
40
|
+
mmx brain append ID --kind evidence --summary TEXT [--source TEXT]
|
|
41
|
+
mmx brain archive ID
|
|
42
|
+
mmx brain review --review-token TOKEN --outcome saved|no-changes|already-covered|deferred --reason TEXT [--id ID]
|
|
43
|
+
Codex hooks supply the token. Pass it to Brain mutations with --review-token TOKEN.
|
|
44
|
+
cat root.md | mmx brain update-root SLUG --expected-version VERSION
|
|
45
|
+
New local/cloud root: --expected-version new. Existing roots require their current version.
|
|
46
|
+
|
|
47
|
+
Cloud discovery and low-level access:
|
|
48
|
+
mmx mcp serve stdio MCP sharing CLI authentication
|
|
49
|
+
mmx workspace list | project list | brain discover
|
|
50
|
+
mmx mcp tools
|
|
51
|
+
mmx mcp call TOOL --args '{"key":"value"}'
|
|
52
|
+
Low-level calls use your credentials and explicit arguments; they do not choose a Brain.
|
|
53
|
+
|
|
54
|
+
Run mmx without arguments in a terminal for the interactive menu.
|
|
55
|
+
All commands accept --project PATH. No automatic cloud-to-local fallback.
|
|
56
|
+
Cursor: startup context + prompt retrieval delivered at first tool call; one stop review.
|
|
57
|
+
Claude Code: startup + prompt context; one stop review. Codex: pre-answer review; Stop recovers a missing review once.
|
|
58
|
+
`;
|
|
59
|
+
|
|
60
|
+
async function stdin(limit = 1024 * 1024) {
|
|
61
|
+
if (process.stdin.isTTY) throw new Error('Pipe content through stdin.');
|
|
62
|
+
let value = '';
|
|
63
|
+
for await (const chunk of process.stdin) {
|
|
64
|
+
value += chunk;
|
|
65
|
+
if (Buffer.byteLength(value) > limit) throw new Error('stdin exceeds 1 MiB.');
|
|
66
|
+
}
|
|
67
|
+
return value;
|
|
68
|
+
}
|
|
69
|
+
const output = value => console.log(JSON.stringify(value, null, 2));
|
|
70
|
+
const need = (value, name) => { if (typeof value !== 'string' || !value.trim()) throw new Error(`${name} is required.`); return value; };
|
|
71
|
+
const body = async () => need((await stdin()).trim(), 'Nonempty stdin');
|
|
72
|
+
function cloudVersion(value) {
|
|
73
|
+
if (!/^[1-9]\d*$/.test(value) || !Number.isSafeInteger(Number(value))) throw new Error('--expected-version must be a positive integer for Cloud updates.');
|
|
74
|
+
return Number(value);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export async function main(argv = process.argv.slice(2)) {
|
|
78
|
+
const options = Object.fromEntries(['project', 'agent', 'brain-id', 'server', 'workspace-id', 'name', 'description', 'id', 'title', 'category', 'status', 'source', 'expected-version', 'summary', 'kind', 'args', 'review-token', 'outcome', 'reason'].map(key => [key, { type: 'string' }]));
|
|
79
|
+
for (const key of ['local', 'online', 'no-open', 'confirm', 'help', 'version', 'yes', 'migrate', 'json', 'keep-login', 'include-external-data', 'fix']) options[key] = { type: 'boolean' };
|
|
80
|
+
const { values: flags, positionals: pos } = parseArgs({ args: argv, options, allowPositionals: true, strict: true });
|
|
81
|
+
if (flags.version) { console.log('0.1.1'); return; }
|
|
82
|
+
if (flags.help || pos[0] === 'help' || (!pos.length && (!process.stdin.isTTY || !process.stderr.isTTY || flags.json || flags.yes))) { console.log(HELP); return; }
|
|
83
|
+
const root = realpathSync(flags.project ? resolve(flags.project) : projectRoot());
|
|
84
|
+
process.chdir(root);
|
|
85
|
+
if (!pos.length) {
|
|
86
|
+
const { runMenu } = await import('./menu.mjs');
|
|
87
|
+
await runMenu(root, { run: async args => {
|
|
88
|
+
process.exitCode = 0;
|
|
89
|
+
await main(['--project', root, ...args]);
|
|
90
|
+
} });
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
const [command, action, ...rest] = pos;
|
|
94
|
+
for (const key of ['title', 'summary', 'source']) {
|
|
95
|
+
if (flags[key] && /[\r\n\0]/.test(flags[key])) throw new Error(`--${key} must be a single line without NUL characters.`);
|
|
96
|
+
}
|
|
97
|
+
const selectedServer = () => serverUrl(flags.server || preferences(root).mindmuxCli?.server || readJson(join(homeDir(), 'config.json'), {}).server || DEFAULT_SERVER);
|
|
98
|
+
if (command === 'clean') {
|
|
99
|
+
const { clean } = await import('./clean.mjs');
|
|
100
|
+
const result = await clean(root, flags);
|
|
101
|
+
if (flags.json) output(result);
|
|
102
|
+
else if (result.cancelled) console.log('Cleanup cancelled.');
|
|
103
|
+
else console.log(`\n✓ Local MindMux setup has been reset.${result.signedOut ? ' You are signed out of the CLI.' : ''}\nCloud Projects and Brains are kept.\n\nRun mmx setup to start again.`);
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
if (command === 'setup' || command === 'remove' || command === 'switch') {
|
|
107
|
+
const { setup, removeSetup, switchBrain } = await import('./setup.mjs');
|
|
108
|
+
const result = await (command === 'switch' ? switchBrain(root, flags) : command === 'setup' ? setup(root, flags) : removeSetup(root, flags));
|
|
109
|
+
if (flags.json) output(result);
|
|
110
|
+
else if (command === 'remove') console.log(result.removed.length ? `Removed connections for ${result.removed.join(', ')}. Brain data, binding and login are kept.` : result.note);
|
|
111
|
+
else {
|
|
112
|
+
const agents = result.agents.map(agent => ({ 'claude-code': 'Claude Code', codex: 'Codex' })[agent] || agent).join(' and ');
|
|
113
|
+
const project = result.binding.kind === 'cloud' ? result.binding.name : basename(result.project);
|
|
114
|
+
const codexNote = result.agents.includes('codex') ? '\nIn Codex, trust this project and review the new or changed hooks with /hooks.' : '';
|
|
115
|
+
console.log(`\n✓ MindMux is ready.\n\nProject: ${project}\nConfigured for: ${agents}\n\nRestart ${agents} in this project and approve any trust prompts to get started.${codexNote}`);
|
|
116
|
+
}
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
if (command === 'mcp' && action === 'serve') {
|
|
120
|
+
const { serveMcp } = await import('./mcp-server.mjs');
|
|
121
|
+
await serveMcp(root); return;
|
|
122
|
+
}
|
|
123
|
+
if (command === 'hook') {
|
|
124
|
+
let input;
|
|
125
|
+
try { input = JSON.parse((await stdin()) || '{}'); }
|
|
126
|
+
catch { output({}); return; }
|
|
127
|
+
output(await runHook(root, flags.agent, action, input)); return;
|
|
128
|
+
}
|
|
129
|
+
if (command === 'login') {
|
|
130
|
+
const server = selectedServer();
|
|
131
|
+
await login(server, { open: !flags['no-open'] });
|
|
132
|
+
writeJson(join(homeDir(), 'config.json'), { server }); return;
|
|
133
|
+
}
|
|
134
|
+
if (command === 'logout') {
|
|
135
|
+
rmSync(credentialPath(selectedServer()), { force: true });
|
|
136
|
+
output({ signedOut: true, note: 'Removed this CLI’s local credentials. This does not revoke other clients or server grants.' }); return;
|
|
137
|
+
}
|
|
138
|
+
if (command === 'init') {
|
|
139
|
+
if (!flags.local) throw new Error('Choose --local explicitly, or run brain bind --brain-id <id> for Cloud.');
|
|
140
|
+
localCommand(root, ['init', '--no-wire']);
|
|
141
|
+
mergePreferences(root, { cloudBrain: { ...preferences(root).cloudBrain, enabled: false } });
|
|
142
|
+
ignoreRuntime(root);
|
|
143
|
+
output({ initialized: true, binding: binding(root), next: 'mmx connect --agent cursor' }); return;
|
|
144
|
+
}
|
|
145
|
+
if (command === 'connect' || command === 'disconnect') {
|
|
146
|
+
output(connect(root, need(flags.agent, '--agent'), { remove: command === 'disconnect' })); return;
|
|
147
|
+
}
|
|
148
|
+
if (command === 'status') {
|
|
149
|
+
const { status, formatStatus } = await import('./status.mjs');
|
|
150
|
+
const report = await status(root, flags);
|
|
151
|
+
if (flags.json) output(report); else console.log(formatStatus(report));
|
|
152
|
+
if (report.live?.accessible === false || report.mcpProbe?.connected === false) process.exitCode = 1;
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
if (command === 'doctor') {
|
|
156
|
+
const { doctor, formatDoctor } = await import('./doctor.mjs');
|
|
157
|
+
const report = await doctor(root, flags);
|
|
158
|
+
if (flags.json) output(report);
|
|
159
|
+
else {
|
|
160
|
+
console.log(formatDoctor(report));
|
|
161
|
+
if (report.repairResult) {
|
|
162
|
+
const result = report.repairResult;
|
|
163
|
+
console.log(result.applied ? '\n✓ Managed configuration repaired. Restart the configured agents.'
|
|
164
|
+
: result.cancelled ? '\nRepair cancelled. No changes were made.'
|
|
165
|
+
: `\n${result.error || result.reason}`);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
if (!report.healthy) process.exitCode = 1;
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
if ((command === 'workspace' && action === 'list') || (command === 'project' && action === 'list') || (command === 'brain' && action === 'discover')) {
|
|
172
|
+
const tool = command === 'workspace' ? 'list_workspaces' : command === 'project' ? 'list_projects' : 'list_brains';
|
|
173
|
+
output(await withCloud(selectedServer(), call => call(tool, flags['workspace-id'] ? { workspaceId: flags['workspace-id'] } : {}))); return;
|
|
174
|
+
}
|
|
175
|
+
if (command === 'project' && action === 'create') {
|
|
176
|
+
const workspaceId = need(flags['workspace-id'], '--workspace-id'), name = need(flags.name, '--name');
|
|
177
|
+
if (!flags.confirm) throw new Error('New projects are visible to all Workspace members. Pass --confirm after selecting this Workspace and Project name.');
|
|
178
|
+
output(await withCloud(selectedServer(), call => call('create_project', { workspaceId, name, description: flags.description || '' }))); return;
|
|
179
|
+
}
|
|
180
|
+
if (command === 'mcp') {
|
|
181
|
+
if (action === 'call') {
|
|
182
|
+
const args = JSON.parse(flags.args || '{}');
|
|
183
|
+
if (!args || Array.isArray(args) || typeof args !== 'object') throw new Error('--args must be a JSON object.');
|
|
184
|
+
output(await withCloud(selectedServer(), call => call(need(rest[0], 'tool name'), args))); return;
|
|
185
|
+
}
|
|
186
|
+
if (action === 'tools') {
|
|
187
|
+
const { listCloudTools } = await import('./cloud.mjs');
|
|
188
|
+
output(await listCloudTools(selectedServer())); return;
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
if (command === 'brain' && action === 'bind') {
|
|
192
|
+
if (flags.local && flags['brain-id']) throw new Error('Choose --local or --brain-id, not both.');
|
|
193
|
+
const prefs = preferences(root);
|
|
194
|
+
if (flags.local) {
|
|
195
|
+
localCommand(root, ['brain-dir']);
|
|
196
|
+
mergePreferences(root, { cloudBrain: { ...prefs.cloudBrain, enabled: false } });
|
|
197
|
+
} else {
|
|
198
|
+
const brainId = need(flags['brain-id'], '--brain-id'), server = selectedServer();
|
|
199
|
+
const result = await withCloud(server, call => call('resolve_brain', { brainId }));
|
|
200
|
+
if (result.status !== 'resolved') throw new Error('Cloud Brain unavailable; binding was not changed.');
|
|
201
|
+
mergePreferences(root, { cloudBrain: { enabled: true, brainId, name: result.brain?.name || brainId }, mindmuxCli: { ...prefs.mindmuxCli, server } });
|
|
202
|
+
}
|
|
203
|
+
ignoreRuntime(root); output(binding(root)); return;
|
|
204
|
+
}
|
|
205
|
+
if (command === 'brain' && action === 'status') { output(binding(root)); return; }
|
|
206
|
+
if (command === 'brain' && action === 'review') {
|
|
207
|
+
output(await finishReview(root, { token: flags['review-token'], outcome: flags.outcome, reason: flags.reason, id: flags.id })); return;
|
|
208
|
+
}
|
|
209
|
+
if (command === 'brain') {
|
|
210
|
+
// Validate operation before opening a cloud connection.
|
|
211
|
+
if (!['index', 'reindex', 'list', 'roots', 'read', 'read-root', 'search', 'recall', 'create', 'update', 'append', 'archive', 'update-root'].includes(action)) throw new Error('Unknown brain command. Run mmx help.');
|
|
212
|
+
let content;
|
|
213
|
+
if (['create', 'update', 'update-root'].includes(action)) content = await body();
|
|
214
|
+
const result = await withBrain(root, async brain => {
|
|
215
|
+
const mutate = (resource, run) => reviewedWrite(root, flags['review-token'], brain, resource, run);
|
|
216
|
+
switch (action) {
|
|
217
|
+
case 'index': return brain.index();
|
|
218
|
+
case 'reindex': return brain.reindex();
|
|
219
|
+
case 'list': return { pages: (await brain.list()).map(({ raw, compiledTruth, ...page }) => page) };
|
|
220
|
+
case 'roots': return { rootPages: await brain.roots() };
|
|
221
|
+
case 'read': return brain.read(need(rest[0], 'page id'));
|
|
222
|
+
case 'read-root': return brain.readRoot(need(rest[0], 'root slug'));
|
|
223
|
+
case 'search': return { pages: await brain.search(need(rest.join(' '), 'query')) };
|
|
224
|
+
case 'recall': return recall(brain, rest.join(' '));
|
|
225
|
+
case 'create': {
|
|
226
|
+
const id = need(flags.id, '--id'), title = need(flags.title, '--title'), category = need(flags.category, '--category');
|
|
227
|
+
if (!/^[a-z0-9][a-z0-9-]*$/.test(id) || /[\r\n]/.test(title)) throw new Error('Invalid page id or multiline title.');
|
|
228
|
+
if (!['project', 'concept', 'decision', 'person', 'reference'].includes(category)) throw new Error('Invalid page category.');
|
|
229
|
+
if (flags.status && !['active', 'draft', 'archived'].includes(flags.status)) throw new Error('Invalid page status.');
|
|
230
|
+
return mutate({ kind: 'page', id }, () => brain.create({ id, title, category, status: flags.status || 'active', compiledTruth: content, creationSummary: flags.source || 'Captured through MindMux CLI' }));
|
|
231
|
+
}
|
|
232
|
+
case 'update': {
|
|
233
|
+
const expected = need(flags['expected-version'], '--expected-version');
|
|
234
|
+
return mutate({ kind: 'page', id: need(rest[0], 'page id') }, () => brain.update({ id: rest[0], compiledTruth: content,
|
|
235
|
+
expectedVersion: brain.target.kind === 'cloud' ? cloudVersion(expected) : expected,
|
|
236
|
+
timelineEntry: { kind: 'decision', summary: need(flags.summary, '--summary'), source: flags.source || 'MindMux CLI' } }));
|
|
237
|
+
}
|
|
238
|
+
case 'append': {
|
|
239
|
+
const kind = flags.kind || 'evidence';
|
|
240
|
+
if (!['decision', 'evidence', 'reversal', 'note'].includes(kind)) throw new Error('Invalid timeline kind.');
|
|
241
|
+
return mutate({ kind: 'page', id: need(rest[0], 'page id') }, () => brain.append({ id: rest[0], entry: { kind, summary: need(flags.summary, '--summary'), source: flags.source || 'MindMux CLI' } }));
|
|
242
|
+
}
|
|
243
|
+
case 'archive': return mutate({ kind: 'page', id: need(rest[0], 'page id') }, () => brain.archive(rest[0]));
|
|
244
|
+
case 'update-root': {
|
|
245
|
+
const expected = need(flags['expected-version'], '--expected-version');
|
|
246
|
+
return mutate({ kind: 'root', id: need(rest[0], 'root slug') }, () => brain.updateRoot({ slug: rest[0], body: content,
|
|
247
|
+
expectedVersion: brain.target.kind === 'cloud' && expected !== 'new' ? cloudVersion(expected) : expected }));
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
});
|
|
251
|
+
output(result); return;
|
|
252
|
+
}
|
|
253
|
+
throw new Error('Unknown command. Run mmx help.');
|
|
254
|
+
}
|
package/src/cloud.mjs
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
2
|
+
import { createServer } from 'node:http';
|
|
3
|
+
import { spawn } from 'node:child_process';
|
|
4
|
+
import { mkdir, rm } from 'node:fs/promises';
|
|
5
|
+
import { mkdirSync, rmSync } from 'node:fs';
|
|
6
|
+
import { join } from 'node:path';
|
|
7
|
+
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
|
|
8
|
+
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
|
|
9
|
+
import { auth } from '@modelcontextprotocol/sdk/client/auth.js';
|
|
10
|
+
import { homeDir, readJson, writeJson, serverUrl } from './storage.mjs';
|
|
11
|
+
|
|
12
|
+
export const credentialPath = server => join(homeDir(), 'auth', `${createHash('sha256').update(server).digest('hex')}.json`);
|
|
13
|
+
export const timedFetch = (url, options = {}) => fetch(url, { ...options,
|
|
14
|
+
signal: options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(6000)]) : AbortSignal.timeout(6000) });
|
|
15
|
+
|
|
16
|
+
const activeLocks = new Set();
|
|
17
|
+
function releaseOnSignal(signal) {
|
|
18
|
+
for (const path of activeLocks) rmSync(path, { recursive: true, force: true });
|
|
19
|
+
process.exit(signal === 'SIGINT' ? 130 : 143);
|
|
20
|
+
}
|
|
21
|
+
const onInterrupt = () => releaseOnSignal('SIGINT');
|
|
22
|
+
const onTerminate = () => releaseOnSignal('SIGTERM');
|
|
23
|
+
|
|
24
|
+
// Serialize token refresh across overlapping hooks and CLI calls. Never replay a write.
|
|
25
|
+
export async function withAuthLock(server, run) {
|
|
26
|
+
const path = `${credentialPath(server)}.lock`;
|
|
27
|
+
mkdirSync(join(homeDir(), 'auth'), { recursive: true, mode: 0o700 });
|
|
28
|
+
const end = Date.now() + 15000;
|
|
29
|
+
for (;;) {
|
|
30
|
+
try { await mkdir(path, { mode: 0o700 }); break; }
|
|
31
|
+
catch (error) {
|
|
32
|
+
if (error.code !== 'EEXIST') throw error;
|
|
33
|
+
if (Date.now() > end) throw new Error(`Authentication is busy. If a previous process crashed, remove ${path}.`);
|
|
34
|
+
await new Promise(resolve => setTimeout(resolve, 80));
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
if (!activeLocks.size) { process.on('SIGINT', onInterrupt); process.on('SIGTERM', onTerminate); }
|
|
38
|
+
activeLocks.add(path);
|
|
39
|
+
const cleanup = () => rmSync(path, { recursive: true, force: true });
|
|
40
|
+
process.once('exit', cleanup);
|
|
41
|
+
try { return await run(); } finally {
|
|
42
|
+
process.removeListener('exit', cleanup);
|
|
43
|
+
await rm(path, { recursive: true, force: true });
|
|
44
|
+
activeLocks.delete(path);
|
|
45
|
+
if (!activeLocks.size) { process.removeListener('SIGINT', onInterrupt); process.removeListener('SIGTERM', onTerminate); }
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export class AuthProvider {
|
|
50
|
+
constructor(server, { interactive = false, redirectUrl, onRedirect } = {}) {
|
|
51
|
+
this.path = credentialPath(server);
|
|
52
|
+
this.data = readJson(this.path, {});
|
|
53
|
+
this.interactive = interactive;
|
|
54
|
+
this.callback = redirectUrl || this.data.redirectUrl;
|
|
55
|
+
this.onRedirect = onRedirect;
|
|
56
|
+
this.oauthState = randomBytes(32).toString('hex');
|
|
57
|
+
}
|
|
58
|
+
get redirectUrl() { return this.callback; }
|
|
59
|
+
get clientMetadata() { return { client_name: 'MindMux CLI', redirect_uris: [this.callback],
|
|
60
|
+
grant_types: ['authorization_code', 'refresh_token'], response_types: ['code'],
|
|
61
|
+
token_endpoint_auth_method: 'none', scope: 'mindmux:brain:read mindmux:brain:write' }; }
|
|
62
|
+
state() { return this.oauthState; }
|
|
63
|
+
clientInformation() { return this.data.client; }
|
|
64
|
+
saveClientInformation(client) { this.data.client = client; this.save(); }
|
|
65
|
+
tokens() { return this.data.tokens; }
|
|
66
|
+
saveTokens(tokens) { this.data.tokens = tokens; this.save(); }
|
|
67
|
+
saveCodeVerifier(verifier) {
|
|
68
|
+
if (!this.interactive) throw new Error('Cloud login required. Run mmx login.');
|
|
69
|
+
this.verifier = verifier;
|
|
70
|
+
}
|
|
71
|
+
codeVerifier() { if (!this.verifier) throw new Error('Missing OAuth verifier. Run mmx login again.'); return this.verifier; }
|
|
72
|
+
redirectToAuthorization(url) {
|
|
73
|
+
if (!this.interactive) throw new Error('Cloud login required. Run mmx login.');
|
|
74
|
+
this.onRedirect(url);
|
|
75
|
+
}
|
|
76
|
+
invalidateCredentials(scope) {
|
|
77
|
+
if (scope === 'all') this.data = {};
|
|
78
|
+
if (scope === 'tokens') delete this.data.tokens;
|
|
79
|
+
if (scope === 'client') delete this.data.client;
|
|
80
|
+
if (scope === 'verifier') this.verifier = undefined;
|
|
81
|
+
this.save();
|
|
82
|
+
}
|
|
83
|
+
save() { if (!this.staging) writeJson(this.path, { ...this.data, redirectUrl: this.callback }); }
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export async function withCloud(server, run) {
|
|
87
|
+
server = serverUrl(server);
|
|
88
|
+
return withAuthLock(server, async () => {
|
|
89
|
+
const provider = new AuthProvider(server);
|
|
90
|
+
if (!provider.tokens()) throw new Error(`Cloud login required. Run mmx login --server ${server}.`);
|
|
91
|
+
const client = new Client({ name: 'mindmux-cli', version: '0.1.1' });
|
|
92
|
+
const transport = new StreamableHTTPClientTransport(new URL(server), { authProvider: provider,
|
|
93
|
+
fetch: timedFetch, reconnectionOptions: { maxRetries: 0 } });
|
|
94
|
+
try {
|
|
95
|
+
await client.connect(transport, { timeout: 6000 });
|
|
96
|
+
const call = async (name, args = {}) => {
|
|
97
|
+
const result = await call.raw(name, args);
|
|
98
|
+
const text = result.content?.filter(item => item.type === 'text').map(item => item.text).join('\n') || '';
|
|
99
|
+
if (result.isError) throw new Error(text || `MCP ${name} failed`);
|
|
100
|
+
if (result.structuredContent) return result.structuredContent;
|
|
101
|
+
try { return JSON.parse(text); } catch { return { text }; }
|
|
102
|
+
};
|
|
103
|
+
call.raw = (name, args = {}) => client.callTool({ name, arguments: args }, undefined, { timeout: 6000 });
|
|
104
|
+
call.listTools = async () => {
|
|
105
|
+
const tools = []; let cursor;
|
|
106
|
+
do { const result = await client.listTools({ cursor }, { timeout: 6000 }); tools.push(...result.tools); cursor = result.nextCursor; } while (cursor);
|
|
107
|
+
return { tools };
|
|
108
|
+
};
|
|
109
|
+
return await run(call);
|
|
110
|
+
} finally { await client.close().catch(() => {}); }
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export const listCloudTools = server => withCloud(server, call => call.listTools());
|
|
115
|
+
|
|
116
|
+
export async function login(server, { open = true, output = console.error, onAuthorization } = {}) {
|
|
117
|
+
server = serverUrl(server);
|
|
118
|
+
return withAuthLock(server, async () => {
|
|
119
|
+
let provider, resolveCode, rejectCode;
|
|
120
|
+
const codePromise = new Promise((resolve, reject) => { resolveCode = resolve; rejectCode = reject; });
|
|
121
|
+
// A callback may reject while discovery is still running.
|
|
122
|
+
codePromise.catch(() => {});
|
|
123
|
+
const callbackServer = createServer((request, response) => {
|
|
124
|
+
const url = new URL(request.url, 'http://127.0.0.1');
|
|
125
|
+
if (url.pathname !== '/callback') { response.writeHead(404).end(); return; }
|
|
126
|
+
if (url.searchParams.get('state') !== provider.oauthState) { response.writeHead(400).end('Invalid OAuth state'); return; }
|
|
127
|
+
if (url.searchParams.has('error')) {
|
|
128
|
+
response.writeHead(400).end('Authorization declined. Return to the terminal.');
|
|
129
|
+
rejectCode(new Error('Authorization declined.')); return;
|
|
130
|
+
}
|
|
131
|
+
const code = url.searchParams.get('code');
|
|
132
|
+
if (!code) { response.writeHead(400).end('Missing code'); return; }
|
|
133
|
+
response.writeHead(200, { 'Content-Type': 'text/plain', 'Cache-Control': 'no-store' }).end('MindMux authorization received. Return to the terminal.');
|
|
134
|
+
resolveCode(code);
|
|
135
|
+
});
|
|
136
|
+
await new Promise((resolve, reject) => { callbackServer.once('error', reject); callbackServer.listen(0, '127.0.0.1', resolve); });
|
|
137
|
+
const redirectUrl = `http://127.0.0.1:${callbackServer.address().port}/callback`;
|
|
138
|
+
provider = new AuthProvider(server, { interactive: true, redirectUrl, onRedirect: url => {
|
|
139
|
+
output(`Authorize MindMux CLI in your browser:\n${url.href}`);
|
|
140
|
+
onAuthorization?.(url);
|
|
141
|
+
if (open) {
|
|
142
|
+
const command = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'explorer.exe' : 'xdg-open';
|
|
143
|
+
const child = spawn(command, [url.href], { stdio: 'ignore' });
|
|
144
|
+
child.on('error', () => output('Open the authorization URL above manually.'));
|
|
145
|
+
child.unref();
|
|
146
|
+
}
|
|
147
|
+
} });
|
|
148
|
+
// A fresh loopback port needs a fresh dynamic registration. Preserve old credentials until successful login.
|
|
149
|
+
provider.data = {};
|
|
150
|
+
provider.staging = true;
|
|
151
|
+
const timer = setTimeout(() => rejectCode(new Error('Login timed out after 3 minutes.')), 180000);
|
|
152
|
+
try {
|
|
153
|
+
const result = await auth(provider, { serverUrl: server, fetchFn: timedFetch });
|
|
154
|
+
if (result === 'REDIRECT') {
|
|
155
|
+
const code = await codePromise;
|
|
156
|
+
const done = await auth(provider, { serverUrl: server, authorizationCode: code, fetchFn: timedFetch });
|
|
157
|
+
if (done !== 'AUTHORIZED') throw new Error('OAuth authorization did not complete.');
|
|
158
|
+
}
|
|
159
|
+
provider.staging = false;
|
|
160
|
+
provider.save();
|
|
161
|
+
output('MindMux CLI is signed in.');
|
|
162
|
+
} finally { clearTimeout(timer); await new Promise(resolve => callbackServer.close(resolve)); }
|
|
163
|
+
});
|
|
164
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process';
|
|
2
|
+
|
|
3
|
+
// Feature discovery avoids guessing a minimum version or changing global Codex settings.
|
|
4
|
+
export function inspectCodexHooks(run = execFileSync) {
|
|
5
|
+
try {
|
|
6
|
+
const output = run('codex', ['features', 'list'], { encoding: 'utf8', timeout: 4000, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
7
|
+
const match = output.split(/\r?\n/).find(line => /^hooks\s/.test(line))?.match(/\s(true|false)\s*$/);
|
|
8
|
+
if (!match) return { supported: false, enabled: false, message: 'Codex does not report hooks support. Update Codex before using this integration.' };
|
|
9
|
+
return { supported: true, enabled: match[1] === 'true', message: match[1] === 'true'
|
|
10
|
+
? 'Codex hooks are enabled. Project and hook trust must still be reviewed in Codex with /hooks.'
|
|
11
|
+
: 'Codex hooks are disabled. Enable them with codex features enable hooks, then review /hooks.' };
|
|
12
|
+
} catch {
|
|
13
|
+
return { supported: null, enabled: null, message: 'Could not verify Codex hooks support. Install or update Codex, then run mmx doctor.' };
|
|
14
|
+
}
|
|
15
|
+
}
|
package/src/doctor.mjs
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { inspectCodexHooks } from './codex-hooks.mjs';
|
|
2
|
+
import { status } from './status.mjs';
|
|
3
|
+
import { planRepair, applyRepair, legacyWarnings } from './setup.mjs';
|
|
4
|
+
import { createSetupPrompts } from './prompts.mjs';
|
|
5
|
+
|
|
6
|
+
export async function diagnose(root, flags = {}, dependencies = {}) {
|
|
7
|
+
let report;
|
|
8
|
+
try { report = await status(root, flags, dependencies); }
|
|
9
|
+
catch (error) {
|
|
10
|
+
return { project: root, healthy: false, checks: [{ state: 'error', message: error.message,
|
|
11
|
+
next: 'Repair the invalid configuration manually, then run mmx doctor again.' }],
|
|
12
|
+
repair: { available: false, reason: 'Invalid or unsafe configuration cannot be repaired automatically.' } };
|
|
13
|
+
}
|
|
14
|
+
const checks = [];
|
|
15
|
+
const check = (ok, message, next) => checks.push({ state: ok ? 'ok' : 'error', message, ...(ok ? {} : { next }) });
|
|
16
|
+
check(report.binding.kind !== 'unbound', report.binding.kind === 'unbound' ? 'No Brain selected.' : 'Project Brain is selected.', 'Run mmx setup to choose a Brain.');
|
|
17
|
+
if (report.binding.kind === 'cloud') check(report.credentialsPresent, report.credentialsPresent ? 'CLI credentials are saved; use --online to validate access.' : 'CLI credentials are missing.', 'Run mmx login, then mmx doctor --online.');
|
|
18
|
+
if (report.mcp.length) checks.push({ state: 'ok', message: 'Setup-managed agents found.' });
|
|
19
|
+
else checks.push({ state: 'warning', message: 'No setup-managed agents found.', next: 'Run mmx setup to configure agents, or keep using your existing connect-only integration.' });
|
|
20
|
+
for (const item of report.mcp) {
|
|
21
|
+
check(item.configured && item.executablePresent, `${item.agent}: MCP configuration and launcher ${item.configured && item.executablePresent ? 'are present' : 'need attention'}.`, 'Run mmx doctor --fix to review a repair plan.');
|
|
22
|
+
if (!report.integrations.some(i => i.agent === item.agent)) checks.push({ state: 'error', message: `${item.agent}: managed instructions and hooks are missing.`, next: 'Run mmx doctor --fix to restore the integration.' });
|
|
23
|
+
}
|
|
24
|
+
for (const integration of report.integrations) {
|
|
25
|
+
check(integration?.rulesPresent && integration?.hookCommandsPresent && integration?.executablePresent,
|
|
26
|
+
`${integration.agent}: project instructions and hooks ${integration?.rulesPresent && integration?.hookCommandsPresent && integration?.executablePresent ? 'are present' : 'need attention'}.`,
|
|
27
|
+
'Run mmx doctor --fix to restore managed instructions and hooks.');
|
|
28
|
+
}
|
|
29
|
+
if (report.mcp.some(item => item.agent === 'codex') || report.integrations.some(item => item.agent === 'codex')) {
|
|
30
|
+
report.codexHooks = (dependencies.codexHooks || inspectCodexHooks)();
|
|
31
|
+
if (report.codexHooks.supported === null) checks.push({ state: 'warning', message: report.codexHooks.message });
|
|
32
|
+
else check(report.codexHooks.supported && report.codexHooks.enabled, report.codexHooks.message, 'Install a compatible Codex with hooks enabled, then review the project and /hooks trust prompts.');
|
|
33
|
+
}
|
|
34
|
+
if (report.live) check(report.live.accessible, report.live.accessible ? 'Brain access check passed.' : `Brain access failed: ${report.live.error}`, 'Check your network, login and Brain permissions; rerun mmx doctor --online.');
|
|
35
|
+
if (report.mcpProbe) check(report.mcpProbe.connected, report.mcpProbe.connected ? 'MCP launch and recall check passed.' : `MCP check failed: ${report.mcpProbe.error}`, 'Run mmx doctor --fix to review the managed configuration.');
|
|
36
|
+
const review = report.receipts.find(item => item.agent === 'codex' && ['stop', 'review', 'interrupt'].includes(item.event));
|
|
37
|
+
if (review && ['review-failed', 'recovery-exhausted', 'review-expired', 'review-unavailable'].includes(review.status)) {
|
|
38
|
+
checks.push({ state: 'warning', message: `Codex memory review: ${review.status}.${review.error ? ` ${review.error}` : ''}`,
|
|
39
|
+
next: 'Inspect mmx status --json. Retry failed Brain operations; use current Codex hooks with session and turn identifiers. Never assume memory was saved.' });
|
|
40
|
+
}
|
|
41
|
+
const warnings = [...legacyWarnings(root), ...report.integrations.filter(i => i.existingBrainMdHook).map(i => `${i.agent}: an existing brain.md hook may deliver duplicate context.`)];
|
|
42
|
+
for (const message of warnings) checks.push({ state: 'warning', message, next: 'Review the existing integration before migrating it with mmx setup --migrate.' });
|
|
43
|
+
let repair;
|
|
44
|
+
try { repair = { available: true, ...planRepair(root) }; }
|
|
45
|
+
catch (error) {
|
|
46
|
+
repair = { available: false, reason: error.message };
|
|
47
|
+
// A setup-managed project failing preflight is unhealthy, even if its files exist.
|
|
48
|
+
// Connect-only installations have no repair plan and remain supported.
|
|
49
|
+
if (report.mcp.length) checks.push({ state: 'error', message: `Configuration preflight failed: ${error.message}`,
|
|
50
|
+
next: 'Resolve the configuration conflict, then run mmx doctor again.' });
|
|
51
|
+
}
|
|
52
|
+
return { ...report, node: process.version, checks, warnings, repair, healthy: !checks.some(item => item.state === 'error') };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function formatDoctor(report) {
|
|
56
|
+
const icons = { ok: '✓', warning: '!', error: '✗' };
|
|
57
|
+
const lines = ['MindMux doctor', ''];
|
|
58
|
+
for (const item of report.checks) {
|
|
59
|
+
lines.push(`${icons[item.state]} ${item.message}`);
|
|
60
|
+
if (item.next) lines.push(` ${item.next}`);
|
|
61
|
+
}
|
|
62
|
+
if (!report.live) lines.push('', 'Use mmx doctor --online to check live Brain access and MCP recall.');
|
|
63
|
+
if (report.integrations?.some(item => item.agent === 'codex')) lines.push('Codex hook trust is managed by Codex. Review /hooks; configuration does not prove trust or execution.');
|
|
64
|
+
if (!report.healthy && !report.repair.available) lines.push('', `Automatic repair unavailable: ${report.repair.reason}`);
|
|
65
|
+
lines.push('', 'Configuration and self-checks do not prove that an agent used recalled knowledge.');
|
|
66
|
+
return lines.join('\n');
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export function formatRepair(plan) {
|
|
70
|
+
return ['Repair plan', ...plan.actions.map(action => `• ${action}`), '', 'Files that may change:', ...plan.files.map(file => ` ${file}`), '', plan.note].join('\n');
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export async function doctor(root, flags = {}, dependencies = {}) {
|
|
74
|
+
const inspect = dependencies.diagnose || diagnose;
|
|
75
|
+
const report = await inspect(root, flags, dependencies);
|
|
76
|
+
if (!flags.fix) return report;
|
|
77
|
+
if (!report.repair.available) return { ...report, repairResult: { applied: false, reason: report.repair.reason } };
|
|
78
|
+
if (report.healthy) return { ...report, repairResult: { applied: false, reason: 'No configuration issues found. No changes were made.' } };
|
|
79
|
+
const interactive = Boolean(dependencies.prompts || (process.stdin.isTTY && process.stderr.isTTY));
|
|
80
|
+
if (!flags.yes) {
|
|
81
|
+
if (!interactive) return { ...report, repairResult: { applied: false, reason: 'Review the plan with mmx doctor --json, then use --fix --yes in a non-interactive terminal.' } };
|
|
82
|
+
process.stderr.write(`Issues found:\n${report.checks.filter(item => item.state === 'error').map(item => `• ${item.message}`).join('\n')}\n\n${formatRepair(report.repair)}\n`);
|
|
83
|
+
try {
|
|
84
|
+
if (!await (dependencies.prompts || createSetupPrompts()).confirm('Apply this repair plan?')) return { ...report, repairResult: { applied: false, cancelled: true } };
|
|
85
|
+
} catch (error) {
|
|
86
|
+
if (error.name !== 'ExitPromptError') throw error;
|
|
87
|
+
return { ...report, repairResult: { applied: false, cancelled: true } };
|
|
88
|
+
}
|
|
89
|
+
} else if (!flags.json) process.stderr.write(`${formatRepair(report.repair)}\n`);
|
|
90
|
+
try {
|
|
91
|
+
const result = await (dependencies.applyRepair || applyRepair)(root, report.repair, flags, dependencies);
|
|
92
|
+
const verified = await inspect(root, flags, dependencies);
|
|
93
|
+
return { ...verified, repairResult: { applied: true, backup: result.backup, next: 'Restart the configured agents in this project.' } };
|
|
94
|
+
} catch (error) { return { ...report, healthy: false, repairResult: { applied: false, error: error.message } }; }
|
|
95
|
+
}
|
package/src/hooks.mjs
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { binding, readJson, writeJson } from './storage.mjs';
|
|
4
|
+
import { withBrain } from './brain.mjs';
|
|
5
|
+
import { recall } from './recall.mjs';
|
|
6
|
+
import { beginReview, currentReview, stopReview, targetKey } from './review.mjs';
|
|
7
|
+
import { CLI_BIN, shellQuote } from './integrations.mjs';
|
|
8
|
+
import { homeDir } from './storage.mjs';
|
|
9
|
+
|
|
10
|
+
const digest = text => createHash('sha256').update(text).digest('hex');
|
|
11
|
+
export { targetKey } from './review.mjs';
|
|
12
|
+
const statePath = (root, agent, input) => join(root, '.mindmux/cli/sessions', `${agent}-${digest(String(input.session_id || input.conversation_id || 'default'))}.json`);
|
|
13
|
+
export function recordHook(root, agent, event, values) {
|
|
14
|
+
writeJson(join(root, `.mindmux/cli/last-${agent}-${event}.json`), { time: new Date().toISOString(), targetKey: targetKey(root), agent, event, ...values });
|
|
15
|
+
}
|
|
16
|
+
const MEMORY_CHECK = 'MindMux memory check (once this turn): if this task settled a durable requirement, constraint or decision that has not already been captured, search/read the bound Brain and record it with its source. Do not store guesses or routine progress. If nothing qualifies, finish without writing. Do not repeat this check. Keep your final response focused on the user’s original request, in the user’s working language and requested format. Do not replace the answer with a memory-check report; if you already answered, preserve the substantive answer in the final response.';
|
|
17
|
+
const unboundContext = 'MindMux: this project has no selected Brain. Ask the user to choose an existing Cloud Brain, create a Project in an explicitly selected Workspace, or use mmx init --local. Do not infer a Brain from the folder name.';
|
|
18
|
+
|
|
19
|
+
function reviewInstructions(root, state) {
|
|
20
|
+
const prefix = `env ${shellQuote('MINDMUX_HOME=' + homeDir())} ${shellQuote(process.execPath)} ${shellQuote(CLI_BIN)} --project ${shellQuote(root)}`;
|
|
21
|
+
return `${state.receipt ? 'MindMux: this turn already has a registered review; repeat it only if new knowledge or another Brain write requires it.\n' : ''}MindMux memory review: BEFORE your final answer, check this entire task for uncaptured confirmed durable knowledge. Do not store greetings, guesses, tentative proposals or routine progress. Write and verify qualifying knowledge through the bound Brain.\nFor ALL Brain mutations this turn, pass --review-token ${state.token} to the CLI, or reviewToken to the mindmux_brain MCP tool. This lets the CLI verify successful writes. Raw Cloud tools cannot provide this verification.\nThen register the outcome: ${prefix} brain review --review-token ${state.token} --outcome <saved|no-changes|already-covered|deferred> --reason "short factual reason in the user's language" [--id existing-page]. saved requires actual verified writes in this turn; already-covered requires a relevant existing Page id; no-changes needs no Brain write. If persistence fails, report deferred with the reason instead of claiming success.\nMCP equivalent: mindmux_brain operation=review, reviewToken=${state.token}, outcome, reason, and id for already-covered. This is local workflow metadata, not a Brain Page. Complete it before answering and give one substantive response to the original task; do not add a separate memory-check report.`;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
async function codexHook(root, event, input) {
|
|
25
|
+
if (event === 'stop' || event === 'interrupt') {
|
|
26
|
+
const result = await stopReview(root, event === 'interrupt' ? { ...input, hook_event_name: 'Interrupt' } : input);
|
|
27
|
+
const { state, ...receipt } = result;
|
|
28
|
+
recordHook(root, 'codex', event, receipt);
|
|
29
|
+
if (state) return { decision: 'block', reason: `${reviewInstructions(root, state)}\nThis is the single recovery attempt. After completing it, preserve a substantive final answer to the original user task in their language. Never return an empty final answer or replace it with a memory-check status. The host may show this recovery and repeat the answer.` };
|
|
30
|
+
return {};
|
|
31
|
+
}
|
|
32
|
+
if (event === 'pre-tool') return {};
|
|
33
|
+
const previous = await currentReview(root, input);
|
|
34
|
+
// Some hosts resubmit the Stop reason as a prompt in the same turn.
|
|
35
|
+
if (event === 'prompt' && previous?.status === 'recovering' && (input.stop_hook_active || String(input.prompt).startsWith('MindMux memory review:'))) return {};
|
|
36
|
+
const state = event === 'prompt' ? await beginReview(root, input) : previous;
|
|
37
|
+
let result;
|
|
38
|
+
try {
|
|
39
|
+
result = binding(root).kind === 'unbound' ? { context: unboundContext, pageIds: [] }
|
|
40
|
+
: await withBrain(root, brain => recall(brain, event === 'prompt' ? String(input.prompt || '').slice(0, 12000) : ''));
|
|
41
|
+
} catch (error) {
|
|
42
|
+
recordHook(root, 'codex', event, { status: 'error', error: error.message.slice(0, 500) });
|
|
43
|
+
// Preserve review instructions even if recall failed; never reuse cached knowledge.
|
|
44
|
+
return { hookSpecificOutput: { hookEventName: event === 'prompt' ? 'UserPromptSubmit' : 'SessionStart',
|
|
45
|
+
additionalContext: `MindMux recall failed. Do not infer missing knowledge or switch Brains. ${state ? reviewInstructions(root, state) : 'Use mmx doctor to inspect the connection.'}` } };
|
|
46
|
+
}
|
|
47
|
+
writeJson(statePath(root, 'codex', input), { targetKey: targetKey(root), ...result, recalledAt: Date.now() });
|
|
48
|
+
recordHook(root, 'codex', event, { status: 'emitted', pageIds: result.pageIds, indexCount: result.count, indexSource: result.indexSource,
|
|
49
|
+
bytes: Buffer.byteLength(result.context), review: state ? state.receipt ? 'registered' : 'pending' : 'unavailable', note: 'Returned to host; model usage is not observable.' });
|
|
50
|
+
return { hookSpecificOutput: { hookEventName: event === 'prompt' ? 'UserPromptSubmit' : 'SessionStart',
|
|
51
|
+
additionalContext: result.context + (state ? '\n\n' + reviewInstructions(root, state) : '') } };
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export async function handleHook(root, agent, event, input) {
|
|
55
|
+
if (!['cursor', 'claude-code', 'codex'].includes(agent)) throw new Error('Hooks support cursor, claude-code and codex.');
|
|
56
|
+
if (!['session-start', 'prompt', 'pre-tool', 'stop', 'interrupt'].includes(event)) throw new Error('Unknown hook event.');
|
|
57
|
+
if (agent === 'codex') return codexHook(root, event, input);
|
|
58
|
+
const path = statePath(root, agent, input);
|
|
59
|
+
let state = readJson(path, {});
|
|
60
|
+
const key = targetKey(root);
|
|
61
|
+
if (state.targetKey !== key) state = { targetKey: key };
|
|
62
|
+
const outputContext = (context, hookEventName) => agent === 'cursor' ? { additional_context: context }
|
|
63
|
+
: { hookSpecificOutput: { hookEventName, additionalContext: context } };
|
|
64
|
+
if (event === 'stop') {
|
|
65
|
+
if (state.stopped || input.stop_hook_active || Number(input.loop_count || 0) > 0 || ['aborted', 'error'].includes(input.status)) return {};
|
|
66
|
+
state.stopped = true;
|
|
67
|
+
writeJson(path, state);
|
|
68
|
+
recordHook(root, agent, event, { status: 'review-requested' });
|
|
69
|
+
return agent === 'cursor' ? { followup_message: MEMORY_CHECK } : { decision: 'block', reason: MEMORY_CHECK };
|
|
70
|
+
}
|
|
71
|
+
if (event === 'pre-tool') {
|
|
72
|
+
if (agent !== 'cursor' || !state.context || state.delivered) return {};
|
|
73
|
+
if (Date.now() - state.recalledAt > 10 * 60 * 1000) return {};
|
|
74
|
+
state.delivered = true;
|
|
75
|
+
writeJson(path, state);
|
|
76
|
+
recordHook(root, agent, event, { status: 'emitted', pageIds: state.pageIds || [], bytes: Buffer.byteLength(state.context),
|
|
77
|
+
note: 'Returned to host; model usage is not observable.' });
|
|
78
|
+
return outputContext(state.context);
|
|
79
|
+
}
|
|
80
|
+
const stopped = false;
|
|
81
|
+
// Invalidate previous-turn context before any retrieval that may fail.
|
|
82
|
+
writeJson(path, { targetKey: key, stopped });
|
|
83
|
+
const result = binding(root).kind === 'unbound' ? { context: unboundContext, pageIds: [] }
|
|
84
|
+
: await withBrain(root, brain => recall(brain, event === 'prompt' ? String(input.prompt || '').slice(0, 12000) : ''));
|
|
85
|
+
state = { targetKey: key, context: result.context, pageIds: result.pageIds, indexCount: result.count, indexSource: result.indexSource, recalledAt: Date.now(), stopped,
|
|
86
|
+
delivered: agent !== 'cursor' || event === 'session-start' };
|
|
87
|
+
writeJson(path, state);
|
|
88
|
+
recordHook(root, agent, event, { status: state.delivered ? 'emitted' : 'retrieved', pageIds: result.pageIds,
|
|
89
|
+
indexCount: result.count, indexSource: result.indexSource, bytes: Buffer.byteLength(result.context), note: state.delivered ? 'Returned to host; model usage is not observable.' : 'Awaiting Cursor preToolUse; tool-free turns receive startup context only.' });
|
|
90
|
+
if (agent === 'cursor' && event === 'prompt') return { continue: true };
|
|
91
|
+
return outputContext(result.context, event === 'session-start' ? 'SessionStart' : 'UserPromptSubmit');
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export async function runHook(root, agent, event, input) {
|
|
95
|
+
// No failing hook should block a task. Bound the entire process as well as individual requests.
|
|
96
|
+
const timer = setTimeout(() => {
|
|
97
|
+
try { recordHook(root, agent, event, { status: 'timeout', error: 'Hook exceeded 8 seconds.' }); } catch {}
|
|
98
|
+
console.log(JSON.stringify(agent === 'cursor' && event === 'prompt' ? { continue: true } : {}));
|
|
99
|
+
process.exit(0);
|
|
100
|
+
}, 8000);
|
|
101
|
+
try { return await handleHook(root, agent, event, input); }
|
|
102
|
+
catch (error) {
|
|
103
|
+
try { recordHook(root, agent, event, { status: 'error', error: error.message.slice(0, 500) }); } catch {}
|
|
104
|
+
return agent === 'cursor' && event === 'prompt' ? { continue: true } : {};
|
|
105
|
+
} finally { clearTimeout(timer); }
|
|
106
|
+
}
|