@mindmux/cli 0.0.0-stage → 0.1.0
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 +55 -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 +41 -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/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.0' });
|
|
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
|
+
}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { existsSync, readFileSync, lstatSync } from 'node:fs';
|
|
2
|
+
import { dirname, join } from 'node:path';
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
5
|
+
import { parse, stringify } from 'smol-toml';
|
|
6
|
+
import { readJson, homeDir, preferences, DEFAULT_SERVER } from './storage.mjs';
|
|
7
|
+
import { CLI_BIN } from './integrations.mjs';
|
|
8
|
+
|
|
9
|
+
const plain = value => value === undefined ? undefined : JSON.parse(JSON.stringify(value));
|
|
10
|
+
const same = (a, b) => isDeepStrictEqual(plain(a), plain(b));
|
|
11
|
+
const BEGIN = '# BEGIN mindmux-cli MCP', END = '# END mindmux-cli MCP';
|
|
12
|
+
export const mcpPath = (root, agent) => join(root, agent === 'codex' ? '.codex/config.toml' : '.mcp.json');
|
|
13
|
+
const entryName = agent => agent === 'codex' ? 'mindmux_cli' : 'mindmux';
|
|
14
|
+
export function guardPath(root, path) {
|
|
15
|
+
for (let current = path; current !== root; current = dirname(current)) {
|
|
16
|
+
if (lstatSync(current, { throwIfNoEntry: false })?.isSymbolicLink()) throw new Error(`Refusing project configuration symlink: ${current}`);
|
|
17
|
+
if (dirname(current) === current) throw new Error('Configuration path escaped project.');
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
export function launcher(root) {
|
|
21
|
+
return { command: process.execPath, args: [CLI_BIN, '--project', root, 'mcp', 'serve'], env: { MINDMUX_HOME: homeDir() } };
|
|
22
|
+
}
|
|
23
|
+
function block(text, content) {
|
|
24
|
+
const starts = text.split(BEGIN).length - 1, ends = text.split(END).length - 1;
|
|
25
|
+
if (starts !== ends || starts > 1 || (starts && text.indexOf(END) < text.indexOf(BEGIN))) throw new Error('Malformed MindMux MCP markers. Repair configuration before continuing.');
|
|
26
|
+
const value = content ? `${BEGIN}\n${content.trim()}\n${END}\n` : '';
|
|
27
|
+
if (starts) return text.slice(0, text.indexOf(BEGIN)) + value + text.slice(text.indexOf(END) + END.length).replace(/^\r?\n/, '');
|
|
28
|
+
return text + (text && !text.endsWith('\n') ? '\n' : '') + value;
|
|
29
|
+
}
|
|
30
|
+
export function hostState(root, agent) {
|
|
31
|
+
const path = mcpPath(root, agent); guardPath(root, path);
|
|
32
|
+
const text = existsSync(path) ? readFileSync(path, 'utf8') : '';
|
|
33
|
+
const data = agent === 'codex' ? parse(text) : readJson(path, {});
|
|
34
|
+
const key = agent === 'codex' ? 'mcp_servers' : 'mcpServers';
|
|
35
|
+
if (data[key] !== undefined && (!data[key] || typeof data[key] !== 'object' || Array.isArray(data[key]))) throw new Error(`Invalid ${key} in ${path}`);
|
|
36
|
+
if (agent === 'codex') block(text, '');
|
|
37
|
+
return { path, text, data, key, name: entryName(agent), entry: data[key]?.[entryName(agent)] };
|
|
38
|
+
}
|
|
39
|
+
function inheritedCodex(root) {
|
|
40
|
+
const path = join(process.env.CODEX_HOME || join(homedir(), '.codex'), 'config.toml');
|
|
41
|
+
const servers = existsSync(path) ? parse(readFileSync(path, 'utf8')).mcp_servers || {} : {};
|
|
42
|
+
const known = preferences(root).mindmuxCli?.server || DEFAULT_SERVER;
|
|
43
|
+
const found = Object.entries(servers).filter(([name, entry]) => name !== 'mindmux_cli' && typeof entry.url === 'string' && (entry.url === known || entry.url.startsWith('https://mcp.mindmux.ai/'))).map(([name]) => name);
|
|
44
|
+
if (servers.mindmux_cli) throw new Error('Global Codex entry mindmux_cli already exists. Rename it before project setup to avoid merged transports.');
|
|
45
|
+
return found;
|
|
46
|
+
}
|
|
47
|
+
export function planHost(root, agent, previous, { migrate = false, remove = false, repair = false } = {}) {
|
|
48
|
+
const state = hostState(root, agent), desired = launcher(root);
|
|
49
|
+
const { data, key, entry, name, path } = state;
|
|
50
|
+
if (previous && !same(entry, previous.installed) && !(repair && entry === undefined)) throw new Error(`MindMux MCP entry changed outside the installer: ${path}. Preserve or repair it before continuing.`);
|
|
51
|
+
if (!previous && entry && !same(entry, desired)) {
|
|
52
|
+
if (!migrate || typeof entry.url !== 'string') throw new Error(`Existing ${name} MCP entry in ${path}. Use --migrate to explicitly replace a remote entry; it will be backed up.`);
|
|
53
|
+
}
|
|
54
|
+
if (remove && !previous) return null;
|
|
55
|
+
const suppress = { ...previous?.suppressed };
|
|
56
|
+
if (agent === 'codex') {
|
|
57
|
+
for (const [legacy, original] of Object.entries(suppress)) {
|
|
58
|
+
if (!same(data[key]?.[legacy], { enabled: false }) && !(repair && data[key]?.[legacy] === undefined)) throw new Error(`Project override for ${legacy} changed outside the installer: ${path}`);
|
|
59
|
+
}
|
|
60
|
+
if (!remove) {
|
|
61
|
+
const candidates = new Set([...inheritedCodex(root), ...Object.entries(data[key] || {}).filter(([id, value]) => id !== name && typeof value.url === 'string' && (id === 'mindmux' || value.url.startsWith('https://mcp.mindmux.ai/'))).map(([id]) => id)]);
|
|
62
|
+
for (const legacy of candidates) {
|
|
63
|
+
if (legacy in suppress) continue;
|
|
64
|
+
if (data[key]?.[legacy] && !migrate) throw new Error(`Existing project ${legacy} MCP entry in ${path}. Use --migrate to disable and back it up for this project.`);
|
|
65
|
+
suppress[legacy] = data[key]?.[legacy] || null;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
const restored = remove ? previous.original : desired;
|
|
70
|
+
const managed = {};
|
|
71
|
+
if (restored) managed[name] = restored;
|
|
72
|
+
for (const [legacy, original] of Object.entries(suppress)) {
|
|
73
|
+
if (!remove) managed[legacy] = { enabled: false };
|
|
74
|
+
else if (original) managed[legacy] = original;
|
|
75
|
+
}
|
|
76
|
+
let content;
|
|
77
|
+
if (agent !== 'codex') {
|
|
78
|
+
data[key] = { ...data[key] };
|
|
79
|
+
if (restored) data[key][name] = restored; else delete data[key][name];
|
|
80
|
+
if (!Object.keys(data[key]).length) delete data[key];
|
|
81
|
+
content = JSON.stringify(data, null, 2) + '\n';
|
|
82
|
+
} else {
|
|
83
|
+
let base = block(state.text, '');
|
|
84
|
+
const baseData = parse(base);
|
|
85
|
+
const keysToReplace = [name, ...Object.keys(suppress)];
|
|
86
|
+
if (keysToReplace.some(id => baseData[key]?.[id])) {
|
|
87
|
+
// Only explicit migration rewrites existing tables. All values survive; comments remain in backup.
|
|
88
|
+
for (const id of keysToReplace) delete baseData[key][id];
|
|
89
|
+
if (baseData[key] && !Object.keys(baseData[key]).length) delete baseData[key];
|
|
90
|
+
base = stringify(baseData);
|
|
91
|
+
}
|
|
92
|
+
content = block(base, Object.keys(managed).length ? stringify({ mcp_servers: managed }) : '');
|
|
93
|
+
}
|
|
94
|
+
if (agent === 'codex') parse(content); else JSON.parse(content);
|
|
95
|
+
return { path, content, record: { installed: desired, original: previous ? previous.original : entry || null, suppressed: suppress } };
|
|
96
|
+
}
|
|
97
|
+
export function inspectMcp(root) {
|
|
98
|
+
const manifest = readJson(join(root, '.mindmux/cli/setup.json'), {});
|
|
99
|
+
return Object.entries(manifest.agents || {}).map(([agent, saved]) => {
|
|
100
|
+
try {
|
|
101
|
+
const state = hostState(root, agent);
|
|
102
|
+
const configured = same(state.entry, saved.installed) && Object.keys(saved.suppressed || {}).every(id => same(state.data[state.key]?.[id], { enabled: false }));
|
|
103
|
+
return { agent, name: state.name, path: state.path, configured,
|
|
104
|
+
executablePresent: existsSync(saved.installed.command) && existsSync(saved.installed.args[0]),
|
|
105
|
+
projectDisabledRemoteServers: Object.keys(saved.suppressed || {}) };
|
|
106
|
+
} catch (error) { return { agent, configured: false, error: error.message }; }
|
|
107
|
+
});
|
|
108
|
+
}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { existsSync, readFileSync, realpathSync, rmSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
import { readJson, writeJson, writeAtomic, ignoreRuntime, homeDir } from './storage.mjs';
|
|
5
|
+
import { MEMORY_POLICY } from './recall.mjs';
|
|
6
|
+
|
|
7
|
+
export const CLI_BIN = fileURLToPath(new URL('../bin/mmx.mjs', import.meta.url));
|
|
8
|
+
export const shellQuote = value => `'${String(value).replaceAll("'", "'\\''")}'`;
|
|
9
|
+
const BEGIN = '<!-- BEGIN mindmux-cli -->', END = '<!-- END mindmux-cli -->';
|
|
10
|
+
const CURSOR_OWNER = '<!-- mindmux-cli managed rule file -->';
|
|
11
|
+
const CURSOR_HEADER = '---\ndescription: Bound project Brain memory\nalwaysApply: true\n---\n';
|
|
12
|
+
export const AGENTS = ['cursor', 'claude-code', 'codex'];
|
|
13
|
+
export function managedBlock(text, content) {
|
|
14
|
+
const starts = text.split(BEGIN).length - 1, ends = text.split(END).length - 1;
|
|
15
|
+
if (starts !== ends || starts > 1 || (starts && text.indexOf(END) < text.indexOf(BEGIN))) throw new Error('Malformed mindmux-cli instruction markers. Repair before continuing.');
|
|
16
|
+
const block = content ? `${BEGIN}\n${content}\n${END}` : '';
|
|
17
|
+
if (starts) return text.slice(0, text.indexOf(BEGIN)) + block + text.slice(text.indexOf(END) + END.length);
|
|
18
|
+
return content ? `${text}${text && !text.endsWith('\n') ? '\n' : ''}\n${block}\n` : text;
|
|
19
|
+
}
|
|
20
|
+
export function integrationFiles(root, agent) {
|
|
21
|
+
if (!AGENTS.includes(agent)) throw new Error(`Unknown agent. Choose ${AGENTS.join(', ')}.`);
|
|
22
|
+
return agent === 'cursor' ? { rules: join(root, '.cursor/rules/mindmux.mdc'), hooks: join(root, '.cursor/hooks.json') }
|
|
23
|
+
: agent === 'claude-code' ? { rules: join(root, 'CLAUDE.md'), hooks: join(root, '.claude/settings.json') }
|
|
24
|
+
: { rules: join(root, 'AGENTS.md'), hooks: join(root, '.codex/hooks.json') };
|
|
25
|
+
}
|
|
26
|
+
function ruleText(root) {
|
|
27
|
+
const command = `env ${shellQuote("MINDMUX_HOME=" + homeDir())} ${shellQuote(process.execPath)} ${shellQuote(CLI_BIN)} --project ${shellQuote(root)}`;
|
|
28
|
+
return `MindMux Project Brain\n\n${MEMORY_POLICY}\n\nUse the following CLI command prefix from any working directory:\n\n\`${command}\`\n\nAt the start of every new task (including discussion), run \`<prefix> brain recall "task keywords"\` if relevant context has not arrived via a hook.\nOperations: \`brain index\` (page summaries and root navigation), \`brain reindex\` (regenerate the derived index), \`brain list\`, \`brain search "keywords"\`, \`brain read <id>\`, \`brain roots\`, \`brain read-root <slug>\`. Results are JSON.\nCapture a confirmed decision: pipe its body to \`<prefix> brain create --id <id> --title "Title" --category decision --source "user confirmed ..."\`.\nUpdate: read first, then pipe the new body to \`<prefix> brain update <id> --expected-version <version> --summary "Why it changed"\`.\nPreserve unchanged values exactly, including code, quotes and backslashes. JSON output escapes are serialization, not literal Markdown content: decode the string before reusing it. Send body text through stdin using a quoted heredoc or a file, without adding shell/JSON escaping to the body. After creating or updating, read the page back and verify the intended changes and unchanged values before reporting success. If correction is needed, use the newly read version and record the reason.\nAppend evidence: \`<prefix> brain append <id> --kind evidence --summary "Evidence" --source "Source"\`.\nUse \`brain create --status draft\` for explicitly requested proposals; never present drafts as settled facts.\nThe CLI resolves the explicit project binding. For Cloud, do not fall back to local tools after an error. An authenticated MCP can also be used only with the same bound brainId shown by \`brain status\`.\nWhen another Brain guide documents local file commands, retain its data-format contract and route this project's operations through the binding above.\nIf unbound, ask the user to select/create a Brain; never infer a cloud Brain from a folder name.\nBefore finishing, check whether any confirmed durable knowledge remains uncaptured. If none, finish without creating a page.\n`;
|
|
29
|
+
}
|
|
30
|
+
function definitions(root, agent) {
|
|
31
|
+
root = realpathSync(root);
|
|
32
|
+
const prefix = `env ${shellQuote("MINDMUX_HOME=" + homeDir())} ${shellQuote(process.execPath)} ${shellQuote(CLI_BIN)} --project ${shellQuote(root)} hook --agent ${agent}`;
|
|
33
|
+
if (agent === 'cursor') return Object.fromEntries([
|
|
34
|
+
['sessionStart', 'session-start'], ['beforeSubmitPrompt', 'prompt'], ['preToolUse', 'pre-tool'], ['stop', 'stop'],
|
|
35
|
+
].map(([event, operation]) => [event, [{ command: `${prefix} ${operation}`, ...(event === 'stop' ? { loop_limit: 1 } : {}) }]]));
|
|
36
|
+
if (agent === 'claude-code' || agent === 'codex') return Object.fromEntries([
|
|
37
|
+
['SessionStart', 'session-start'], ['UserPromptSubmit', 'prompt'], ['Stop', 'stop'], ...(agent === 'codex' ? [['Interrupt', 'interrupt']] : []),
|
|
38
|
+
].map(([event, operation]) => [event, [{ hooks: [{ type: 'command', command: `${prefix} ${operation}`, timeout: 10, ...(agent === 'codex' && ['SessionStart', 'UserPromptSubmit'].includes(event) ? { additionalContextLimit: 10000 } : {}) }] }]]));
|
|
39
|
+
return {};
|
|
40
|
+
}
|
|
41
|
+
const commandOf = definition => definition.command || definition.hooks?.[0]?.command;
|
|
42
|
+
|
|
43
|
+
export function connect(root, agent, { remove = false } = {}) {
|
|
44
|
+
const files = integrationFiles(root, agent);
|
|
45
|
+
const manifestPath = join(root, '.mindmux/cli/integrations.json');
|
|
46
|
+
const manifest = readJson(manifestPath, {});
|
|
47
|
+
const previous = manifest[agent]?.commands || [];
|
|
48
|
+
let text = existsSync(files.rules) ? readFileSync(files.rules, 'utf8') : '';
|
|
49
|
+
// Recognize an empty skeleton left by v0.1's old uninstaller as well as owned rules.
|
|
50
|
+
if (agent === 'cursor' && text && !text.includes(BEGIN) && !text.includes(CURSOR_OWNER) && text.trim() !== CURSOR_HEADER.trim()) throw new Error(`Refusing to overwrite foreign rule: ${files.rules}`);
|
|
51
|
+
text = managedBlock(text, remove ? '' : ruleText(root));
|
|
52
|
+
let removeRule = false;
|
|
53
|
+
if (agent === 'cursor') {
|
|
54
|
+
if (!text.startsWith('---')) text = `${CURSOR_HEADER}${text}`;
|
|
55
|
+
removeRule = remove && !text.replace(CURSOR_HEADER, '').replace(CURSOR_OWNER, '').trim();
|
|
56
|
+
if (!removeRule && !text.includes(CURSOR_OWNER)) text += `\n${CURSOR_OWNER}\n`;
|
|
57
|
+
}
|
|
58
|
+
let settings;
|
|
59
|
+
const defs = remove ? {} : definitions(root, agent);
|
|
60
|
+
if (files.hooks) {
|
|
61
|
+
settings = readJson(files.hooks, agent === 'cursor' ? { version: 1 } : {});
|
|
62
|
+
if (settings.hooks !== undefined && (!settings.hooks || typeof settings.hooks !== 'object' || Array.isArray(settings.hooks))) throw new Error(`Invalid hooks object: ${files.hooks}`);
|
|
63
|
+
settings.hooks = { ...settings.hooks };
|
|
64
|
+
// Compute and validate everything before the first write.
|
|
65
|
+
for (const event of new Set([...Object.keys(settings.hooks), ...Object.keys(defs)])) {
|
|
66
|
+
const current = settings.hooks[event] || [];
|
|
67
|
+
if (!Array.isArray(current)) throw new Error(`Invalid hook array ${event}: ${files.hooks}`);
|
|
68
|
+
const kept = current.filter(item => !previous.includes(commandOf(item)));
|
|
69
|
+
const desired = defs[event] || [];
|
|
70
|
+
settings.hooks[event] = [...kept, ...desired.filter(item => !kept.some(old => commandOf(old) === commandOf(item)))];
|
|
71
|
+
if (!settings.hooks[event].length) delete settings.hooks[event];
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
if (removeRule) rmSync(files.rules, { force: true });
|
|
75
|
+
else writeAtomic(files.rules, text);
|
|
76
|
+
if (settings) writeJson(files.hooks, settings);
|
|
77
|
+
if (remove) delete manifest[agent];
|
|
78
|
+
else manifest[agent] = { installedAt: new Date().toISOString(), bin: CLI_BIN, node: process.execPath,
|
|
79
|
+
commands: Object.values(defs).flat().map(commandOf), mode: 'hooks' };
|
|
80
|
+
writeJson(manifestPath, manifest);
|
|
81
|
+
ignoreRuntime(root, agent === 'codex' && !remove ? ['/.codex/hooks.json'] : []);
|
|
82
|
+
return { agent, installed: !remove, mode: 'hooks', ...files,
|
|
83
|
+
note: agent === 'codex' ? 'Restart Codex, trust the project, and review the installed hooks with /hooks. Hook execution requires a compatible Codex with hooks enabled.' : 'Restart/reload the agent and review hook trust. doctor reports configured state; real delivery requires host execution.' };
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export function inspectIntegrations(root) {
|
|
87
|
+
const manifest = readJson(join(root, '.mindmux/cli/integrations.json'), {});
|
|
88
|
+
return Object.entries(manifest).map(([agent, installed]) => {
|
|
89
|
+
const files = integrationFiles(root, agent);
|
|
90
|
+
const text = existsSync(files.rules) ? readFileSync(files.rules, 'utf8') : '';
|
|
91
|
+
const hooks = files.hooks ? readJson(files.hooks, {}).hooks || {} : {};
|
|
92
|
+
const actualCommands = Object.values(hooks).filter(Array.isArray).flat().map(commandOf);
|
|
93
|
+
const expected = Object.values(definitions(root, agent)).flat().map(commandOf);
|
|
94
|
+
return { agent, mode: installed.mode, rulesPresent: text.includes(BEGIN) && text.includes(END),
|
|
95
|
+
hookCommandsPresent: installed.commands.length > 0 && installed.commands.every(command => actualCommands.includes(command))
|
|
96
|
+
&& expected.every(command => actualCommands.includes(command)),
|
|
97
|
+
executablePresent: existsSync(installed.bin) && existsSync(installed.node),
|
|
98
|
+
existingBrainMdHook: JSON.stringify(hooks).includes('brain-session-start') };
|
|
99
|
+
});
|
|
100
|
+
}
|