@theronap/agnoclast-mcp 0.9.271 → 0.9.272

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.
@@ -58,6 +58,14 @@ if (process.env.CORTEX_SUMMARIZING && CONTEXT_HOOK_COMMANDS.has(cmd)) {
58
58
  process.exit(0)
59
59
  }
60
60
 
61
+ // ── A confidential-brain session runs NO ordinary hooks ──────────────────────────────────────────
62
+ // `cortex-mcp confidential` starts the agent with AGNOCLAST_CONFIDENTIAL set (lib/confidential_session.mjs).
63
+ // Every hook here works on the person's ORDINARY account: capture would file this session's transcript into
64
+ // another brain, and hydrate/status would send its prompts there. So each one stands down, silently.
65
+ if (process.env.AGNOCLAST_CONFIDENTIAL && (CONTEXT_HOOK_COMMANDS.has(cmd) || cmd === 'capture' || cmd === 'statusline')) {
66
+ process.exit(0)
67
+ }
68
+
61
69
  // ADR-0020 Stage 2, amended 2026-09-25 — stamp THIS session's identity on the read-only context
62
70
  // hooks. Until now setSessionKey was called ONLY in server.mjs, so a one-shot hook sent no
63
71
  // x-cortex-session-key header, /api/mcp-context resolved the person-wide pointer, and the settling
