@theronap/agnoclast-mcp 0.9.302 → 0.9.304

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
@@ -249,6 +249,40 @@ function llmOnce(prompt, model, system, env) {
249
249
  })
250
250
  }
251
251
 
252
+ const READER_BIN = join(dirname(fileURLToPath(import.meta.url)), 'closeout_reader.mjs')
253
+ const EXPLORE_BUDGET_USD = '3'
254
+ const EXPLORE_TIMEOUT_MS = 900_000
255
+
256
+ /**
257
+ * One Sonnet run that may search and read the wiki, and nothing else: its only server is the read-only one, and its only
258
+ * permitted tools are those two. Manual close-outs find most of the pages they fix by searching and following links,
259
+ * which one prompt over a fixed set of pages cannot do (ADR-0107, 2026-11-03). Null if it gave no result.
260
+ */
261
+ export function llmExplore(prompt, sessionId, env = process.env) {
262
+ const dir = join(tmpdir(), `agnoclast-closeout-${process.pid}-${Date.now()}`)
263
+ mkdirSync(dir, { recursive: true })
264
+ const config = join(dir, 'mcp.json')
265
+ writeFileSync(config, JSON.stringify({ mcpServers: { agnoclast: { command: process.execPath, args: [READER_BIN, sessionId] } } }))
266
+ const args = ['-p', '--no-session-persistence', '--model', 'sonnet', '--max-budget-usd', EXPLORE_BUDGET_USD, '--output-format', 'json', '--tools', '', '--mcp-config', config, '--strict-mcp-config', '--allowedTools', 'mcp__agnoclast__grep,mcp__agnoclast__read_page']
267
+ return new Promise((resolve) => {
268
+ const child = spawn('claude', args, { cwd: dir, env: edgeSafeEnv(env, { CORTEX_SUMMARIZING: '1' }), stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true })
269
+ let stdout = ''
270
+ child.stdout.on('data', (b) => { stdout += b })
271
+ child.stderr.on('data', () => {})
272
+ child.stdin.on('error', () => {})
273
+ const done = (r) => { clearTimeout(timer); rmSync(dir, { recursive: true, force: true }); resolve(r) }
274
+ const timer = setTimeout(() => child.kill('SIGKILL'), EXPLORE_TIMEOUT_MS)
275
+ child.on('error', () => done(null))
276
+ child.on('close', () => {
277
+ try {
278
+ const j = JSON.parse(stdout)
279
+ done({ text: j.result ?? '', cost: j.total_cost_usd ?? 0 })
280
+ } catch { done(null) }
281
+ })
282
+ child.stdin.end(prompt)
283
+ })
284
+ }
285
+
252
286
  /** Throws when every attempt failed: a record built on a missing chunk is worse than a retry on the next sweep. */
253
287
  export async function llm(prompt, model, system, env = process.env) {
254
288
  for (let i = 0; i < LLM_ATTEMPTS; i++) {
@@ -443,6 +477,7 @@ export async function openTools(sessionId, env = process.env, home = homedir())
443
477
  const r = await client.callTool({ name, arguments: args }, undefined, { timeout: 120_000 })
444
478
  return { text: (r.content ?? []).map((c) => c.text ?? '').join('\n'), isError: Boolean(r.isError) }
445
479
  },
480
+ list: async () => (await client.listTools()).tools.filter((t) => ALLOWED_TOOLS.has(t.name)),
446
481
  close: () => client.close(),
447
482
  }
448
483
  }
@@ -539,7 +574,8 @@ async function closeSession(session, { env, home, stopAtLog = false, write = tru
539
574
  if (digest.blocking.length) return { ok: false, why: digest.blocking.join('; '), cost: digest.cost, digest }
540
575
  let cost = digest.cost
541
576
  const call = async (prompt, model) => { const r = await llm(prompt, model, undefined, env); cost += r.cost; return r.text }
542
- 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) })
577
+ const explore = async (prompt) => { const r = await llmExplore(prompt, session.id, env); cost += r?.cost ?? 0; return r?.text ?? '' }
578
+ 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), explore })
543
579
  if (!write) return { ok: true, cost, digest, wiki }
544
580
  const accepted = wiki?.accepted ?? []
545
581
  // Pages first, so the record that follows has them attached: the server attaches what this session wrote.
