@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/src/setup.mjs ADDED
@@ -0,0 +1,297 @@
1
+ import { existsSync, readFileSync, mkdirSync, rmSync, statSync, chmodSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { homedir } from 'node:os';
4
+ import { randomUUID, createHash } from 'node:crypto';
5
+ import { execFileSync } from 'node:child_process';
6
+ import { UnauthorizedError } from '@modelcontextprotocol/sdk/client/auth.js';
7
+ import { binding, preferences, mergePreferences, readJson, writeJson, writeAtomic, homeDir, DEFAULT_SERVER, serverUrl, ignoreRuntime } from './storage.mjs';
8
+ import { login, credentialPath, withCloud } from './cloud.mjs';
9
+ import { connect, integrationFiles, managedBlock } from './integrations.mjs';
10
+ import { localCommand } from './brain.mjs';
11
+ import { planHost, hostState, guardPath } from './host-config.mjs';
12
+ import { probeMcp } from './mcp-server.mjs';
13
+ import { inspectCodexHooks } from './codex-hooks.mjs';
14
+ import { createSetupPrompts } from './prompts.mjs';
15
+
16
+ const supported = ['claude-code', 'codex'];
17
+ const setupPath = root => join(root, '.mindmux/cli/setup.json');
18
+ function agentsFrom(value) {
19
+ const agents = [...new Set((value || '').split(',').map(x => x.trim()).filter(Boolean))];
20
+ if (agents.some(x => !supported.includes(x))) throw new Error('setup supports --agent claude-code,codex.');
21
+ return agents;
22
+ }
23
+ export function legacyWarnings(root) {
24
+ const warnings = [];
25
+ for (const agent of supported) {
26
+ const file = join(root, agent === 'codex' ? '.codex/hooks.json' : '.claude/settings.json');
27
+ if (existsSync(file) && readFileSync(file, 'utf8').includes('brain-session-start')) warnings.push(`${agent}: project brain.md hook detected; use setup --migrate to remove the recognized old hook.`);
28
+ }
29
+ for (const folder of ['.claude/skills', '.codex/skills', '.agents/skills']) {
30
+ if (existsSync(join(homedir(), folder, 'brain-page'))) warnings.push(`Global brain.md skill detected in ~/${folder}; uninstall with the original brain.md installer if replacing it. Global integrations are not removed by project setup.`);
31
+ }
32
+ return warnings;
33
+ }
34
+ function pathsFor(root, agents) {
35
+ return [...new Set([join(root, '.mindmux/preferences.json'), join(root, '.gitignore'), setupPath(root), join(root, '.mindmux/cli/integrations.json'),
36
+ ...agents.flatMap(agent => {
37
+ const f = integrationFiles(root, agent);
38
+ return [f.rules, f.hooks, hostState(root, agent).path, join(root, agent === 'codex' ? '.codex/hooks.json' : '.claude/settings.json'), join(root, agent === 'codex' ? '.codex/hooks/brain-session-start' : '.claude/hooks/brain-session-start')].filter(Boolean);
39
+ })])];
40
+ }
41
+ function snapshot(root, paths) {
42
+ return paths.map(path => {
43
+ guardPath(root, path);
44
+ return { path, content: existsSync(path) ? readFileSync(path, 'utf8') : null, mode: existsSync(path) ? statSync(path).mode & 0o777 : null };
45
+ });
46
+ }
47
+ function restore(files) {
48
+ for (const file of [...files].reverse()) {
49
+ if (file.content === null) rmSync(file.path, { force: true });
50
+ else { writeAtomic(file.path, file.content); chmodSync(file.path, file.mode); }
51
+ }
52
+ }
53
+ async function transaction(root, files, run) {
54
+ const backup = join(homeDir(), 'backups', createHash('sha256').update(root).digest('hex'), `${Date.now()}-${randomUUID()}.json`);
55
+ writeJson(backup, { createdAt: new Date().toISOString(), files });
56
+ const interrupted = () => {
57
+ try { restore(files); } catch (error) { console.error(`Interrupted setup rollback failed: ${error.message}. Backup: ${backup}`); }
58
+ };
59
+ process.once('exit', interrupted);
60
+ try {
61
+ const result = await run();
62
+ process.removeListener('exit', interrupted);
63
+ return { ...result, backup };
64
+ }
65
+ catch (error) {
66
+ process.removeListener('exit', interrupted);
67
+ try { restore(files); } catch (rollback) { throw new Error(`${error.message}; rollback failed: ${rollback.message}. Backup: ${backup}`); }
68
+ throw new Error(`${error.message} Project configuration restored. Backup: ${backup}`);
69
+ }
70
+ }
71
+ function preflight(root, agents, manifest, migrate, remove = false, repair = false) {
72
+ return agents.map(agent => {
73
+ const files = integrationFiles(root, agent);
74
+ guardPath(root, files.rules);
75
+ managedBlock(existsSync(files.rules) ? readFileSync(files.rules, 'utf8') : '', 'preflight');
76
+ if (files.hooks) {
77
+ const settings = readJson(files.hooks, {});
78
+ if (settings.hooks !== undefined && (!settings.hooks || typeof settings.hooks !== 'object' || Array.isArray(settings.hooks))) throw new Error(`Invalid hooks: ${files.hooks}`);
79
+ for (const hooks of Object.values(settings.hooks || {})) if (!Array.isArray(hooks)) throw new Error(`Invalid hook array: ${files.hooks}`);
80
+ }
81
+ return { agent, plan: planHost(root, agent, manifest.agents?.[agent], { migrate, remove, repair }) };
82
+ });
83
+ }
84
+ const fingerprint = files => createHash('sha256').update(JSON.stringify(files)).digest('hex');
85
+ export function planRepair(root) {
86
+ const manifest = readJson(setupPath(root), {});
87
+ const agents = Object.keys(manifest.agents || {});
88
+ if (!agents.length) throw new Error('No setup-managed agents. Run mmx setup to configure this project.');
89
+ if (agents.some(agent => !supported.includes(agent))) throw new Error('Unknown setup-managed agent. Inspect the setup manifest before repairing.');
90
+ if (binding(root).kind === 'unbound') throw new Error('No Brain selected. Run mmx setup to choose one.');
91
+ preflight(root, agents, manifest, false, false, true);
92
+ const files = snapshot(root, pathsFor(root, agents));
93
+ return { agents, files: files.map(file => file.path), fingerprint: fingerprint(files),
94
+ actions: ['Refresh managed MCP launchers and restore missing managed entries.',
95
+ 'Refresh managed project instructions and hooks; preserve surrounding user content.',
96
+ 'Back up project configuration and verify MCP launch and Brain recall.'],
97
+ note: 'Brain binding and data are kept. Cloud validation may require browser login. Restart the selected agents after repair.' };
98
+ }
99
+ export async function applyRepair(root, plan, flags = {}, dependencies = {}) {
100
+ const target = binding(root);
101
+ return setup(root, { json: flags.json, yes: true, 'no-open': flags['no-open'], agent: plan.agents.join(','), ...(target.kind === 'local' ? { local: true } : {}) },
102
+ { ...dependencies, repair: true, expectedFingerprint: plan.fingerprint });
103
+ }
104
+
105
+ export async function switchBrain(root, flags = {}, dependencies = {}) {
106
+ const agents = Object.keys(readJson(setupPath(root), {}).agents || {});
107
+ if (!agents.length) throw new Error('No setup-managed agents. Run mmx setup first.');
108
+ return setup(root, { ...flags, agent: agents.join(',') }, { ...dependencies, reselect: true });
109
+ }
110
+
111
+ export async function setup(root, flags = {}, dependencies = {}) {
112
+ let stage = 'checking project configuration';
113
+ let recovery;
114
+ let selectedAgents = flags.agent;
115
+ const step = (message) => {
116
+ stage = message;
117
+ if (!flags.json) process.stderr.write(`• ${message}…\n`);
118
+ };
119
+ const interactive = !flags.yes && Boolean(dependencies.prompts || (process.stdin.isTTY && process.stderr.isTTY));
120
+ const prompts = dependencies.prompts || createSetupPrompts();
121
+ const cloud = dependencies.cloud || withCloud;
122
+ const runtime = join(root, '.mindmux/cli'); guardPath(root, runtime);
123
+ mkdirSync(runtime, { recursive: true, mode: 0o700 });
124
+ const lock = join(runtime, 'setup.lock');
125
+ try { mkdirSync(lock); } catch { throw new Error(`Another setup/remove is active. If it crashed, remove ${lock}.`); }
126
+ const cleanup = () => rmSync(lock, { recursive: true, force: true });
127
+ const interrupt = () => process.exit(130), terminate = () => process.exit(143);
128
+ process.on('SIGINT', interrupt); process.on('SIGTERM', terminate);
129
+ process.once('exit', cleanup);
130
+ try {
131
+ let agents = agentsFrom(flags.agent);
132
+ if (!agents.length) {
133
+ if (!interactive) throw new Error('Specify --agent claude-code,codex in a non-interactive terminal.');
134
+ const installed = supported.filter(name => { try { execFileSync('/usr/bin/which', [name === 'claude-code' ? 'claude' : name], { stdio: 'ignore' }); return true; } catch { return false; } });
135
+ agents = agentsFrom(await prompts.agents(installed));
136
+ }
137
+ selectedAgents = agents.join(',');
138
+ if (flags.local && (flags['brain-id'] || flags.name || flags['workspace-id'] || flags.server)) throw new Error('--local cannot be combined with Cloud selection flags.');
139
+ if (flags['brain-id'] && (flags.name || flags['workspace-id'])) throw new Error('Choose --brain-id or Workspace/project creation flags.');
140
+ if (flags.name && !flags['workspace-id']) throw new Error('--workspace-id is required with --name.');
141
+ const manifest = readJson(setupPath(root), {});
142
+ let migrate = Boolean(flags.migrate);
143
+ let plans;
144
+ try { plans = preflight(root, agents, manifest, migrate, false, Boolean(dependencies.repair)); }
145
+ catch (error) {
146
+ if (!interactive || migrate || !error.message.includes('--migrate')) throw error;
147
+ migrate = await prompts.confirm(`${error.message}\nReplace and back up the existing MCP configuration?`);
148
+ if (!migrate) throw error;
149
+ plans = preflight(root, agents, manifest, migrate, false, Boolean(dependencies.repair));
150
+ }
151
+ const files = snapshot(root, pathsFor(root, agents));
152
+ if (dependencies.expectedFingerprint && fingerprint(files) !== dependencies.expectedFingerprint) throw new Error('Configuration changed after the repair plan was shown. Run mmx doctor --fix again.');
153
+ const codexHooks = agents.includes('codex') ? (dependencies.codexHooks || inspectCodexHooks)() : undefined;
154
+ const warnings = [...legacyWarnings(root), ...(codexHooks && (!codexHooks.supported || !codexHooks.enabled) ? [codexHooks.message] : [])];
155
+ if (warnings.length) console.error(warnings.join('\n'));
156
+ const current = binding(root);
157
+ const server = serverUrl(flags.server || (current.kind === 'cloud' ? current.server : readJson(join(homeDir(), 'config.json'), {}).server) || DEFAULT_SERVER);
158
+ let selected, created = manifest.created;
159
+ const pendingPath = join(runtime, 'setup-pending.json');
160
+ const createOrReuse = async (workspaceId, name, description = '') => {
161
+ const match = value => value?.server === server && value?.workspaceId === workspaceId && value?.name === name;
162
+ const pending = readJson(pendingPath, {});
163
+ if (match(pending)) {
164
+ if (!pending.brainId) throw new Error('A prior project creation has an unknown outcome. Run mmx project list and select its --brain-id; do not blindly retry creation. Inspect ' + pendingPath);
165
+ created = pending; recovery = pending; return pending;
166
+ }
167
+ if (match(created)) return created;
168
+ const intent = { server, workspaceId, name, state: 'requesting' };
169
+ writeJson(pendingPath, intent);
170
+ let result;
171
+ step('Creating Cloud Project');
172
+ try { result = await cloud(server, call => call('create_project', { workspaceId, name, description })); }
173
+ catch (error) { throw new Error(`${error.message} Project creation outcome may be unknown. Inspect project list before retrying. Journal: ${pendingPath}`); }
174
+ created = { ...intent, state: 'created', brainId: result.brainId };
175
+ if (!created.brainId) throw new Error('Project creation returned no brainId. Inspect project list before retrying.');
176
+ recovery = created;
177
+ writeJson(pendingPath, created);
178
+ return created;
179
+ };
180
+ if (!flags.local) {
181
+ step('Checking Cloud login');
182
+ if (!readJson(credentialPath(server), {}).tokens) await (dependencies.login || login)(server, { open: !flags['no-open'] });
183
+ // Authenticate/refresh through a harmless real request. Do not start browser auth after arbitrary network errors.
184
+ try { await cloud(server, call => call.listTools()); }
185
+ catch (error) {
186
+ if (error instanceof UnauthorizedError || ['InvalidGrantError', 'InvalidTokenError'].includes(error.name) || error.message.startsWith('Cloud login required.')) {
187
+ await (dependencies.login || login)(server, { open: !flags['no-open'] });
188
+ await cloud(server, call => call.listTools());
189
+ } else throw error;
190
+ }
191
+ if (flags['brain-id']) selected = { brainId: flags['brain-id'] };
192
+ else if (flags.name) {
193
+ if (!flags['workspace-id']) throw new Error('--workspace-id is required with --name.');
194
+ if (!flags.confirm && !(interactive && await prompts.confirm(`Create Project ${flags.name}? All Workspace members can access it.`))) throw new Error('Project creation requires --confirm.');
195
+ selected = await createOrReuse(flags['workspace-id'], flags.name, flags.description || '');
196
+ } else if (current.kind === 'cloud' && current.server === server && !flags['workspace-id'] && !dependencies.reselect) selected = { ...preferences(root).cloudBrain, ...current };
197
+ else {
198
+ if (!interactive) throw new Error('Select --brain-id, or --workspace-id plus --name --confirm; no Brain is inferred from directory names.');
199
+ step('Loading Workspaces');
200
+ const workspaces = (await cloud(server, call => call('list_workspaces'))).workspaces;
201
+ if (!workspaces.length) throw new Error('No accessible Workspaces. Check Workspace membership and subscription.');
202
+ const workspace = flags['workspace-id'] ? workspaces.find(w => (w.id || w.workspaceId) === flags['workspace-id']) : await prompts.choose('Select a Workspace:', workspaces.map(w => ({ name: w.name, value: w })));
203
+ if (!workspace) throw new Error('Workspace is unavailable.');
204
+ const workspaceId = workspace.id || workspace.workspaceId;
205
+ step('Loading Projects');
206
+ const projects = (await cloud(server, call => call('list_projects', { workspaceId }))).projects;
207
+ while (!selected) {
208
+ const choice = await prompts.choose('Select a Project or create a new one:', [
209
+ { name: '+ Create a new Project', value: { kind: 'create' } },
210
+ ...projects.map(project => ({ name: project.name, value: { kind: 'existing', project } })),
211
+ ]);
212
+ if (choice.kind === 'existing') selected = { ...choice.project, workspaceId, workspaceName: workspace.name };
213
+ else {
214
+ const name = await prompts.projectName(projects);
215
+ if (await prompts.confirm(`Create Project "${name}"? All Workspace members can access it.`)) {
216
+ selected = { ...await createOrReuse(workspaceId, name), workspaceName: workspace.name };
217
+ }
218
+ }
219
+ }
220
+ }
221
+ if (!selected?.brainId) throw new Error('Selected Project has no Cloud Brain.');
222
+ step('Validating selected Brain');
223
+ const resolved = await cloud(server, call => call('resolve_brain', { brainId: selected.brainId }));
224
+ if (resolved.status !== 'resolved') throw new Error('Selected Cloud Brain is inaccessible. Project binding was not changed.');
225
+ selected = { brainId: selected.brainId, name: resolved.brain?.name || selected.name || selected.brainId, ...(selected.workspaceId ? { workspaceId: selected.workspaceId, workspaceName: selected.workspaceName } : {}) };
226
+ }
227
+ // Do not roll back over edits made during browser authorization or selection.
228
+ for (const file of files) if ((existsSync(file.path) ? readFileSync(file.path, 'utf8') : null) !== file.content) throw new Error(`Configuration changed during setup: ${file.path}. Rerun setup.`);
229
+ step('Installing project integrations');
230
+ return await transaction(root, files, async () => {
231
+ if (flags.local) {
232
+ // Local Brain data survives a configuration rollback and is never deleted by remove.
233
+ if (!dependencies.repair) {
234
+ localCommand(root, ['init', '--no-wire']);
235
+ mergePreferences(root, { cloudBrain: { ...preferences(root).cloudBrain, enabled: false } });
236
+ }
237
+ } else mergePreferences(root, { cloudBrain: { enabled: true, ...selected }, mindmuxCli: { ...preferences(root).mindmuxCli, server } });
238
+ for (const { agent, plan } of plans) {
239
+ if (migrate) localCommand(root, ['uninstall-hooks', '--agent', agent]);
240
+ connect(root, agent);
241
+ writeAtomic(plan.path, plan.content);
242
+ }
243
+ const next = { ...manifest, agents: { ...manifest.agents }, created, updatedAt: new Date().toISOString() };
244
+ for (const { agent, plan } of plans) next.agents[agent] = plan.record;
245
+ writeJson(setupPath(root), next);
246
+ ignoreRuntime(root);
247
+ const ignored = join(root, '.gitignore'); let text = readFileSync(ignored, 'utf8');
248
+ for (const entry of ['/.mcp.json', '/.codex/config.toml']) if (!text.split(/\r?\n/).includes(entry)) text += `${text.endsWith('\n') ? '' : '\n'}${entry}\n`;
249
+ writeAtomic(ignored, text);
250
+ step('Checking MCP launch and Brain recall');
251
+ const probe = await (dependencies.probe || probeMcp)(root);
252
+ const pending = readJson(pendingPath, {});
253
+ if (pending.brainId && pending.brainId === selected?.brainId) rmSync(pendingPath, { force: true });
254
+ return { installed: true, project: root, binding: binding(root), agents, mcp: probe, codexHooks, warnings,
255
+ next: 'Restart the selected Agent in this project and approve its MCP/project/hook trust prompts. For Codex, trust the project and review the installed hooks with /hooks.' };
256
+ });
257
+ } catch (error) {
258
+ if (error.name === 'ExitPromptError') throw new Error('Setup cancelled.');
259
+ const quote = value => "'" + String(value).replaceAll("'", "'\"'\"'") + "'";
260
+ const retry = recovery?.brainId
261
+ ? `Cloud Project was created and retained. Resume without creating it again: mmx --project ${quote(root)} setup --brain-id ${quote(recovery.brainId)} --server ${quote(recovery.server)} --agent ${quote(selectedAgents)}`
262
+ : 'Check the error above, then rerun the command. If Project creation has an unknown outcome, list Projects before retrying creation.';
263
+ throw new Error(`${stage} failed: ${error.message}\n${retry}`);
264
+ } finally {
265
+ process.removeListener('exit', cleanup);
266
+ process.removeListener('SIGINT', interrupt); process.removeListener('SIGTERM', terminate); cleanup();
267
+ }
268
+ }
269
+
270
+ export async function removeSetup(root, flags = {}, { lockHeld = false } = {}) {
271
+ const manifest = readJson(setupPath(root), {});
272
+ const agents = agentsFrom(flags.agent || Object.keys(manifest.agents || {}).join(','));
273
+ if (!agents.length) return { removed: [], note: 'No setup-managed integrations. Existing connect-only integrations can be removed with disconnect.' };
274
+ const runtime = join(root, '.mindmux/cli'); guardPath(root, runtime); mkdirSync(runtime, { recursive: true });
275
+ const lock = join(runtime, 'setup.lock');
276
+ try { if (!lockHeld) mkdirSync(lock); } catch { throw new Error(`Another setup/remove is active: ${lock}`); }
277
+ const cleanup = () => { if (!lockHeld) rmSync(lock, { recursive: true, force: true }); };
278
+ const interrupt = () => process.exit(130), terminate = () => process.exit(143);
279
+ process.on('SIGINT', interrupt); process.on('SIGTERM', terminate); process.once('exit', cleanup);
280
+ try {
281
+ const plans = preflight(root, agents, manifest, false, true);
282
+ const files = snapshot(root, pathsFor(root, agents));
283
+ return await transaction(root, files, async () => {
284
+ for (const { agent, plan } of plans) {
285
+ if (!plan) continue;
286
+ connect(root, agent, { remove: true });
287
+ writeAtomic(plan.path, plan.content);
288
+ delete manifest.agents[agent];
289
+ }
290
+ writeJson(setupPath(root), manifest);
291
+ return { removed: plans.filter(p => p.plan).map(p => p.agent), note: 'Brain data, binding, CLI login and unrelated configuration retained. Migrated remote MCP entries restored.' };
292
+ });
293
+ } finally {
294
+ process.removeListener('SIGINT', interrupt); process.removeListener('SIGTERM', terminate);
295
+ process.removeListener('exit', cleanup); cleanup();
296
+ }
297
+ }
package/src/status.mjs ADDED
@@ -0,0 +1,65 @@
1
+ import { existsSync, readdirSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { binding, preferences, readJson } from './storage.mjs';
4
+ import { credentialPath } from './cloud.mjs';
5
+ import { withBrain } from './brain.mjs';
6
+ import { inspectMcp } from './host-config.mjs';
7
+ import { inspectIntegrations } from './integrations.mjs';
8
+ import { targetKey } from './hooks.mjs';
9
+
10
+ export async function status(root, flags = {}, dependencies = {}) {
11
+ const target = binding(root);
12
+ const runtime = join(root, '.mindmux/cli');
13
+ const manifest = readJson(join(runtime, 'setup.json'), {});
14
+ const key = targetKey(root);
15
+ const receipts = existsSync(runtime) ? readdirSync(runtime)
16
+ .filter(name => /^last-.*\.json$/.test(name))
17
+ .map(name => readJson(join(runtime, name), {}))
18
+ .filter(item => item.targetKey === key && (!manifest.updatedAt || item.time >= manifest.updatedAt))
19
+ .sort((a, b) => b.time.localeCompare(a.time)) : [];
20
+ const report = { project: root, binding: target,
21
+ workspace: target.kind === 'cloud' ? preferences(root).cloudBrain?.workspaceName : undefined,
22
+ credentialsPresent: target.kind === 'cloud' ? Boolean(readJson(credentialPath(target.server), {}).tokens) : undefined,
23
+ mcp: inspectMcp(root), integrations: inspectIntegrations(root), receipts,
24
+ adoption: 'Model use of recalled knowledge cannot be inferred from configuration or tool calls.' };
25
+ if (flags.online && target.kind !== 'unbound') {
26
+ try {
27
+ report.live = await (dependencies.withBrain || withBrain)(root, async brain => ({ accessible: true, activePages: (await brain.list()).length }));
28
+ } catch (error) { report.live = { accessible: false, error: error.message }; }
29
+ if (report.live.accessible && report.mcp.some(item => item.configured)) {
30
+ try {
31
+ const probe = dependencies.probe || (await import('./mcp-server.mjs')).probeMcp;
32
+ report.mcpProbe = await probe(root);
33
+ } catch (error) { report.mcpProbe = { connected: false, error: error.message }; }
34
+ }
35
+ }
36
+ return report;
37
+ }
38
+
39
+ export function formatStatus(report) {
40
+ const names = { 'claude-code': 'Claude Code', codex: 'Codex', cursor: 'Cursor' };
41
+ const lines = ['MindMux status', '', `Brain: ${report.binding.kind === 'cloud' ? report.binding.name || report.binding.brainId : report.binding.kind === 'local' ? report.binding.directory : 'Not selected'}`];
42
+ if (report.binding.kind === 'cloud') {
43
+ lines.push(`Workspace: ${report.workspace || 'Not recorded (choose it with mmx switch)'}`);
44
+ lines.push(`Login: ${report.credentialsPresent ? 'Saved credentials (not proof of a valid session)' : 'Not signed in; run mmx login'}`);
45
+ }
46
+ if (!report.mcp.length) lines.push('Agents: Not configured; run mmx setup');
47
+ for (const item of report.mcp) {
48
+ const rules = report.integrations.find(i => i.agent === item.agent);
49
+ lines.push(`${names[item.agent] || item.agent}: ${item.configured && item.executablePresent && rules?.rulesPresent && rules?.hookCommandsPresent && rules?.executablePresent ? 'Configured' : 'Configuration needs attention; run mmx doctor'}`);
50
+ }
51
+ lines.push(`Connection check: ${report.live ? report.live.accessible ? 'Brain reachable' + (report.mcpProbe?.recall ? '; MCP launch and recall passed' : '') : `Failed: ${report.live.error}` : 'Not run; use mmx status --online'}`);
52
+ if (report.mcpProbe?.connected === false) lines.push(`MCP check: Failed: ${report.mcpProbe.error}`);
53
+ if (report.integrations.some(item => item.agent === 'codex')) lines.push('Codex hooks require project trust and review in /hooks. Configuration does not prove execution.');
54
+ const call = report.receipts.find(item => item.event === 'tool-call' && item.status === 'success');
55
+ const hook = report.receipts.find(item => item.status === 'emitted');
56
+ lines.push(`MCP activity: ${call ? `${call.client} called ${call.tool} at ${call.time}` : 'No tool calls observed for the current setup'}`);
57
+ lines.push(`Hook context: ${hook ? `Delivered to ${hook.agent} at ${hook.time}` : 'No delivery observed for the current setup'}`);
58
+ const review = report.receipts.find(item => item.agent === 'codex' && ['stop', 'review', 'interrupt'].includes(item.event));
59
+ if (review) lines.push(`Codex memory review: ${review.status}${review.outcome ? ` (${review.outcome})` : ''} at ${review.time}`);
60
+ const failure = report.receipts.find(item => ['error', 'timeout', 'review-failed', 'recovery-exhausted', 'review-expired'].includes(item.status));
61
+ if (failure) lines.push(`Recent issue: ${failure.agent || failure.client}: ${failure.error || failure.status}`);
62
+ lines.push('', report.adoption);
63
+ if (report.binding.kind === 'unbound') lines.push('Run mmx setup to get started.');
64
+ return lines.join('\n');
65
+ }
@@ -0,0 +1,76 @@
1
+ import { existsSync, readFileSync, mkdirSync, writeFileSync, renameSync, chmodSync } from 'node:fs';
2
+ import { dirname, join, resolve } from 'node:path';
3
+ import { homedir } from 'node:os';
4
+ import { randomUUID } from 'node:crypto';
5
+
6
+ export const DEFAULT_SERVER = 'https://mcp.mindmux.ai/mcp';
7
+ export const homeDir = () => resolve(process.env.MINDMUX_HOME || join(homedir(), '.mindmux-cli'));
8
+ export function readJson(path, fallback) {
9
+ if (!existsSync(path)) return fallback;
10
+ let data;
11
+ try { data = JSON.parse(readFileSync(path, 'utf8')); }
12
+ catch { throw new Error(`Invalid JSON: ${path}. Repair it before continuing.`); }
13
+ if (!data || typeof data !== 'object' || Array.isArray(data)) throw new Error(`Expected an object: ${path}`);
14
+ return data;
15
+ }
16
+ export function writeJson(path, value) { writeAtomic(path, `${JSON.stringify(value, null, 2)}\n`); }
17
+ export function writeAtomic(path, content) {
18
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
19
+ const temp = `${path}.${randomUUID()}.tmp`;
20
+ writeFileSync(temp, content, { mode: 0o600 });
21
+ renameSync(temp, path);
22
+ chmodSync(path, 0o600);
23
+ }
24
+ export function projectRoot(start = process.cwd()) {
25
+ let dir = resolve(start);
26
+ for (;;) {
27
+ if (existsSync(join(dir, '.mindmux/preferences.json')) || existsSync(join(dir, '.git'))) return dir;
28
+ const parent = dirname(dir);
29
+ if (parent === dir) return resolve(start);
30
+ dir = parent;
31
+ }
32
+ }
33
+ export const preferencesPath = root => join(root, '.mindmux/preferences.json');
34
+ export const preferences = root => readJson(preferencesPath(root), {});
35
+ export function mergePreferences(root, patch) {
36
+ const previous = preferences(root), next = { ...previous, version: 1, ...patch };
37
+ const selection = prefs => JSON.stringify([prefs.cloudBrain?.enabled, prefs.cloudBrain?.brainId, prefs.brainRoot, prefs.mindmuxCli?.server]);
38
+ if (selection(previous) !== selection(next)) {
39
+ // A -> B -> A must not revive a token issued before the binding changed.
40
+ next.mindmuxCli = { ...next.mindmuxCli, bindingRevision: randomUUID() };
41
+ }
42
+ writeJson(preferencesPath(root), next);
43
+ }
44
+ export function serverUrl(value = DEFAULT_SERVER) {
45
+ const url = new URL(value);
46
+ if (url.protocol !== 'https:' && !(url.protocol === 'http:' && ['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname))) {
47
+ throw new Error('Server must use HTTPS (HTTP is allowed only on loopback).');
48
+ }
49
+ if (url.username || url.password || url.hash || url.search) throw new Error('Server URL must not contain credentials, query or fragment.');
50
+ return url.href.replace(/\/$/, '');
51
+ }
52
+ export function binding(root) {
53
+ const prefs = preferences(root);
54
+ if (prefs.cloudBrain?.enabled === true) {
55
+ if (!prefs.cloudBrain.brainId) throw new Error('Cloud Brain is enabled without brainId. Run mmx brain bind --brain-id <id>.');
56
+ return { kind: 'cloud', brainId: prefs.cloudBrain.brainId, name: prefs.cloudBrain.name,
57
+ server: serverUrl(prefs.mindmuxCli?.server || DEFAULT_SERVER) };
58
+ }
59
+ if (prefs.cloudBrain?.enabled === false || prefs.brainRoot || existsSync(join(root, 'brain/index.md'))) {
60
+ return { kind: 'local', directory: resolve(root, prefs.brainRoot || 'brain') };
61
+ }
62
+ return { kind: 'unbound' };
63
+ }
64
+ export function requireBinding(root) {
65
+ const value = binding(root);
66
+ if (value.kind === 'unbound') throw new Error('No Brain selected. Run mmx init --local or mmx brain bind --brain-id <id>.');
67
+ return value;
68
+ }
69
+ export function ignoreRuntime(root, extraEntries = []) {
70
+ const path = join(root, '.gitignore');
71
+ let text = existsSync(path) ? readFileSync(path, 'utf8') : '';
72
+ for (const entry of ['/.mindmux/preferences.json', '/.mindmux/cli/', ...extraEntries]) {
73
+ if (!text.split(/\r?\n/).includes(entry)) text += `${text && !text.endsWith('\n') ? '\n' : ''}${entry}\n`;
74
+ }
75
+ writeAtomic(path, text);
76
+ }