@theronap/agnoclast-mcp 0.9.295 → 0.9.297

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/closeout.mjs CHANGED
@@ -43,8 +43,9 @@ const TAIL_CHARS = 30_000
43
43
  const CHECK_RAW_CHARS = 110_000
44
44
  const MAX_PAGES_PER_SEGMENT = 6
45
45
  const MIN_SUMMARY_CHARS = 200
46
- // False since the wiki step failed its scored test (ADR-0107): accepted proposals go on the record instead of the page.
47
- const WIKI_WRITES = false
46
+ // On since the second scored test (ADR-0107): 25 edits on 8 unseen sessions, all true, none damaging. Off, accepted
47
+ // proposals go on the record under "Pages to update" instead of the page.
48
+ const WIKI_WRITES = true
48
49
 
49
50
  const WORK_TOOLS = new Set(['Edit', 'Write', 'NotebookEdit', 'mcp__agnoclast__author', 'mcp__agnoclast__edit_page'])
50
51
  const COMMITTED = /\bgit\b[^\n]*\b(commit|push)\b|\bgh pr (create|merge)\b/
@@ -384,6 +385,9 @@ export function prStates(prs, lastAt, env = process.env) {
384
385
  })
385
386
  }
386
387
 
388
+ /** PURE. The session's last day in this machine's timezone, which is the person's: a UTC date put an evening merge on the next day. */
389
+ export const localDay = (iso) => (iso ? new Date(iso).toLocaleDateString('en-CA') : undefined)
390
+
387
391
  /** The whole digest. Writes nothing; the caller decides. */
