@theronap/agnoclast-mcp 0.9.278 → 0.9.280

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.
@@ -196,6 +196,12 @@ if (cmd === 'login') {
196
196
  await runStatus()
197
197
  const { closeFetch } = await import('../lib/diagnose.mjs')
198
198
  await closeFetch()
199
+ // Heal the confidential-brain guard (lib/confidential_guard.mjs) onto seats wired before it existed, so it is in
200
+ // place from the NEXT session without anyone re-running setup. Best-effort and silent.
201
+ try {
202
+ const { healConfidentialGuard } = await import('../lib/editors/claude.mjs')
203
+ healConfidentialGuard()
204
+ } catch { /* never fail session start over this */ }
199
205
  } else if (cmd === 'capture') {
200
206
  const { runCapture } = await import('../lib/capture.mjs')
201
207
  await runCapture()
@@ -276,7 +282,7 @@ if (cmd === 'login') {
276
282
  // ADR-0033 §5 C2. Guarded: adds the new namespace's allow rules and VERIFIES them from disk
277
283
  // before flipping mcpServers.cortex -> .agnoclast, so a seat that never received C1 cannot end up
278
284
  // with renamed tools and no permissions. Idempotent; --dry-run reports the plan and changes
279
- // nothing. NOT wired into any hook yet — activating it is the C2 release itself.
285
+ // nothing. Also runs on its own at every server start since 0.9.279 (autoMigrateKeys).
280
286
  const { runKeyMigration } = await import('../lib/migrate_key.mjs')
281
287
  const res = runKeyMigration({ dryRun: rest.includes('--dry-run') })
282
288
  process.stdout.write(JSON.stringify(res, null, 2) + '\n')
@@ -331,6 +337,10 @@ if (cmd === 'login') {
331
337
  // on their next install/repair; drop this branch a release after that has had time to propagate.
332
338
  } else {
333
339
  // Default: run the MCP server (stays alive; never exits).
340
+ // First, finish the cortex -> agnoclast key flip if this machine still has the old key. Best-effort,
341
+ // stderr only (stdout is the MCP channel); see autoMigrateKeys.
342
+ const { autoMigrateKeys } = await import('../lib/migrate_key.mjs')
343
+ autoMigrateKeys()
334
344
  const { runServer } = await import('../lib/server.mjs')
335
345
  await runServer(VERSION)
336
346
  }
@@ -0,0 +1,96 @@
1
+ #!/usr/bin/env node
2
+ // THE OTHER-CONNECTIONS GUARD (Theron, 2026-10-28; Agnoclast page "Confidential brains — design").
3
+ //
4
+ // The first-touch lock binds requests that say which session they come from: the local cortex-mcp sends the
5
+ // session id on every request, and the server holds a locked-in session to its confidential brain. But one Claude
6
+ // Code session can carry a SECOND Agnoclast connection — the claude.ai connector — which sends no session id, so the
7
+ // server cannot tie its requests to the session. In a session locked into a confidential brain, that connection
8
+ // could read every ordinary brain, or write confidential content into one.
9
+ //
10
+ // So Claude Code runs this before every MCP tool call (a PreToolUse hook, wired by setup and healed by `status`).
11
+ // It does nothing unless this session is locked in — the local server leaves a marker when it locks — and then it
12
+ // refuses any Agnoclast tool reached through a connection that is NOT a local cortex-mcp server. The local servers
13
+ // stay allowed because the server already enforces the lock on them.
14
+ //
15
+ // Like the Claude Code account check, it stops accidents, not someone who edits their own settings.
16
+ //
17
+ // ⚠ SELF-CONTAINED ON PURPOSE: setup copies this one file to ~/.cortex/hooks/ and Claude Code runs it with plain
18
+ // `node` on every MCP call, so it may import only Node built-ins (no npx start-up on the hot path).
19
+
20
+ import { readFileSync, existsSync } from 'node:fs'
21
+ import { homedir } from 'node:os'
22
+ import { join } from 'node:path'
23
+ import { createHash } from 'node:crypto'
24
+
25
+ const markerPath = (home, sessionKey) =>
26
+ join(home, '.cortex', 'confidential-sessions', createHash('sha256').update(String(sessionKey)).digest('hex'))
27
+
28
+ /** The MCP server names in a Claude Code config that run the local Agnoclast server. */
29
+ export function localAgnoclastServers(...configs) {
30
+ const names = new Set()
31
+ for (const cfg of configs) {
32
+ const servers = { ...(cfg?.mcpServers ?? {}) }
33
+ for (const p of Object.values(cfg?.projects ?? {})) Object.assign(servers, p?.mcpServers ?? {})
34
+ for (const [name, s] of Object.entries(servers)) {
35
+ const line = [s?.command, ...(Array.isArray(s?.args) ? s.args : [])].join(' ')
36
+ if ((s?.type ?? 'stdio') === 'stdio' && /(cortex|agnoclast)-mcp/.test(line)) names.add(name)
37
+ }
38
+ }
39
+ return names
40
+ }
41
+
42
+ /**
43
+ * PURE. Allow or deny one tool call. `marker` is the locked-in marker ({ brain, tools }) or null when the session is
44
+ * not locked in. `tools` are the names the local Agnoclast server registered, so a connector exposing the same
45
+ * tools is recognised by what it offers, whatever it is called.
46
+ */
47
+ export function guardDecision({ toolName, marker, localServers }) {
48
+ if (!marker) return { allow: true }
49
+ const m = /^mcp__(.+?)__(.+)$/.exec(String(toolName ?? ''))
50
+ if (!m) return { allow: true }
51
+ const [, server, tool] = m
52
+ if (localServers.has(server)) return { allow: true }
53
+ const tools = new Set(Array.isArray(marker.tools) ? marker.tools : [])
54
+ if (!tools.has(tool)) return { allow: true }
55
+ return {
56
+ allow: false,
57
+ reason: `This session is locked to the confidential brain "${marker.brain}". Agnoclast reached through "${server}" is not bound to that lock, so it is blocked for the rest of this session. Use the local Agnoclast tools, or start a new session for other work.`,
58
+ }
59
+ }
60
+
61
+ /** Run as a hook: read Claude Code's PreToolUse payload on stdin, answer with a deny decision or nothing. */
62
+ export function runGuard({ input, home = homedir(), read = readFileSync, exists = existsSync } = {}) {
63
+ let payload
64
+ try { payload = JSON.parse(input) } catch { return null }
65
+ const path = payload?.session_id ? markerPath(home, payload.session_id) : null
66
+ if (!path || !exists(path)) return null
67
+ let decision
68
+ try {
69
+ const marker = JSON.parse(read(path, 'utf8'))
70
+ const configs = []
71
+ for (const f of [join(home, '.claude.json'), join(payload.cwd ?? '.', '.mcp.json')]) {
72
+ try { configs.push(JSON.parse(read(f, 'utf8'))) } catch { /* absent or unreadable */ }
73
+ }
74
+ decision = guardDecision({ toolName: payload.tool_name, marker, localServers: localAgnoclastServers(...configs) })
75
+ } catch {
76
+ // A locked-in session whose marker cannot be read: refuse anything that looks like a second Agnoclast connection
77
+ // rather than guess. The local server's own calls are still checked on the server.
78
+ decision = /^mcp__/.test(String(payload.tool_name ?? ''))
79
+ ? { allow: false, reason: 'This session is locked to a confidential brain and its lock could not be read, so other MCP connections are blocked.' }
80
+ : { allow: true }
81
+ }
82
+ if (decision.allow) return null
83
+ return { hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: decision.reason } }
84
+ }
85
+
86
+ // Run directly (the hook), never on import (setup and tests import it).
87
+ if (process.argv[1] && import.meta.url === new URL(`file://${process.argv[1]}`).href) {
88
+ let input = ''
89
+ process.stdin.setEncoding('utf8')
90
+ process.stdin.on('data', (d) => { input += d })
91
+ process.stdin.on('end', () => {
92
+ const out = runGuard({ input })
93
+ if (out) process.stdout.write(JSON.stringify(out))
94
+ process.exit(0)
95
+ })
96
+ }
@@ -134,7 +134,8 @@ export async function fetchMyConfidential({ base, token, proof, fetchImpl }) {
134
134
  })
