@mindmux/cli 0.1.7 → 0.1.9

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/cli.mjs CHANGED
@@ -1,10 +1,13 @@
1
+ import { OPTIONS, schema, validateBrainArguments } from './command-schema.mjs';
2
+ import { CliError, usageError, errorResult } from './errors.mjs';
3
+ import { automation, setAutomation } from './automation.mjs';
1
4
  import { VERSION } from './version.mjs';
2
5
  import { parseArgs } from 'node:util';
3
6
  import { resolve, join, basename } from 'node:path';
4
7
  import { existsSync, rmSync, realpathSync } from 'node:fs';
5
8
  import { binding, projectRoot, preferences, mergePreferences, ignoreRuntime, readJson, writeJson, homeDir, serverUrl, DEFAULT_SERVER } from './storage.mjs';
6
9
  import { localCommand, withBrain } from './brain.mjs';
7
- import { withCloud, login, credentialPath } from './cloud.mjs';
10
+ import { withCloud, withAuthLock, login, credentialPath } from './cloud.mjs';
8
11
  import { connect } from './integrations.mjs';
9
12
  import { runHook } from './hooks.mjs';
10
13
  import { recall } from './recall.mjs';
@@ -13,6 +16,8 @@ import { reviewedWrite, finishReview } from './review.mjs';
13
16
  const HELP = `mmx — project Brain operations and agent integrations (v${VERSION})
14
17
 
15
18
  Setup:
19
+ mmx schema [COMMAND...] inspect command metadata as JSON (offline)
20
+ mmx pause | resume manually pause/resume automatic memory in this project
16
21
  mmx --skill print the self-contained Agent Skill (Markdown; read-only)
17
22
  mmx setup [--agent claude-code,codex] login, choose Brain, install MCP + rules/hooks
18
23
  mmx setup --local --agent codex --yes local Brain without Cloud login
@@ -35,6 +40,7 @@ Setup:
35
40
  mmx connect --agent cursor|claude-code|codex
36
41
  mmx disconnect --agent NAME remove only owned integration entries
37
42
  mmx doctor [--online] [--json] diagnose configuration and connectivity
43
+ mmx doctor --support print a local, redacted support report
38
44
  mmx doctor --fix [--yes] review and apply managed configuration repair
39
45
 
40
46
  Brain (JSON output, automatically uses the selected local/cloud Brain):
@@ -62,8 +68,9 @@ Cloud discovery and low-level access:
62
68
 
63
69
  Run mmx without arguments in a terminal for the interactive menu.
64
70
  All commands accept --project PATH. No automatic cloud-to-local fallback.
65
- Cursor: startup context + prompt retrieval delivered at first tool call; one stop review.
66
- Claude Code: startup + prompt context; one stop review. Codex: pre-answer review; Stop recovers a missing review once.
71
+ Cursor: startup context + prompt retrieval delivered at first tool call.
72
+ Claude Code: startup + prompt context. Codex: pre-answer review with verified write receipts.
73
+ Stop records memory status without blocking answers or forcing another turn.
67
74
  `;
68
75
 
69
76
  const UPDATE_HELP = `mmx update — upgrade MindMux CLI and refresh managed integrations
@@ -99,25 +106,24 @@ configuration checks do not prove that a running agent loaded or executed its ho
99
106
  `;
100
107
 
101
108
  async function stdin(limit = 1024 * 1024) {
102
- if (process.stdin.isTTY) throw new Error('Pipe content through stdin.');
109
+ if (process.stdin.isTTY) throw usageError('Pipe content through stdin.');
103
110
  let value = '';
104
111
  for await (const chunk of process.stdin) {
105
112
  value += chunk;
106
- if (Buffer.byteLength(value) > limit) throw new Error('stdin exceeds 1 MiB.');
113
+ if (Buffer.byteLength(value) > limit) throw usageError('stdin exceeds 1 MiB.');
107
114
  }
108
115
  return value;
109
116
  }
110
117
  const output = value => console.log(JSON.stringify(value, null, 2));
111
- const need = (value, name) => { if (typeof value !== 'string' || !value.trim()) throw new Error(`${name} is required.`); return value; };
118
+ const need = (value, name) => { if (typeof value !== 'string' || !value.trim()) throw usageError(`${name} is required.`); return value; };
112
119
  const body = async () => need((await stdin()).trim(), 'Nonempty stdin');
113
120
  function cloudVersion(value) {
114
- if (!/^[1-9]\d*$/.test(value) || !Number.isSafeInteger(Number(value))) throw new Error('--expected-version must be a positive integer for Cloud updates.');
121
+ if (!/^[1-9]\d*$/.test(value) || !Number.isSafeInteger(Number(value))) throw usageError('--expected-version must be a positive integer for Cloud updates.');
115
122
  return Number(value);
116
123
  }
117
124
 