388
392
  export async function digestSession(text, { brains, brainNames, privateBrain, env = process.env, stopAtLog = false, onCost = () => {} }) {
389
393
  let cost = 0
@@ -414,7 +418,7 @@ ${facts}`, 'sonnet')
414
418
  if (fixed.includes('SEGMENT') && fixed.length >= 0.9 * record.length) record = fixed
415
419
  }
416
420
  const checks = checkSegments(parseRecord(record), { brainNames, privateBrain, prs })
417
- return { ...checks, cost, facts, raw: rawForCheck(read.log), read: { ...read, prs, log: undefined }, chars: read.log.length, chunks: parts.length }
421
+ return { ...checks, cost, facts, raw: rawForCheck(read.log), log: read.log, read: { ...read, prs, log: undefined }, chars: read.log.length, chunks: parts.length }
418
422
  }
419
423
 
420
424
  // ⚠ THE WHOLE OF WHAT AN UNATTENDED CLOSE-OUT CAN DO. Nothing here sends, deletes or changes who can see anything.
@@ -522,11 +526,12 @@ async function closeSession(session, { env, home, stopAtLog = false, write = tru
522
526
  if (digest.blocking.length) return { ok: false, why: digest.blocking.join('; '), cost: digest.cost, digest }
523
527
  let cost = digest.cost
524
528
  const call = async (prompt, model) => { const r = await llm(prompt, model, undefined, env); cost += r.cost; return r.text }
525
- const wiki = noWiki ? null : await proposeWikiEdits({ segments: digest.segments, read: digest.read, facts: digest.facts, raw: digest.raw, call, readPage: currentPage(tools), search: pageSearch(tools) })
529
+ const wiki = noWiki ? null : await proposeWikiEdits({ segments: digest.segments, read: digest.read, facts: digest.facts, raw: digest.raw, log: digest.log, call, readPage: currentPage(tools), search: pageSearch(tools), asOf: localDay(digest.read.lastAt) })
526
530
  if (!write) return { ok: true, cost, digest, wiki }
527
531
  const accepted = wiki?.accepted ?? []
532
+ // Pages first, so the record that follows has them attached: the server attaches what this session wrote.
533
+ const edits = WIKI_WRITES && accepted.length ? await applyWikiEdits(tools, accepted) : []
528
534
  const written = await writeSegments(tools, session.id, WIKI_WRITES ? digest.segments : withPageProposals(digest.segments, accepted))
529
- const edits = written.ok && WIKI_WRITES && accepted.length ? await applyWikiEdits(tools, accepted) : []
530
535
  return { ok: written.ok, records: written.records, why: written.ok ? null : written.text.slice(0, 600), cost, digest, wiki, edits }
531
536
  } finally {
532
537
  await tools.close().catch(() => {})
@@ -6,9 +6,11 @@
6
6
  // passage can only be replaced by text at least as supported as the session's own log.
7
7
  import { scrub } from './closeout.mjs'
8
8
 
9
- const MAX_PAGES = 8
10
- const SEARCH_HITS = 4
11
- const MAX_EDITS = 5
9
+ const MAX_PAGES = 12
10
+ const SEARCH_HITS = 8
11
+ const MAX_EDITS = 10
12
+ const EVIDENCE_WINDOW = 1_500
13
+ const MAX_EVIDENCE = 60_000
12
14
  const MAX_PAGE_CHARS = 24_000
13
15
  const MIN_KEPT_RATIO = 0.6
14
16
 
@@ -19,6 +21,12 @@ export function wikiCandidates(segments, read, found = []) {
19
21
  return [...new Set([...named, ...read.pages, ...reads.slice(0, 3), ...found])].slice(0, MAX_PAGES)
20
22
  }
21
23
 
24
+ /** PURE. What to search for pages the session never opened: each segment's title and each workstream heading in it. */
25
+ export function searchQueries(segments) {
26
+ const headings = segments.flatMap((s) => [...s.summary.matchAll(/^\*\*([^*\n]{4,80})\*\*\s*$/gm)].map((m) => m[1].trim()))
27
+ return [...new Set([...segments.map((s) => s.title ?? s.summary.slice(0, 80)), ...headings])]
28
+ }
29
+
22
30
  /** PURE. Page names in a `grep` reply, best first. */
23
31
  export function parseGrepPages(text) {
24
32
  return [...new Set([...text.matchAll(/^- \[page\] (.+?)(?: > .*)? \[\w+\]$/gm)].map((m) => m[1]))]
@@ -27,7 +35,8 @@ export function parseGrepPages(text) {
27
35
  /** PURE. The proposer's prompt. */
28
36
  export function proposePrompt({ segments, pages, facts, asOf }) {
29
37
  return `A work session has just closed. Its record is below, then the current text of wiki pages it touched. Propose the passage edits a careful colleague would make so these pages stop being wrong or behind.
30
- Propose an edit only for something this session established first-hand, and only where the page is now stale, wrong, or missing a status or decision a reader of that page needs. Most pages need nothing; an empty list is a fine answer.
38
+ Go through every page and ask: after this session, what on it is now false, out of date, or missing a status or decision its reader needs? A page the session wrote, or whose subject the session's work changed, usually needs its status brought current. A page it only read may need nothing. Propose an edit only for something this session established first-hand.
39
+ State a status only as it stood when the session ended: the fact notes run in order and later ones win, so a thing first described as not done and later done is done.
31
40
  Prefer correcting the sentence that went stale over adding a new paragraph. Copy the page's style. Date what you state, in the form ${asOf ?? 'YYYY-MM-DD'}. Keep every [[link]] in the passage you replace. No process remarks, no mention of this session or record.
32
41
  A page in a shared brain must not gain family, friends, classes, health, private messages or phone numbers.
33
42
  Reply with JSON only: an array of at most ${MAX_EDITS} objects {"page": exact page name, "heading": exact section heading without any "· as of" date, "old_string": text copied exactly from that section, appearing once, "new_string": the replacement, "reason": one short phrase}.
@@ -42,12 +51,42 @@ PAGES:
42
51
  ${pages.map((p) => `=== PAGE: ${p.name} (brain: ${p.brain}) ===\n${p.text.slice(0, MAX_PAGE_CHARS)}`).join('\n\n')}`
43
52
  }
44
53
 
45
- /** PURE. The check of each edit against the raw log. */
46
- export function verifyPrompt(edits, raw) {
47
- return `Each edit below changes a wiki page because of a work session. Using only the raw session log, decide each one. Keep an edit only if the log shows its new text is true and final: not later corrected, not rehearsal, not merely advised, and its dates are right. Reply with JSON only: an array of the zero-based indexes to keep.
54
+ const IDENTIFIER = /#\d{3,5}\b|\b\d{8,14}_\w+|\bv?\d+\.\d+\.\d+(?:-[\w.]+)?\b|`[^`\n]{3,80}`|\b[0-9a-f]{7,40}\b/g
55
+
56
+ /**
57
+ * PURE. The parts of the WHOLE log that bear on an edit: the last mentions of each identifier its new text names. The
58
+ * check once saw only the start and end of a long log, and passed a migration as unapplied that the middle applied.
59
+ */
60
+ export function evidenceFor(edit, log) {
61
+ const terms = [...new Set((edit.new_string.match(IDENTIFIER) ?? []).map((t) => t.replace(/`/g, '')))]
62
+ const spans = []
63
+ for (const term of terms) {
64
+ let at = log.length
65
+ for (let n = 0; n < 3; n++) {
66
+ at = log.lastIndexOf(term, at - 1)
67
+ if (at < 0) break
68
+ spans.push([Math.max(0, at - EVIDENCE_WINDOW), Math.min(log.length, at + term.length + EVIDENCE_WINDOW)])
69
+ }
70
+ }
71
+ spans.sort((a, b) => a[0] - b[0])
72
+ const merged = []
73
+ for (const s of spans) {
74
+ const last = merged[merged.length - 1]
75
+ if (last && s[0] <= last[1]) last[1] = Math.max(last[1], s[1])
76
+ else merged.push([...s])
77
+ }
78
+ return merged.map(([a, b]) => log.slice(a, b)).join('\n[...]\n').slice(-MAX_EVIDENCE)
79
+ }
80
+
81
+ /** PURE. The check of each edit against the session: the fact notes in order, the log's end, and each edit's own evidence. */
82
+ export function verifyPrompt(edits, { raw, facts = '', log = '' }) {
83
+ return `Each edit below changes a wiki page because of a work session. Decide each one from the session's own material below. Keep an edit only if it shows the new text is true as of the END of the session: not later corrected, not rehearsal, not merely advised, and its dates are right. The fact notes run in order and later ones win. Reply with JSON only: an array of the zero-based indexes to keep.
48
84
 
49
85
  EDITS:
50
- ${JSON.stringify(edits.map((e, i) => ({ i, page: e.page, old: e.old_string, new: e.new_string })), null, 1)}
86
+ ${JSON.stringify(edits.map((e, i) => ({ i, page: e.page, old: e.old_string, new: e.new_string, evidence: log ? evidenceFor(e, log) : undefined })), null, 1)}
87
+
88
+ FACT NOTES (in order):
89
+ ${facts.slice(-60_000)}
51
90
 
52
91
  RAW SESSION LOG:
53
92
  ${raw}`
@@ -86,11 +125,12 @@ export function gateEdit(edit, { page, allowedBrains, evidence }) {
86
125
  }
87
126
 
88
127
  /** Propose, gate, verify. Writes nothing. `readPage(name, brain)` gives {name, brain, tier, version, text} or null. */
89
- export async function proposeWikiEdits({ segments, read, facts, raw, call, readPage, search = async () => [], asOf }) {
128
+ export async function proposeWikiEdits({ segments, read, facts, raw, log = '', call, readPage, search = async () => [], asOf }) {
90
129
  const allowedBrains = segments.map((s) => s.brain)
91
130
  const pages = []
92
- // Manual close-outs also fix pages the session never opened, like a package's status page. Search finds those.
93
- const found = (await Promise.all(segments.map((s) => search(s.title ?? s.summary.slice(0, 80))))).flat().slice(0, SEARCH_HITS)
131
+ // Manual close-outs also fix pages the session never opened, like a package's status page: in the two longest
132
+ // sessions of the 2026-11-02 test, 17 of 22 such pages. Searching each workstream finds those.
133
+ const found = [...new Set((await Promise.all(searchQueries(segments).map(search))).flat())].slice(0, SEARCH_HITS)
94
134
  for (const name of wikiCandidates(segments, read, found)) {
95
135
  const page = await readPage(name, allowedBrains)
96
136
  if (page) pages.push(page)
@@ -106,7 +146,7 @@ export async function proposeWikiEdits({ segments, read, facts, raw, call, readP
106
146
  else passed.push(edit)
107
147
  }
108
148
  if (!passed.length) return { proposed, accepted: [], refused }
109
- const keep = new Set(parseJsonArray(await call(verifyPrompt(passed, raw), 'sonnet')))
149
+ const keep = new Set(parseJsonArray(await call(verifyPrompt(passed, { raw, facts, log }), 'sonnet')))
110
150
  passed.forEach((e, i) => { if (!keep.has(i)) refused.push({ ...e, why: 'not supported by the log' }) })
111
151
  return { proposed, accepted: passed.filter((_, i) => keep.has(i)).map((e) => { const p = pages.find((x) => x.name === e.page); return { ...e, version: p.version, brain: p.brain } }), refused }
112
152
  }
@@ -3,11 +3,48 @@
3
3
  // once at start-up, which tools this caller must NOT see (GET /api/me/release) and removes them before the
4
4
  // first tools/list. Fails CLOSED: no answer within the budget → hide GATED_FALLBACK, a copy of every gated tool
5
5
  // that web/lib/engine/release.test.ts pins to the server's registry.
6
+ //
7
+ // ⚠ UNLESS THIS MACHINE HAS HEARD AN ANSWER BEFORE (2026-11-02). A runner that starts a process per call (Frack on
8
+ // Muse) meets a slow server often, and each slow start hid every gated tool, so a poller saw "tasks_waiting not
9
+ // found" and its tasks went unseen. The last answer is kept in ~/.cortex/release-state.json and used when the server
10
+ // does not answer in time. It is keyed by server, not token: Muse hands each process a fresh stand-in for the token.
11
+ // That is safe because hiding a tool is a courtesy, and every gated route checks its own flag on the server.
6
12
 
7
13
  /** Tools any release flag gates — hidden when the server cannot be asked. Mirror of allGatedTools(). */
8
14
  export const GATED_FALLBACK = ['arrivals', 'attach_document', 'document_diff', 'export_page', 'file_arrival', 'file_document', 'find_documents', 'finish_task', 'get_document', 'hand_task', 'handed_tasks', 'hold_task', 'import_document_as_page', 'intake_shadow', 'list_documents', 'my_messages', 'my_tasks', 'pin_document', 'read_conversation', 'read_document', 'send_message', 'set_manager', 'tasks_waiting', 'upload_document_version']
9
15
 
10
16
  export const RELEASE_FETCH_TIMEOUT_MS = 2500
17
+ /** A remembered answer older than this is not trusted: a week covers a quiet weekend without hiding tools for long. */
18
+ export const RELEASE_CACHE_MAX_AGE_MS = 7 * 24 * 3600_000
19
+
20
+ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
21
+ import { homedir } from 'node:os'
22
+ import { join } from 'node:path'
23
+
24
+ const cachePath = (home) => join(home, '.cortex', 'release-state.json')
25
+
26
+ /** Keep a fresh answer for the next slow start. Never throws. */
27
+ export function rememberReleaseState(base, state, { home = homedir(), nowMs = Date.now() } = {}) {
28
+ if (!state?.known) return
29
+ try {
30
+ let all = {}
31
+ try { all = JSON.parse(readFileSync(cachePath(home), 'utf8')) ?? {} } catch { /* first answer */ }
32
+ all[base] = { hidden: state.hidden, at: nowMs }
33
+ mkdirSync(join(home, '.cortex'), { recursive: true })
34
+ writeFileSync(cachePath(home), JSON.stringify(all))
35
+ } catch { /* a cache that cannot be written only means the next slow start falls back */ }
36
+ }
37
+
38
+ /** The last answer this machine heard from `base`, if recent. Null otherwise. Never throws. */
39
+ export function rememberedReleaseState(base, { home = homedir(), nowMs = Date.now() } = {}) {
40
+ try {
41
+ const e = JSON.parse(readFileSync(cachePath(home), 'utf8'))?.[base]
42
+ if (!e || !Array.isArray(e.hidden) || typeof e.at !== 'number' || nowMs - e.at > RELEASE_CACHE_MAX_AGE_MS) return null
43
+ return { known: true, hidden: e.hidden.filter((t) => typeof t === 'string') }
44
+ } catch {
45
+ return null
46
+ }
47
+ }
11
48
 
12
49
  /** → { known: true, hidden: string[] } | { known: false }. 404 (server predates cohorts) = nothing hidden. Never throws. */
13
50
  export async function fetchReleaseState(base, token, fetchImpl) {
package/lib/server.mjs CHANGED
@@ -35,7 +35,7 @@ import { formatCreated, formatDryRun, formatSources, homeFromArgs, pickSource, r
35
35
  import { formatSeriesRefusal, formatSeriesUpdated } from './series_render.mjs'
36
36
  import { formatSends } from './sends_render.mjs'
37
37
  import { applyLock, fetchLockState, lockedAnswerFor, lockStateWithin } from './locked_tools.mjs'
38
- import { applyRelease, fetchReleaseState, releaseStateWithin } from './release_gate.mjs'
38
+ import { applyRelease, fetchReleaseState, releaseStateWithin, rememberReleaseState, rememberedReleaseState } from './release_gate.mjs'
39
39
  import { filterUnshownSettling, renderSettlingV2 } from './settling_shown.mjs'
40
40
  import { renderContactBriefing, renderContactCandidates, renderContactList } from './contacts_render.mjs'
41
41
  import { renderConversation, renderMessageInbox } from './messages_render.mjs'
@@ -479,7 +479,7 @@ export async function runServer(version) {
479
479
  // Lite account's AI sees already marks the Regular-only tools 🔒. Regular accounts: nothing changes.
480
480
  const lockP = fetchLockState(BASE, TOKEN, fetchCortex)
481
481
  // RELEASE COHORTS (lib/release_gate.mjs): tools behind a flag this caller's brains lack are removed before the handshake.
482
- const releaseP = fetchReleaseState(BASE, TOKEN, fetchCortex)
482
+ const releaseP = fetchReleaseState(BASE, TOKEN, fetchCortex).then((state) => { rememberReleaseState(BASE, state); return state })
483
483
  const toolHandles = new Map()
484
484
  let lockedTools = new Set()
485
485
  // Nothing wakes a delegate agent, so a waiting task is mentioned on the first result of a process (each Frack call
@@ -8241,7 +8241,8 @@ function renderNudge(payload) {
8241
8241
  },
8242
8242
  )
8243
8243
 
8244
- applyRelease(toolHandles, await releaseStateWithin(releaseP))
8244
+ const release = await releaseStateWithin(releaseP)
8245
+ applyRelease(toolHandles, release.known ? release : (rememberedReleaseState(BASE) ?? release))
8245
8246
  lockedTools = applyLock(toolHandles, await lockStateWithin(lockP))
8246
8247
  // Bounded so a slow lookup never holds up the handshake — but a lookup that is merely LATE still lands: until it
8247
8248
  // does, a tool naming a brain waits for it (the wrapper), so a cold start cannot make the confidential brains
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theronap/agnoclast-mcp",
3
- "version": "0.9.295",
3
+ "version": "0.9.297",
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": {