@theronap/agnoclast-mcp 0.9.274 → 0.9.276

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,12 +58,18 @@ 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)
61
+ // ── A session locked into a confidential brain runs NO ordinary hooks ────────────────────────────────
62
+ // The first time a session uses a confidential brain, its MCP server locks it in and leaves a marker
63
+ // (lib/confidential_session.mjs). Every hook here works on the person's ORDINARY account: capture would file
64
+ // the session's transcript into another brain, hydrate/status would send its prompts there, and the local
65
+ // summarizer runs on whatever AI account this machine has. So each one stands down, silently. Every hook also
66
+ // names the AI account it runs under, so the server refuses one dedicated to a confidential brain.
67
+ if (CONTEXT_HOOK_COMMANDS.has(cmd) || cmd === 'capture' || cmd === 'statusline') {
68
+ const { sessionLockedIn, hookAiAccount } = await import('../lib/confidential_session.mjs')
69
+ const { hookSessionKey } = await import('../lib/session_key.mjs')
70
+ if (sessionLockedIn(hookSessionKey(process.env))) process.exit(0)
71
+ const { setAiAccount } = await import('../lib/diagnose.mjs')
72
+ setAiAccount(hookAiAccount(process.env))
67
73
  }
68
74
 
69
75
  // ADR-0020 Stage 2, amended 2026-09-25 — stamp THIS session's identity on the read-only context