118
125
  export async function main(argv = process.argv.slice(2)) {
119
- const options = Object.fromEntries(['project', 'agent', 'brain-id', 'server', 'workspace-id', 'name', 'description', 'id', 'title', 'category', 'status', 'source', 'expected-version', 'change-kind', 'summary', 'kind', 'args', 'review-token', 'outcome', 'reason', 'manager'].map(key => [key, { type: 'string' }]));
120
- for (const key of ['local', 'online', 'no-open', 'confirm', 'help', 'version', 'skill', 'yes', 'migrate', 'json', 'keep-login', 'include-external-data', 'fix', 'check', 'refresh-integrations', 'all-projects', 'non-interactive']) options[key] = { type: 'boolean' };
126
+ const options = OPTIONS;
121
127
  // -agent is an exact single-dash alias, distinct from --agent NAME.
122
128
  // Do not rewrite option values or positional content after --.
123
129
  const args = [];
@@ -129,17 +135,22 @@ export async function main(argv = process.argv.slice(2)) {
129
135
  }
130
136
  const { values: flags, positionals: pos } = parseArgs({ args, options, allowPositionals: true, strict: true });
131
137
  if (flags.skill) {
132
- if (pos.length || Object.keys(flags).some(key => !['skill', 'project'].includes(key))) throw new Error('Run mmx --skill by itself (optional --project PATH). Output is Markdown, not JSON.');
138
+ if (pos.length || Object.keys(flags).some(key => !['skill', 'project'].includes(key))) throw usageError('Run mmx --skill by itself (optional --project PATH). Output is Markdown, not JSON.');
133
139
  const { readSkill } = await import('./skill.mjs');
134
140
  process.stdout.write(readSkill());
135
141
  return;
136
142
  }
137
143
  if (flags['non-interactive']) flags.json = true;
144
+ if (pos[0] === 'schema' && !flags.help) {
145
+ if (Object.keys(flags).some(key => !['json', 'project', 'non-interactive'].includes(key))) throw usageError('Run mmx schema [COMMAND...] [--json].');
146
+ output(schema(pos.slice(1))); return;
147
+ }
138
148
  if (flags.version) { console.log(VERSION); return; }
139
149
  if ((flags.help && pos[0] === 'update') || (pos[0] === 'help' && pos[1] === 'update')) { console.log(UPDATE_HELP); return; }
140
150
  if (flags.help || pos[0] === 'help' || (!pos.length && (!process.stdin.isTTY || !process.stderr.isTTY || flags.json || flags.yes))) { console.log(HELP); return; }
141
- const root = realpathSync(flags.project ? resolve(flags.project) : projectRoot());
142
- process.chdir(root);
151
+ let root;
152
+ try { root = realpathSync(flags.project ? resolve(flags.project) : projectRoot()); process.chdir(root); }
153
+ catch (cause) { throw new CliError('PROJECT_UNAVAILABLE', 'Project directory is unavailable.', { next: 'Use --project with an existing project directory.', cause }); }
143
154
  if (!pos.length) {
144
155
  const { runMenu } = await import('./menu.mjs');
145
156
  await runMenu(root, { run: async args => {
@@ -150,12 +161,12 @@ export async function main(argv = process.argv.slice(2)) {
150
161
  }
151
162
  const [command, action, ...rest] = pos;
152
163
  for (const key of ['title', 'summary', 'source']) {
153
- if (flags[key] && /[\r\n\0]/.test(flags[key])) throw new Error(`--${key} must be a single line without NUL characters.`);
164
+ if (flags[key] && /[\r\n\0]/.test(flags[key])) throw usageError(`--${key} must be a single line without NUL characters.`);
154
165
  }
155
166
  if (command === 'update') {
156
- if (action || rest.length) throw new Error('Run mmx update [--check] [--yes] [--json] [--manager npm|pnpm].');
167
+ if (action || rest.length) throw usageError('Run mmx update [--check] [--yes] [--json] [--manager npm|pnpm].');
157
168
  if (flags['refresh-integrations']) {
158
- if (flags.check || flags.manager) throw new Error('Integration refresh cannot be combined with update selection flags.');
169
+ if (flags.check || flags.manager) throw usageError('Integration refresh cannot be combined with update selection flags.');
159
170
  // Older updaters call this entry without --all-projects after installing a release.
160
171
  // Default to the full recorded scope so their first upgrade also repairs other projects.
161
172
  const result = await (await import('./update-projects.mjs')).refreshUpdateProjects(root, { allProjects: true });
@@ -174,6 +185,15 @@ export async function main(argv = process.argv.slice(2)) {
174
185
  if (result.status === 'manual') process.exitCode = 1;
175
186
  return result;
176
187
  }
188
+ if (command === 'pause' || command === 'resume') {
189
+ if (action || rest.length || Object.keys(flags).some(key => !['project', 'json'].includes(key))) throw usageError('Run mmx pause or mmx resume manually in the intended project.');
190
+ const state = setAutomation(root, command === 'pause');
191
+ const note = state.paused
192
+ ? 'Automatic memory is paused for this project. Explicit Brain commands still work. Run mmx resume to restore automatic hooks. Already delivered context and dispatched operations cannot be recalled.'
193
+ : 'Automatic memory is enabled for future hook events. Skipped tasks will not be replayed.';
194
+ if (flags.json) output({ ...state, note }); else console.log(note);
195
+ return;
196
+ }
177
197
  const selectedServer = () => serverUrl(flags.server || preferences(root).mindmuxCli?.server || readJson(join(homeDir(), 'config.json'), {}).server || DEFAULT_SERVER);
178
198
  if (command === 'clean') {
179
199
  const { clean } = await import('./clean.mjs');
@@ -186,7 +206,10 @@ export async function main(argv = process.argv.slice(2)) {
186
206
  if (command === 'setup' || command === 'remove' || command === 'switch') {
187
207
  const { setup, removeSetup, switchBrain } = await import('./setup.mjs');
188
208
  const result = await (command === 'switch' ? switchBrain(root, flags) : command === 'setup' ? setup(root, flags) : removeSetup(root, flags));
189
- if (result.status === 'error') process.exitCode = 1;
209
+ if (result.status === 'error') {
210
+ Object.assign(result, { ...errorResult(new Error(result.error)), ...result });
211
+ process.exitCode = 1;
212
+ }
190
213
  if (flags.json) output(result);
191
214
  else if (command === 'remove') console.log(result.removed.length ? `Removed connections for ${result.removed.join(', ')}. Brain data, binding and login are kept.` : result.note);
192
215
  else {
@@ -214,17 +237,22 @@ export async function main(argv = process.argv.slice(2)) {
214
237
  output(publicLoginState(flags.status === 'check' ? loginSession(server) : await startLoginSession(server, { retry: true })));
215
238
  return;
216
239
  }
217
- await login(server, { open: !flags['no-open'] });
218
- writeJson(join(homeDir(), 'config.json'), { server }); return;
240
+ await login(server, { open: !flags['no-open'], onAuthorized: () => writeJson(join(homeDir(), 'config.json'), { server }) });
241
+ if (flags.json) output({ signedIn: true, server });
242
+ return;
219
243
  }
220
244
  if (command === 'logout') {
221
245
  const { pendingLogin } = await import('./login-session.mjs');
222
246
  if (pendingLogin()) throw new Error('Browser authorization is pending. Complete it or wait for it to expire before signing out.');
223
- rmSync(credentialPath(selectedServer()), { force: true });
247
+ const server = selectedServer();
248
+ await withAuthLock(server, async () => {
249
+ if (pendingLogin()) throw new Error('Browser authorization is pending. Complete it or wait for it to expire before signing out.');
250
+ rmSync(credentialPath(server), { force: true });
251
+ });
224
252
  output({ signedOut: true, note: 'Removed this CLI’s local credentials. This does not revoke other clients or server grants.' }); return;
225
253
  }
226
254
  if (command === 'init') {
227
- if (!flags.local) throw new Error('Choose --local explicitly, or run brain bind --brain-id <id> for Cloud.');
255
+ if (!flags.local) throw usageError('Choose --local explicitly, or run brain bind --brain-id <id> for Cloud.');
228
256
  localCommand(root, ['init', '--no-wire']);
229
257
  mergePreferences(root, { cloudBrain: { ...preferences(root).cloudBrain, enabled: false } });
230
258
  ignoreRuntime(root);
@@ -241,6 +269,11 @@ export async function main(argv = process.argv.slice(2)) {
241
269
  return;
242
270
  }
243
271
  if (command === 'doctor') {
272
+ if (flags.support) {
273
+ if (flags.online || flags.fix || flags.yes) throw usageError('--support is local and read-only; do not combine it with --online, --fix or --yes.');
274
+ const { supportReport } = await import('./support-report.mjs');
275
+ output(supportReport(root)); return;
276
+ }
244
277
  const { doctor, formatDoctor } = await import('./doctor.mjs');
245
278
  const report = await doctor(root, flags);
246
279
  if (flags.json) output(report);
@@ -262,13 +295,14 @@ export async function main(argv = process.argv.slice(2)) {
262
295
  }
263
296
  if (command === 'project' && action === 'create') {
264
297
  const workspaceId = need(flags['workspace-id'], '--workspace-id'), name = need(flags.name, '--name');
265
- if (!flags.confirm) throw new Error('New projects are visible to all Workspace members. Pass --confirm after selecting this Workspace and Project name.');
298
+ if (!flags.confirm) throw usageError('New projects are visible to all Workspace members. Pass --confirm after selecting this Workspace and Project name.');
266
299
  output(await withCloud(selectedServer(), call => call('create_project', { workspaceId, name, description: flags.description || '' }))); return;
267
300
  }
268
301
  if (command === 'mcp') {
269
302
  if (action === 'call') {
270
- const args = JSON.parse(flags.args || '{}');
271
- if (!args || Array.isArray(args) || typeof args !== 'object') throw new Error('--args must be a JSON object.');
303
+ let args;
304
+ try { args = JSON.parse(flags.args || '{}'); } catch { throw usageError('--args must be valid JSON.'); }
305
+ if (!args || Array.isArray(args) || typeof args !== 'object') throw usageError('--args must be a JSON object.');
272
306
  output(await withCloud(selectedServer(), call => call(need(rest[0], 'tool name'), args))); return;
273
307
  }
274
308
  if (action === 'tools') {
@@ -277,7 +311,7 @@ export async function main(argv = process.argv.slice(2)) {
277
311
  }
278
312
  }
279
313
  if (command === 'brain' && action === 'bind') {
280
- if (flags.local && flags['brain-id']) throw new Error('Choose --local or --brain-id, not both.');
314
+ if (flags.local && flags['brain-id']) throw usageError('Choose --local or --brain-id, not both.');
281
315
  const prefs = preferences(root);
282
316
  if (flags.local) {
283
317
  localCommand(root, ['brain-dir']);
@@ -290,13 +324,14 @@ export async function main(argv = process.argv.slice(2)) {
290
324
  }
291
325
  ignoreRuntime(root); output(binding(root)); return;
292
326
  }
293
- if (command === 'brain' && action === 'status') { output(binding(root)); return; }
327
+ if (command === 'brain' && action === 'status') { validateBrainArguments(action, rest, flags); output({ ...binding(root), automation: automation(root) }); return; }
294
328
  if (command === 'brain' && action === 'review') {
329
+ validateBrainArguments(action, rest, flags);
295
330
  output(await finishReview(root, { token: flags['review-token'], outcome: flags.outcome, reason: flags.reason, id: flags.id })); return;
296
331
  }
297
332
  if (command === 'brain') {
298
- // Validate operation before opening a cloud connection.
299
- 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.');
333
+ // Validate before opening a connection or waiting on stdin.
334
+ validateBrainArguments(action, rest, flags);
300
335
  let content;
301
336
  if (['create', 'update', 'update-root'].includes(action)) content = await body();
302
337
  const result = await withBrain(root, async brain => {
@@ -312,17 +347,12 @@ export async function main(argv = process.argv.slice(2)) {
312
347
  case 'recall': return recall(brain, rest.join(' '));
313
348
  case 'create': {
314
349
  const id = need(flags.id, '--id'), title = need(flags.title, '--title'), category = need(flags.category, '--category');
315
- if (!/^[a-z0-9][a-z0-9-]*$/.test(id) || /[\r\n]/.test(title)) throw new Error('Invalid page id or multiline title.');
316
- if (!['project', 'concept', 'decision', 'person', 'reference'].includes(category)) throw new Error('Invalid page category.');
317
- if (flags.status && !['active', 'draft', 'archived'].includes(flags.status)) throw new Error('Invalid page status.');
318
350
  return mutate({ kind: 'page', id }, () => brain.create({ id, title, category, status: flags.status || 'active', compiledTruth: content, creationSummary: flags.source || 'Captured through MindMux CLI' }));
319
351
  }
320
352
  case 'update': {
321
353
  const expected = need(flags['expected-version'], '--expected-version');
322
354
  const changeKind = flags['change-kind'] ?? 'substantive';
323
- if (!['correction', 'substantive'].includes(changeKind)) throw new Error('--change-kind must be correction or substantive.');
324
- if (changeKind === 'correction' && (flags.summary !== undefined || flags.source !== undefined)) throw new Error('A correction must omit --summary and --source; it does not add a Timeline entry.');
325
- if (changeKind === 'correction' && brain.target.kind !== 'cloud') throw new Error('Timeline-free correction is supported only for Cloud Brain. Local brain.md updates require --change-kind substantive and --summary.');
355
+ if (changeKind === 'correction' && brain.target.kind !== 'cloud') throw usageError('Timeline-free correction is supported only for Cloud Brain. Local brain.md updates require --change-kind substantive and --summary.');
326
356
  const timeline = changeKind === 'substantive'
327
357
  ? { timelineEntry: { kind: 'decision', summary: need(flags.summary, '--summary'), source: flags.source || 'MindMux CLI' } }
328
358
  : {};
@@ -331,7 +361,6 @@ export async function main(argv = process.argv.slice(2)) {
331
361
  }
332
362
  case 'append': {
333
363
  const kind = flags.kind || 'evidence';
334
- if (!['decision', 'evidence', 'reversal', 'note'].includes(kind)) throw new Error('Invalid timeline kind.');
335
364
  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' } }));
336
365
  }
337
366
  case 'archive': return mutate({ kind: 'page', id: need(rest[0], 'page id') }, () => brain.archive(rest[0]));
@@ -344,5 +373,5 @@ export async function main(argv = process.argv.slice(2)) {
344
373
  });
345
374
  output(result); return;
346
375
  }
347
- throw new Error('Unknown command. Run mmx help.');
376
+ throw usageError('Unknown command. Run mmx schema or mmx help.');
348
377
  }
package/src/cloud.mjs CHANGED
@@ -1,9 +1,12 @@
1
+ import { CliError, upstreamError } from './errors.mjs';
1
2
  import { VERSION } from './version.mjs';
2
3
  import { createHash, randomBytes } from 'node:crypto';
3
4
  import { createServer } from 'node:http';
4
5
  import { spawn } from 'node:child_process';
5
- import { mkdir, rm } from 'node:fs/promises';
6
- import { mkdirSync, rmSync } from 'node:fs';
6
+ import { mkdirSync } from 'node:fs';
7
+ import { acquireProcessLock } from './process-lock.mjs';
8
+ import { tryAuthResetGate, authBusyError } from './auth-reset-gate.mjs';
9
+ import { operationBudget, requestTimeout } from './operation-budget.mjs';
7
10
  import { join } from 'node:path';
8
11
  import { Client } from '@modelcontextprotocol/sdk/client/index.js';
9
12
  import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
@@ -12,7 +15,7 @@ import { homeDir, readJson, writeJson, serverUrl } from './storage.mjs';
12
15
 
13
16
  export const credentialPath = server => join(homeDir(), 'auth', `${createHash('sha256').update(server).digest('hex')}.json`);
14
17
  export const timedFetch = (url, options = {}) => fetch(url, { ...options,
15
- signal: options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(6000)]) : AbortSignal.timeout(6000) });
18
+ signal: AbortSignal.any([options.signal, operationBudget()?.signal, AbortSignal.timeout(requestTimeout())].filter(Boolean)) });
16
19
 
17
20
  export function authorizationSuccessPage() {
18
21
  return `<!doctype html>
@@ -49,34 +52,41 @@ export function authorizationSuccessPage() {
49
52
 
50
53
  const activeLocks = new Set();
51
54
  function releaseOnSignal(signal) {
52
- for (const path of activeLocks) rmSync(path, { recursive: true, force: true });
55
+ for (const release of activeLocks) { try { release(); } catch {} }
53
56
  process.exit(signal === 'SIGINT' ? 130 : 143);
54
57
  }
55
58
  const onInterrupt = () => releaseOnSignal('SIGINT');
56
59
  const onTerminate = () => releaseOnSignal('SIGTERM');
57
60
 
58
61
  // Serialize token refresh across overlapping hooks and CLI calls. Never replay a write.
59
- export async function withAuthLock(server, run) {
62
+ export async function withAuthLock(server, run, { waitMs = operationBudget()?.authWaitMs ?? 15000 } = {}) {
60
63
  const path = `${credentialPath(server)}.lock`;
61
- mkdirSync(join(homeDir(), 'auth'), { recursive: true, mode: 0o700 });
62
- const end = Date.now() + 15000;
64
+ const end = Date.now() + waitMs;
65
+ let release;
63
66
  for (;;) {
64
- try { await mkdir(path, { mode: 0o700 }); break; }
65
- catch (error) {
66
- if (error.code !== 'EEXIST') throw error;
67
- if (Date.now() > end) throw new Error(`Authentication is busy. If a previous process crashed, remove ${path}.`);
68
- await new Promise(resolve => setTimeout(resolve, 80));
67
+ operationBudget()?.signal.throwIfAborted();
68
+ const releaseGate = tryAuthResetGate();
69
+ if (releaseGate) {
70
+ try {
71
+ mkdirSync(join(homeDir(), 'auth'), { recursive: true, mode: 0o700 });
72
+ release = acquireProcessLock(path);
73
+ if (release) {
74
+ if (!activeLocks.size) { process.on('SIGINT', onInterrupt); process.on('SIGTERM', onTerminate); }
75
+ activeLocks.add(release);
76
+ process.once('exit', release);
77
+ }
78
+ } finally { releaseGate(); }
69
79
  }
80
+ if (release) break;
81
+ if (Date.now() >= end) throw authBusyError();
82
+ await new Promise(resolve => setTimeout(resolve, 20));
70
83
  }
71
- if (!activeLocks.size) { process.on('SIGINT', onInterrupt); process.on('SIGTERM', onTerminate); }
72
- activeLocks.add(path);
73
- const cleanup = () => rmSync(path, { recursive: true, force: true });
74
- process.once('exit', cleanup);
75
84
  try { return await run(); } finally {
76
- process.removeListener('exit', cleanup);
77
- await rm(path, { recursive: true, force: true });
78
- activeLocks.delete(path);
79
- if (!activeLocks.size) { process.removeListener('SIGINT', onInterrupt); process.removeListener('SIGTERM', onTerminate); }
85
+ process.removeListener('exit', release);
86
+ try { release(); } finally {
87
+ activeLocks.delete(release);
88
+ if (!activeLocks.size) { process.removeListener('SIGINT', onInterrupt); process.removeListener('SIGTERM', onTerminate); }
89
+ }
80
90
  }
81
91
  }
82
92
 
@@ -99,12 +109,12 @@ export class AuthProvider {
99
109
  tokens() { return this.data.tokens; }
100
110
  saveTokens(tokens) { this.data.tokens = tokens; this.save(); }
101
111
  saveCodeVerifier(verifier) {
102
- if (!this.interactive) throw new Error('Cloud login required. Run mmx login.');
112
+ if (!this.interactive) throw new CliError('AUTH_REQUIRED', 'Cloud login required. Run mmx login.', { next: 'Run mmx login --non-interactive --json to authorize, then retry.' });
103
113
  this.verifier = verifier;
104
114
  }
105
115
  codeVerifier() { if (!this.verifier) throw new Error('Missing OAuth verifier. Run mmx login again.'); return this.verifier; }
106
116
  redirectToAuthorization(url) {
107
- if (!this.interactive) throw new Error('Cloud login required. Run mmx login.');
117
+ if (!this.interactive) throw new CliError('AUTH_REQUIRED', 'Cloud login required. Run mmx login.', { next: 'Run mmx login --non-interactive --json to authorize, then retry.' });
108
118
  this.onRedirect(url);
109
119
  }
110
120
  invalidateCredentials(scope) {
@@ -121,23 +131,23 @@ export async function withCloud(server, run) {
121
131
  server = serverUrl(server);
122
132
  return withAuthLock(server, async () => {
123
133
  const provider = new AuthProvider(server);
124
- if (!provider.tokens()) throw new Error(`Cloud login required. Run mmx login --server ${server}.`);
134
+ if (!provider.tokens()) throw new CliError('AUTH_REQUIRED', `Cloud login required. Run mmx login --server ${server}.`, { next: `Run mmx login --server ${server} --non-interactive --json to authorize, then retry.` });
125
135
  const client = new Client({ name: 'mindmux-cli', version: VERSION });
126
136
  const transport = new StreamableHTTPClientTransport(new URL(server), { authProvider: provider,
127
137
  fetch: timedFetch, reconnectionOptions: { maxRetries: 0 } });
128
138
  try {
129
- await client.connect(transport, { timeout: 6000 });
139
+ await client.connect(transport, { timeout: requestTimeout() });
130
140
  const call = async (name, args = {}) => {
131
141
  const result = await call.raw(name, args);
132
142
  const text = result.content?.filter(item => item.type === 'text').map(item => item.text).join('\n') || '';
133
- if (result.isError) throw new Error(text || `MCP ${name} failed`);
143
+ if (result.isError) throw upstreamError(result, `MCP ${name} failed`);
134
144
  if (result.structuredContent) return result.structuredContent;
135
145
  try { return JSON.parse(text); } catch { return { text }; }
136
146
  };
137
- call.raw = (name, args = {}) => client.callTool({ name, arguments: args }, undefined, { timeout: 6000 });
147
+ call.raw = (name, args = {}) => client.callTool({ name, arguments: args }, undefined, { timeout: requestTimeout() });
138
148
  call.listTools = async () => {
139
149
  const tools = []; let cursor;
140
- do { const result = await client.listTools({ cursor }, { timeout: 6000 }); tools.push(...result.tools); cursor = result.nextCursor; } while (cursor);
150
+ do { const result = await client.listTools({ cursor }, { timeout: requestTimeout() }); tools.push(...result.tools); cursor = result.nextCursor; } while (cursor);
141
151
  return { tools };
142
152
  };
143
153
  return await run(call);
@@ -147,7 +157,7 @@ export async function withCloud(server, run) {
147
157
 
148
158
  export const listCloudTools = server => withCloud(server, call => call.listTools());
149
159
 
150
- export async function login(server, { open = true, output = console.error, onAuthorization } = {}) {
160
+ export async function login(server, { open = true, output = console.error, onAuthorization, onAuthorized } = {}) {
151
161
  server = serverUrl(server);
152
162
  return withAuthLock(server, async () => {
153
163
  let provider, resolveCode, rejectCode;
@@ -192,6 +202,7 @@ export async function login(server, { open = true, output = console.error, onAut
192
202
  }
193
203
  provider.staging = false;
194
204
  provider.save();
205
+ await onAuthorized?.();
195
206
  output('MindMux CLI is signed in.');
196
207
  } finally { clearTimeout(timer); await new Promise(resolve => callbackServer.close(resolve)); }
197
208
  });
@@ -0,0 +1,149 @@
1
+ import { VERSION } from './version.mjs';
2
+ import { usageError } from './errors.mjs';
3
+
4
+ export const OPTIONS = Object.fromEntries([
5
+ ...['project', 'agent', 'brain-id', 'server', 'workspace-id', 'name', 'description', 'id', 'title', 'category', 'status', 'source', 'expected-version', 'change-kind', 'summary', 'kind', 'args', 'review-token', 'outcome', 'reason', 'manager'].map(key => [key, { type: 'string' }]),
6
+ ...['local', 'online', 'no-open', 'confirm', 'help', 'version', 'skill', 'yes', 'migrate', 'json', 'keep-login', 'include-external-data', 'fix', 'check', 'refresh-integrations', 'all-projects', 'non-interactive', 'support'].map(key => [key, { type: 'boolean' }]),
7
+ ]);
8
+ // Parse output intent even when parseArgs rejects another argument. Never mistake
9
+ // string option values or literal arguments after -- for an output flag.
10
+ export function jsonRequested(argv) {
11
+ let command;
12
+ for (let i = 0; i < argv.length; i++) {
13
+ const arg = argv[i];
14
+ if (arg === '--') break;
15
+ if (['--json', '--non-interactive', '-agent'].includes(arg)) return true;
16
+ if (arg.startsWith('--') && OPTIONS[arg.slice(2)]?.type === 'string') { i++; continue; }
17
+ if (!arg.startsWith('-') && !command) { command = arg; if (command === 'schema') return true; }
18
+ }
19
+ return false;
20
+ }
21
+ const string = description => ({ type: 'string', minLength: 1, ...(description ? { description } : {}) });
22
+ const enumeration = values => ({ type: 'string', enum: values });
23
+ export const BRAIN_FIELDS = {
24
+ id: { ...string(), pattern: '^[a-z0-9][a-z0-9-]*$' }, title: string(),
25
+ category: enumeration(['project', 'concept', 'decision', 'person', 'reference']),
26
+ status: enumeration(['active', 'draft', 'archived']), source: string(),
27
+ expectedVersion: string('Use the version returned by read; Cloud uses a positive integer string, Local uses a content hash. Root creation uses new.'),
28
+ changeKind: enumeration(['correction', 'substantive']), summary: string(),
29
+ kind: enumeration(['decision', 'evidence', 'reversal', 'note']), query: string(),
30
+ slug: enumeration(['background', 'architecture', 'flow', 'mindmap', 'stack', 'roadmap']),
31
+ body: string('Complete plain Markdown content through stdin; do not JSON-escape it.'),
32
+ reviewToken: { ...string(), pattern: '^[a-f0-9]{64}$' }, outcome: enumeration(['saved', 'no-changes', 'already-covered', 'deferred']), reason: { ...string(), maxLength: 1000 },
33
+ };
34
+ const read = (description, fields = [], required = [], positional) => ({ description, fields, required, positional, effect: 'read' });
35
+ const write = (description, fields, required, positional, stdin = false) => ({ description, fields, required, positional, stdin, effect: 'brain-write' });
36
+ export const BRAIN_OPERATIONS = {
37
+ status: read('Return the selected project binding without contacting Cloud.'),
38
+ index: read('Read the current index, summaries and root navigation.'),
39
+ reindex: write('Regenerate the derived Brain index.', [], []),
40
+ list: read('List active Pages with summaries.'),
41
+ roots: read('List root Pages.'),
42
+ read: read('Read a complete Page and its version.', ['id'], ['id'], 'id'),
43
+ 'read-root': read('Read a complete root Page and its version.', ['slug'], ['slug'], 'slug'),
44
+ search: read('Search active Pages.', ['query'], ['query'], 'query'),
45
+ recall: read('Retrieve task context and index navigation.', ['query'], [], 'query'),
46
+ create: write('Create a Page with confirmed knowledge.', ['id', 'title', 'category', 'status', 'source', 'reviewToken', 'body'], ['id', 'title', 'category', 'body'], undefined, true),
47
+ update: { ...write('Replace the complete current Page at its read version.', ['id', 'expectedVersion', 'changeKind', 'summary', 'source', 'reviewToken', 'body'], ['id', 'expectedVersion', 'body'], 'id', true),
48
+ conditions: [
49
+ { if: { properties: { changeKind: { const: 'correction' } }, required: ['changeKind'] }, then: { not: { anyOf: [{ required: ['summary'] }, { required: ['source'] }] } }, else: { required: ['summary'] } },
50
+ ], notes: ['changeKind defaults to substantive. Timeline-free correction requires Cloud. Read the complete Page before updating.'] },
51
+ append: write('Append evidence that does not replace current knowledge.', ['id', 'kind', 'summary', 'source', 'reviewToken'], ['id', 'summary'], 'id'),
52
+ archive: write('Archive a Page.', ['id', 'reviewToken'], ['id'], 'id'),
53
+ 'update-root': write('Replace a complete root Page; expectedVersion=new creates it.', ['slug', 'expectedVersion', 'body', 'reviewToken'], ['slug', 'expectedVersion', 'body'], 'slug', true),
54
+ review: { ...read('Register local Codex review metadata, not a Brain Page.', ['reviewToken', 'outcome', 'reason', 'id'], ['reviewToken', 'outcome', 'reason']), effect: 'local-write',
55
+ conditions: [{ if: { properties: { outcome: { const: 'already-covered' } }, required: ['outcome'] }, then: { required: ['id'] } }] },
56
+ };
57
+ export const flagName = key => ({ expectedVersion: 'expected-version', changeKind: 'change-kind', reviewToken: 'review-token' })[key] || key;
58
+ export function brainInputSchema(operation) {
59
+ const spec = Object.hasOwn(BRAIN_OPERATIONS, operation) ? BRAIN_OPERATIONS[operation] : null;
60
+ if (!spec) throw usageError('Unknown Brain operation.');
61
+ return { type: 'object', properties: Object.fromEntries(spec.fields.map(key => [key, BRAIN_FIELDS[key]])), required: spec.required, additionalProperties: false,
62
+ ...(spec.conditions ? { allOf: spec.conditions } : {}) };
63
+ }
64
+ export function validateBrainArguments(operation, rest, flags) {
65
+ const spec = Object.hasOwn(BRAIN_OPERATIONS, operation) ? BRAIN_OPERATIONS[operation] : null;
66
+ if (!spec) throw usageError('Unknown brain command. Run mmx schema.');
67
+ const allowed = new Set(['project', 'json', 'non-interactive', ...spec.fields.filter(key => key !== spec.positional && key !== 'body').map(flagName)]);
68
+ for (const key of Object.keys(flags)) if (!allowed.has(key)) throw usageError(`--${key} is not supported by brain ${operation}.`);
69
+ if ((!spec.positional && rest.length) || (spec.positional && spec.positional !== 'query' && rest.length > 1)) throw usageError(`Unexpected arguments for brain ${operation}.`);
70
+ const values = {};
71
+ for (const key of spec.fields) {
72
+ if (key === 'body') continue;
73
+ const value = key === spec.positional ? key === 'query' ? rest.join(' ') || undefined : rest[0] : flags[flagName(key)];
74
+ if (spec.required.includes(key) && (typeof value !== 'string' || !value.trim())) throw usageError(`${key === spec.positional ? key : '--' + flagName(key)} is required.`);
75
+ if (value === undefined) continue;
76
+ const field = BRAIN_FIELDS[key];
77
+ if (!value.trim() || (field.maxLength && value.length > field.maxLength) || (field.enum && !field.enum.includes(value)) || (field.pattern && !new RegExp(field.pattern).test(value))) throw usageError(`Invalid ${key}.`);
78
+ if (['title', 'source', 'summary', 'reason'].includes(key) && /[\r\n\0]/.test(value)) throw usageError(`${key} must be a single line without NUL characters.`);
79
+ values[key] = value;
80
+ }
81
+ if (operation === 'update') {
82
+ if (values.changeKind === 'correction' && (values.summary !== undefined || values.source !== undefined)) throw usageError('A correction must omit --summary and --source.');
83
+ if (values.changeKind !== 'correction' && !values.summary) throw usageError('--summary is required for substantive updates.');
84
+ }
85
+ if (operation === 'review' && values.outcome === 'already-covered' && !values.id) throw usageError('already-covered requires --id.');
86
+ }
87
+
88
+ const object = { type: 'object', additionalProperties: true };
89
+ const versionValue = { type: ['string', 'integer'] };
90
+ const page = { type: 'object', properties: { id: { type: 'string' }, title: { type: 'string' }, summary: { type: 'string' }, status: { type: 'string' }, category: { type: 'string' }, version: versionValue, compiledTruth: { type: 'string' } }, additionalProperties: true };
91
+ const rootPage = { type: 'object', properties: { slug: { type: 'string' }, title: { type: 'string' }, version: versionValue, body: { type: 'string' } }, additionalProperties: true };
92
+ const pages = { type: 'array', items: page };
93
+ const rootPages = { type: 'array', items: rootPage };
94
+ const strings = { type: 'array', items: { type: 'string' } };
95
+ const resultObject = (properties, required = []) => ({ type: 'object', properties, required, additionalProperties: true });
96
+ function brainOutputSchema(operation) {
97
+ switch (operation) {
98
+ case 'status': return resultObject({ kind: enumeration(['local', 'cloud', 'unbound']), brainId: { type: 'string' }, directory: { type: 'string' }, name: { type: 'string' }, server: { type: 'string' }, automation: resultObject({ paused: { type: 'boolean' }, revision: { type: 'string' } }, ['paused', 'revision']) }, ['kind', 'automation']);
99
+ case 'list': case 'search': return resultObject({ pages }, ['pages']);
100
+ case 'roots': return resultObject({ rootPages }, ['rootPages']);
101
+ case 'index': case 'reindex': return resultObject({ body: { type: 'string' }, pages, rootPages, count: { type: 'integer' }, source: { type: 'string' }, generated: { type: 'boolean' } });
102
+ case 'recall': return resultObject({ context: { type: 'string' }, indexSource: { type: 'string' }, pageIds: strings, retrievedPageIds: strings, rootSlugs: strings, count: { type: 'integer' } }, ['context', 'pageIds', 'count']);
103
+ case 'review': return resultObject({ reviewed: { type: 'boolean' }, outcome: BRAIN_FIELDS.outcome, retryable: { type: 'boolean' }, deferred: { type: 'boolean' } }, ['reviewed', 'outcome']);
104
+ case 'read-root': case 'update-root': return resultObject({ ...rootPage.properties, rootPage });
105
+ default: return resultObject({ ...page.properties, page, raw: { type: 'string' } });
106
+ }
107
+ }
108
+ const setupProperties = Object.fromEntries(['agent', 'brain-id', 'server', 'workspace-id', 'name', 'description', 'local', 'yes', 'confirm', 'non-interactive', 'migrate', 'no-open', 'json'].map(key => [key, { type: OPTIONS[key].type }]));
109
+ const otherCommands = {
110
+ setup: { description: 'Login, select a Brain and install project integrations. -agent aliases --non-interactive --json.', effect: 'configuration-and-cloud-write', inputSchema: { type: 'object', properties: setupProperties, additionalProperties: false }, notes: ['Use -agent for resumable Agent setup. input_required is a successful intermediate state. Never guess user selections.', 'Project creation requires explicit confirmation. --local excludes Cloud selection flags. --brain-id excludes --workspace-id/--name. --name requires --workspace-id.'] },
111
+ status: { description: 'Inspect configuration and observed activity.', flags: ['online', 'json'], effect: 'read' },
112
+ doctor: { description: 'Diagnose connectivity; --fix explicitly repairs configuration.', flags: ['online', 'json', 'fix', 'yes', 'support'], effect: 'configuration-write-with-fix' },
113
+ update: { description: 'Upgrade with the owning installer and refresh managed connections.', flags: ['check', 'yes', 'json', 'manager', 'refresh-integrations', 'all-projects'], effect: 'installation-write-unless-check' },
114
+ login: { description: 'Authorize Cloud access; use --non-interactive --json for resumable browser authorization.', flags: ['server', 'no-open', 'non-interactive', 'json', 'status'], effect: 'credentials-write' },
115
+ logout: { description: 'Remove saved CLI credentials.', flags: ['server'], effect: 'credentials-write' },
116
+ init: { description: 'Initialize a local Brain; --local is required.', flags: ['local'], effect: 'brain-write' },
117
+ connect: { description: 'Install project integration for --agent.', flags: ['agent'], effect: 'configuration-write' },
118
+ disconnect: { description: 'Remove owned integration for --agent.', flags: ['agent'], effect: 'configuration-write' },
119
+ remove: { description: 'Remove setup connections, keeping data and login.', flags: ['agent', 'json'], effect: 'configuration-write' },
120
+ switch: { description: 'Choose a different explicit Brain binding.', flags: ['agent', 'local', 'brain-id', 'server', 'workspace-id', 'name', 'confirm', 'yes', 'json', 'non-interactive'], effect: 'configuration-and-cloud-write' },
121
+ clean: { description: 'Reset local setup and data; preserve Cloud data.', flags: ['keep-login', 'yes', 'json', 'include-external-data'], effect: 'local-data-delete' },
122
+ 'brain bind': { description: 'Explicitly select --local or --brain-id.', flags: ['local', 'brain-id', 'server'], effect: 'configuration-write' },
123
+ 'brain discover': { description: 'List available Cloud Brains.', flags: ['server', 'workspace-id'], effect: 'read' },
124
+ 'workspace list': { description: 'List accessible Workspaces.', flags: ['server'], effect: 'read' },
125
+ 'project list': { description: 'List accessible Projects, optionally scoped to a Workspace.', flags: ['server', 'workspace-id'], effect: 'read' },
126
+ 'project create': { description: 'Create a shared Project using --workspace-id --name --confirm.', flags: ['server', 'workspace-id', 'name', 'description', 'confirm'], effect: 'cloud-write' },
127
+ 'mcp tools': { description: 'Discover upstream Cloud tools and their schemas.', flags: ['server'], effect: 'read' },
128
+ 'mcp call': { description: 'Invoke TOOL with --args JSON using explicit arguments; no implicit Brain binding.', flags: ['server', 'args'], effect: 'tool-dependent', positional: 'TOOL' },
129
+ 'mcp serve': { description: 'Serve the project-bound MCP over stdio; stdout is MCP protocol only.', flags: [], effect: 'tool-dependent', outputSchema: undefined },
130
+ };
131
+ function commandSchema(command) {
132
+ const operation = command.startsWith('brain ') ? command.slice(6) : null;
133
+ const spec = Object.hasOwn(BRAIN_OPERATIONS, operation) ? BRAIN_OPERATIONS[operation] : null;
134
+ if (spec) return { command, description: spec.description, effect: spec.effect, inputSchema: brainInputSchema(operation),
135
+ cli: { positional: spec.positional || null, flags: Object.fromEntries(spec.fields.filter(key => key !== spec.positional && key !== 'body').map(key => [flagName(key), key])), stdin: spec.stdin ? { required: true, format: 'markdown', maxBytes: 1048576 } : null },
136
+ notes: spec.notes || [], outputSchema: brainOutputSchema(operation), outputDescription: 'Existing success payload is unchanged. Local and Cloud adapters may return different fields; read returns complete content and a version.' };
137
+ const other = Object.hasOwn(otherCommands, command) ? otherCommands[command] : null;
138
+ if (!other) throw usageError(`Unknown command schema: ${command}. Run mmx schema to list supported commands.`);
139
+ const { flags = [], ...details } = other;
140
+ return { command, outputSchema: object, ...details, inputSchema: details.inputSchema || { type: 'object', properties: Object.fromEntries(flags.map(key => [key, { type: OPTIONS[key].type }])), additionalProperties: false } };
141
+ }
142
+ export function schema(parts = []) {
143
+ const base = { schemaVersion: 1, cliVersion: VERSION };
144
+ if (parts.length) return { ...base, ...commandSchema(parts.join(' ')) };
145
+ return { ...base, commands: [...Object.keys(BRAIN_OPERATIONS).map(op => `brain ${op}`), ...Object.keys(otherCommands)].map(command => { const spec = commandSchema(command); return { command, description: spec.description, effect: spec.effect }; }),
146
+ globalOptions: { project: { type: 'string' }, json: { type: 'boolean' } },
147
+ errors: { type: 'object', required: ['status', 'error', 'code', 'retryable', 'outcome', 'next'], properties: { status: { const: 'error' }, error: { type: 'string' }, code: { type: 'string' }, retryable: { type: 'boolean' }, outcome: enumeration(['not-started', 'unknown']), next: { type: 'string' } } },
148
+ notes: ['Inspect a command with mmx schema <command>. Brain input field names map to CLI flags via cli.flags; body goes through stdin.', 'Machine errors use --json; --non-interactive and -agent imply --json. Success payloads remain compatible.', 'Unknown mutation outcomes must be verified by reading before retrying. Never automatically replay a mutation.'] };
149
+ }
package/src/doctor.mjs CHANGED
@@ -44,10 +44,29 @@ export async function diagnose(root, flags = {}, dependencies = {}) {
44
44
  if (report.live) check(report.live.accessible, report.live.accessible ? 'Brain access check passed.' : `Brain access failed: ${report.live.error}`, 'Check your network, login and Brain permissions; rerun mmx doctor --online.');
45
45
  if (report.mcpProbe) check(report.mcpProbe.connected, report.mcpProbe.connected ? 'MCP launch and recall check passed.' : `MCP check failed: ${report.mcpProbe.error}`, 'Run mmx doctor --fix to review the managed configuration.');
46
46
  const review = report.receipts.find(item => item.agent === 'codex' && ['stop', 'review', 'interrupt'].includes(item.event));
47
- if (review && ['review-failed', 'recovery-exhausted', 'review-expired', 'review-unavailable'].includes(review.status)) {
47
+ if (review && ['review-failed', 'recovery-exhausted', 'review-expired', 'review-unavailable', 'review-missed', 'review-deferred'].includes(review.status)) {
48
48
  checks.push({ state: 'warning', message: `Codex memory review: ${review.status}.${review.error ? ` ${review.error}` : ''}`,
49
49
  next: 'Inspect mmx status --json. Retry failed Brain operations; use current Codex hooks with session and turn identifiers. Never assume memory was saved.' });
50
50
  }
51
+ for (const item of report.receipts.filter(item => ['session-start', 'prompt'].includes(item.event) && ['error', 'timeout'].includes(item.status))) {
52
+ checks.push({ state: 'warning', message: `${item.agent} recall: ${item.status}. The main task was allowed to continue.`,
53
+ next: 'Run mmx doctor --support for a local redacted report. Use --online separately to check current connectivity.' });
54
+ }
55
+ if (report.binding.kind === 'cloud') {
56
+ const { credentialPath } = await import('./cloud.mjs');
57
+ const { inspectProcessLock } = await import('./support-report.mjs');
58
+ const lock = inspectProcessLock(credentialPath(report.binding.server) + '.lock');
59
+ if (lock.state !== 'absent') checks.push({ state: 'warning', message: `CLI authentication lock: ${lock.state}.`,
60
+ next: lock.state === 'dead' ? 'The next CLI Cloud operation will reclaim the dead owner lock.' : 'Finish active CLI operations. Unowned legacy locks require inspection; never delete a live lock.' });
61
+ }
62
+ {
63
+ const { homeDir } = await import('./storage.mjs');
64
+ const { join } = await import('node:path');
65
+ const { inspectProcessLock } = await import('./support-report.mjs');
66
+ const gate = inspectProcessLock(join(homeDir(), 'auth-reset.lock'));
67
+ if (gate.state !== 'absent') checks.push({ state: 'warning', message: `CLI authentication reset gate: ${gate.state}.`,
68
+ next: 'Finish active cleanup. Dead owners are recovered on the next operation; unowned locks require inspection.' });
69
+ }
51
70
  const warnings = [...legacyWarnings(root), ...report.integrations.filter(i => i.existingBrainMdHook).map(i => `${i.agent}: an existing brain.md hook may deliver duplicate context.`)];
52
71
  for (const message of warnings) checks.push({ state: 'warning', message, next: 'Review the existing integration before migrating it with mmx setup --migrate.' });
53
72
  let repair;