@theronap/agnoclast-mcp 0.9.271 → 0.9.273

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
@@ -132,6 +132,11 @@ export function formatPressing(pressing) {
132
132
  } else if (p?.kind === 'declined') {
133
133
  lines.push(`↩ ${who(p.by)} DECLINED ${named(p.text)}: ${named(p.reason)}. It is still yours. (${p.obligationId})`)
134
134
  }
135
+ // ADR-0100 — another of the person's own sessions asks THIS session to hand over an obligation it holds.
136
+ // Session business: answer it yourself; mention it to the user only if you cannot tell which is right.
137
+ else if (p?.kind === 'hold_request') {
138
+ lines.push(`🤝 Another of your sessions asks THIS session to hand over ${named(p.text)}${p.note ? ` — its note: ${named(p.note)}` : ''}. If you are not actively on it, hand it over: \`answer_hold_request\` hand_over: true; otherwise hand_over: false and keep it. (${p.obligationId})`)
139
+ }
135
140
  // 2026-10-12 — recordings. Nothing arrived for an in-person recording (fix 4), or a meeting unit
136
141
  // with a fully deterministic home has waited in intake (fix 5 — a notice; nothing is auto-filed).
137
142
  else if (p?.kind === 'meeting_missing') {
@@ -168,7 +173,7 @@ export function pressingAcks(pressing) {
168
173
  const out = []
169
174
  for (const p of Array.isArray(pressing) ? pressing : []) {
170
175
  if (typeof p?.subject !== 'string' || typeof p?.bucket !== 'string') continue
171
- const handoff = p.kind === 'asked' || p.kind === 'given' || p.kind === 'declined' || p.kind === 'lapsed'
176
+ const handoff = p.kind === 'asked' || p.kind === 'given' || p.kind === 'declined' || p.kind === 'lapsed' || p.kind === 'hold_request'
172
177
  || p.kind === 'meeting_missing' || p.kind === 'meeting_waiting'
173
178
  const rollup = (p.kind === 'due_today' || p.kind === 'work_now') && Number(p.count) > 0
174
179
  if (p.kind === 'event' || p.kind === 'record_offer' || p.kind === 'due_soon' || handoff || rollup) {
@@ -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'. */
@@ -51,6 +51,9 @@ export const ALLOWED_TOOL_NAMES = [
51
51
  'set_page_validity', 'snooze_red_link', 'attribute_thread',
52
52
  // clears only the caller's OWN notice that a page was handed to them; the page is already theirs
53
53
  'confirm_page_ownership',
54
+ // ADR-0100: which of the caller's OWN sessions is working on one of their obligations. Changes no owner, tier
55
+ // or page, and a prompt on each would make sessions skip the step that stops two of them doing the same work
56
+ 'take_obligation', 'release_obligation', 'request_obligation', 'answer_hold_request',
54
57
  ]
55
58
 
56
59
  // ⚠ DELIBERATELY ABSENT, and not an oversight to be tidied up later: `grant_page_access`,
@@ -129,6 +129,8 @@ export function renderObligations(obs, now = Date.now(), extras = null) {
129
129
  // Whose idea it was, and whether it is on its way to someone else. Both change what to DO with it.
130
130
  if (o.askedBy) lines.push(` asked for by ${who(o.askedBy)}`)
131
131
  if (o.offeredTo) lines.push(` offered to ${who(o.offeredTo)} — waiting for their answer; still yours until they accept`)
132
+ const hold = holdLine(o.hold, o.holdRequest, now)
133
+ if (hold) lines.push(hold)
132
134
  // ⚠ EVIDENCE IS RENDERED AS A QUESTION, NEVER AS A VERDICT. The phrasing is the feature:
133
135
  // "is this done?" costs the reader a second, "you still owe this" about finished work costs
134
136
  // the channel its credibility.
@@ -162,3 +164,29 @@ function windowNote(workFrom, now) {
162
164
  if (!workFrom) return ''
163
165
  return new Date(workFrom).getTime() <= now ? ` · IN ITS WORK WINDOW since ${String(workFrom).slice(0, 10)}` : ` · work from ${String(workFrom).slice(0, 10)}`
164
166
  }
167
+
168
+ /**
169
+ * ADR-0100 — which of the person's sessions is working on it. PURE. `now` is ms.
170
+ * A hold is not ownership: it is one of the SAME person's sessions saying "I'm on this".
171
+ */
172
+ export function holdLine(hold, request, now) {
173
+ if (!hold || typeof hold !== 'object') return null
174
+ const ago = (iso) => {
175
+ const m = Math.max(0, Math.round((now - new Date(iso).getTime()) / 60000))
176
+ return m < 60 ? `${m} min ago` : m < 2880 ? `${Math.round(m / 60)} h ago` : `${Math.round(m / 1440)} days ago`
177
+ }
178
+ const clean = (s, n) => String(s ?? '').replace(/\s+/g, ' ').trim().slice(0, n)
179
+ const note = hold.note ? ` · “${clean(hold.note, 100)}”` : ''
180
+ const where = hold.cwd ? clean(hold.cwd, 80) : 'a session'
181
+ const seen = hold.lastSeen ? `active ${ago(hold.lastSeen)}` : `taken ${ago(hold.heldAt)}`
182
+ let line
183
+ if (hold.mine) line = ` ⛳ held by THIS session${note}`
184
+ else if (hold.status === 'lapsed') line = ` ⛳ last held by ${where}${note}, quiet since ${ago(hold.lastSeen ?? hold.heldAt)} — LAPSED: take_obligation to pick it up`
185
+ else line = ` ⛳ held by another session (${where}${note}), ${seen}${hold.status === 'away' ? ', not running now' : ''} — leave it, or request_obligation`
186
+ if (request) {
187
+ line += request.mine
188
+ ? '\n ⏳ you asked for it — waiting on the holding session'
189
+ : `\n 🤝 another session asks for it${request.note ? `: “${clean(request.note, 100)}”` : ''} — answer_hold_request`
190
+ }
191
+ return line
192
+ }
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'
@@ -21,7 +22,7 @@ import { runCodeGraphQuery } from './code_graph_cli.mjs'
21
22
  import { repoFullNameFrom, workingFilesFrom } from './capture.mjs'
22
23
  import { findTranscript, createWorkedFilesTracker } from './working_files.mjs'
23
24
  import { spawnObligationWorker } from './obligations_worker.mjs'
24
- import { renderObligations, renderPageObligations, tierReads, who } from './obligations_render.mjs'
25
+ import { renderObligations, renderPageObligations, tierReads, who, holdLine } from './obligations_render.mjs'
25
26
  import { renderLeaveQuestion, renderLeft, renderRemovalQuestion, renderRemoved } from './member_remove_render.mjs'
26
27
  import { renderSettings } from './settings_render.mjs'
27
28
  import { renderConversationOffer, renderMaterializeBatch, renderPreviewBatch } from './intake_batch_render.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).
@@ -3248,9 +3279,10 @@ function renderNudge(payload) {
3248
3279
  limit: z.number().optional().describe('default 50'),
3249
3280
  page: z.string().optional().describe("a page's `ref:` as read_page prints it. Lists EVERYONE's open obligations on that page that the person may see — theirs first, then other people's under each owner's name. Use it when a page read says other people have obligations there and the person asks to see them; seeing one does not make it theirs."),
3250
3281
  owed_to: z.string().optional().describe("a person's page `ref:` — only what the person owes THEM (\"what do I owe Tanner?\"), across every page"),
3282
+ unheld: z.boolean().optional().describe('true = leave out what ANOTHER of the person\'s sessions is working on (holds it with take_obligation). "What is nobody on?"'),
3251
3283
  },
3252
3284
  },
3253
- async ({ closed, limit, page, owed_to }) => {
3285
+ async ({ closed, limit, page, owed_to, unheld }) => {
3254
3286
  let res
3255
3287
  if (page) {
3256
3288
  try {
@@ -3265,6 +3297,7 @@ function renderNudge(payload) {
3265
3297
  if (closed) qs.set('closed', 'true')
3266
3298
  if (limit) qs.set('limit', String(limit))
3267
3299
  if (owed_to) qs.set('owedTo', owed_to.trim())
3300
+ if (unheld) qs.set('unheld', 'true')
3268
3301
  res = await fetchCortex(`${BASE}/api/obligations?${qs}`, { headers: { Authorization: `Bearer ${TOKEN}` } })
3269
3302
  } catch (e) { return toolError(`Could not reach obligations: ${e.message}`) }
3270
3303
  const out = await res.json().catch(() => null)
@@ -3274,6 +3307,108 @@ function renderNudge(payload) {
3274
3307
  },
3275
3308
  )
3276
3309
 
3310
+ // ADR-0100 — one of the person's sessions says "I'm on this". Not ownership: the obligation stays the person's.
3311
+ const holdCall = async (action, body) => {
3312
+ let res
3313
+ try {
3314
+ res = await fetchCortex(`${BASE}/api/obligations/hold`, {
3315
+ method: 'POST',
3316
+ headers: { Authorization: `Bearer ${TOKEN}`, 'Content-Type': 'application/json' },
3317
+ body: JSON.stringify({ action, ...body }),
3318
+ })
3319
+ } catch (e) { return { error: `Could not reach obligations: ${e.message}` } }
3320
+ return { status: res.status, out: await res.json().catch(() => null) }
3321
+ }
3322
+ const holdError = (r) => {
3323
+ if (r.error) return toolError(r.error)
3324
+ const e = r.out?.error
3325
+ const by = r.out?.hold ? holdLine(r.out.hold, r.out.request ?? null, Date.now())?.trim() : ''
3326
+ const say = {
3327
+ no_session: 'This client has no session key, so it cannot hold anything. Only a local cortex-mcp session can.',
3328
+ bad_id: 'That is not an obligation id. Use the full id my_obligations prints.',
3329
+ not_found: 'No obligation of yours has that id. List them with my_obligations.',
3330
+ closed: 'It is already discharged or cancelled.',
3331
+ held: `Another session holds it. ${by}\nAsk it with request_obligation; take it with force only if the person says to.`,
3332
+ not_holder: `This session does not hold it. ${by}`,
3333
+ not_held: 'No session holds it.',
3334
+ no_request: 'Nobody has asked for it.',
3335
+ }
3336
+ return toolError(say[e] ?? `Could not do that: ${e ?? r.status}`)
3337
+ }
3338
+
3339
+ server.registerTool(
3340
+ 'take_obligation',
3341
+ {
3342
+ title: 'Work on an obligation in this session',
3343
+ description: "Say THIS session is working on one of the person's obligations, so their other sessions see it in my_obligations and leave it alone. Do it when you START work on something the person owes. It is not ownership: the obligation stays theirs, and nothing about who owes it changes. Refused while another session holds it: ask that session with request_obligation instead. A hold lasts while this session runs and while no session runs; it lapses once this session has been gone for 2 hours while another is running. Give it up with release_obligation when you stop; resolve_obligation ends it too.",
3344
+ inputSchema: {
3345
+ obligation_id: z.string().describe('the full id from my_obligations'),
3346
+ note: z.string().optional().describe('what this session is doing about it, in a few words — other sessions see it'),
3347
+ force: z.boolean().optional().describe('take it even though another session holds it. ONLY when the person tells you to.'),
3348
+ },
3349
+ },
3350
+ async ({ obligation_id, note, force }) => {
3351
+ const r = await holdCall('take', { obligationId: obligation_id.trim(), note, force })
3352
+ if (r.error || !r.out?.ok) return holdError(r)
3353
+ const o = r.out
3354
+ const said = {
3355
+ taken: 'This session now holds it.',
3356
+ already_yours: 'This session already holds it.' + (note ? ' Note updated.' : ''),
3357
+ replaced: `This session now holds it, replacing another session's hold.${o.replaced ? ` That was: ${holdLine(o.replaced, null, Date.now())?.trim()}` : ''}`,
3358
+ }
3359
+ return { content: [{ type: 'text', text: `${said[o.outcome] ?? o.outcome} Other sessions now see it as in progress. release_obligation when you stop.` }] }
3360
+ },
3361
+ )
3362
+
3363
+ server.registerTool(
3364
+ 'release_obligation',
3365
+ {
3366
+ title: 'Stop working on an obligation in this session',
3367
+ description: "Give up THIS session's hold on an obligation, so another session can pick it up. Use it when you stop working on something without finishing it. It changes nothing else: the obligation stays open and stays the person's. A hold that has lapsed can be released by any session.",
3368
+ inputSchema: { obligation_id: z.string().describe('the full id from my_obligations') },
3369
+ },
3370
+ async ({ obligation_id }) => {
3371
+ const r = await holdCall('release', { obligationId: obligation_id.trim() })
3372
+ if (r.error || !r.out?.ok) return holdError(r)
3373
+ return { content: [{ type: 'text', text: 'Released. No session holds it now; it is still open.' }] }
3374
+ },
3375
+ )
3376
+
3377
+ server.registerTool(
3378
+ 'request_obligation',
3379
+ {
3380
+ title: "Ask another session for an obligation it holds",
3381
+ description: "Ask the session holding one of the person's obligations to hand it to THIS session. That session is told on its next prompt and answers with answer_hold_request; see the answer in my_obligations. If nobody holds it, or the hold has lapsed, this simply takes it.",
3382
+ inputSchema: {
3383
+ obligation_id: z.string().describe('the full id from my_obligations'),
3384
+ note: z.string().optional().describe('why this session wants it, in a few words — the holder reads it'),
3385
+ },
3386
+ },
3387
+ async ({ obligation_id, note }) => {
3388
+ const r = await holdCall('request', { obligationId: obligation_id.trim(), note })
3389
+ if (r.error || !r.out?.ok) return holdError(r)
3390
+ if (r.out.outcome !== 'requested') return { content: [{ type: 'text', text: 'Nobody was holding it, so this session now holds it.' }] }
3391
+ return { content: [{ type: 'text', text: `Asked. ${holdLine(r.out.hold, null, Date.now())?.trim() ?? ''}\nIt is still theirs until they answer; my_obligations shows the answer.` }] }
3392
+ },
3393
+ )
3394
+
3395
+ server.registerTool(
3396
+ 'answer_hold_request',
3397
+ {
3398
+ title: 'Answer another session asking for an obligation',
3399
+ description: "Another of the person's sessions asked THIS session to hand over an obligation it holds. hand_over true gives the hold to that session; false keeps it here. Hand it over unless this session is actively working on it.",
3400
+ inputSchema: {
3401
+ obligation_id: z.string().describe('the full id from the notice or my_obligations'),
3402
+ hand_over: z.boolean().describe('true = give it to the asking session · false = keep it'),
3403
+ },
3404
+ },
3405
+ async ({ obligation_id, hand_over }) => {
3406
+ const r = await holdCall('answer', { obligationId: obligation_id.trim(), handOver: hand_over })
3407
+ if (r.error || !r.out?.ok) return holdError(r)
3408
+ return { content: [{ type: 'text', text: r.out.outcome === 'handed_over' ? 'Handed over. The asking session holds it now.' : 'Kept. This session still holds it; the request is cleared.' }] }
3409
+ },
3410
+ )
3411
+
3277
3412
  server.registerTool(
3278
3413
  'track_obligation',
3279
3414
  {
@@ -7816,3 +7951,14 @@ function renderNudge(payload) {
7816
7951
  lockedTools = applyLock(toolHandles, await lockStateWithin(lockP))
7817
7952
  await server.connect(new StdioServerTransport())
7818
7953
  }
7954
+
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.271",
3
+ "version": "0.9.273",
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": {