@@ -125,7 +131,6 @@ if (cmd === '--help' || cmd === '-h' || cmd === 'help') {
125
131
  ` hydrate UserPromptSubmit hook — inject query-centered context on the first substantive turn\n` +
126
132
  ` migrate-key [--dry-run] move the MCP config key to its new name, allow rules first\n` +
127
133
  ` 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` +
129
134
  ` statusline ambient presence line for the Claude Code statusline (local read only)\n` +
130
135
  ` capture Stop-hook capturer (invoked by Claude Code)\n` +
131
136
  ` ingest-folder <path> ingest a local markdown folder as your authored records\n` +
@@ -277,30 +282,9 @@ if (cmd === 'login') {
277
282
  process.stdout.write(JSON.stringify(res, null, 2) + '\n')
278
283
  process.exitCode = res.status === 'aborted' ? 1 : 0
279
284
  } 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
- }
285
+ // Retired 2026-10-28 (0.9.275): a confidential brain opens from an ordinary session, the first time it is used.
286
+ process.stderr.write('cortex-mcp confidential is retired. Start Claude Code or Codex as usual and use the confidential brain by name: the first time a session uses it, the session is locked to it (or, if it used another brain first, locked out of it).\n')
287
+ process.exitCode = 2
304
288
  } else if (cmd === 'with-token') {
305
289
  // Run a command with the resolved token in its environment. Exists so generated helper scripts
306
290
  // (launchd/cron wrappers) never inline their own config parse — those files are frozen on disk and
@@ -221,6 +221,19 @@ export function formatUnheld(groups, { more = false, shadow = false } = {}) {
221
221
  return lines
222
222
  }
223
223
 
224
+ /** Arrivals assigned to a session that may still lock into a confidential brain: shown, not to be touched yet. */
225
+ export function formatHeldForLock(groups) {
226
+ const n = groups.reduce((t, g) => t + (Number(g?.count) || 1), 0)
227
+ const lines = [`📥 ${n} arrival${n === 1 ? ' is' : 's are'} assigned to this session — LEAVE ${n === 1 ? 'IT' : 'THEM'} FOR NOW: do not file, claim or dispatch a filer this turn.`]
228
+ for (const g of groups.slice(0, MAX_ASSIGNED)) {
229
+ const many = Number(g?.count) > 1 ? ` ×${g.count}` : ''
230
+ lines.push(` ${g?.source ?? '?'}${many} — ${g?.title ?? '(unreadable)'} · ${g?.hoursAgo ?? '?'}h`)
231
+ }
232
+ if (groups.length > MAX_ASSIGNED) lines.push(` … and ${groups.length - MAX_ASSIGNED} more groups`)
233
+ lines.push(' This person has a 🔒 confidential brain, and this session has not used Agnoclast yet. Filing would use an ordinary brain and lock the session out of the confidential one. Do the user\'s request first: if it uses the confidential brain, these pass to another session; otherwise they are shown again on the next prompt.')
234
+ return lines
235
+ }
236
+
224
237
  export function formatNotice(signals) {
225
238
  const lines = formatPressing(signals?.pressing)
226
239
  const offers = signals?.settling?.offers ?? []
@@ -236,7 +249,14 @@ export function formatNotice(signals) {
236
249
  const split = all.some((g) => typeof g?.held === 'boolean')
237
250
  const assigned = split ? all.filter((g) => g?.held === true) : all
238
251
  const unheld = split ? all.filter((g) => g?.held === false) : []
239
- if (assigned.length) {
252
+ if (all.length && signals?.holdForConfidentialLock === true) {
253
+ // CONFIDENTIAL BRAINS (web/lib/engine/confidential_lock.ts; Theron, 2026-10-28). The person holds a confidential
254
+ // seat and this session has not used Agnoclast yet. Filing an arrival — inline or by the background filer — is a
255
+ // use of an ordinary brain and would lock the session OUT of the confidential one before the person's own first
256
+ // request decides. So: name them, and leave them. If the session locks in, the server hands them to another
257
+ // session; if it locks out, the next prompt shows them as usual.
258
+ lines.push(...formatHeldForLock(all))
259
+ } else if (assigned.length) {
240
260
  const n = assigned.reduce((t, g) => t + (Number(g?.count) || 1), 0)
241
261
  lines.push(`📥 ${n} arrival${n === 1 ? ' is' : 's are'} ASSIGNED TO THIS SESSION — you are ${n === 1 ? 'its' : 'their'} only owner. Handle ${n === 1 ? 'it' : 'them'} before the user's request, then answer the user:`)
242
262
  for (const g of assigned.slice(0, MAX_ASSIGNED)) {
@@ -247,7 +267,7 @@ export function formatNotice(signals) {
247
267
  if (assigned.length > MAX_ASSIGNED) lines.push(` … and ${assigned.length - MAX_ASSIGNED} more groups`)
248
268
  lines.push(' `intake_claim {intakeItemIds}` → `intake_materialize` (or `intake_discard` for junk) · `not_mine` hands one to the next session · only what only the user can decide → `intake_defer`.')
249
269
  }
250
- if (unheld.length) lines.push(...formatUnheld(unheld, { more: assigned.length > 0, shadow: signals?.routineShadow === true }))
270
+ if (unheld.length && signals?.holdForConfidentialLock !== true) lines.push(...formatUnheld(unheld, { more: assigned.length > 0, shadow: signals?.routineShadow === true }))
251
271
  if (delta) {
252
272
  lines.push(`⚡ ${delta} new arrival${delta === 1 ? '' : 's'} in the pile since this session was last told.`)
253
273
  }
@@ -1,10 +1,11 @@
1
- import { readFileSync, mkdirSync, writeFileSync } from 'node:fs'
1
+ import { readFileSync, mkdirSync, writeFileSync, existsSync } from 'node:fs'
2
2
  import { homedir } from 'node:os'
3
3
  import { join } from 'node:path'
4
4
  import { execFileSync } from 'node:child_process'
5
+ import { createHash } from 'node:crypto'
5
6
 
6
- // CONFIDENTIAL BRAINS FROM A CODING AGENT (server: web/lib/engine/confidential_agent.ts, migration
7
- // 20261027065716; Agnoclast page "Confidential brains — design").
7
+ // CONFIDENTIAL BRAINS FROM A CODING AGENT (server: web/lib/engine/confidential_agent.ts and confidential_lock.ts;
8
+ // migrations 20261027065716 and 20261028201517; Agnoclast page "Confidential brains — design").
8
9
  //
9
10
  // A confidential brain's data may reach only an AI account its admin approved. This process runs inside the
10
11
  // agent, so it is the one place that can see which account that is:
@@ -12,14 +13,13 @@ import { execFileSync } from 'node:child_process'
12
13
  // (CLAUDE_CODE_ACCOUNT_UUID / CLAUDE_CODE_ORGANIZATION_UUID — seen on 2026-10-27 in the env of a live
13
14
  // cortex-mcp under Claude Code). Unsigned: it stops the accident, not a forger.
14
15
  // • 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'
16
+ //
17
+ // THE FIRST-TOUCH LOCK (Theron, 2026-10-28). A session starts the ordinary way, with the ordinary server. The first
18
+ // time a tool names a confidential brain, this process proves the AI account and trades the person's token for a
19
+ // 15-minute token on the person's SEAT; from then on every request goes through the seat, and the server holds
20
+ // the session IN that brain. If the session used any other brain first, the server refuses the seat — it is
21
+ // locked OUT. Once locked in, this process leaves a marker so every hook (capture, context, the local summarizer)
22
+ // stands down for the rest of the session: they work on the person's ordinary account.
23
23
 
24
24
  /**
25
25
  * The NEAREST coding agent above this process: 'codex', 'claude', or null. Nearest, because agents nest — a
@@ -90,53 +90,75 @@ export async function requestSeatToken({ base, token, brain, proof, fetchImpl })
90
90
  if (res.ok && body?.status === 'approved' && typeof body.token === 'string') {
91
91
  return { token: body.token, expiresIn: Number(body.expiresIn) || 900, brain: body.brain ?? brain, account: body.account }
92
92
  }
93
+ if (body?.status === 'pending' && body.awaiting === 'owner') {
94
+ return { message: `"${body.brain}" approved this AI account (${body.account}) only as DEDICATED to it: once you agree, it can never reach any other brain. To agree, POST { brain, account: "${body.accountId}", decision: "agree" } to /api/brains/confidential/ai-accounts; then try again.` }
95
+ }
93
96
  if (body?.status === 'pending') {
94
- 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.` }
97
+ 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 try again.` }
95
98
  }
96
- return { message: `"${brain}" did not open: ${body?.error ?? `HTTP ${res.status}`}` }
99
+ return { message: `"${brain}" did not open: ${body?.error ?? body?.message ?? `HTTP ${res.status}`}` }
97
100
  }
98
101
 
99
- /** Should this hook or ordinary server stand down? True inside a session started by `cortex-mcp confidential`. */
100
- export function inConfidentialSession(env = process.env) {
101
- return !!env[CONFIDENTIAL_SESSION_ENV]
102
+ /**
103
+ * The AI account this process runs under, as the server spells it ('anthropic:<org>:<account>' /
104
+ * 'openai:<chatgpt account>:<user>'), or null. Sent as x-cortex-ai-account so the server can refuse an account
105
+ * dedicated to a confidential brain everywhere else. Attested, like the Claude Code proof: it stops accidents.
106
+ */
107
+ export function aiAccountOf(proof) {
108
+ if (!proof) return null
109
+ if (proof.kind === 'claude-code') return `anthropic:${proof.organizationUuid.toLowerCase()}:${proof.accountUuid.toLowerCase()}`
110
+ try {
111
+ const claims = JSON.parse(Buffer.from(String(proof.idToken).split('.')[1], 'base64url').toString('utf8'))
112
+ const auth = claims['https://api.openai.com/auth'] ?? {}
113
+ return auth.chatgpt_account_id && auth.chatgpt_user_id ? `openai:${auth.chatgpt_account_id}:${auth.chatgpt_user_id}` : null
114
+ } catch { return null }
102
115
  }
103
116
 
104
117
  /**
105
- * `cortex-mcp confidential <brain> [claude|codex]` — write the agent config that holds ONLY this brain's
106
- * server, and return the command that starts the agent with it. Nothing ordinary is loaded alongside: for
107
- * Claude Code, --strict-mcp-config; for Codex, the ordinary `cortex` server is switched off for that run.
118
+ * The account a HOOK runs under. Hooks are Claude Code's, so only its environment is read — no process walk on
119
+ * every hook. Null under an API key or a cloud provider, where the login does not say.
108
120
  */
109
- /** The [mcp_servers.<name>] entries in a Codex config.toml that run the ordinary Agnoclast server. */
110
- export function codexAgnoclastServers(toml) {
111
- const names = []
112
- const sections = String(toml).split(/^(?=\[)/m)
113
- for (const s of sections) {
114
- const m = s.match(/^\[mcp_servers\.([A-Za-z0-9_-]+)\]/)
115
- if (m && m[1] !== 'agnoclast_confidential' && /(cortex|agnoclast)-mcp/.test(s)) names.push(m[1])
116
- }
117
- return names
121
+ export function hookAiAccount(env = process.env) {
122
+ if (!env.CLAUDECODE || env.ANTHROPIC_API_KEY || env.CLAUDE_CODE_USE_BEDROCK || env.CLAUDE_CODE_USE_VERTEX) return null
123
+ const a = env.CLAUDE_CODE_ACCOUNT_UUID, o = env.CLAUDE_CODE_ORGANIZATION_UUID
124
+ return a && o ? `anthropic:${o.toLowerCase()}:${a.toLowerCase()}` : null
118
125
  }
119
126
 
120
- export function confidentialLaunch({ brain, agent, token, spec = '@theronap/cortex-mcp@latest', home = homedir(), write = writeFileSync, mkdir = mkdirSync, readFile = readFileSync }) {
121
- const env = { CORTEX_TOKEN: token, [CONFIDENTIAL_BRAIN_ENV]: brain, [CONFIDENTIAL_SESSION_ENV]: '1' }
122
- if (agent === 'claude') {
123
- const dir = join(home, '.cortex', 'confidential')
124
- mkdir(dir, { recursive: true, mode: 0o700 })
125
- const slug = brain.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 48) || 'brain'
126
- const file = join(dir, `${slug}.mcp.json`)
127
- write(file, JSON.stringify({ mcpServers: { 'agnoclast-confidential': { command: 'npx', args: ['-y', spec], env } } }, null, 2), { mode: 0o600 })
128
- return { command: 'claude', args: ['--strict-mcp-config', '--mcp-config', file], env: { [CONFIDENTIAL_SESSION_ENV]: '1' } }
127
+ /** Ask which confidential brains this person holds a seat in, and the one this AI account is dedicated to. Locks nothing. */
128
+ export async function fetchMyConfidential({ base, token, proof, fetchImpl }) {
129
+ try {
130
+ const res = await fetchImpl(`${base}/api/brains/confidential/mine`, {
131
+ method: 'POST',
132
+ headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
133
+ body: JSON.stringify(proof ? { proof } : {}),
134
+ })
135
+ if (!res.ok) return { brains: [], dedicatedTo: null }
136
+ const body = await res.json()
137
+ return { brains: Array.isArray(body?.brains) ? body.brains : [], dedicatedTo: typeof body?.dedicatedTo === 'string' ? body.dedicatedTo : null }
138
+ } catch {
139
+ return { brains: [], dedicatedTo: null }
129
140
  }
130
- const q = (s) => JSON.stringify(s)
131
- let configText = ''
132
- try { configText = readFile(join(home, '.codex', 'config.toml'), 'utf8') } catch { /* no config: nothing to switch off */ }
133
- const args = [
134
- // Codex passes MCP servers only the environment its config names, so the ordinary server could not see
135
- // AGNOCLAST_CONFIDENTIAL and stand down by itself. Switch every ordinary Agnoclast entry off for this run.
136
- ...codexAgnoclastServers(configText).flatMap((name) => ['-c', `mcp_servers.${name}.enabled=false`]),
137
- '-c', `mcp_servers.agnoclast_confidential.command=${q('npx')}`,
138
- '-c', `mcp_servers.agnoclast_confidential.args=${JSON.stringify(['-y', spec])}`,
139
- ...Object.entries(env).flatMap(([k, v]) => ['-c', `mcp_servers.agnoclast_confidential.env.${k}=${q(v)}`]),
140
- ]
141
- return { command: 'codex', args, env: { [CONFIDENTIAL_SESSION_ENV]: '1' } }
141
+ }
142
+
143
+ /** The confidential brain a tool's `brain` argument names (by name or org id, any case), or null. */
144
+ export function confidentialBrainNamed(brains, arg) {
145
+ if (typeof arg !== 'string' || !arg.trim()) return null
146
+ const a = arg.trim().toLowerCase()
147
+ return brains.find((b) => b.orgId?.toLowerCase() === a || b.name?.toLowerCase() === a) ?? null
148
+ }
149
+
150
+ // ── The locked-in marker: how a hook learns its session belongs to a confidential brain ─────────────────────────
151
+
152
+ const markerDir = (home) => join(home, '.cortex', 'confidential-sessions')
153
+ const markerFile = (home, sessionKey) => join(markerDir(home), createHash('sha256').update(String(sessionKey)).digest('hex'))
154
+
155
+ export function markLockedIn(sessionKey, brain, { home = homedir(), write = writeFileSync, mkdir = mkdirSync } = {}) {
156
+ if (!sessionKey) return
157
+ mkdir(markerDir(home), { recursive: true, mode: 0o700 })
158
+ write(markerFile(home, sessionKey), JSON.stringify({ brain, at: new Date().toISOString() }), { mode: 0o600 })
159
+ }
160
+
161
+ /** Is this session locked into a confidential brain? A hook asks this before doing anything. */
162
+ export function sessionLockedIn(sessionKey, { home = homedir(), exists = existsSync } = {}) {
163
+ return !!sessionKey && exists(markerFile(home, sessionKey))
142
164
  }
package/lib/diagnose.mjs CHANGED
@@ -283,6 +283,12 @@ export function classify(status, contentType, bodyText, requestId) {
283
283
  let SESSION_KEY = null
284
284
  export function setSessionKey(key) { SESSION_KEY = key || null }
285
285
 
286
+ // THE AI ACCOUNT this process runs under (confidential_session.mjs aiAccountOf/hookAiAccount), sent as
287
+ // x-cortex-ai-account. The server refuses an account dedicated to a confidential brain everywhere else
288
+ // (web/lib/engine/confidential_lock.ts). Null → no header → nothing changes.
289
+ let AI_ACCOUNT = null
290
+ export function setAiAccount(v) { AI_ACCOUNT = v || null }
291
+
286
292
  // WHO IS CALLING — an identity INDEPENDENT of the session key, and it must stay independent.
287
293
  //
288
294
  // The server labels every page revision's `actor_source` from this header. It used to default to
@@ -429,7 +435,7 @@ async function fetchCortexOnce(url, opts = {}, policy = {}) {
429
435
  const { timeoutMs: optTimeout, signal: callerSignal, ...rest } = opts
430
436
  // x-cortex-tool: the tool this request is for (the running one, else the path map) — the server
431
437
  // counts calls per tool for staff usage stats (api_requests). A name only; arguments never travel.
432
- const baseHeaders = { ...(rest.headers ?? {}), 'x-cortex-client': CLIENT_ID, 'x-cortex-tool': toolForUrl(url) }
438
+ const baseHeaders = { ...(rest.headers ?? {}), 'x-cortex-client': CLIENT_ID, 'x-cortex-tool': toolForUrl(url), ...(AI_ACCOUNT ? { 'x-cortex-ai-account': AI_ACCOUNT } : {}) }
433
439
  const fetchOpts = SESSION_KEY
434
440
  ? { ...rest, headers: { ...baseHeaders, 'x-cortex-session-key': SESSION_KEY } }
435
441
  : { ...rest, headers: baseHeaders }
@@ -539,6 +545,8 @@ const PATH_TOOLS = {
539
545
  'held': 'held_items', 'held/absorb': 'absorb',
540
546
  // Opening a confidential brain from a coding agent (lib/confidential_session.mjs, 2026-10-27).
541
547
  'brains/confidential/agent-session': 'confidential_session',
548
+ 'brains/confidential/mine': 'confidential_session',
549
+ 'brains/confidential/ai-accounts': 'confidential_session',
542
550
  }
543
551
 
544
552
  /** 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
@@ -6,13 +6,13 @@ import { homedir } from 'os'
6
6
  import { join } from 'path'
7
7
  import { createHash, randomUUID } from 'crypto'
8
8
  import { seatChargeRefusal, seatChargeQuestion } from './seat_charge.mjs'
9
- import { fetchCortex, classify, resolveBase, resolveEnvToken, setSessionKey, setClientVersion, runWithTool, heartbeatPolicy, nextPingFailures, clockMark, sleptBetween, internetReachable } from './diagnose.mjs'
9
+ import { fetchCortex, classify, resolveBase, resolveEnvToken, setSessionKey, setAiAccount, setClientVersion, runWithTool, heartbeatPolicy, nextPingFailures, clockMark, sleptBetween, internetReachable } from './diagnose.mjs'
10
10
  import { REPORT_KINDS, REPORT_ISSUE_DESCRIPTION, fileIssue } from './report_issue.mjs'
11
11
  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
+ import { aiAccountOf, confidentialBrainNamed, fetchMyConfidential, gatherAgentProof, markLockedIn, requestSeatToken } from './confidential_session.mjs'
16
16
  import { runSendImessage } from './imessage_send.mjs'
17
17
  import { formatGrepHits } from './grep_cli.mjs'
18
18
  import { buildProposal, renderProposal, withAskNotice } from './propose_obligation.mjs'
@@ -257,9 +257,13 @@ export async function gate5StatusFromResponse(res) {
257
257
  // The Agnoclast MCP server (stdio). Serves the signed-in employee's scoped org
258
258
  // context to their AI assistant. CORTEX_TOKEN identifies the user + org.
259
259
 
260
+ // See the registerTool wrapper in runServer: read tools that take an optional `brain` naming a confidential brain.
261
+ const CONFIDENTIAL_ENTRY_TOOLS = new Set(['grep', 'read_page', 'search_org', 'list_brain_pages', 'list_records', 'project_status', 'my_obligations', 'edit_page', 'my_context'])
262
+ const CONFIDENTIAL_BRAIN_ARG = z.string().optional().describe('ONLY to work in a 🔒 confidential brain that my_brains lists: its name. Using it locks this session to that brain (or is refused if the session already used another brain). Omit it otherwise.')
263
+
260
264
  export async function runServer(version) {
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.
265
+ // `let`, not `const`: once this session uses a confidential brain (lib/confidential_session.mjs), the person's
266
+ // token is traded for a 15-minute SEAT token, renewed below, and every request reads this binding at call time.
263
267
  let TOKEN = resolveEnvToken().token
264
268
  const BASE = resolveBase(process.env.CORTEX_URL)
265
269
 
@@ -268,34 +272,6 @@ export async function runServer(version) {
268
272
  process.exit(1)
269
273
  }
270
274
 
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
-
299
275
  // Self active-sessions (ADR-0017): one MCP process = one AI session. A stable per-process key + the
300
276
  // working dir identify this session; we heartbeat /api/session-ping while alive so the user can see
301
277
  // all THEIR sessions via my_sessions. Self-only on the server; best-effort (never breaks serving).
@@ -315,6 +291,50 @@ export async function runServer(version) {
315
291
  // resolve THIS session's brain pointer. Must be set BEFORE the first fetchCortex call below —
316
292
  // otherwise the opening requests of a session would silently resolve by the account pointer.
317
293
  setSessionKey(SESSION_KEY)
294
+
295
+ // ── CONFIDENTIAL BRAINS: THE FIRST-TOUCH LOCK (Theron, 2026-10-28) ─────────────────────────────────────────
296
+ // Only for a person who holds a confidential seat; for everyone else `confidential.brains` is empty and nothing
297
+ // below runs. The first tool call that names a confidential brain opens it: the AI account is proved, the
298
+ // person's token is traded for a seat token, and the server locks the session IN. Anything else used first
299
+ // locks it OUT on the server, which then refuses the seat with a message this passes on. An AI account
300
+ // dedicated to a confidential brain opens it at once, before any tool runs.
301
+ //
302
+ // Asked in parallel with registering tools and awaited (bounded) before the handshake, like the release state.
303
+ // The AI account is only worked out — a walk up the process tree — for someone who holds a seat.
304
+ let confidential = { brains: [], dedicatedTo: null }
305
+ const confidentialP = (async () => {
306
+ const seats = await fetchMyConfidential({ base: BASE, token: TOKEN, proof: null, fetchImpl: fetchCortex })
307
+ if (!seats.brains.length) return seats
308
+ const got = gatherAgentProof()
309
+ setAiAccount(got.proof ? aiAccountOf(got.proof) : null)
310
+ return got.proof ? fetchMyConfidential({ base: BASE, token: TOKEN, proof: got.proof, fetchImpl: fetchCortex }) : seats
311
+ })().catch(() => ({ brains: [], dedicatedTo: null }))
312
+ let lockedInto = null
313
+ async function openConfidential(brainName) {
314
+ if (lockedInto) return lockedInto.toLowerCase() === brainName.toLowerCase() ? null : `This session is locked to the confidential brain "${lockedInto}". Start a new session to use "${brainName}".`
315
+ const mint = async () => {
316
+ const got = gatherAgentProof()
317
+ if (got.refused) return { message: got.refused }
318
+ return requestSeatToken({ base: BASE, token: resolveEnvToken().token, brain: brainName, proof: got.proof, fetchImpl: fetchCortex })
319
+ }
320
+ const first = await mint().catch((e) => ({ message: String(e?.message ?? e) }))
321
+ if (!first.token) return first.message
322
+ TOKEN = first.token
323
+ lockedInto = first.brain
324
+ // Nothing from this session may reach a local summarizer, or a hook on the person's ordinary account.
325
+ process.env.CORTEX_SUMMARIZE_DISABLED = '1'
326
+ try { markLockedIn(SESSION_KEY, lockedInto) } catch (e) { process.stderr.write(`cortex-mcp: could not mark the session confidential: ${e?.message ?? e}\n`) }
327
+ // Renew a few minutes early, re-proving the account each time: a /login to another account stops the next
328
+ // renewal, and a renewal that fails leaves a token the server refuses, so the session fails closed.
329
+ const every = Math.max(60, first.expiresIn - 180) * 1000
330
+ setInterval(async () => {
331
+ const next = await mint().catch((e) => ({ message: String(e?.message ?? e) }))
332
+ if (next.token) { TOKEN = next.token; return }
333
+ TOKEN = 'confidential-session-closed'
334
+ process.stderr.write(`cortex-mcp: confidential session closed — ${next.message}\n`)
335
+ }, every).unref()
336
+ return null
337
+ }
318
338
  // Paired with setSessionKey and set at the same moment, but a SEPARATE signal on purpose: the
319
339
  // server labels actor_source from this and watches for `mcp` + no session. Tying the two together
320
340
  // would make that pair impossible and blind the detector. See actorSourceFrom in auth_cloud.ts.
@@ -464,8 +484,19 @@ export async function runServer(version) {
464
484
  // attributed to the tool that hit it rather than guessed from a URL shared by several tools.
465
485
  const registerTool = server.registerTool.bind(server)
466
486
  server.registerTool = (name, config, handler) => {
487
+ // The tools a session usually STARTS with read across brains and take no `brain`, so a confidential brain could
488
+ // never be opened through them: give them an optional one. The wrapper below reads it; the handler ignores it.
489
+ if (CONFIDENTIAL_ENTRY_TOOLS.has(name) && config?.inputSchema && !config.inputSchema.brain) {
490
+ config = { ...config, inputSchema: { ...config.inputSchema, brain: CONFIDENTIAL_BRAIN_ARG } }
491
+ }
467
492
  const takesArgs = !!config?.inputSchema
468
493
  const handle = registerTool(name, config, (...args) => runWithTool(name, async () => {
494
+ // A tool naming a confidential brain opens it first (the first-touch lock, above).
495
+ const named = confidential.brains.length && takesArgs ? confidentialBrainNamed(confidential.brains, args[0]?.brain) : null
496
+ if (named) {
497
+ const refused = await openConfidential(named.name)
498
+ if (refused) return { content: [{ type: 'text', text: refused }], isError: true }
499
+ }
469
500
  // A LOCKED tool runs nothing: the server's answer says what it would have done and how Regular is
470
501
  // reached. "Not locked any more" (the trial started mid-session) → the tool runs as usual; a check that
471
502
  // cannot be made → nothing runs (fails closed).
@@ -4930,7 +4961,14 @@ function renderNudge(payload) {
4930
4961
  const header = brains.length === 1
4931
4962
  ? 'Your brain:'
4932
4963
  : 'Your brains (reads span all of them; an edit routes to the brain holding the page; creating a NEW page takes an explicit `brain`):'
4933
- return { content: [{ type: 'text', text: `${header}\n${lines.join('\n')}` }] }
4964
+ // Confidential brains are reached through a seat, so /api/brains never lists them: say they exist and how
4965
+ // they open, so the AI can use one by name.
4966
+ const seats = !lockedInto && confidential.brains.length
4967
+ ? `\n\n🔒 Confidential (a session works in one of these ALONE): ${confidential.brains.map((b) => b.name).join(', ')}\n` +
4968
+ ' Pass its name as `brain` to any tool. If this session has not used another brain yet, that locks the session to it; ' +
4969
+ 'if it has, the brain stays locked away — start a new session and use it first.'
4970
+ : ''
4971
+ return { content: [{ type: 'text', text: `${header}\n${lines.join('\n')}${seats}` }] }
4934
4972
  },
4935
4973
  )
4936
4974
 
@@ -7949,16 +7987,13 @@ function renderNudge(payload) {
7949
7987
 
7950
7988
  applyRelease(toolHandles, await releaseStateWithin(releaseP))
7951
7989
  lockedTools = applyLock(toolHandles, await lockStateWithin(lockP))
7990
+ confidential = await Promise.race([confidentialP, new Promise((r) => setTimeout(() => r({ brains: [], dedicatedTo: null }), 5000).unref())])
7991
+ if (confidential.dedicatedTo) {
7992
+ // An AI account dedicated to a confidential brain opens it before any tool runs. If it cannot, it reaches
7993
+ // nothing: the server refuses its ordinary token too.
7994
+ const refused = await openConfidential(confidential.dedicatedTo)
7995
+ if (refused) process.stderr.write(`cortex-mcp: ${refused}\n`)
7996
+ }
7952
7997
  await server.connect(new StdioServerTransport())
7953
7998
  }
7954
7999
 
7955
- // A confidential brain that did not open: serve one tool that says why, so the AI can tell the person,
7956
- // rather than an empty server that looks like a broken install.
7957
- async function serveConfidentialRefusal(version, message) {
7958
- const server = new McpServer({ name: 'cortex', version })
7959
- server.registerTool('confidential_status', {
7960
- title: 'Why the confidential brain did not open',
7961
- description: 'The confidential brain this session was started for did not open. Call this and tell the person why.',
7962
- }, async () => ({ content: [{ type: 'text', text: message }] }))
7963
- await server.connect(new StdioServerTransport())
7964
- }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theronap/agnoclast-mcp",
3
- "version": "0.9.274",
3
+ "version": "0.9.276",
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": {