@mindmux/cli 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +58 -2
- package/bin/mindmux.mjs +3 -0
- package/bin/mmx.mjs +6 -0
- package/docs/README.md +14 -0
- package/docs/agents.md +61 -0
- package/docs/brain.md +54 -0
- package/docs/cloud.md +29 -0
- package/docs/development.md +24 -0
- package/docs/installation.md +86 -0
- package/docs/setup.md +116 -0
- package/package.json +40 -4
- package/src/brain-index.mjs +31 -0
- package/src/brain.mjs +117 -0
- package/src/clean.mjs +119 -0
- package/src/cli.mjs +254 -0
- package/src/cloud.mjs +164 -0
- package/src/codex-hooks.mjs +15 -0
- package/src/doctor.mjs +95 -0
- package/src/hooks.mjs +106 -0
- package/src/host-config.mjs +108 -0
- package/src/integrations.mjs +100 -0
- package/src/mcp-server.mjs +114 -0
- package/src/menu.mjs +49 -0
- package/src/prompts.mjs +31 -0
- package/src/recall.mjs +64 -0
- package/src/review.mjs +166 -0
- package/src/setup.mjs +297 -0
- package/src/status.mjs +65 -0
- package/src/storage.mjs +76 -0
package/docs/setup.md
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
# Project setup and maintenance
|
|
2
|
+
|
|
3
|
+
[Back to README](../README.md) · [Documentation](README.md)
|
|
4
|
+
|
|
5
|
+
Run `mmx setup` inside the project you want to connect.
|
|
6
|
+
|
|
7
|
+
Use the Up/Down arrow keys and Enter to select agents, Workspaces, Projects, and confirmations. Select **+ Create a new Project** to create a Project; only its name requires typing. Empty, overlong, and duplicate names are validated in place so you can correct them without restarting. Cancelling creation returns to the Project menu; Ctrl+C exits setup.
|
|
8
|
+
|
|
9
|
+
The wizard also handles browser login. It installs project-level MCP configuration and agent instructions/hooks, then performs a real stdio MCP handshake and a read-only recall check.
|
|
10
|
+
|
|
11
|
+
Setup prints progress for login, discovery, validation, installation, and the MCP check. Progress goes to stderr and is suppressed with `--json`. Setup finishes with a short confirmation and instructions to restart your agent. For scripts or troubleshooting, use `mmx setup --json` to return the full structured result, including diagnostics and the backup path.
|
|
12
|
+
|
|
13
|
+
Existing valid credentials and project bindings are reused. Repeating setup updates managed entries without registering duplicates. Browser authorization and the agent's own project, MCP, and hook trust prompts still require user interaction.
|
|
14
|
+
|
|
15
|
+
Explicit options are available for automation:
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
# Connect an existing Cloud Brain.
|
|
19
|
+
mmx setup --agent claude-code,codex --brain-id <brain-id> --yes
|
|
20
|
+
|
|
21
|
+
# Create a Project visible to all members of the selected Workspace.
|
|
22
|
+
mmx setup --agent codex --workspace-id <workspace-id> --name 'My Project' --confirm --yes
|
|
23
|
+
|
|
24
|
+
# Use a local Brain without Cloud login.
|
|
25
|
+
mmx setup --local --agent codex --yes
|
|
26
|
+
|
|
27
|
+
mmx doctor --online
|
|
28
|
+
mmx remove
|
|
29
|
+
mmx remove --agent codex
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
`--yes` disables terminal questions. It does not bypass OAuth, agent trust prompts, or the `--confirm` requirement for Project creation. Non-interactive Cloud setup requires explicit agents and either an existing Cloud binding, a Brain ID, or Project creation options. `--no-open` prints the authorization URL instead of opening a browser.
|
|
33
|
+
|
|
34
|
+
Claude Code uses the `mindmux` entry in `.mcp.json`, plus `CLAUDE.md` and hooks. Codex uses `mindmux_cli` in `.codex/config.toml`, plus `AGENTS.md` instructions and native hooks in `.codex/hooks.json`. These MCP identifiers remain unchanged by the executable rename. Generated MCP configuration contains executable paths and `MINDMUX_HOME`, rather than copied OAuth tokens. Restart the agent after setup and approve the applicable trust prompts.
|
|
35
|
+
|
|
36
|
+
## Codex hook setup and upgrades
|
|
37
|
+
|
|
38
|
+
The [official Codex hooks documentation](https://learn.chatgpt.com/docs/hooks) describes the host protocol and trust controls. Codex hooks require a compatible Codex installation with the `hooks` feature enabled. Setup checks `codex features list` and warns if support cannot be verified or hooks are disabled; it does not change global Codex settings. Doctor reports unsupported or disabled hooks as errors and unavailable capability checks as warnings. If needed, update Codex or run `codex features enable hooks`.
|
|
39
|
+
|
|
40
|
+
For an existing instructions-only installation, rerun `mmx setup --agent codex` (add `--local` for a local Brain), or use `mmx doctor --fix`. Setup installs SessionStart, UserPromptSubmit, Stop, and Interrupt handlers in `.codex/hooks.json`, preserves unrelated hooks, and keeps `AGENTS.md` as workflow guidance. It does not change the brain.md storage implementation. Status and doctor detect older instructions-only installs as missing hooks. Setup adds `.codex/hooks.json` to the project's `.gitignore`; run setup in each worktree that needs these hooks.
|
|
41
|
+
|
|
42
|
+
Restart Codex, trust the project, and open `/hooks` to review new or changed definitions. Codex skips untrusted hooks; the CLI does not approve hooks or alter Codex's trust records. Hooks may also exist in global or inline TOML configuration, so inspect `/hooks` for duplicates. `mmx remove --agent codex` removes the hooks installed by setup while preserving unrelated hook definitions; `mmx clean` also removes the managed hooks as part of its local reset.
|
|
43
|
+
|
|
44
|
+
SessionStart injects base Brain context (including after resume/compaction); UserPromptSubmit retrieves relevant project knowledge. UserPromptSubmit supplies a token for the agent to register its memory review before answering. Stop silently accepts a registered review; otherwise it requests at most one recovery, and continuation prompts do not reset this guard. Interrupt invalidates the active review token. See [Agent behavior](agents.md) for the review protocol and failure limits. Writes still require the agent to identify confirmed durable knowledge and call the CLI/MCP. Hook failures are recorded and allow the task to proceed; no automatic Cloud-to-local fallback occurs. Use `mmx status` to inspect observed hook delivery, or `mmx doctor` to check installation and Codex hook capability; neither can verify that Codex trusted a definition or used the returned context.
|
|
45
|
+
|
|
46
|
+
## Interactive menu
|
|
47
|
+
|
|
48
|
+
Run `mmx` without arguments in a terminal to open the arrow-key menu. An unconfigured project offers setup first. Configured projects offer status, live connection checks, diagnosis and repair, Brain switching, and agent configuration. More options include removing selected agent connections and resetting local setup. Removal requires confirmation; local reset retains its own scope preview and confirmation. Actions return to the menu, and Ctrl+C or Exit closes it.
|
|
49
|
+
|
|
50
|
+
`mmx --help` always prints command help. Running without arguments in a non-interactive environment, or with `--json` or `--yes`, prints help without waiting for input. Explicit subcommands remain available for scripts.
|
|
51
|
+
|
|
52
|
+
## Diagnose and repair
|
|
53
|
+
|
|
54
|
+
```bash
|
|
55
|
+
mmx doctor # Readable local diagnostics; no network calls.
|
|
56
|
+
mmx doctor --online # Also check Brain access and MCP recall.
|
|
57
|
+
mmx doctor --fix # Review the repair plan and confirm with arrow keys.
|
|
58
|
+
mmx doctor --json # Structured report, including the repair plan.
|
|
59
|
+
mmx doctor --fix --yes --json # Explicit non-interactive repair approval.
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
Doctor explains each problem and the suggested next action. Repair restores missing setup-managed entries and instructions/hooks, refreshes stale executable paths, and preserves unrelated configuration, the Brain binding, login, and Brain data. It backs up project configuration and runs an MCP recall check; a failed check rolls back configuration. Cloud repair can require browser login. Restart the configured agents after successful repair.
|
|
63
|
+
|
|
64
|
+
Modified MCP entries, malformed configuration, unsafe paths, and conflicting integrations are not overwritten. If project files change after the repair plan is shown, repair stops so you can review a new plan. Connect-only integrations are diagnosed, but automatic repair requires a setup-managed installation. Use `mmx setup` for initial configuration. Diagnostics return a nonzero exit status while errors remain; warnings alone do not fail the command. Doctor output now defaults to text, so scripts should explicitly pass `--json`.
|
|
65
|
+
|
|
66
|
+
## Check status and switch Brains
|
|
67
|
+
|
|
68
|
+
```bash
|
|
69
|
+
mmx status # Local configuration and observed activity; no network calls.
|
|
70
|
+
mmx status --online # Also check Brain access and the configured MCP launcher.
|
|
71
|
+
mmx status --json # Structured details for scripts.
|
|
72
|
+
mmx switch # Choose a Workspace and Project with arrow keys.
|
|
73
|
+
mmx switch --brain-id <brain-id> --yes
|
|
74
|
+
mmx switch --local --yes
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
`status` distinguishes saved credentials, agent configuration, live read-only checks, successful MCP client tool calls, and hook context delivery. Successful setup is described as **Configured for**, because it does not establish that the agent has connected. Codex uses native lifecycle hooks alongside project instructions. Project-local hooks require a trusted project and review of each hook definition through `/hooks`. Neither a tool call nor delivered context proves that the model used the knowledge in its answer.
|
|
78
|
+
|
|
79
|
+
Usage receipts are bounded to the most recent successful MCP tool call and each hook event. They record timestamps, client/tool/operation names and a binding fingerprint, without tool arguments or results. Setup and status probes do not count as agent activity. Status ignores receipts from a different binding or before the latest successful setup; it cannot observe calls made directly to a separate remote MCP connection or CLI.
|
|
80
|
+
|
|
81
|
+
`switch` requires an existing `setup` installation and reuses all setup-managed agents. It keeps login credentials and Brain data. The selected Brain must pass validation and the MCP recall check; failures restore the previous binding and project configuration. Ctrl+C at a selection prompt cancels without changing the binding. Restart the agent after switching so its MCP server uses the new Brain.
|
|
82
|
+
|
|
83
|
+
If Cloud Project creation succeeds but a later setup step fails, the error provides a command with that Brain ID to resume installation. The Cloud Project is retained. A local creation journal prevents a known creation from being replayed. If a creation request loses its response, inspect `mmx project list` before trying again; writes are never automatically retried.
|
|
84
|
+
|
|
85
|
+
## Existing integrations and migration
|
|
86
|
+
|
|
87
|
+
Codex merges global and project entries with the same name. The local transport therefore uses a separate name. Recognized global MindMux remote entries are disabled only in the current project through an `enabled = false` override; global configuration remains intact. Setup stops if a global `mindmux_cli` entry would conflict with the project transport.
|
|
88
|
+
|
|
89
|
+
Use `mmx setup --migrate` to replace an existing project-level remote MCP entry. The original value is backed up and restored by `remove`. Initial TOML migration may reorder content or move comments; the complete original file is retained in the backup. Subsequent ordinary installs preserve unmanaged content. User-modified managed MCP entries are protected from replacement and removal.
|
|
90
|
+
|
|
91
|
+
Migration also invokes the official brain.md project hook uninstaller for recognized legacy SessionStart hooks. Global brain.md skills and other global settings are reported but are not removed. Inspect custom aliases and higher-priority Claude local-scope entries in the agent itself.
|
|
92
|
+
|
|
93
|
+
Configuration backups are stored under `~/.mindmux-cli/backups/` or `MINDMUX_HOME/backups/`, outside the project, with mode `0600`. Failed installation or self-check restores project configuration. Brain data and successfully created remote Projects survive rollback. A creation journal prevents blindly repeating a remote creation whose outcome is unknown; inspect `mmx project list` before retrying when instructed.
|
|
94
|
+
|
|
95
|
+
`remove` removes setup-managed project integrations while retaining Brain data, binding, login, and unrelated configuration. For integrations installed only with `connect`, use `disconnect`.
|
|
96
|
+
|
|
97
|
+
## Reset for testing
|
|
98
|
+
|
|
99
|
+
Run `mmx clean` in the project to reset its local MindMux state. The arrow-key confirmation lists the cleanup scope before anything is removed.
|
|
100
|
+
|
|
101
|
+
```bash
|
|
102
|
+
mmx clean
|
|
103
|
+
mmx setup
|
|
104
|
+
|
|
105
|
+
# Reset the project while keeping CLI login.
|
|
106
|
+
mmx clean --keep-login
|
|
107
|
+
|
|
108
|
+
# Explicit confirmation for non-interactive scripts.
|
|
109
|
+
mmx clean --yes --json
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
Cleanup removes managed MCP entries, instructions and hooks, project binding, session caches, local Brain data, and this project's configuration backups. By default, it also removes **all CLI login credentials and the saved server setting** from the current `MINDMUX_HOME`, which signs out other projects sharing that CLI login. `--keep-login` retains both. This removes local credentials; it does not revoke server grants or end a browser session.
|
|
113
|
+
|
|
114
|
+
**Cloud Projects and Brains are always kept.** Existing cloud Projects can be selected in the next setup. Unrelated agent configuration, custom instructions, unknown preference fields, and other projects' backups are preserved. Empty generated files are removed, and an unchanged brain.md scaffold is removed with local Brain data. Git ignore rules are retained.
|
|
115
|
+
|
|
116
|
+
Cleanup refuses modified managed MCP entries, unsafe paths, symbolic links, and active setup/write/authentication locks. Stop active agents before resetting. A configured local Brain outside the project requires `--include-external-data`; its path is shown in the confirmation. Local data deletion cannot be undone by `remove`.
|
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.1",
|
|
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
|
+
}
|