135
135
  if (!res.ok) return { brains: [], dedicatedTo: null }
136
136
  const body = await res.json()
137
- return { brains: Array.isArray(body?.brains) ? body.brains : [], dedicatedTo: typeof body?.dedicatedTo === 'string' ? body.dedicatedTo : null }
137
+ const lock = body?.lock?.state === 'in' || body?.lock?.state === 'out' ? body.lock : null
138
+ return { brains: Array.isArray(body?.brains) ? body.brains : [], dedicatedTo: typeof body?.dedicatedTo === 'string' ? body.dedicatedTo : null, lock }
138
139
  } catch {
139
140
  return { brains: [], dedicatedTo: null }
140
141
  }
@@ -152,13 +153,31 @@ export function confidentialBrainNamed(brains, arg) {
152
153
  const markerDir = (home) => join(home, '.cortex', 'confidential-sessions')
153
154
  const markerFile = (home, sessionKey) => join(markerDir(home), createHash('sha256').update(String(sessionKey)).digest('hex'))
154
155
 
155
- export function markLockedIn(sessionKey, brain, { home = homedir(), write = writeFileSync, mkdir = mkdirSync } = {}) {
156
+ /**
157
+ * `tools`: the names this server registered. The guard (confidential_guard.mjs) recognises a second Agnoclast
158
+ * connection — a claude.ai connector — by offering the same tools under another server name.
159
+ */
160
+ export function markLockedIn(sessionKey, brain, { tools = [], home = homedir(), write = writeFileSync, mkdir = mkdirSync } = {}) {
156
161
  if (!sessionKey) return
157
162
  mkdir(markerDir(home), { recursive: true, mode: 0o700 })
158
- write(markerFile(home, sessionKey), JSON.stringify({ brain, at: new Date().toISOString() }), { mode: 0o600 })
163
+ write(markerFile(home, sessionKey), JSON.stringify({ brain, tools, at: new Date().toISOString() }), { mode: 0o600 })
159
164
  }
160
165
 
161
166
  /** Is this session locked into a confidential brain? A hook asks this before doing anything. */
162
167
  export function sessionLockedIn(sessionKey, { home = homedir(), exists = existsSync } = {}) {
163
168
  return !!sessionKey && exists(markerFile(home, sessionKey))
164
169
  }
170
+
171
+ /**
172
+ * The line every tool result carries while this session is locked into a confidential brain, and what my_brains says
173
+ * before then (Theron, 2026-10-28: make the lock state visible, so no AI mistakes the state it is in).
174
+ */
175
+ export function lockStateLine({ lockedInto = null, lock = null, brains = [] } = {}) {
176
+ if (lockedInto) return `🔒 This session is LOCKED to the confidential brain "${lockedInto}": no other brain is reachable from it, and Agnoclast through any other connection (such as a claude.ai connector) is blocked in Claude Code.`
177
+ if (!brains.length) return ''
178
+ const names = brains.map((b) => b.name).join(', ')
179
+ if (lock?.state === 'in') return `🔒 This session is LOCKED to the confidential brain "${lock.brain}".`
180
+ if (lock?.state === 'out') return `🔒 Confidential: ${names} — LOCKED AWAY from this session: it used another brain first. Start a new session and use the confidential brain first.`
181
+ return `🔒 Confidential (a session works in one of these ALONE): ${names}\n` +
182
+ ' This session is NOT locked yet. Pass the name as `brain` to any tool to lock the session to it; using any other brain first locks these away from the session instead.'
183
+ }
@@ -2,7 +2,7 @@
2
2
  // setup.mjs. setup.mjs imports THESE SAME functions (and re-exports them), so the config bytes are
3
3
  // structurally identical, not merely "supposed to match".
4
4
  import { homedir } from 'node:os'
5
- import { existsSync } from 'node:fs'
5
+ import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs'
6
6
  import { join } from 'node:path'
7
7
  import { readJson, backupFile, ensureDir, writeJson } from './_fsutil.mjs'
8
8
  import { markCommand, isManagedSubcommand } from '../managed.mjs'
@@ -75,6 +75,46 @@ export const CORTEX_ALLOWED_TOOLS = allowedToolsFor('cortex')
75
75
  * never removed, so a machine can carry both and neither ordering can strand it at a prompt. */
76
76
  export const MANAGED_ALLOWED_TOOLS = [...allowedToolsFor('cortex'), ...allowedToolsFor('agnoclast')]
77
77
 
78
+ export const CONFIDENTIAL_GUARD_MATCHER = 'mcp__.*'
79
+ export const CONFIDENTIAL_GUARD_COMMAND =
80
+ `[ -d "$HOME/.cortex/confidential-sessions" ] && node "$HOME/.cortex/hooks/confidential-guard.mjs" --agnoclast-managed || true`
81
+
82
+ /** Copy the guard (lib/confidential_guard.mjs, self-contained) to where its hook runs it. Rewrites only on change. */
83
+ export function installConfidentialGuard({ home = homedir() } = {}) {
84
+ const src = readFileSync(new URL('../confidential_guard.mjs', import.meta.url), 'utf8')
85
+ const dir = join(home, '.cortex', 'hooks')
86
+ const dest = join(dir, 'confidential-guard.mjs')
87
+ let cur = null
88
+ try { cur = readFileSync(dest, 'utf8') } catch { /* not installed yet */ }
89
+ if (cur === src) return false
90
+ mkdirSync(dir, { recursive: true, mode: 0o700 })
91
+ writeFileSync(dest, src, { mode: 0o600 })
92
+ return true
93
+ }
94
+
95
+ /** True when a settings.json object already carries the guard hook (what `status` checks before healing it). */
96
+ export function hasConfidentialGuard(settings) {
97
+ return (settings?.hooks?.PreToolUse ?? []).some((g) => (g.hooks ?? []).some((h) => h.command === CONFIDENTIAL_GUARD_COMMAND))
98
+ }
99
+
100
+ /**
101
+ * SessionStart self-heal (`status`): copy the guard, and add ONLY its hook to settings.json when it is missing —
102
+ * nothing else in the file is touched. A malformed settings.json is left alone. Takes effect from the next session,
103
+ * since Claude Code reads hooks when a session starts.
104
+ */
105
+ export function healConfidentialGuard({ home = homedir() } = {}) {
106
+ installConfidentialGuard({ home })
107
+ const file = join(home, '.claude', 'settings.json')
108
+ if (!existsSync(file)) return false
109
+ const s = JSON.parse(readFileSync(file, 'utf8'))
110
+ if (hasConfidentialGuard(s)) return false
111
+ s.hooks = s.hooks ?? {}
112
+ s.hooks.PreToolUse = Array.isArray(s.hooks.PreToolUse) ? s.hooks.PreToolUse : []
113
+ s.hooks.PreToolUse.push({ matcher: CONFIDENTIAL_GUARD_MATCHER, hooks: [{ type: 'command', command: CONFIDENTIAL_GUARD_COMMAND }] })
114
+ writeFileSync(file, JSON.stringify(s, null, 2))
115
+ return true
116
+ }
117
+
78
118
  /** Merge Agnoclast's Claude Code hooks into a ~/.claude/settings.json object. Pure + idempotent: drops
79
119
  * any prior cortex entry (old token/path/version) from each hook array before appending the current
80
120
  * one — capture (Stop), status + skills-repair + snapshot-context (SessionStart), hydrate
@@ -211,6 +251,20 @@ export function mergeClaudeSettings(existing, spec) {
211
251
  }
212
252
  hgrp.hooks.push({ type: 'command', command: arrivalsEmitCmd })
213
253
 
254
+ // PreToolUse — the confidential-brain guard (lib/confidential_guard.mjs; Theron, 2026-10-28). Once a session is
255
+ // locked into a confidential brain, it refuses Agnoclast tools reached through any connection other than the local
256
+ // server (a claude.ai connector sends no session id, so the server cannot bind it to the lock).
257
+ //
258
+ // ⚠ IT RUNS ON EVERY MCP CALL, SO IT IS NOT AN NPX COMMAND. Plain `node` on a file setup copies into ~/.cortex/hooks,
259
+ // behind a directory test: a machine that has never locked a session into a confidential brain pays one `[ -d ]`.
260
+ // It answers with a JSON decision and always exits 0, so the trailing `|| true` cannot swallow a refusal.
261
+ s.hooks.PreToolUse = Array.isArray(s.hooks.PreToolUse) ? s.hooks.PreToolUse : []
262
+ for (const pg of s.hooks.PreToolUse) {
263
+ if (Array.isArray(pg.hooks)) pg.hooks = pg.hooks.filter((h) => !isManagedSubcommand(h.command, 'confidential-guard'))
264
+ }
265
+ s.hooks.PreToolUse = s.hooks.PreToolUse.filter((g) => (g.hooks ?? []).length)
266
+ s.hooks.PreToolUse.push({ matcher: CONFIDENTIAL_GUARD_MATCHER, hooks: [{ type: 'command', command: CONFIDENTIAL_GUARD_COMMAND }] })
267
+
214
268
  // PreCompact — REMOVED, and this block is the migration that unwires existing seats.
215
269
  //
216
270
  // The "author now" reminder wrote to stdout on the assumption the harness surfaced it as context for
@@ -289,6 +343,7 @@ export default {
289
343
  const bak = backupFile(settingsJson)
290
344
  ensureDir(settingsJson)
291
345
  writeJson(settingsJson, mergeClaudeSettings(s, spec))
346
+ installConfidentialGuard({ home })
292
347
  wrote.push(settingsJson)
293
348
  log(` ✓ Capture + hydrate hooks + status line → ${settingsJson}${bak ? ' (backup saved)' : ''}`)
294
349
  } catch (e) {
@@ -1,5 +1,5 @@
1
1
  import { homedir } from 'node:os'
2
- import { existsSync } from 'node:fs'
2
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs'
3
3
  import { join } from 'node:path'
4
4
  import { readJson, backupFile, ensureDir, writeJson } from './editors/_fsutil.mjs'
5
5
  import { allowedToolsFor } from './editors/claude.mjs'
@@ -41,6 +41,13 @@ export function migratedMcpServers(servers) {
41
41
  const out = { ...(servers ?? {}) }
42
42
  if (out[NEW_KEY] && !out[OLD_KEY]) return { servers: out, moved: false, reason: 'already-new-key' }
43
43
  if (!out[OLD_KEY]) return { servers: out, moved: false, reason: 'no-entry' }
44
+ // BOTH keys (a pre-0.9.277 setup re-created `cortex` beside a migrated `agnoclast`): the new key is
45
+ // the one to keep — it is the one the person or a newer setup last chose. Copying `cortex` over it
46
+ // would carry the older spec across, which is how a @latest seat gets knocked back to @stable.
47
+ if (out[NEW_KEY]) {
48
+ delete out[OLD_KEY]
49
+ return { servers: out, moved: true, reason: 'dropped-duplicate' }
50
+ }
44
51
  // Carry the entry across untouched: command, args (the package spec) and env all survive, so a
45
52
  // dogfooder pinned to @latest stays pinned and the token is not re-derived.
46
53
  out[NEW_KEY] = out[OLD_KEY]
@@ -79,14 +86,18 @@ export function runKeyMigration({ home = homedir(), dryRun = false, io = {} } =
79
86
  const statePath = migrationStatePath(home)
80
87
  const required = allowedToolsFor(NEW_KEY)
81
88
 
82
- if (exists(statePath)) {
83
- try { if (read(statePath)?.to === NEW_KEY) return { status: 'already', statePath } } catch { /* re-run */ }
84
- }
85
-
89
+ // The config is checked BEFORE the state file. The state file used to short-circuit on its own, so
90
+ // a `cortex` entry re-created after the flip (an older setup run, 2026-10) was never looked at
91
+ // again. "Done" is only true while the config agrees.
86
92
  let cfg