@@ -117,6 +125,7 @@ if (cmd === '--help' || cmd === '-h' || cmd === 'help') {
117
125
  ` hydrate UserPromptSubmit hook — inject query-centered context on the first substantive turn\n` +
118
126
  ` migrate-key [--dry-run] move the MCP config key to its new name, allow rules first\n` +
119
127
  ` with-token -- <cmd> run <cmd> with your token in its environment (for cron/launchd wrappers)\n` +
128
+ ` confidential "<brain>" [claude|codex] start an agent locked to one confidential brain (approved AI accounts only)\n` +
120
129
  ` statusline ambient presence line for the Claude Code statusline (local read only)\n` +
121
130
  ` capture Stop-hook capturer (invoked by Claude Code)\n` +
122
131
  ` ingest-folder <path> ingest a local markdown folder as your authored records\n` +
@@ -267,6 +276,31 @@ if (cmd === 'login') {
267
276
  const res = runKeyMigration({ dryRun: rest.includes('--dry-run') })
268
277
  process.stdout.write(JSON.stringify(res, null, 2) + '\n')
269
278
  process.exitCode = res.status === 'aborted' ? 1 : 0
279
+ } else if (cmd === 'confidential') {
280
+ // Start Claude Code or Codex locked to ONE confidential brain (lib/confidential_session.mjs): only that
281
+ // brain's server is loaded, and every ordinary hook stands down for the session.
282
+ const [brain, agentArg = 'claude', ...agentArgs] = rest
283
+ const agent = agentArg === 'codex' ? 'codex' : agentArg === 'claude' ? 'claude' : null
284
+ if (!brain || !agent) {
285
+ process.stderr.write('Usage: cortex-mcp confidential "<brain name>" [claude|codex] [-- agent args…]\n')
286
+ process.exitCode = 2
287
+ } else {
288
+ const { resolveTokenSource } = await import('../lib/diagnose.mjs')
289
+ const { confidentialLaunch } = await import('../lib/confidential_session.mjs')
290
+ const { token } = resolveTokenSource()
291
+ if (!token) {
292
+ process.stderr.write('cortex-mcp confidential: no Agnoclast token wired on this machine. Run `npx -y @theronap/cortex-mcp login` first.\n')
293
+ process.exitCode = 3
294
+ } else {
295
+ const { spawnSync } = await import('node:child_process')
296
+ const launch = confidentialLaunch({ brain, agent, token })
297
+ const extra = agentArgs[0] === '--' ? agentArgs.slice(1) : agentArgs
298
+ process.stderr.write(`Starting ${agent === 'codex' ? 'Codex' : 'Claude Code'} for the confidential brain "${brain}". Nothing else in Agnoclast is reachable from this session.\n`)
299
+ const r = spawnSync(launch.command, [...launch.args, ...extra], { stdio: 'inherit', windowsHide: true, env: { ...process.env, ...launch.env } })
300
+ if (r.error) process.stderr.write(`cortex-mcp confidential: could not start ${launch.command}: ${r.error.message}\n`)
301
+ process.exitCode = r.status ?? 1
302
+ }
303
+ }
270
304
  } else if (cmd === 'with-token') {
271
305
  // Run a command with the resolved token in its environment. Exists so generated helper scripts
272
306
  // (launchd/cron wrappers) never inline their own config parse — those files are frozen on disk and
@@ -0,0 +1,134 @@
1
+ import { readFileSync, mkdirSync, writeFileSync } from 'node:fs'
2
+ import { homedir } from 'node:os'
3
+ import { join } from 'node:path'
4
+ import { execFileSync } from 'node:child_process'
5
+
6
+ // CONFIDENTIAL BRAINS FROM A CODING AGENT (server: web/lib/engine/confidential_agent.ts, migration
7
+ // 20261027065716; Agnoclast page "Confidential brains — design").
8
+ //
9
+ // A confidential brain's data may reach only an AI account its admin approved. This process runs inside the
10
+ // agent, so it is the one place that can see which account that is:
11
+ // • Claude Code puts the signed-in account and organization in its children's environment
12
+ // (CLAUDE_CODE_ACCOUNT_UUID / CLAUDE_CODE_ORGANIZATION_UUID — seen on 2026-10-27 in the env of a live
13
+ // cortex-mcp under Claude Code). Unsigned: it stops the accident, not a forger.
14
+ // • Codex keeps an OpenAI-signed id_token in ~/.codex/auth.json. The server verifies the signature.
15
+ // The proof goes to the server with the person's own token, which answers with a 15-minute token on the
16
+ // person's SEAT, or "pending" for an AI account no admin has approved yet. Anything it cannot identify —
17
+ // another editor, an API key in place of a login, Bedrock/Vertex — is refused here, before any request.
18
+
19
+ export const CONFIDENTIAL_BRAIN_ENV = 'AGNOCLAST_CONFIDENTIAL_BRAIN'
20
+ // Set on the whole agent process by `cortex-mcp confidential`. Every hook and the ordinary Agnoclast server
21
+ // stand down under it, so nothing from this session is captured into, or read from, another brain.
22
+ export const CONFIDENTIAL_SESSION_ENV = 'AGNOCLAST_CONFIDENTIAL'
23
+
24
+ /** Is some ancestor of this process the Codex CLI? Unix only; anywhere else, no. */
25
+ export function hasCodexAncestor({ pid = process.ppid, exec = execFileSync, platform = process.platform } = {}) {
26
+ if (platform === 'win32') return false
27
+ let cur = pid
28
+ for (let i = 0; i < 16 && cur > 1; i++) {
29
+ let line
30
+ try { line = String(exec('ps', ['-o', 'ppid=,comm=', '-p', String(cur)], { encoding: 'utf8', windowsHide: true })).trim() } catch { return false }
31
+ const m = line.match(/^(\d+)\s+(.*)$/)
32
+ if (!m) return false
33
+ if (/(^|\/)codex[^/]*$/i.test(m[2].trim())) return true
34
+ cur = Number(m[1])
35
+ }
36
+ return false
37
+ }
38
+
39
+ /**
40
+ * Which AI account runs this agent, as a proof the server can check — or { refused } saying why there is none.
41
+ * Claude Code is checked first: its environment is set by the process actually running, while a Codex
42
+ * auth file can sit on a machine whose agent is something else.
43
+ */
44
+ export function gatherAgentProof({ env = process.env, readFile = readFileSync, home = homedir(), codexAncestor = hasCodexAncestor } = {}) {
45
+ if (env.CLAUDECODE) {
46
+ if (env.ANTHROPIC_API_KEY || env.CLAUDE_CODE_USE_BEDROCK || env.CLAUDE_CODE_USE_VERTEX || env.ANTHROPIC_AUTH_TOKEN) {
47
+ return { refused: 'Claude Code is running on an API key or a cloud provider, so it cannot say which Claude account runs the model. Sign in with your approved Claude account (/login) and start again.' }
48
+ }
49
+ const accountUuid = env.CLAUDE_CODE_ACCOUNT_UUID, organizationUuid = env.CLAUDE_CODE_ORGANIZATION_UUID
50
+ if (!accountUuid || !organizationUuid) {
51
+ return { refused: 'This Claude Code did not say which account it is signed in with, so a confidential brain cannot open here. Update Claude Code and sign in with your approved account.' }
52
+ }
53
+ return { proof: { kind: 'claude-code', accountUuid, organizationUuid, email: env.CLAUDE_CODE_USER_EMAIL || null } }
54
+ }
55
+ if (codexAncestor()) {
56
+ let auth
57
+ try { auth = JSON.parse(readFile(join(env.CODEX_HOME || join(home, '.codex'), 'auth.json'), 'utf8')) } catch {
58
+ return { refused: 'Codex is not signed in on this machine (no ~/.codex/auth.json). Run `codex login` with your approved ChatGPT account.' }
59
+ }
60
+ const idToken = auth?.tokens?.id_token
61
+ if (typeof idToken !== 'string' || !idToken) {
62
+ return { refused: 'Codex is using an API key, not a ChatGPT sign-in, so it cannot say which account runs the model. Run `codex login` with your approved ChatGPT account.' }
63
+ }
64
+ return { proof: { kind: 'codex', idToken } }
65
+ }
66
+ return { refused: 'A confidential brain opens only from Codex or Claude Code signed in with an approved account, or from its approved connector. This editor cannot show which AI account it runs on.' }
67
+ }
68
+
69
+ /** Ask the server for a seat token. Returns { token, expiresIn, brain } or { message } explaining the refusal. */
70
+ export async function requestSeatToken({ base, token, brain, proof, fetchImpl }) {
71
+ let res
72
+ try {
73
+ res = await fetchImpl(`${base}/api/brains/confidential/agent-session`, {
74
+ method: 'POST',
75
+ headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
76
+ body: JSON.stringify({ brain, proof }),
77
+ })
78
+ } catch (e) {
79
+ return { message: `Could not reach Agnoclast to open "${brain}": ${e?.message ?? e}` }
80
+ }
81
+ const body = await res.json().catch(() => ({}))
82
+ if (res.ok && body?.status === 'approved' && typeof body.token === 'string') {
83
+ return { token: body.token, expiresIn: Number(body.expiresIn) || 900, brain: body.brain ?? brain, account: body.account }
84
+ }
85
+ if (body?.status === 'pending') {
86
+ return { message: `"${body.brain}" has not approved this AI account yet: ${body.account}. An owner or admin of the brain approves it (account id ${body.accountId}); then start again.` }
87
+ }
88
+ return { message: `"${brain}" did not open: ${body?.error ?? `HTTP ${res.status}`}` }
89
+ }
90
+
91
+ /** Should this hook or ordinary server stand down? True inside a session started by `cortex-mcp confidential`. */
92
+ export function inConfidentialSession(env = process.env) {
93
+ return !!env[CONFIDENTIAL_SESSION_ENV]
94
+ }
95
+
96
+ /**
97
+ * `cortex-mcp confidential <brain> [claude|codex]` — write the agent config that holds ONLY this brain's
98
+ * server, and return the command that starts the agent with it. Nothing ordinary is loaded alongside: for
99
+ * Claude Code, --strict-mcp-config; for Codex, the ordinary `cortex` server is switched off for that run.
100
+ */
101
+ /** The [mcp_servers.<name>] entries in a Codex config.toml that run the ordinary Agnoclast server. */
102
+ export function codexAgnoclastServers(toml) {
103
+ const names = []
104
+ const sections = String(toml).split(/^(?=\[)/m)
105
+ for (const s of sections) {
106
+ const m = s.match(/^\[mcp_servers\.([A-Za-z0-9_-]+)\]/)
107
+ if (m && m[1] !== 'agnoclast_confidential' && /(cortex|agnoclast)-mcp/.test(s)) names.push(m[1])
108
+ }
109
+ return names
110
+ }
111
+
112
+ export function confidentialLaunch({ brain, agent, token, spec = '@theronap/cortex-mcp@latest', home = homedir(), write = writeFileSync, mkdir = mkdirSync, readFile = readFileSync }) {
113
+ const env = { CORTEX_TOKEN: token, [CONFIDENTIAL_BRAIN_ENV]: brain, [CONFIDENTIAL_SESSION_ENV]: '1' }
114
+ if (agent === 'claude') {
115
+ const dir = join(home, '.cortex', 'confidential')
116
+ mkdir(dir, { recursive: true, mode: 0o700 })
117
+ const slug = brain.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 48) || 'brain'
118
+ const file = join(dir, `${slug}.mcp.json`)
119
+ write(file, JSON.stringify({ mcpServers: { 'agnoclast-confidential': { command: 'npx', args: ['-y', spec], env } } }, null, 2), { mode: 0o600 })
120
+ return { command: 'claude', args: ['--strict-mcp-config', '--mcp-config', file], env: { [CONFIDENTIAL_SESSION_ENV]: '1' } }
121
+ }
122
+ const q = (s) => JSON.stringify(s)
123
+ let configText = ''
124
+ try { configText = readFile(join(home, '.codex', 'config.toml'), 'utf8') } catch { /* no config: nothing to switch off */ }
125
+ const args = [
126
+ // Codex passes MCP servers only the environment its config names, so the ordinary server could not see
127
+ // AGNOCLAST_CONFIDENTIAL and stand down by itself. Switch every ordinary Agnoclast entry off for this run.
128
+ ...codexAgnoclastServers(configText).flatMap((name) => ['-c', `mcp_servers.${name}.enabled=false`]),
129
+ '-c', `mcp_servers.agnoclast_confidential.command=${q('npx')}`,
130
+ '-c', `mcp_servers.agnoclast_confidential.args=${JSON.stringify(['-y', spec])}`,
131
+ ...Object.entries(env).flatMap(([k, v]) => ['-c', `mcp_servers.agnoclast_confidential.env.${k}=${q(v)}`]),
132
+ ]
133
+ return { command: 'codex', args, env: { [CONFIDENTIAL_SESSION_ENV]: '1' } }
134
+ }
package/lib/diagnose.mjs CHANGED
@@ -537,6 +537,8 @@ const PATH_TOOLS = {
537
537
  'brain/capture-default': 'set_capture_brain',
538
538
  // Agnoclast Lite step 2 (2026-10-13): the waiting calls and notes, and filing one into the wiki.
539
539
  'held': 'held_items', 'held/absorb': 'absorb',
540
+ // Opening a confidential brain from a coding agent (lib/confidential_session.mjs, 2026-10-27).
541
+ 'brains/confidential/agent-session': 'confidential_session',
540
542
  }
541
543
 
542
544
  /** PURE. The tool an outage on `url` belongs to: the running tool if known, else a path mapping, else 'other'. */
package/lib/server.mjs CHANGED
@@ -12,6 +12,7 @@ import { folderClaimLine } from './folder_claims.mjs'
12
12
  import { renderFolderClaimOffers, renderIdentifierResolution, renderUnroutedPathStamps } from './identifier_routes.mjs'
13
13
  import { renderDeclines, renderFolderDecisionsApplied, renderFolderQuestions } from './folder_decisions.mjs'
14
14
  import { resolveSessionKey, resolveLogSessionId } from './session_key.mjs'
15
+ import { CONFIDENTIAL_BRAIN_ENV, gatherAgentProof, inConfidentialSession, requestSeatToken } from './confidential_session.mjs'
15
16
  import { runSendImessage } from './imessage_send.mjs'
16
17
  import { formatGrepHits } from './grep_cli.mjs'
17
18
  import { buildProposal, renderProposal, withAskNotice } from './propose_obligation.mjs'
@@ -257,7 +258,9 @@ export async function gate5StatusFromResponse(res) {
257
258
  // context to their AI assistant. CORTEX_TOKEN identifies the user + org.
258
259
 
259
260
  export async function runServer(version) {
260
- const TOKEN = resolveEnvToken().token
261
+ // `let`, not `const`: in a confidential session (lib/confidential_session.mjs) the person's token is traded
262
+ // for a 15-minute SEAT token, renewed below, and every request reads this binding at call time.
263
+ let TOKEN = resolveEnvToken().token
261
264
  const BASE = resolveBase(process.env.CORTEX_URL)
262
265
 
263
266
  if (!TOKEN) {
@@ -265,6 +268,34 @@ export async function runServer(version) {
265
268
  process.exit(1)
266
269
  }
267
270
 
271
+ const confidentialBrain = process.env[CONFIDENTIAL_BRAIN_ENV]
272
+ if (!confidentialBrain && inConfidentialSession()) {
273
+ // The ordinary server, inside a session started for a confidential brain: it must reach nothing else.
274
+ process.stderr.write('cortex-mcp: this session is for a confidential brain, so the ordinary Agnoclast server stays off.\n')
275
+ process.exit(0)
276
+ }
277
+ if (confidentialBrain) {
278
+ // Nothing from this session may reach a local summarizer running on some other AI account.
279
+ process.env.CORTEX_SUMMARIZE_DISABLED = '1'
280
+ const open = async () => {
281
+ const got = gatherAgentProof()
282
+ if (got.refused) return { message: got.refused }
283
+ return requestSeatToken({ base: BASE, token: resolveEnvToken().token, brain: confidentialBrain, proof: got.proof, fetchImpl: fetchCortex })
284
+ }
285
+ const first = await open()
286
+ if (!first.token) return serveConfidentialRefusal(version, first.message)
287
+ TOKEN = first.token
288
+ // Renew a few minutes early, re-proving the account each time: a /login to another account stops the
289
+ // next renewal, and a renewal that fails leaves a token the server refuses, so the session fails closed.
290
+ const every = Math.max(60, first.expiresIn - 180) * 1000
291
+ setInterval(async () => {
292
+ const next = await open().catch((e) => ({ message: String(e?.message ?? e) }))
293
+ if (next.token) { TOKEN = next.token; return }
294
+ TOKEN = 'confidential-session-closed'
295
+ process.stderr.write(`cortex-mcp: confidential session closed — ${next.message}\n`)
296
+ }, every).unref()
297
+ }
298
+
268
299
  // Self active-sessions (ADR-0017): one MCP process = one AI session. A stable per-process key + the
269
300
  // working dir identify this session; we heartbeat /api/session-ping while alive so the user can see
270
301
  // all THEIR sessions via my_sessions. Self-only on the server; best-effort (never breaks serving).
@@ -7816,3 +7847,14 @@ function renderNudge(payload) {
7816
7847
  lockedTools = applyLock(toolHandles, await lockStateWithin(lockP))
7817
7848
  await server.connect(new StdioServerTransport())
7818
7849
  }
7850
+
7851
+ // A confidential brain that did not open: serve one tool that says why, so the AI can tell the person,
7852
+ // rather than an empty server that looks like a broken install.
7853
+ async function serveConfidentialRefusal(version, message) {
7854
+ const server = new McpServer({ name: 'cortex', version })
7855
+ server.registerTool('confidential_status', {
7856
+ title: 'Why the confidential brain did not open',
7857
+ description: 'The confidential brain this session was started for did not open. Call this and tell the person why.',
7858
+ }, async () => ({ content: [{ type: 'text', text: message }] }))
7859
+ await server.connect(new StdioServerTransport())
7860
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theronap/agnoclast-mcp",
3
- "version": "0.9.271",
3
+ "version": "0.9.272",
4
4
  "description": "Connect your AI assistant to Cortex — your org's projects, activity, gaps, and directives, scoped to you.",
5
5
  "type": "module",
6
6
  "bin": {