@theronap/cortex-mcp 0.9.79 → 0.9.80

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/server.mjs CHANGED
@@ -11,6 +11,7 @@ import { runSendImessage } from './imessage_send.mjs'
11
11
  import { formatGrepHits } from './grep_cli.mjs'
12
12
  import { renderTriage } from './red_link_triage.mjs'
13
13
  import { runCodeGraphQuery } from './code_graph_cli.mjs'
14
+ import { renderTimelineClaimReceipt } from './timeline_claim_receipt.mjs'
14
15
 
15
16
  // Reactive red-link triage (Mechanism 2). On a read_page miss, ask the server whether the name is a
16
17
  // tracked wanted page, whether a bare node exists for it, and whether it's a deliberately demoted page,
@@ -40,7 +41,7 @@ async function redLinkTriage(BASE, TOKEN, name) {
40
41
  // file-request tools, and a module-level `fail` would be silently shadowed by it from that point on.
41
42
  const toolError = (text) => ({ content: [{ type: 'text', text }], isError: true })
42
43
 
43
- // The Cortex MCP server (stdio). Serves the signed-in employee's scoped org
44
+ // The Agnoclast MCP server (stdio). Serves the signed-in employee's scoped org
44
45
  // context to their AI assistant. CORTEX_TOKEN identifies the user + org.
45
46
 
46
47
  export async function runServer(version) {
@@ -48,7 +49,7 @@ export async function runServer(version) {
48
49
  const BASE = resolveBase(process.env.CORTEX_URL)
49
50
 
50
51
  if (!TOKEN) {
51
- process.stderr.write('cortex-mcp: CORTEX_TOKEN is required. Get yours from the Cortex console → Connect your AI.\n')
52
+ process.stderr.write('cortex-mcp: CORTEX_TOKEN is required. Get yours from the Agnoclast console → Connect your AI.\n')
52
53
  process.exit(1)
53
54
  }
54
55
 
@@ -90,7 +91,7 @@ export async function runServer(version) {
90
91
  const now = Date.now()
91
92
  if (cache && now - cache.ts < 5 * 60 * 1000) return cache.text
92
93
  // fetchCortex retries transient infra/5xx; classify turns a failure into an honest message
93
- // (token vs infra-block vs network) instead of a bare "Cortex API 403: unknown".
94
+ // (token vs infra-block vs network) instead of a bare "Agnoclast API 403: unknown".
94
95
  const res = await fetchCortex(`${BASE}/api/mcp-context`, { headers: { Authorization: `Bearer ${TOKEN}` } })
95
96
  if (!res.ok) {
96
97
  const body = await res.text()
@@ -117,7 +118,7 @@ export async function runServer(version) {
117
118
  server.registerTool(
118
119
  'my_context',
119
120
  {
120
- title: 'My Cortex context',
121
+ title: 'My Agnoclast context',
121
122
  description: 'Your current work context from the org. Pass a question to get query-centered session context seeded from the most relevant node and its neighborhood; omit it for the baseline snapshot.',
122
123
  inputSchema: { question: z.string().optional().describe('optional opening user question to center the context around') },
123
124
  },
@@ -137,6 +138,53 @@ export async function runServer(version) {
137
138
  },
138
139
  )
139
140
 
141
+ // Where this machine's unattended session captures land. The server half shipped 2026-08-09 with no
142
+ // client surface at all, so the only way to set it was a hand-written authenticated HTTP call —
143
+ // which meant three real users whose sessions were silently being held could not fix it themselves.
144
+ // This is the surface that makes it answerable in conversation: "put my sessions in TTO".
145
+ server.registerTool(
146
+ 'set_capture_brain',
147
+ {
148
+ title: 'Choose where your session captures are saved',
149
+ description:
150
+ 'Set which brain THIS PERSON\'s unattended session captures (the automatic end-of-session record) land in, or read the current setting by omitting `brain`. WHEN TO USE: whenever the user says their sessions are not being saved, asks where their work is going, or a session-start notice says captures are being HELD. WHY IT IS NEEDED: with more than one brain, a capture that names no brain cannot be routed and is held outside every brain — correct, but invisible, so it accumulates silently. This is per-PERSON and applies to their own captures only; it cannot be set for someone else. ⚠ PASS THE ORG ID when the user has two brains with the SAME NAME (e.g. two called "Personal") — a name matching more than one is REFUSED rather than guessed, and the error lists the ids to choose from. Setting this does NOT file already-held captures; those keep their original dates and may belong in different brains, so sort them deliberately rather than dumping them into the new default.',
151
+ inputSchema: {
152
+ brain: z.string().optional().describe('the brain name or org id (from my_brains) where this person\'s session captures should land. Omit to read the current setting instead of changing it.'),
153
+ },
154
+ },
155
+ async ({ brain }) => {
156
+ const url = `${BASE}/api/brain/capture-default`
157
+ if (!brain?.trim()) {
158
+ const res = await fetchCortex(url, { headers: { Authorization: `Bearer ${TOKEN}` } })
159
+ if (!res.ok) {
160
+ const body = await res.text()
161
+ throw new Error(classify(res.status, res.headers.get('content-type'), body, res.headers.get('x-vercel-id')).message)
162
+ }
163
+ const { defaults } = await res.json()
164
+ if (!defaults?.length) {
165
+ return { content: [{ type: 'text', text: 'No capture brain is set. If you belong to more than one brain, your session captures are being HELD outside every brain until you set one. Call this tool again with `brain` to fix it.' }] }
166
+ }
167
+ const lines = defaults.map((d) => `${d.sourceType} captures land in "${d.orgName}" (${d.orgId}), set ${String(d.updatedAt).slice(0, 10)}`)
168
+ return { content: [{ type: 'text', text: lines.join('\n') }] }
169
+ }
170
+ const res = await fetchCortex(url, {
171
+ method: 'POST',
172
+ headers: { Authorization: `Bearer ${TOKEN}`, 'Content-Type': 'application/json' },
173
+ body: JSON.stringify({ sourceType: 'claude-code', brain: brain.trim() }),
174
+ })
175
+ const body = await res.text()
176
+ if (!res.ok) {
177
+ // Prefer the server's own error: a 409 lists the org ids of an ambiguous name, which IS the
178
+ // remedy, and a generic classification would throw that away.
179
+ let msg
180
+ try { msg = JSON.parse(body).error } catch { /* fall through to the classified message */ }
181
+ throw new Error(msg ?? classify(res.status, res.headers.get('content-type'), body, res.headers.get('x-vercel-id')).message)
182
+ }
183
+ const j = JSON.parse(body)
184
+ return { content: [{ type: 'text', text: `✓ Your Claude Code sessions now land in "${j.brain}" (${j.orgId}). Sessions captured before now are still held and keep their original dates — file those deliberately, they may not all belong in this brain.` }] }
185
+ },
186
+ )
187
+
140
188
  // T8: cortex-log's authoritative writer. The skill composes a curated summary, then calls this to
141
189
  // persist it AS the durable record (capture_source='skill'). The ingest conflict guard ensures the
142
190
  // auto-capture hook never clobbers it. Pass the SAME sessionId the hook uses so the two dedupe onto
@@ -144,8 +192,8 @@ export async function runServer(version) {
144
192
  server.registerTool(
145
193
  'log_session',
146
194
  {
147
- title: 'Log this session to Cortex',
148
- description: 'Persist a CURATED summary of this work session as its durable Cortex record (authoritative — supersedes the auto-capture hook). Call at session close after composing the summary. Pass sessionId (the Claude Code session id) if you have it so this dedupes with the auto-capture of the same session.',
195
+ title: 'Log this session to Agnoclast',
196
+ description: 'Persist a CURATED summary of this work session as its durable Agnoclast record (authoritative — supersedes the auto-capture hook). Call at session close after composing the summary. Pass sessionId (the Claude Code session id) if you have it so this dedupes with the auto-capture of the same session.',
149
197
  inputSchema: {
150
198
  summary: z.string().describe('the curated session summary (what was done, decided, left open) — becomes the durable record'),
151
199
  project: z.string().optional().describe('project key/name this session worked in'),
@@ -172,7 +220,7 @@ export async function runServer(version) {
172
220
  throw new Error(classify(res.status, res.headers.get('content-type'), body, res.headers.get('x-vercel-id')).message)
173
221
  }
174
222
  const j = await res.json().catch(() => ({}))
175
- return { content: [{ type: 'text', text: `Logged to Cortex (authoritative): "${j.title ?? title ?? 'session'}" — ${j.inserted ? 'new record' : 'updated existing'}.` }] }
223
+ return { content: [{ type: 'text', text: `Logged to Agnoclast (authoritative): "${j.title ?? title ?? 'session'}" — ${j.inserted ? 'new record' : 'updated existing'}.` }] }
176
224
  },
177
225
  )
178
226
 
@@ -252,8 +300,12 @@ export async function runServer(version) {
252
300
  const body = await res.text()
253
301
  throw new Error(classify(res.status, res.headers.get('content-type'), body, res.headers.get('x-vercel-id')).message)
254
302
  }
255
- const { threads, records } = await res.json()
256
- if (!threads?.length && !records?.length) return { content: [{ type: 'text', text: 'Nothing in the backlog — everything captured so far has been claimed.' }] }
303
+ const { threads, records, claim } = await res.json()
304
+ const receipt = renderTimelineClaimReceipt(claim)
305
+ if (!threads?.length && !records?.length) {
306
+ const empty = 'Nothing in the backlog — everything captured so far has been claimed.'
307
+ return { content: [{ type: 'text', text: receipt ? `${empty}\n\n${receipt}` : empty }] }
308
+ }
257
309
 
258
310
  const sections = []
259
311
 
@@ -282,32 +334,44 @@ export async function runServer(version) {
282
334
  sections.push(`Unclaimed records (${records.length}) from other sources — newest first:\n${lines.join('\n')}`)
283
335
  }
284
336
 
337
+ if (receipt) sections.push(receipt)
285
338
  return { content: [{ type: 'text', text: sections.join('\n\n') }] }
286
339
  },
287
340
  )
288
341
 
342
+ // Read-only evidence status for the Gate 4 live trial. This MUST remain an aggregate query: a
343
+ // monitor needs to know whether enough sessions have exercised the loop, not who they were or what
344
+ // work they handled. In particular, it must never call timeline_pull as a shortcut, since that would
345
+ // manufacture the evidence it claims to observe.
289
346
  server.registerTool(
290
- 'maintenance_candidates',
347
+ 'gate4_status',
291
348
  {
292
- title: 'Review recent project-linked maintenance evidence',
293
- description: 'Start here when preparing a handoff, status, or next step for a NAMED project. Returns a bounded, RLS-scoped set of recent raw records already linked to that project, before you trust the authored page. These are candidate evidence, not a command to edit: read them, call project_status, then decide whether a material contradiction warrants a minimal accountable correction. Never mutate merely to clear a candidate.',
349
+ title: 'Gate 4 live-evidence status',
350
+ description: 'Read the aggregate, rolling-window status of the Gate 4 trial. This does not claim, attribute, resolve, or expose captured work. It reports machine-observable session, attribution, and recovery counts; a human still confirms that the qualifying sessions were normal work.',
294
351
  inputSchema: {
295
- project: z.string().describe('the project key from the task, e.g. "checkout-v2"'),
296
- since_days: z.number().optional().describe('how far back to inspect (1-90 days, default 30)'),
297
- limit: z.number().optional().describe('max candidate records (1-50, default 20)'),
352
+ days: z.number().optional().describe('rolling observation window in days (default 14; capped at 30)'),
298
353
  },
299
354
  },
300
- async ({ project, since_days, limit }) => {
301
- const qs = new URLSearchParams({ project })
302
- if (since_days != null) qs.set('since_days', String(since_days))
303
- if (limit != null) qs.set('limit', String(limit))
304
- const res = await fetchCortex(`${BASE}/api/maintenance/candidates?${qs}`, { headers: { Authorization: `Bearer ${TOKEN}` } })
355
+ async ({ days }) => {
356
+ const qs = typeof days === 'number' ? `?days=${encodeURIComponent(String(days))}` : ''
357
+ const res = await fetchCortex(`${BASE}/api/timeline/observation${qs}`, { headers: { Authorization: `Bearer ${TOKEN}` } })
305
358
  if (!res.ok) {
306
359
  const body = await res.text()
307
360
  throw new Error(classify(res.status, res.headers.get('content-type'), body, res.headers.get('x-vercel-id')).message)
308
361
  }
309
- const { text } = await res.json()
310
- return { content: [{ type: 'text', text }] }
362
+ const s = await res.json()
363
+ const machine = s.machineEvidencePassed ? 'MET' : 'NOT YET MET'
364
+ return {
365
+ content: [{ type: 'text', text:
366
+ `Gate 4 evidence, last ${s.window?.days ?? 14} days\n` +
367
+ `- session claims: ${s.sessionCount ?? 0}/3\n` +
368
+ `- session-attributed completions: ${s.attributedDone ?? 0} (need 1+)\n` +
369
+ `- expiry recoveries: ${s.recoveredClaims ?? 0} (need 1+)\n` +
370
+ `- anonymous session claims: ${s.anonymousSessionClaims ?? 0} (need 0)\n` +
371
+ `- non-session rows in window (reported, excluded): ${s.nonSessionClaims ?? 0}\n\n` +
372
+ `Machine evidence: ${machine}. Human attestation remains required: qualifying sessions must be normal work, not a staged demo.`,
373
+ }],
374
+ }
311
375
  },
312
376
  )
313
377
 
@@ -379,7 +443,7 @@ export async function runServer(version) {
379
443
  {
380
444
  title: 'Query the local code structure graph (graphify)',
381
445
  description:
382
- 'Query a structural code graph for the repo at the CURRENT working directory, built locally by graphify (tree-sitter AST — deterministic, no LLM, no server round-trip; this is LOCAL MACHINE data, not org-shared Cortex content, and reflects a snapshot of one commit, not live files). Use for MULTI-HOP questions a single grep cannot answer: what calls/imports/depends on X, how A structurally reaches B, or a repo-wide overview (hub/community files). Do NOT use for single-hop lookups (does file X import Y) — grep is faster and always current. Structure only — it knows what imports/calls what, never WHY; read the actual files or authored Cortex pages for intent.',
446
+ 'Query a structural code graph for the repo at the CURRENT working directory, built locally by graphify (tree-sitter AST — deterministic, no LLM, no server round-trip; this is LOCAL MACHINE data, not org-shared Agnoclast content, and reflects a snapshot of one commit, not live files). Use for MULTI-HOP questions a single grep cannot answer: what calls/imports/depends on X, how A structurally reaches B, or a repo-wide overview (hub/community files). Do NOT use for single-hop lookups (does file X import Y) — grep is faster and always current. Structure only — it knows what imports/calls what, never WHY; read the actual files or authored Agnoclast pages for intent.',
383
447
  inputSchema: {
384
448
  action: z.enum(['query', 'path', 'explain']).describe('"query" = open-ended natural-language question (graph traversal); "path" = shortest structural path between two named nodes; "explain" = describe one node and list its direct connections'),
385
449
  question: z.string().optional().describe('required for action:"query" — the natural-language question'),
@@ -444,7 +508,7 @@ export async function runServer(version) {
444
508
  description:
445
509
  'READ the full authored wiki page for one node (project/person/org/you) by its canonical name — every section, every tier you can see. This is how you READ a node; `grep` only LOCATES pages (snippets + their [[links]]), it does not read them. Navigate like a researcher: read the page you need, then FOLLOW its inline [[links]] by calling read_page on each linked name — keep following while the linked pages stay relevant, stop when they do not. You decide how deep to go. Returns only what you are permitted to see.',
446
510
  inputSchema: {
447
- name: z.string().describe('the canonical node name exactly as written (e.g. "Cortex", "Ben", or a [[link]] target) — identifier links ([[repo:owner/name]]) resolve to their authored HOME + a visible-event count'),
511
+ name: z.string().describe('the canonical node name exactly as written (e.g. "Agnoclast", "Ben", or a [[link]] target) — identifier links ([[repo:owner/name]]) resolve to their authored HOME + a visible-event count'),
448
512
  kind: z.enum(['project', 'person', 'org', 'user']).optional().describe('node kind (default project; pass person/org for people/teams)'),
449
513
  expand: z.boolean().optional().describe('identifier names only: also list recent visible timeline events for this identifier (default: home + count)'),
450
514
  history: z.boolean().optional().describe('node names only: return the node\'s TIMELINE (events joined via its [[repo:…]] stamps, reverse-chron, viewer-visible) instead of the page body. The page is the present; this is the history.'),
@@ -618,7 +682,7 @@ export async function runServer(version) {
618
682
  title: 'See a wiki page\'s edit history',
619
683
  description: 'Show the VERSION history of an authored wiki page — every prior version, who changed it and when, newest first. This is how you see "what changed on this page and by whom", and it includes privacy changes (re-tiers). Then use `read_page` with a version to view an old body, or `rollback_page` to restore one. (Distinct from read_page\'s `history: true`, which is the raw event timeline via [[repo:…]] stamps.) RLS-scoped: you see history only for pages you may read.',
620
684
  inputSchema: {
621
- name: z.string().describe('the canonical node name exactly as written (e.g. "Cortex", "Ben")'),
685
+ name: z.string().describe('the canonical node name exactly as written (e.g. "Agnoclast", "Ben")'),
622
686
  kind: z.enum(['project', 'person', 'org', 'user']).optional().describe('node kind (default project)'),
623
687
  limit: z.number().int().optional().describe('how many recent versions to show (default 20, max 200)'),
624
688
  },
@@ -744,7 +808,14 @@ export async function runServer(version) {
744
808
  }
745
809
  const out = await res.json().catch(() => null)
746
810
  if (!res.ok) return toolError(`Could not roll back "${name}": ${out?.error ?? res.status}`)
747
- return { content: [{ type: 'text', text: `Done "${name}" ${out.note}. \`read_page "${name}"\` to confirm the current content.` }] }
811
+ // #477: when the target revision had no summary, the page's CURRENT summary was kept rather than
812
+ // erased. Say it on its own line instead of at the tail of `note` — this is the 2026-08-04 W3
813
+ // shape, where empty summaries copied over populated ones destroyed 31 of them under a report
814
+ // that read as success. A rescue the operator does not see is still a silent write.
815
+ const keptLine = out.summaryKept === 'current'
816
+ ? `\n\n⚠ That revision had NO summary, so the page's current summary was KEPT rather than erased — check it still describes the restored body, and use set_summary if not.`
817
+ : ''
818
+ return { content: [{ type: 'text', text: `Done — "${name}" ${out.note}. \`read_page "${name}"\` to confirm the current content.${keptLine}` }] }
748
819
  },
749
820
  )
750
821
 
@@ -910,13 +981,15 @@ export async function runServer(version) {
910
981
  'writing_style',
911
982
  {
912
983
  title: 'How the user writes (for drafting in their voice)',
913
- description: 'Returns the user\'s saved writing-style profile so you can DRAFT in their voice (email, message, doc). Call this right before composing anything on their behalf. Self-only — it is always the calling user\'s own profile. If none is saved, it tells you to derive one and save it with set_writing_style.',
914
- inputSchema: {},
984
+ description: 'Returns the user\'s saved writing-style profile so you can DRAFT in their voice (email, message, doc). Call this right before composing anything on their behalf. Self-only — it is always the calling user\'s own profile. If none is saved, it tells you to derive one and save it with set_writing_style. A profile is stored per (user, BRAIN) — it is injected into authoring IN a brain — so if you hold several, name the one you are drafting in.',
985
+ inputSchema: {
986
+ brain: z.string().optional().describe('which brain\'s style profile, by name or org id. Unnecessary when you only have one brain; pass the org id when a name matches more than one of yours'),
987
+ },
915
988
  },
916
- async () => {
989
+ async ({ brain } = {}) => {
917
990
  let res
918
991
  try {
919
- res = await fetchCortex(`${BASE}/api/style`, { headers: { Authorization: `Bearer ${TOKEN}` } })
992
+ res = await fetchCortex(`${BASE}/api/style${brain ? `?brain=${encodeURIComponent(brain)}` : ''}`, { headers: { Authorization: `Bearer ${TOKEN}` } })
920
993
  } catch (e) {
921
994
  return toolError(`Could not load writing style: ${e.message}`)
922
995
  }
@@ -934,12 +1007,15 @@ export async function runServer(version) {
934
1007
  {
935
1008
  title: 'Save the user\'s writing-style profile',
936
1009
  description: 'Save (or update) a description of HOW the user writes — tone, sentence rhythm, structure, formatting habits, signature quirks — derived from prose you have seen them write this session. Store the STYLE, never their private content. Self-only: it always updates the calling user\'s own profile. Pass an empty string to clear it.',
937
- inputSchema: { style_md: z.string().describe('a concise markdown description of the user\'s writing voice (tone/structure/quirks), ~1-2 paragraphs') },
1010
+ inputSchema: {
1011
+ style_md: z.string().describe('a concise markdown description of the user\'s writing voice (tone/structure/quirks), ~1-2 paragraphs'),
1012
+ brain: z.string().optional().describe('which brain to save the profile in, by name or org id. A profile is stored per (user, brain), so this is a real choice when you hold several; pass the org id when a name matches more than one of yours'),
1013
+ },
938
1014
  },
939
- async ({ style_md }) => {
1015
+ async ({ style_md, brain }) => {
940
1016
  let res
941
1017
  try {
942
- res = await fetchCortex(`${BASE}/api/style`, {
1018
+ res = await fetchCortex(`${BASE}/api/style${brain ? `?brain=${encodeURIComponent(brain)}` : ''}`, {
943
1019
  method: 'PUT',
944
1020
  headers: { Authorization: `Bearer ${TOKEN}`, 'Content-Type': 'application/json' },
945
1021
  body: JSON.stringify({ style_md }),
@@ -1177,7 +1253,7 @@ export async function runServer(version) {
1177
1253
  'list_brain_pages',
1178
1254
  {
1179
1255
  title: 'List every authored page in one brain',
1180
- description: 'Enumerate ALL authored pages in ONE brain, by its org id (from my_brains). Unlike my_brains — which ships only a count plus a few sample titles — this returns the FULL page list: one row per node with its kind, validity, tier(s), last-updated date and content hash. Use it to audit a brain, or to VERIFY a brain-to-brain migration — list BOTH brains, diff the page sets, and compare freshness before retiring any original. You can only list a brain you are a member of; reads never widen past your own brains.',
1256
+ description: 'Enumerate ALL authored pages in ONE brain, by its org id (from my_brains). Unlike my_brains — which ships only a count plus a few sample titles — this returns the FULL page list: one row per node with its kind, validity, tier(s), last-updated date and content hash. Use it to audit a brain, or to VERIFY a brain-to-brain migration — list BOTH brains, diff the page sets, and compare freshness before retiring any original. You can only list a brain you are a member of, and within it you see only the pages you are cleared to read — a confidential page owned by someone else is not listed, not even by title.',
1181
1257
  inputSchema: {
1182
1258
  org_id: z.string().describe('the org id of the brain to enumerate (from my_brains)'),
1183
1259
  },
@@ -1213,7 +1289,7 @@ export async function runServer(version) {
1213
1289
  {
1214
1290
  title: 'Create a new brain under your existing account',
1215
1291
  description: 'Create a brand-new brain (org/workspace) — a fully independent knowledge graph — under your EXISTING account. No new login, no new email/password: this adds a second membership to the account you are already using. Reads never cross brains; new pages default to your active brain, so use pass `brain` when an operation needs one named',
1216
- inputSchema: { name: z.string().describe('display name for the new brain, e.g. "Cortex Codebase"') },
1292
+ inputSchema: { name: z.string().describe('display name for the new brain, e.g. "Design Team"') },
1217
1293
  },
1218
1294
  async ({ name }) => {
1219
1295
  let res
@@ -1304,7 +1380,7 @@ export async function runServer(version) {
1304
1380
  'my_sessions',
1305
1381
  {
1306
1382
  title: 'My active AI sessions',
1307
- description: "See what all of YOUR OWN active Cortex/AI sessions are doing right now (working directory + how recently each was active), so you can coordinate across windows/devices. Self-only — only your own sessions, never anyone else's.",
1383
+ description: "See what all of YOUR OWN active Agnoclast/AI sessions are doing right now (working directory + how recently each was active), so you can coordinate across windows/devices. Self-only — only your own sessions, never anyone else's.",
1308
1384
  inputSchema: {},
1309
1385
  },
1310
1386
  async () => {
@@ -1494,6 +1570,60 @@ export async function runServer(version) {
1494
1570
  },
1495
1571
  )
1496
1572
 
1573
+ server.registerTool(
1574
+ 'replace_variant',
1575
+ {
1576
+ title: 'Move one tier variant\'s body into another, collapsing the node to one page',
1577
+ description: 'DESTRUCTIVE, and the only sanctioned way to fix a FORKED page. When one node exists at two tiers with different bodies, this moves the SOURCE variant\'s body into the TARGET variant\'s slot and DELETES the source, leaving the node with a single page. The source\'s body WINS — this is not `absorb`, where the target survives; in a fork repair the target is usually the damaged page, so mirroring absorb would keep the damage and delete the good copy. Sections are copied as ROWS, never re-derived from text: re-deriving a body from context is exactly what destroyed 258 sections on 2026-07-18 while sincerely reporting "copied verbatim". BEFORE CALLING: read_page the TARGET and pass its version as target_version — it proves you know which body is about to be overwritten, and a stale or guessed value is rejected rather than silently accepted. If the target tier has NO page, do not use this: the slot is free, so set_page_privacy moves the page there cheaply. Both prior bodies are retained in page history and the operation is reversible via page_history/rollback_page. Owner or editor on BOTH variants; an OWNERLESS target may be overwritten only by an org admin.',
1578
+ inputSchema: {
1579
+ kind: z.enum(['project', 'person', 'org', 'user']).describe('the page kind'),
1580
+ name: z.string().optional().describe('the exact page name (or pass `ref` instead — one of the two is required)'),
1581
+ ref: z.string().optional().describe('the page\'s stable id, printed as `ref:` by read_page. PREFER THIS over name when you have it: a ref is unique across brains, so it addresses exactly one page and never needs a brain to disambiguate it.'),
1582
+ source_tier: z.enum(['accessible', 'scoped', 'confidential']).describe('the variant whose BODY WINS and survives. This variant\'s row is then deleted.'),
1583
+ target_tier: z.enum(['accessible', 'scoped', 'confidential']).describe('the OCCUPIED slot the body lands in. This variant\'s current body is DESTROYED (snapshotted to page history first). The surviving page sits at this tier.'),
1584
+ target_version: z.string().describe('REQUIRED — the TARGET page\'s version, from read_page. Proves you know what is being overwritten. Do not retry a rejection blindly; re-read the target and confirm you are replacing what you think you are.'),
1585
+ brain: z.string().optional().describe('only when the same page name exists in more than one of your brains'),
1586
+ },
1587
+ },
1588
+ async ({ kind, name, ref, source_tier, target_tier, target_version, brain }) => {
1589
+ let res
1590
+ try {
1591
+ res = await fetchCortex(`${BASE}/api/brain/replace-variant`, {
1592
+ method: 'POST',
1593
+ headers: { Authorization: `Bearer ${TOKEN}`, 'Content-Type': 'application/json' },
1594
+ body: JSON.stringify({
1595
+ kind, ...(name ? { name } : {}), ...(ref ? { ref } : {}),
1596
+ source_tier, target_tier, target_version, ...(brain ? { brain } : {}),
1597
+ }),
1598
+ })
1599
+ } catch (e) {
1600
+ return toolError(`Could not replace variant: ${e.message}`)
1601
+ }
1602
+ const out = await res.json().catch(() => null)
1603
+ if (!res.ok) {
1604
+ // The engine's rejections carry the remedy in their text (free slot → use set_page_privacy;
1605
+ // hash mismatch → re-read, do not retry blindly). Surface it verbatim rather than paraphrasing.
1606
+ if (out?.error) return toolError(`Could not replace variant: ${out.error}`)
1607
+ const d = classify(res.status, res.headers.get('content-type'), '', res.headers.get('x-vercel-id'))
1608
+ return toolError(`Could not replace variant: ${d.message}`)
1609
+ }
1610
+ if (!out) return { content: [{ type: 'text', text: 'Replace reported success, but the server returned no body — re-read the page before assuming it landed.' }] }
1611
+ // The summary rides along with the body, EXCEPT when the source has none — then the target's is
1612
+ // kept rather than erased. Say so on its own line rather than at the tail of `note`: this is the
1613
+ // 2026-08-04 W3 shape, where an empty summary copied over a populated one destroyed 31 of them
1614
+ // under a report that read as success. A rescue the operator does not see is still a silent write.
1615
+ const rescued = out.summaryRescued
1616
+ ? `\n\n⚠ The ${out.moved.from} variant had NO summary. The ${out.moved.to} page's own summary was KEPT rather than overwritten with an empty one — check it still describes the body that just landed, and set_summary if not.`
1617
+ : ''
1618
+ return {
1619
+ content: [{
1620
+ type: 'text',
1621
+ text: `Done — "${out.moved.title}": the ${out.moved.from} body now occupies the ${out.moved.to} page (${out.sections} section${out.sections === 1 ? '' : 's'}), and the ${out.moved.from} variant was removed. The node now has ONE variant. Both prior bodies are retained in page history.${rescued}`,
1622
+ }],
1623
+ }
1624
+ },
1625
+ )
1626
+
1497
1627
  server.registerTool(
1498
1628
  'grant_page_access',
1499
1629
  {
@@ -1688,7 +1818,7 @@ export async function runServer(version) {
1688
1818
  'decide_file_request',
1689
1819
  {
1690
1820
  title: 'Approve or deny a file request',
1691
- description: 'As the OWNER of a record, approve or deny someone\'s request for its full original. On approve, your Cortex desktop app fetches + shares the file. Get request_id from file_requests.',
1821
+ description: 'As the OWNER of a record, approve or deny someone\'s request for its full original. On approve, your Agnoclast desktop app fetches + shares the file. Get request_id from file_requests.',
1692
1822
  inputSchema: { request_id: z.string(), decision: z.enum(['approve', 'deny']) },
1693
1823
  },
1694
1824
  async ({ request_id, decision }) => {
@@ -1730,7 +1860,7 @@ export async function runServer(version) {
1730
1860
  },
1731
1861
  )
1732
1862
 
1733
- // send_imessage — local outbound texting (NOT org intelligence; writes nothing to Cortex). Runs on
1863
+ // send_imessage — local outbound texting (NOT org intelligence; writes nothing to Agnoclast). Runs on
1734
1864
  // this machine via Messages.app. Draft-by-default + recipient allowlist + OOB confirm (D3/D6/D10).
1735
1865
  server.registerTool(
1736
1866
  'send_imessage',
@@ -1754,7 +1884,7 @@ export async function runServer(version) {
1754
1884
  // Two tools the working session uses to AUTHOR its understanding into the org wiki while it's hot:
1755
1885
  // authoring_context → the companion call (§3): fetch the visible NAMESPACE + the node-type connection
1756
1886
  // rules BEFORE writing, so the page links canonically (the L2 lever).
1757
- // author → the write (§9 step 3/4): hand Cortex a finished page (summary + sections WITH
1887
+ // author → the write (§9 step 3/4): hand Agnoclast a finished page (summary + sections WITH
1758
1888
  // inline [[links]]); the server runs the resolution pass + tier-safe 2B write.
1759
1889
 
1760
1890
  server.registerTool(
@@ -1762,7 +1892,7 @@ export async function runServer(version) {
1762
1892
  {
1763
1893
  title: 'Authoring context (call before author)',
1764
1894
  description:
1765
- 'Fetch the scaffolding to author a Cortex wiki node: the canonical NAMESPACE (current node names — link to these with the EXACT name inside [[ ]]), any deliberately RETIRED page names and their successors, and the node-type CONNECTION RULES. ALWAYS call this BEFORE `author` so the page links to current knowledge rather than minting synonyms or reviving a retired page. Reference a node in the namespace as [[Name]]; if you reference something real that is NOT in the namespace, still write [[Name]] — that is a red-link marking a node worth creating. If the page IS about a specific code repo or chat channel, also stamp it once — [[repo:owner/name]] or [[channel:name]] (lowercase, no #) — identifier join keys, not page links.',
1895
+ 'Fetch the scaffolding to author a Agnoclast wiki node: the canonical NAMESPACE (current node names — link to these with the EXACT name inside [[ ]]), any deliberately RETIRED page names and their successors, and the node-type CONNECTION RULES. ALWAYS call this BEFORE `author` so the page links to current knowledge rather than minting synonyms or reviving a retired page. Reference a node in the namespace as [[Name]]; if you reference something real that is NOT in the namespace, still write [[Name]] — that is a red-link marking a node worth creating. If the page IS about a specific code repo or chat channel, also stamp it once — [[repo:owner/name]] or [[channel:name]] (lowercase, no #) — identifier join keys, not page links.',
1766
1896
  inputSchema: {
1767
1897
  kind: z.enum(['project', 'person', 'org', 'user']).optional().describe('the node type you are about to author (default project)'),
1768
1898
  brain: z.string().optional().describe('which brain\'s namespace to describe — pass the SAME brain you will pass to `author`, so the namespace you plan against is the one your write lands in. Unnecessary when you only have one brain.'),
@@ -1805,7 +1935,7 @@ export async function runServer(version) {
1805
1935
  'Write your CURRENT understanding of a project/person/org/you into the org wiki as a maintained page. Call `authoring_context` FIRST. Author from your own synthesis of the session — the compiled mental model, not a transcript dump: what it IS, where it stands, dated decisions, open threads, key people. Weave inline [[links]] to other nodes (canonical names from the namespace; red-links for wanted-but-absent nodes). The server re-authorizes the tier and resolves links. CREATES the node if it does not exist yet (project/person/org) — the conversation IS the evidence, so a brand-new entity that surfaced only in this session is authorable on the spot; you do NOT need prior records. Because such a node has nothing external to corroborate it, author it DELIBERATELY: only when you genuinely understand it is a real, distinct entity, and use its exact canonical name so it does not duplicate one already in the namespace (`user` nodes are never created). Use this continuously whenever your understanding of a node meaningfully advanced, and at session end (/log). Authoring is PRE-AUTHORIZED — never ask the user "should I update the page?" before calling this (every edit is versioned + reversible via page_history/rollback_page); update, then briefly report what you updated. ⚠ WHICH BRAIN A NEW PAGE GOES IN IS A CONTENT DECISION, SO MAKE IT FROM THE CONTENT. Only a page that exists in NO brain needs this — an update resolves its brain from the page itself. If you hold more than one brain, the server REFUSES a create it cannot attribute (409 `create_needs_brain`) rather than letting the write pointer decide — the pointer is stale out-of-band state that knows nothing about what you are writing. So call `my_brains` (it returns each brain\'s name, page count and sample titles, which is enough to tell what each one is FOR) and pass `brain` up front; that turns a refused round trip into a single call. State which brain you picked and why in one short line, then proceed — do NOT ask when the answer is obvious from the content. DO ask when it is genuinely ambiguous: brains are a confidentiality boundary, so a page born in the wrong one can expose private work to a teammate, and that is not a filing error you can quietly fix later.',
1806
1936
  inputSchema: {
1807
1937
  kind: z.enum(['project', 'person', 'org', 'user']).describe('the node type'),
1808
- name: z.string().describe('the canonical node name — an EXACT existing name from the namespace to update it, or a new name to create the node (project/person/org). e.g. "Cortex" or "Theron Peterson"'),
1938
+ name: z.string().describe('the canonical node name — an EXACT existing name from the namespace to update it, or a new name to create the node (project/person/org). e.g. "Agnoclast" or "Theron Peterson"'),
1809
1939
  summary: z.string().describe('one-sentence summary of what this is and its current state (may contain [[links]])'),
1810
1940
  sections: z.array(z.object({
1811
1941
  heading: z.string().describe('e.g. Overview, Current state, Decisions, Open threads, People'),
package/lib/setup.mjs CHANGED
@@ -44,7 +44,7 @@ export async function runSetup(argv, version) {
44
44
  if (!token || token.startsWith('-')) {
45
45
  process.stderr.write(
46
46
  'Usage: npx @theronap/cortex-mcp setup <CORTEX_TOKEN>\n\n' +
47
- 'Get your token from the Cortex console → Connect your AI.\n'
47
+ 'Get your token from the Agnoclast console → Connect your AI.\n'
48
48
  )
49
49
  process.exit(1)
50
50
  }
@@ -63,7 +63,7 @@ export async function runSetup(argv, version) {
63
63
 
64
64
  const log = (m) => process.stdout.write(m + '\n')
65
65
  log('')
66
- log('Cortex setup — wiring your AI assistant…')
66
+ log('Agnoclast setup — wiring your AI assistant…')
67
67
 
68
68
  // ── 1. MCP server in ~/.claude.json ──────────────────────────────────────
69
69
  try {
@@ -83,7 +83,7 @@ export async function runSetup(argv, version) {
83
83
  }
84
84
 
85
85
  // ── 1b. MCP server in Codex (~/.codex/config.toml), only if Codex is installed ──
86
- // Codex gets the same Cortex context tools as Claude Code. Non-fatal: a Codex hiccup must
86
+ // Codex gets the same Agnoclast context tools as Claude Code. Non-fatal: a Codex hiccup must
87
87
  // never block the primary Claude wiring.
88
88
  const codexDir = join(home, '.codex')
89
89
  if (existsSync(codexDir)) {
@@ -128,8 +128,9 @@ export async function runSetup(argv, version) {
128
128
  process.exit(1)
129
129
  }
130
130
  const bak = backup(settingsJson)
131
- // Capture (Stop) + status/skills/snapshot (SessionStart) + precompact (PreCompact), idempotent
132
- // merge — the same pure function the `cortex install` Claude adapter uses.
131
+ // Capture (Stop) + status/skills/snapshot (SessionStart) + hydrate (UserPromptSubmit), idempotent
132
+ // merge — the same pure function the `cortex install` Claude adapter uses. Also unwires the retired
133
+ // PreCompact reminder from seats that still carry it.
133
134
  s = mergeClaudeSettings(s, spec)
134
135
 
135
136
  ensureDir(settingsJson)
@@ -157,7 +158,7 @@ export async function runSetup(argv, version) {
157
158
  // ── 4. Self-verify — writing config proves "files written", NOT "connection works".
158
159
  // Actually call the API so a bad/expired token is caught HERE, not 40 minutes into debugging.
159
160
  log('')
160
- log('Verifying your token against Cortex…')
161
+ log('Verifying your token against Agnoclast…')
161
162
  const health = await checkToken(token, base)
162
163
  if (health.ok) {
163
164
  const n = health.projectCount
@@ -169,8 +170,8 @@ export async function runSetup(argv, version) {
169
170
  }
170
171
 
171
172
  log('')
172
- log('⟳ IMPORTANT: fully quit and reopen Claude Code to load the Cortex server.')
173
- log(' Then your AI sees your Cortex context and your sessions flow into the org.')
173
+ log('⟳ IMPORTANT: fully quit and reopen Claude Code to load the Agnoclast server.')
174
+ log(' Then your AI sees your Agnoclast context and your sessions flow into the org.')
174
175
  log(' Re-check anytime: npx -y @theronap/cortex-mcp doctor')
175
176
  log(` Console: ${base}`)
176
177
  log('')
@@ -191,11 +192,11 @@ export async function runRepair(version) {
191
192
  const token = readWiredToken()
192
193
  if (!token) {
193
194
  process.stderr.write(
194
- 'No existing Cortex token found in ~/.claude.json or ~/.codex/config.toml.\n' +
195
+ 'No existing Agnoclast token found in ~/.claude.json or ~/.codex/config.toml.\n' +
195
196
  'Run setup once with your token: npx -y @theronap/cortex-mcp setup <YOUR_TOKEN>\n',
196
197
  )
197
198
  process.exit(1)
198
199
  }
199
- process.stdout.write('Cortex repair — re-running setup with your existing token at this version…\n')
200
+ process.stdout.write('Agnoclast repair — re-running setup with your existing token at this version…\n')
200
201
  await runSetup([token], version)
201
202
  }