87
93
  try { cfg = read(claudeJson) } catch (e) { return { status: 'aborted', step: 'read-config', reason: e.message } }
88
94
  const plan = migratedMcpServers(cfg?.mcpServers)
89
- if (!plan.moved) return { status: 'nothing-to-migrate', reason: plan.reason }
95
+ if (!plan.moved) {
96
+ if (exists(statePath)) {
97
+ try { if (read(statePath)?.to === NEW_KEY) return { status: 'already', statePath } } catch { /* fall through */ }
98
+ }
99
+ return { status: 'nothing-to-migrate', reason: plan.reason }
100
+ }
90
101
 
91
102
  // ── 1+2. Allowlist FIRST, then verify from disk. ───────────────────────────
92
103
  let settings
@@ -130,10 +141,73 @@ export function runKeyMigration({ home = homedir(), dryRun = false, io = {} } =
130
141
  if (!cfgAfter?.mcpServers?.[NEW_KEY]) {
131
142
  return { status: 'aborted', step: 'verify-config', reason: 'config key did not persist' }
132
143
  }
144
+ if (cfgAfter.mcpServers[OLD_KEY]) {
145
+ return { status: 'aborted', step: 'verify-config', reason: 'old key still present' }
146
+ }
133
147
 
134
148
  // ── 5. Record it. Best-effort: a missing state file only costs an idempotent re-run. ──
135
- const record = { from: OLD_KEY, to: NEW_KEY, allowsAdded: missing.length }
149
+ const record = { from: OLD_KEY, to: NEW_KEY, allowsAdded: missing.length, ...(plan.reason ? { reason: plan.reason } : {}) }
136
150
  try { mkdir(statePath); write(statePath, record) } catch { /* non-fatal */ }
137
151
 
138
152
  return { status: 'migrated', ...record, statePath }
139
153
  }