@@ -0,0 +1,22 @@
1
+ // THE CLOSE-OUT'S READ-ONLY SERVER (ADR-0107). The exploring wiki step runs `claude -p` with this as its only MCP
2
+ // server, so the model reading the wiki can search and read pages and nothing else: a write is not a tool it has.
3
+ // Each call goes through `openTools`, which refuses any name outside ALLOWED_TOOLS as well.
4
+ //
5
+ // Run as: node closeout_reader.mjs <closed session id>
6
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js'
7
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'
8
+ import { ListToolsRequestSchema, CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js'
9
+ import { openTools } from './closeout.mjs'
10
+
11
+ export const READ_TOOLS = ['grep', 'read_page']
12
+
13
+ const tools = await openTools(process.argv[2])
14
+ const listed = (await tools.list()).filter((t) => READ_TOOLS.includes(t.name))
15
+ const server = new Server({ name: 'agnoclast', version: '1' }, { capabilities: { tools: {} } })
16
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: listed }))
17
+ server.setRequestHandler(CallToolRequestSchema, async (req) => {
18
+ if (!READ_TOOLS.includes(req.params.name)) return { content: [{ type: 'text', text: `${req.params.name} is not available here` }], isError: true }
19
+ const r = await tools.call(req.params.name, req.params.arguments ?? {})
20
+ return { content: [{ type: 'text', text: r.text }], isError: r.isError }
21
+ })
22
+ await server.connect(new StdioServerTransport())
@@ -6,9 +6,12 @@
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 = 12
10
- const SEARCH_HITS = 8
9
+ const MAX_PAGES = 24
10
+ const PAGES_PER_CALL = 5
11
+ const SEARCH_HITS = 12
12
+ const HITS_PER_QUERY = 2
11
13
  const MAX_EDITS = 10
14
+ const MAX_EXPLORED_EDITS = 30
12
15
  const EVIDENCE_WINDOW = 1_500
13
16
  const MAX_EVIDENCE = 60_000
14
17
  const MAX_PAGE_CHARS = 24_000
