@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/package.json
CHANGED
|
@@ -1,6 +1,42 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mindmux/cli",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Brain operations and lifecycle integrations for coding agents",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"mmx": "bin/mmx.mjs"
|
|
8
|
+
},
|
|
9
|
+
"files": [
|
|
10
|
+
"bin",
|
|
11
|
+
"src",
|
|
12
|
+
"docs",
|
|
13
|
+
"README.md",
|
|
14
|
+
"LICENSE"
|
|
15
|
+
],
|
|
16
|
+
"engines": {
|
|
17
|
+
"node": ">=22"
|
|
18
|
+
},
|
|
19
|
+
"scripts": {
|
|
20
|
+
"test": "node --test test/*.test.mjs",
|
|
21
|
+
"demo": "node scripts/demo.mjs",
|
|
22
|
+
"check": "node --check bin/mmx.mjs && node --check bin/mindmux.mjs && npm test"
|
|
23
|
+
},
|
|
24
|
+
"dependencies": {
|
|
25
|
+
"@inquirer/prompts": "^7.10.1",
|
|
26
|
+
"@mindmux/brain-md": "0.4.1",
|
|
27
|
+
"@modelcontextprotocol/sdk": "^1.30.0",
|
|
28
|
+
"smol-toml": "^1.9.1"
|
|
29
|
+
},
|
|
30
|
+
"devDependencies": {
|
|
31
|
+
"zod": "^4.2.0"
|
|
32
|
+
},
|
|
33
|
+
"license": "Apache-2.0",
|
|
34
|
+
"repository": {
|
|
35
|
+
"type": "git",
|
|
36
|
+
"url": "git+https://github.com/mindmuxai/mindmux-cli.git"
|
|
37
|
+
},
|
|
38
|
+
"homepage": "https://github.com/mindmuxai/mindmux-cli#readme",
|
|
39
|
+
"bugs": {
|
|
40
|
+
"url": "https://github.com/mindmuxai/mindmux-cli/issues"
|
|
41
|
+
}
|
|
42
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
// Index entries are navigation, never substitutes for reading a page before updating it.
|
|
2
|
+
export function pageSummary(text = '', fallback = '') {
|
|
3
|
+
const first = text.trim().split(/\r?\n/).find(line => line.trim()) || fallback;
|
|
4
|
+
return [...first.replace(/\s+/g, ' ').trim()].slice(0, 240).join('');
|
|
5
|
+
}
|
|
6
|
+
const line = value => String(value ?? '').replace(/[\r\n]+/g, ' ');
|
|
7
|
+
export function renderIndex(pages, roots = []) {
|
|
8
|
+
return ['# MindMux Brain Index', '', '_Auto-generated from current Brain pages. Read pages for full, current details._', '',
|
|
9
|
+
...pages.map(p => `- [${line(p.id)}](pages/${line(p.id)}.md) — ${line(p.title)} | category: ${line(p.category || '?')} | status: ${line(p.status || 'active')}${p.tags?.length ? ` | tags: [${p.tags.map(line).join(', ')}]` : ''} | version: ${line(p.version || '?')} | updated: ${line(p.updated || '?')} | ${pageSummary(p.summary, p.title)}`),
|
|
10
|
+
...(!pages.length ? ['_(no active Pages yet)_'] : []),
|
|
11
|
+
...(roots.length ? ['', '## Root pages', '', ...roots.map(p => `- [${line(p.slug)}](${line(p.slug)}.md) — ${line(p.title || p.slug)} | version: ${line(p.version || '?')} | updated: ${line(p.updated || '?')}`)] : []), ''].join('\n');
|
|
12
|
+
}
|
|
13
|
+
export async function indexSnapshot(brain) {
|
|
14
|
+
if (brain.index) return brain.index();
|
|
15
|
+
// Compatibility for Cloud servers not yet upgraded. Keep Cloud as the source.
|
|
16
|
+
const [pages, rootPages] = await Promise.all([brain.list(), brain.roots()]);
|
|
17
|
+
return { path: 'brain/index.md', body: renderIndex(pages, rootPages), pages, rootPages, count: pages.length, source: 'page-list-compatibility' };
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// Preserve complete index rows and tell the model how to fetch omitted entries.
|
|
21
|
+
export function indexContext(index, maxBytes = 3500) {
|
|
22
|
+
const notice = '\n[Index preview truncated. Run brain index for the complete index.]';
|
|
23
|
+
if (Buffer.byteLength(index.body) <= maxBytes) return index.body;
|
|
24
|
+
const lines = []; let bytes = Buffer.byteLength(notice);
|
|
25
|
+
for (const row of index.body.split('\n')) {
|
|
26
|
+
const size = Buffer.byteLength(row) + 1;
|
|
27
|
+
if (bytes + size > maxBytes) break;
|
|
28
|
+
lines.push(row); bytes += size;
|
|
29
|
+
}
|
|
30
|
+
return lines.join('\n') + notice;
|
|
31
|
+
}
|
package/src/brain.mjs
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import { createRequire } from 'node:module';
|
|
2
|
+
import { dirname, join } from 'node:path';
|
|
3
|
+
import { pathToFileURL } from 'node:url';
|
|
4
|
+
import { spawnSync } from 'node:child_process';
|
|
5
|
+
import { createHash } from 'node:crypto';
|
|
6
|
+
import { existsSync, mkdirSync, rmSync } from 'node:fs';
|
|
7
|
+
import { requireBinding } from './storage.mjs';
|
|
8
|
+
import { withCloud } from './cloud.mjs';
|
|
9
|
+
import { pageSummary, renderIndex } from './brain-index.mjs';
|
|
10
|
+
|
|
11
|
+
const require = createRequire(import.meta.url);
|
|
12
|
+
export const brainPackage = dirname(require.resolve('@mindmux/brain-md/package.json'));
|
|
13
|
+
export const brainBin = join(brainPackage, 'skills/brain-page/bin/brain.mjs');
|
|
14
|
+
const lib = () => import(pathToFileURL(join(brainPackage, 'skills/brain-page/lib/brain.mjs')).href);
|
|
15
|
+
export function localCommand(root, args, input = '') {
|
|
16
|
+
const result = spawnSync(process.execPath, [brainBin, ...args], { cwd: root, input, encoding: 'utf8', timeout: 6000, maxBuffer: 4 * 1024 * 1024 });
|
|
17
|
+
if (result.error) throw result.error;
|
|
18
|
+
if (result.status !== 0) throw new Error(result.stderr.trim() || result.stdout.trim() || 'Local Brain operation failed.');
|
|
19
|
+
return result.stdout.trim();
|
|
20
|
+
}
|
|
21
|
+
const idCheck = id => { if (!/^[a-z0-9][a-z0-9-]*$/.test(id || '')) throw new Error('Page id must use lowercase letters, digits and hyphens.'); };
|
|
22
|
+
const rootCheck = slug => { if (!['background', 'architecture', 'flow', 'mindmap', 'stack', 'roadmap'].includes(slug)) throw new Error('Unknown root page slug.'); };
|
|
23
|
+
const version = raw => createHash('sha256').update(raw).digest('hex');
|
|
24
|
+
|
|
25
|
+
function localMutation(root, run) {
|
|
26
|
+
const lock = join(root, '.mindmux/cli/write.lock');
|
|
27
|
+
mkdirSync(dirname(lock), { recursive: true });
|
|
28
|
+
try { mkdirSync(lock); } catch (error) {
|
|
29
|
+
if (error.code === 'EEXIST') throw new Error(`Another local write is active. If it crashed, remove ${lock}.`);
|
|
30
|
+
throw error;
|
|
31
|
+
}
|
|
32
|
+
try { return run(); } finally { rmSync(lock, { recursive: true, force: true }); }
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export async function withBrain(root, run) {
|
|
36
|
+
const target = requireBinding(root);
|
|
37
|
+
if (target.kind === 'cloud') return withCloud(target.server, async call => {
|
|
38
|
+
const resolved = await call('resolve_brain', { brainId: target.brainId });
|
|
39
|
+
if (resolved.status !== 'resolved') throw new Error('Bound Cloud Brain is unavailable. Rebind explicitly; no local fallback was used.');
|
|
40
|
+
const invoke = (name, args = {}) => call(name, { ...args, brainId: target.brainId });
|
|
41
|
+
const index = async () => {
|
|
42
|
+
const tools = (await call.listTools()).tools;
|
|
43
|
+
if (tools.some(tool => tool.name === 'read_brain_index')) return invoke('read_brain_index');
|
|
44
|
+
const pages = (await invoke('list_pages')).pages;
|
|
45
|
+
const rootPages = (await invoke('list_root_pages')).rootPages;
|
|
46
|
+
return { path: 'brain/index.md', body: renderIndex(pages, rootPages), pages, rootPages, count: pages.length, source: 'page-list-compatibility' };
|
|
47
|
+
};
|
|
48
|
+
return run({ target, invoke, index,
|
|
49
|
+
reindex: () => invoke('reindex_brain'),
|
|
50
|
+
list: async () => (await invoke('list_pages')).pages,
|
|
51
|
+
read: id => invoke('read_page', { id }),
|
|
52
|
+
roots: async () => (await invoke('list_root_pages')).rootPages,
|
|
53
|
+
readRoot: slug => invoke('read_root_page', { slug }),
|
|
54
|
+
search: async query => (await invoke('search_pages', { query, maxResults: 10 })).pages.filter(p => !p.status || p.status === 'active'),
|
|
55
|
+
create: args => invoke('create_page', args),
|
|
56
|
+
update: args => invoke('update_compiled_truth', args),
|
|
57
|
+
append: args => invoke('append_timeline', args),
|
|
58
|
+
archive: id => invoke('archive_page', { id }),
|
|
59
|
+
updateRoot: async args => {
|
|
60
|
+
if (args.expectedVersion === 'new') {
|
|
61
|
+
const { rootPages } = await invoke('list_root_pages');
|
|
62
|
+
if (rootPages.some(page => page.slug === args.slug)) throw new Error('Root already exists. Read its current version before updating.');
|
|
63
|
+
const { expectedVersion, ...creation } = args;
|
|
64
|
+
return invoke('update_root_page', creation);
|
|
65
|
+
}
|
|
66
|
+
return invoke('update_root_page', args);
|
|
67
|
+
},
|
|
68
|
+
});
|
|
69
|
+
});
|
|
70
|
+
if (process.cwd() !== root) throw new Error('Local adapter must run from the project root.');
|
|
71
|
+
const api = await lib();
|
|
72
|
+
const normalize = doc => ({ ...doc.frontmatter, id: doc.id, version: version(doc.raw),
|
|
73
|
+
compiledTruth: api.extractSection(doc.body, 'compiled_truth'), raw: doc.raw,
|
|
74
|
+
summary: pageSummary(api.extractSection(doc.body, 'compiled_truth'), doc.frontmatter.title) });
|
|
75
|
+
const read = id => { idCheck(id); return normalize(api.loadDoc(join(target.directory, 'pages', `${id}.md`))); };
|
|
76
|
+
const list = () => api.listPages().filter(p => p.frontmatter.status === 'active').map(normalize);
|
|
77
|
+
const checkVersion = (current, expected) => {
|
|
78
|
+
if (!expected || String(current.version) !== String(expected)) throw new Error('Version conflict or missing --expected-version. Read the current page before updating.');
|
|
79
|
+
};
|
|
80
|
+
const roots = () => api.listRootPages().map(doc => ({ slug: doc.id, title: doc.frontmatter.title, version: version(doc.raw), updated: doc.frontmatter.updated }));
|
|
81
|
+
const index = () => {
|
|
82
|
+
const pages = list(), rootPages = roots();
|
|
83
|
+
return { path: join(target.directory, 'index.md'), body: renderIndex(pages, rootPages), storedIndexPresent: existsSync(join(target.directory, 'index.md')), pages: pages.map(({ raw, compiledTruth, ...p }) => p), rootPages, count: pages.length, source: 'current-pages' };
|
|
84
|
+
};
|
|
85
|
+
return run({ target, list, read, index,
|
|
86
|
+
reindex: () => localMutation(root, () => {
|
|
87
|
+
api.reindexBrain();
|
|
88
|
+
return { ...index(), generated: true };
|
|
89
|
+
}),
|
|
90
|
+
roots,
|
|
91
|
+
readRoot: slug => { rootCheck(slug); const doc = api.loadDoc(join(target.directory, `${slug}.md`)); return { slug, body: doc.body, version: version(doc.raw) }; },
|
|
92
|
+
search: query => list().filter(p => `${p.title}\n${p.compiledTruth}`.toLowerCase().includes(query.toLowerCase())),
|
|
93
|
+
create: args => localMutation(root, () => {
|
|
94
|
+
localCommand(root, ['create-page', '--id', args.id, '--category', args.category, '--title', args.title, '--status', args.status || 'active', '--source', args.creationSummary || 'MindMux CLI']);
|
|
95
|
+
localCommand(root, ['update-truth', '--id', args.id, '--summary', args.creationSummary || 'Capture settled knowledge'], args.compiledTruth);
|
|
96
|
+
return read(args.id);
|
|
97
|
+
}),
|
|
98
|
+
update: args => localMutation(root, () => {
|
|
99
|
+
checkVersion(read(args.id), args.expectedVersion);
|
|
100
|
+
localCommand(root, ['update-truth', '--id', args.id, '--summary', args.timelineEntry.summary, '--source', args.timelineEntry.source || 'MindMux CLI'], args.compiledTruth);
|
|
101
|
+
return read(args.id);
|
|
102
|
+
}),
|
|
103
|
+
append: args => localMutation(root, () => {
|
|
104
|
+
idCheck(args.id);
|
|
105
|
+
localCommand(root, ['append-timeline', '--id', args.id, '--kind', args.entry.kind, '--summary', args.entry.summary, '--source', args.entry.source || 'MindMux CLI']);
|
|
106
|
+
return read(args.id);
|
|
107
|
+
}),
|
|
108
|
+
archive: id => localMutation(root, () => { idCheck(id); localCommand(root, ['archive-page', '--id', id]); return read(id); }),
|
|
109
|
+
updateRoot: args => localMutation(root, () => {
|
|
110
|
+
rootCheck(args.slug);
|
|
111
|
+
const path = join(target.directory, `${args.slug}.md`);
|
|
112
|
+
checkVersion({ version: existsSync(path) ? version(api.loadDoc(path).raw) : 'new' }, args.expectedVersion);
|
|
113
|
+
localCommand(root, ['update-root', args.slug], args.body);
|
|
114
|
+
return { slug: args.slug, version: version(api.loadDoc(path).raw) };
|
|
115
|
+
}),
|
|
116
|
+
});
|
|
117
|
+
}
|
package/src/clean.mjs
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import { existsSync, lstatSync, readFileSync, readdirSync, mkdirSync, rmSync, rmdirSync, realpathSync } from 'node:fs';
|
|
2
|
+
import { dirname, join, resolve, relative, isAbsolute } from 'node:path';
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
import { createHash } from 'node:crypto';
|
|
5
|
+
import { homeDir, preferences, preferencesPath, readJson, writeJson } from './storage.mjs';
|
|
6
|
+
import { AGENTS, connect, integrationFiles, managedBlock } from './integrations.mjs';
|
|
7
|
+
import { guardPath, planHost } from './host-config.mjs';
|
|
8
|
+
import { removeSetup } from './setup.mjs';
|
|
9
|
+
import { brainPackage } from './brain.mjs';
|
|
10
|
+
import { createSetupPrompts } from './prompts.mjs';
|
|
11
|
+
|
|
12
|
+
const inside = (parent, path) => { const rel = relative(parent, path); return rel === '' || (!rel.startsWith('..' + '/') && rel !== '..' && !isAbsolute(rel)); };
|
|
13
|
+
function noSymlinks(path) {
|
|
14
|
+
for (let current = path; ; current = dirname(current)) {
|
|
15
|
+
if (lstatSync(current, { throwIfNoEntry: false })?.isSymbolicLink() && !(process.platform === 'darwin' && ['/var', '/tmp', '/etc'].includes(current) && realpathSync(current) === '/private' + current)) throw new Error(`Refusing cleanup through a symbolic link: ${current}`);
|
|
16
|
+
if (dirname(current) === current) return;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
function prune(path) {
|
|
20
|
+
if (lstatSync(path, { throwIfNoEntry: false })?.isDirectory() && readdirSync(path).length === 0) rmdirSync(path);
|
|
21
|
+
}
|
|
22
|
+
function cleanPlan(root, flags) {
|
|
23
|
+
const home = homeDir();
|
|
24
|
+
if (home === homedir() || inside(home, root)) throw new Error('MINDMUX_HOME must be a dedicated CLI directory, not the project, home directory, or an ancestor of the project.');
|
|
25
|
+
noSymlinks(home);
|
|
26
|
+
const runtime = join(root, '.mindmux/cli'); guardPath(root, runtime);
|
|
27
|
+
const prefs = preferences(root);
|
|
28
|
+
const setup = readJson(join(runtime, 'setup.json'), {});
|
|
29
|
+
const integrations = readJson(join(runtime, 'integrations.json'), {});
|
|
30
|
+
const agents = [...new Set([...Object.keys(setup.agents || {}), ...Object.keys(integrations)])];
|
|
31
|
+
for (const agent of agents) {
|
|
32
|
+
if (!AGENTS.includes(agent)) throw new Error(`Unknown integration in cleanup manifest: ${agent}`);
|
|
33
|
+
if (setup.agents?.[agent]) planHost(root, agent, setup.agents[agent], { remove: true });
|
|
34
|
+
const files = integrationFiles(root, agent);
|
|
35
|
+
for (const file of Object.values(files)) guardPath(root, file);
|
|
36
|
+
managedBlock(existsSync(files.rules) ? readFileSync(files.rules, 'utf8') : '', '');
|
|
37
|
+
if (files.hooks) {
|
|
38
|
+
const settings = readJson(files.hooks, {});
|
|
39
|
+
if (settings.hooks !== undefined && (!settings.hooks || typeof settings.hooks !== 'object' || Array.isArray(settings.hooks) || Object.values(settings.hooks).some(value => !Array.isArray(value)))) throw new Error(`Invalid hooks: ${files.hooks}`);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
const data = [...new Set([join(root, 'brain'), ...(prefs.brainRoot ? [resolve(root, prefs.brainRoot)] : [])])].filter(existsSync);
|
|
43
|
+
for (const path of data) {
|
|
44
|
+
noSymlinks(path);
|
|
45
|
+
if (inside(path, root) || inside(path, home) || inside(home, path) || existsSync(join(path, '.git'))) throw new Error(`Unsafe local Brain directory: ${path}`);
|
|
46
|
+
if (!inside(root, path) && !flags['include-external-data']) throw new Error(`Local Brain is outside this project: ${path}. Use --include-external-data to include this explicitly configured directory.`);
|
|
47
|
+
if (!existsSync(join(path, 'index.md')) || !readFileSync(join(path, 'index.md'), 'utf8').startsWith('# Brain Index')) throw new Error(`Refusing to delete an unrecognized Brain directory: ${path}`);
|
|
48
|
+
}
|
|
49
|
+
const backup = join(home, 'backups', createHash('sha256').update(root).digest('hex'));
|
|
50
|
+
const paths = [preferencesPath(root), runtime, backup, ...data];
|
|
51
|
+
if (!flags['keep-login']) paths.push(join(home, 'auth'), join(home, 'config.json'));
|
|
52
|
+
for (const path of paths) noSymlinks(path);
|
|
53
|
+
return { root, home, runtime, prefs, setup, agents, data, backup };
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export async function clean(root, flags = {}, dependencies = {}) {
|
|
57
|
+
const plan = cleanPlan(root, flags);
|
|
58
|
+
const interactive = Boolean(dependencies.prompts || (process.stdin.isTTY && process.stderr.isTTY));
|
|
59
|
+
if (!flags.yes) {
|
|
60
|
+
if (!interactive) throw new Error('clean deletes local data. Run interactively or pass --yes to confirm.');
|
|
61
|
+
const prompts = dependencies.prompts || createSetupPrompts();
|
|
62
|
+
const scope = [
|
|
63
|
+
`Reset MindMux in ${root}?`,
|
|
64
|
+
'Remove managed agent integrations, project binding, caches, and this project\'s configuration backups.',
|
|
65
|
+
...plan.data.map(path => `Delete local Brain data: ${path}`),
|
|
66
|
+
flags['keep-login'] ? 'Keep CLI login.' : 'Sign out of the CLI for all servers (affects other projects using this CLI login).',
|
|
67
|
+
'Cloud Projects and Brains will be kept.',
|
|
68
|
+
].join('\n');
|
|
69
|
+
try { if (!await prompts.confirm(scope)) return { cleaned: false, cancelled: true }; }
|
|
70
|
+
catch (error) { if (error.name === 'ExitPromptError') return { cleaned: false, cancelled: true }; throw error; }
|
|
71
|
+
}
|
|
72
|
+
// Revalidate after the confirmation, before acquiring the same lock as setup/remove.
|
|
73
|
+
const current = cleanPlan(root, flags);
|
|
74
|
+
if (JSON.stringify(current) !== JSON.stringify(plan)) throw new Error('Configuration changed during confirmation. Run clean again.');
|
|
75
|
+
if (existsSync(join(plan.runtime, 'write.lock'))) throw new Error('A local Brain write is active. Finish it before running clean.');
|
|
76
|
+
if (!flags['keep-login'] && existsSync(join(plan.home, 'auth')) && readdirSync(join(plan.home, 'auth')).some(name => name.endsWith('.lock'))) throw new Error('CLI authentication is busy. Stop active agents or finish login before running clean.');
|
|
77
|
+
mkdirSync(plan.runtime, { recursive: true, mode: 0o700 });
|
|
78
|
+
const lock = join(plan.runtime, 'setup.lock');
|
|
79
|
+
try { mkdirSync(lock); } catch { throw new Error(`Another setup/remove/clean is active: ${lock}`); }
|
|
80
|
+
const unlock = () => rmSync(lock, { recursive: true, force: true });
|
|
81
|
+
process.once('exit', unlock);
|
|
82
|
+
try {
|
|
83
|
+
await removeSetup(root, {}, { lockHeld: true });
|
|
84
|
+
for (const agent of plan.agents) {
|
|
85
|
+
if (!plan.setup.agents?.[agent]) connect(root, agent, { remove: true });
|
|
86
|
+
const files = integrationFiles(root, agent);
|
|
87
|
+
if (existsSync(files.rules) && !readFileSync(files.rules, 'utf8').trim()) rmSync(files.rules);
|
|
88
|
+
if (files.hooks && existsSync(files.hooks)) {
|
|
89
|
+
const settings = readJson(files.hooks, {});
|
|
90
|
+
if (settings.hooks && !Object.keys(settings.hooks).length) delete settings.hooks;
|
|
91
|
+
if (!Object.keys(settings).length || (agent === 'cursor' && Object.keys(settings).length === 1 && settings.version === 1)) rmSync(files.hooks);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
for (const [agent, record] of Object.entries(plan.setup.agents || {})) {
|
|
95
|
+
const file = join(root, agent === 'codex' ? '.codex/config.toml' : '.mcp.json');
|
|
96
|
+
if (!record.original && existsSync(file) && (agent === 'codex' ? !readFileSync(file, 'utf8').trim() : !Object.keys(readJson(file, {})).length)) rmSync(file);
|
|
97
|
+
}
|
|
98
|
+
const remaining = { ...plan.prefs };
|
|
99
|
+
for (const key of ['cloudBrain', 'mindmuxCli', 'brainRoot']) delete remaining[key];
|
|
100
|
+
if (Object.keys(remaining).some(key => key !== 'version')) writeJson(preferencesPath(root), remaining);
|
|
101
|
+
else rmSync(preferencesPath(root), { force: true });
|
|
102
|
+
const scaffold = join(root, 'BRAIN.md');
|
|
103
|
+
const original = join(brainPackage, 'skills/brain-setup/assets/BRAIN.md');
|
|
104
|
+
if (plan.data.length && existsSync(scaffold) && readFileSync(scaffold, 'utf8') === readFileSync(original, 'utf8')) rmSync(scaffold);
|
|
105
|
+
for (const path of plan.data) rmSync(path, { recursive: true, force: true });
|
|
106
|
+
rmSync(plan.backup, { recursive: true, force: true });
|
|
107
|
+
if (!flags['keep-login']) {
|
|
108
|
+
rmSync(join(plan.home, 'auth'), { recursive: true, force: true });
|
|
109
|
+
rmSync(join(plan.home, 'config.json'), { force: true });
|
|
110
|
+
}
|
|
111
|
+
// Keep our lock until every other project cleanup operation has completed.
|
|
112
|
+
for (const name of readdirSync(plan.runtime)) if (name !== 'setup.lock') rmSync(join(plan.runtime, name), { recursive: true, force: true });
|
|
113
|
+
return { cleaned: true, signedOut: !flags['keep-login'], localDataRemoved: plan.data, cloudDataDeleted: false, next: 'Run mmx setup to start again.' };
|
|
114
|
+
} finally {
|
|
115
|
+
process.removeListener('exit', unlock); unlock();
|
|
116
|
+
prune(plan.runtime); prune(join(root, '.mindmux'));
|
|
117
|
+
for (const dir of ['.codex', '.claude', '.cursor/rules', '.cursor']) prune(join(root, dir));
|
|
118
|
+
}
|
|
119
|
+
}
|
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.0)
|
|
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.0'); 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
|
+
}
|