154
+
155
+ /** PURE. A Codex config.toml with our `cortex` tables renamed to `agnoclast` — or, when `agnoclast`
156
+ * tables are already there, with the `cortex` ones dropped. Returns null when there is nothing to do.
157
+ * Only our two table headers are touched; every other line survives byte for byte. */
158
+ export function migratedCodexToml(text) {
159
+ const lines = (text || '').split('\n')
160
+ const header = (l) => { const t = l.trim(); return t.startsWith('[') && t.endsWith(']') ? t : null }
161
+ const OLD = new Set([`[mcp_servers.${OLD_KEY}]`, `[mcp_servers.${OLD_KEY}.env]`])
162
+ if (!lines.some((l) => OLD.has(header(l)))) return null
163
+ if (lines.some((l) => header(l) === `[mcp_servers.${NEW_KEY}]`)) {
164
+ const kept = []
165
+ let skipping = false
166
+ for (const l of lines) {
167
+ const h = header(l)
168
+ if (h) skipping = OLD.has(h)
169
+ if (!skipping) kept.push(l)
170
+ }
171
+ return kept.join('\n')
172
+ }
173
+ return lines.map((l) => (OLD.has(header(l)) ? l.replace(`mcp_servers.${OLD_KEY}`, `mcp_servers.${NEW_KEY}`) : l)).join('\n')
174
+ }
175
+
176
+ /** Cursor and Codex: the same flip, no allowlist to order against (neither has one). Best-effort per
177
+ * editor; returns what changed. A malformed file is left alone, never rewritten. */
178
+ export function migrateOtherEditors({ home = homedir() } = {}) {
179
+ const changed = []
180
+ const cursor = join(home, '.cursor', 'mcp.json')
181
+ try {
182
+ if (existsSync(cursor)) {
183
+ const cfg = readJson(cursor)
184
+ const plan = migratedMcpServers(cfg?.mcpServers)
185
+ if (plan.moved) { backupFile(cursor); writeJson(cursor, { ...cfg, mcpServers: plan.servers }); changed.push('cursor') }
186
+ }
187
+ } catch { /* leave it */ }
188
+ const codex = join(home, '.codex', 'config.toml')
189
+ try {
190
+ if (existsSync(codex)) {
191
+ const next = migratedCodexToml(readFileSync(codex, 'utf8'))
192
+ if (next !== null) { backupFile(codex); writeFileSync(codex, next); changed.push('codex') }
193
+ }
194
+ } catch { /* leave it */ }
195
+ return changed
196
+ }
197
+
198
+ /** Run at every MCP server start (bin/cortex-mcp.mjs default branch) — the C2 activation that was
199
+ * planned in ADR-0033 and never wired, so seats that were told "it will happen for you" kept the
200
+ * `cortex` key for months. NEVER throws and NEVER writes stdout: stdout is the MCP stdio channel.
201
+ * The new name takes effect at the editor's next start; the running session keeps its servers. */
202
+ export function autoMigrateKeys({ home = homedir(), log = (m) => process.stderr.write(m + '\n') } = {}) {
203
+ try {
204
+ const res = runKeyMigration({ home })
205
+ const others = migrateOtherEditors({ home })
206
+ if (res.status === 'migrated' || others.length) {
207
+ log(`agnoclast: renamed the \`${OLD_KEY}\` MCP entry to \`${NEW_KEY}\` (${[res.status === 'migrated' ? 'claude' : null, ...others].filter(Boolean).join(', ')}); takes effect next restart`)
208
+ }
209
+ return { claude: res, others }
210
+ } catch (e) {
211
+ return { claude: { status: 'aborted', step: 'unexpected', reason: e?.message }, others: [] }
212
+ }
213
+ }
package/lib/server.mjs CHANGED
@@ -12,7 +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 { aiAccountOf, confidentialBrainNamed, fetchMyConfidential, gatherAgentProof, markLockedIn, requestSeatToken } from './confidential_session.mjs'
15
+ import { aiAccountOf, confidentialBrainNamed, fetchMyConfidential, gatherAgentProof, lockStateLine, 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'
@@ -323,7 +323,7 @@ export async function runServer(version) {
323
323
  lockedInto = first.brain
324
324
  // Nothing from this session may reach a local summarizer, or a hook on the person's ordinary account.
325
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`) }
326
+ try { markLockedIn(SESSION_KEY, lockedInto, { tools: [...toolHandles.keys()] }) } catch (e) { process.stderr.write(`cortex-mcp: could not mark the session confidential: ${e?.message ?? e}\n`) }
327
327
  // Renew a few minutes early, re-proving the account each time: a /login to another account stops the next
328
328
  // renewal, and a renewal that fails leaves a token the server refuses, so the session fails closed.
329
329
  const every = Math.max(60, first.expiresIn - 180) * 1000
@@ -504,7 +504,12 @@ export async function runServer(version) {
504
504
  const check = await lockedAnswerFor(BASE, TOKEN, name, takesArgs ? args[0] : {}, fetchCortex)
505
505
  if (!check.run) return { content: [{ type: 'text', text: check.text }] }
506
506
  }
507
- return handler(...args)
507
+ const result = await handler(...args)
508
+ // Locked in: every result says so (Theron, 2026-10-28), so an AI never mistakes which state the session is in.
509
+ if (lockedInto && Array.isArray(result?.content)) {
510
+ return { ...result, content: [...result.content, { type: 'text', text: lockStateLine({ lockedInto }) }] }
511
+ }
512
+ return result
508
513
  }))
509
514
  toolHandles.set(name, { handle, description: config?.description })
510
515
  return handle
@@ -4963,11 +4968,11 @@ function renderNudge(payload) {
4963
4968
  : 'Your brains (reads span all of them; an edit routes to the brain holding the page; creating a NEW page takes an explicit `brain`):'
4964
4969
  // Confidential brains are reached through a seat, so /api/brains never lists them: say they exist and how
4965
4970
  // 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
+ // The session's actual state is asked of the server, so it is never inferred (the wrapper adds the locked-in line).
4972
+ const now = !lockedInto && confidential.brains.length
4973
+ ? await fetchMyConfidential({ base: BASE, token: TOKEN, proof: null, fetchImpl: fetchCortex })
4974
+ : null
4975
+ const seats = now ? `\n\n${lockStateLine({ lock: now.lock, brains: confidential.brains })}` : ''
4971
4976
  return { content: [{ type: 'text', text: `${header}\n${lines.join('\n')}${seats}` }] }
4972
4977
  },
4973
4978
  )
package/lib/setup.mjs CHANGED
@@ -6,7 +6,7 @@ import { resolveChannel } from './channel.mjs'
6
6
  import { installSkills } from './skills.mjs'
7
7
  // Pure config-merge functions live in the editor adapters; setup imports (and re-exports) THE SAME
8
8
  // functions the `cortex install` path uses, so both write byte-identical config.
9
- import { mergeClaudeMcp, mergeClaudeSettings } from './editors/claude.mjs'
9
+ import { mergeClaudeMcp, mergeClaudeSettings, installConfidentialGuard } from './editors/claude.mjs'
10
10
  import { mergeCodexToml, mergeCodexHooks } from './editors/codex.mjs'
11
11
 
12
12
  // One-command employee onboarding. Wires both:
@@ -154,6 +154,7 @@ export async function runSetup(argv, version) {
154
154
  // merge — the same pure function the `cortex install` Claude adapter uses. Also unwires the retired
155
155
  // PreCompact reminder from seats that still carry it.
156
156
  s = mergeClaudeSettings(s, spec)
157
+ installConfidentialGuard()
157
158
 
158
159
  ensureDir(settingsJson)
159
160
  writeFileSync(settingsJson, JSON.stringify(s, null, 2))
package/lib/uninstall.mjs CHANGED
@@ -31,7 +31,7 @@ const CORTEX_DIR = join(HOME, '.cortex')
31
31
  const LAUNCH_AGENTS = join(HOME, 'Library', 'LaunchAgents')
32
32
  // Hook events the installer writes (editors/claude.mjs). UserPromptSubmit was MISSING here until
33
33
  // 2026-08-19, so every uninstall left the `hydrate` hook behind while reporting success.
34
- export const MANAGED_HOOK_EVENTS = ['Stop', 'SessionStart', 'UserPromptSubmit', 'PreCompact']
34
+ export const MANAGED_HOOK_EVENTS = ['Stop', 'SessionStart', 'UserPromptSubmit', 'PreCompact', 'PreToolUse']
35
35
 
36
36
  export function runUninstall(argv = []) {
37
37
  const dry = argv.includes('--dry-run') || argv.includes('-n')
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theronap/agnoclast-mcp",
3
- "version": "0.9.278",
3
+ "version": "0.9.280",
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": {