@@ -18,7 +21,21 @@ const MIN_KEPT_RATIO = 0.6
18
21
  export function wikiCandidates(segments, read, found = []) {
19
22
  const named = segments.flatMap((s) => s.pages)
20
23
  const reads = Object.entries(read.pagesRead ?? {}).sort((a, b) => b[1] - a[1]).map(([name]) => name)
21
- return [...new Set([...named, ...read.pages, ...reads.slice(0, 3), ...found])].slice(0, MAX_PAGES)
24
+ // Every page it read, not only the three most read (the 2026-11-03 test missed 8 important edits on pages read once),
25
+ // but search hits before the rest: most pages a manual close-out fixes were never opened before it.
26
+ return [...new Set([...named, ...read.pages, ...reads.slice(0, 3), ...found, ...reads])].slice(0, MAX_PAGES)
27
+ }
28
+
29
+ /**
30
+ * PURE. The heading of the section an anchor sits in, as `edit_page` names it: the last heading line above it, less the
31
+ * one "· as of" stamp `read_page` appends. The model guessed it, and stripped every stamp, so a heading that holds one
32
+ * of its own failed twice on 2026-11-03 ("What this is · as of 2026-10-13").
33
+ */
34
+ export function sectionHeading(text, anchor) {
35
+ const at = text.indexOf(anchor)
36
+ if (at < 0) return null
37
+ const lines = [...text.slice(0, at).matchAll(/^#{1,6} +(.+)$/gm)]
38
+ return lines.length ? lines.at(-1)[1].trim().replace(/ · as of \S+$/, '') : null
22
39
  }
23
40
 
24
41
  /** PURE. What to search for pages the session never opened: each segment's title and each workstream heading in it. */
@@ -27,6 +44,23 @@ export function searchQueries(segments) {
27
44
  return [...new Set([...segments.map((s) => s.title ?? s.summary.slice(0, 80)), ...headings])]
28
45
  }
29
46
 
47
+ /**
48
+ * PURE. Asks for the searches a person closing this session would run. Manual close-outs find most of the pages they
49
+ * fix by grepping pointed phrases ("stale deployment Safari old code skew"); on 2026-11-03, 20 of the 25 pages they
50
+ * edited were never opened before the close, and segment titles found almost none of them.
51
+ */
52
+ export function queryPrompt({ segments, facts }) {
53
+ return `A work session has just closed. Below are its record and fact notes. List the searches you would run over the team wiki to find existing pages this session's work made wrong or out of date: a feature, system, decision, project, bug list, status page or person page it changed.
54
+ Each search is 2 to 6 distinctive words: names, identifiers, feature or file names, PR numbers. No generic words.
55
+ Reply with JSON only: an array of at most 10 strings.
56
+
57
+ SESSION RECORD:
58
+ ${segments.map((s) => s.summary).join('\n\n')}
59
+
60
+ FACT NOTES:
61
+ ${facts.slice(-30_000)}`
62
+ }
63
+
30
64
  /** PURE. Page names in a `grep` reply, best first. */
31
65
  export function parseGrepPages(text) {
32
66
  return [...new Set([...text.matchAll(/^- \[page\] (.+?)(?: > .*)? \[\w+\]$/gm)].map((m) => m[1]))]
@@ -80,7 +114,7 @@ export function evidenceFor(edit, log) {
80
114
 
81
115
  /** 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
116
  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.
117
+ 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. Promised, planned, requested or still owed is not done: drop an edit that states as done what the session only promised or left open. Drop an edit whose new text loses a warning, risk, caveat or reason the old text gave, unless the session showed it no longer holds. Reply with JSON only: an array of the zero-based indexes to keep.
84
118
 
85
119
  EDITS:
86
120
  ${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)}
@@ -94,13 +128,16 @@ ${raw}`
94
128
 
95
129
  /** PURE. The first JSON array in a model's reply, or []. */
96
130
  export function parseJsonArray(text) {
97
- const start = text.indexOf('[')
98
- const end = text.lastIndexOf(']')
99
- if (start < 0 || end < start) return []
100
- try {
101
- const parsed = JSON.parse(text.slice(start, end + 1))
102
- return Array.isArray(parsed) ? parsed : []
103
- } catch { return [] }
131
+ // A fenced block first, then each "[" that opens an array: the exploring run writes prose with [[links]] before it.
132
+ const fenced = [...text.matchAll(/```(?:json)?\s*\n([\s\S]*?)```/g)].map((m) => m[1].trim()).filter((b) => b.startsWith('['))
133
+ const tries = [...fenced.reverse(), ...[...text.matchAll(/\[(?=\s*[{\]"\d])/g)].map((m) => text.slice(m.index, text.lastIndexOf(']') + 1))]
134
+ for (const t of tries) {
135
+ try {
136
+ const parsed = JSON.parse(t)
137
+ if (Array.isArray(parsed)) return parsed
138
+ } catch {}
139
+ }
140
+ return []
104
141
  }
105
142
 
106
143
  const FIGURE = /\d[\d,.]*\d|\d/g
@@ -124,19 +161,65 @@ export function gateEdit(edit, { page, allowedBrains, evidence }) {
124
161
  return null
125
162
  }
126
163
 
127
- /** Propose, gate, verify. Writes nothing. `readPage(name, brain)` gives {name, brain, tier, version, text} or null. */
128
- export async function proposeWikiEdits({ segments, read, facts, raw, log = '', call, readPage, search = async () => [], asOf }) {
129
- const allowedBrains = segments.map((s) => s.brain)
164
+ /**
165
+ * PURE. The exploring proposer's prompt: it has `grep` and `read_page` and finds the pages itself, the way a person
166
+ * closing a session does.
167
+ */
168
+ export function explorePrompt({ segments, read, facts, asOf }) {
169
+ const seen = [...new Set([...segments.flatMap((s) => s.pages), ...read.pages, ...Object.keys(read.pagesRead ?? {})])]
170
+ return `A work session has just closed. Its record and fact notes are below. Bring the team wiki up to date with what it established, the way a careful colleague closing the session would.
171
+ Use grep to find every existing page this session's work made wrong, out of date or incomplete: the feature, system, decision, project, status, bug-list and person pages it touched. Search for names, identifiers, PR numbers and phrases from the work, follow [[links]] on the pages you read, and read each page before proposing an edit to it. Run at least one search for every workstream in the record, even when you already know a page for it: the pages a session made stale are mostly ones it never opened. Pages it opened: ${seen.join(', ') || 'none'}.
172
+ Only pages in these brains: ${segments.map((s) => s.brain).join(', ')}. Never a confidential page.
173
+ 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. Propose an edit only for something this session established first-hand.
174
+ 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. A page in a shared brain must not gain family, friends, classes, health, private messages or phone numbers.
175
+ Finish with JSON only: an array of at most ${MAX_EXPLORED_EDITS} objects {"page": exact page name, "heading": the section heading, "old_string": text copied exactly from what read_page printed, appearing once on the page, "new_string": the replacement, "reason": one short phrase}.
176
+
177
+ SESSION RECORD:
178
+ ${segments.map((s) => `[${s.brain}]\n${s.summary}`).join('\n\n')}
179
+
180
+ FACT NOTES:
181
+ ${facts.slice(-40_000)}`
182
+ }
183
+
184
+ /** The fixed proposer: search, read a set of pages, and propose over them a few at a time. */
185
+ async function proposeFromPages({ segments, read, facts, call, readPage, search, asOf, allowedBrains }) {
130
186
  const pages = []
131
187
  // Manual close-outs also fix pages the session never opened, like a package's status page: in the two longest
132
188
  // 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)
189
+ const asked = parseJsonArray(await call(queryPrompt({ segments, facts }), 'haiku')).filter((q) => typeof q === 'string')
190
+ const hits = await Promise.all([...asked, ...searchQueries(segments)].map(search))
191
+ // The best two from each search, so one broad search cannot fill every slot.
192
+ const found = [...new Set(hits.flatMap((h) => h.slice(0, HITS_PER_QUERY)))].slice(0, SEARCH_HITS)
134
193
  for (const name of wikiCandidates(segments, read, found)) {
135
194
  const page = await readPage(name, allowedBrains)
136
195
  if (page) pages.push(page)
137
196
  }
138
- if (!pages.length) return { proposed: [], accepted: [], refused: [] }
139
- const proposed = parseJsonArray(await call(proposePrompt({ segments, pages, facts, asOf }), 'sonnet')).slice(0, MAX_EDITS)
197
+ if (!pages.length) return { proposed: [], pages }
198
+ // A few pages per call: one call over all of them stopped at 10 edits where a manual close-out made 31.
199
+ const batches = []
200
+ for (let i = 0; i < pages.length; i += PAGES_PER_CALL) batches.push(pages.slice(i, i + PAGES_PER_CALL))
201
+ const proposed = (await Promise.all(batches.map(async (b) => parseJsonArray(await call(proposePrompt({ segments, pages: b, facts, asOf }), 'sonnet')).slice(0, MAX_EDITS)))).flat()
202
+ return { proposed, pages }
203
+ }
204
+
205
+ /**
206
+ * Propose, gate, verify. Writes nothing. `readPage(name, brains)` gives {name, brain, tier, version, text} or null.
207
+ * `explore(prompt)` is a model run that can search and read the wiki; when it gives nothing, the fixed proposer runs.
208
+ * Either way every edit is checked against the page as read here, never as the model saw it.
209
+ */
210
+ export async function proposeWikiEdits({ segments, read, facts, raw, log = '', call, readPage, search = async () => [], asOf, explore }) {
211
+ const allowedBrains = segments.map((s) => s.brain)
212
+ let proposed = explore ? parseJsonArray(await explore(explorePrompt({ segments, read, facts, asOf })) ?? '').slice(0, MAX_EXPLORED_EDITS) : []
213
+ let pages = []
214
+ if (proposed.length) {
215
+ for (const name of new Set(proposed.map((e) => e.page))) {
216
+ const page = await readPage(name, allowedBrains)
217
+ if (page) pages.push(page)
218
+ }
219
+ } else {
220
+ ;({ proposed, pages } = await proposeFromPages({ segments, read, facts, call, readPage, search, asOf, allowedBrains }))
221
+ }
222
+ if (!pages.length) return { proposed, accepted: [], refused: [] }
140
223
  const evidence = `${facts}\n${raw}`
141
224
  const refused = []
142
225
  const passed = []
@@ -148,7 +231,7 @@ export async function proposeWikiEdits({ segments, read, facts, raw, log = '', c
148
231
  if (!passed.length) return { proposed, accepted: [], refused }
149
232
  const keep = new Set(parseJsonArray(await call(verifyPrompt(passed, { raw, facts, log }), 'sonnet')))
150
233
  passed.forEach((e, i) => { if (!keep.has(i)) refused.push({ ...e, why: 'not supported by the log' }) })
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 }
234
+ return { proposed, accepted: passed.filter((_, i) => keep.has(i)).map((e) => { const p = pages.find((x) => x.name === e.page); return { ...e, heading: sectionHeading(p.text, e.old_string) ?? e.heading, version: p.version, brain: p.brain } }), refused }
152
235
  }
153
236
 
154
237
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theronap/agnoclast-mcp",
3
- "version": "0.9.302",
3
+ "version": "0.9.304",
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": {