@theronap/agnoclast-mcp 0.9.303 → 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())
@@ -11,6 +11,7 @@ const PAGES_PER_CALL = 5
11
11
  const SEARCH_HITS = 12
12
12
  const HITS_PER_QUERY = 2
13
13
  const MAX_EDITS = 10
14
+ const MAX_EXPLORED_EDITS = 30
14
15
  const EVIDENCE_WINDOW = 1_500
15
16
  const MAX_EVIDENCE = 60_000
16
17
  const MAX_PAGE_CHARS = 24_000
@@ -113,7 +114,7 @@ export function evidenceFor(edit, log) {
113
114
 
114
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. */
115
116
  export function verifyPrompt(edits, { raw, facts = '', log = '' }) {
116
- 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.
117
118
 
118
119
  EDITS:
119
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)}
@@ -127,13 +128,16 @@ ${raw}`
127
128
 
128
129
  /** PURE. The first JSON array in a model's reply, or []. */
129
130
  export function parseJsonArray(text) {
130
- const start = text.indexOf('[')
131
- const end = text.lastIndexOf(']')
132
- if (start < 0 || end < start) return []
133
- try {
134
- const parsed = JSON.parse(text.slice(start, end + 1))
135
- return Array.isArray(parsed) ? parsed : []
136
- } 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 []
137
141
  }
138
142
 
139
143
  const FIGURE = /\d[\d,.]*\d|\d/g
@@ -157,9 +161,28 @@ export function gateEdit(edit, { page, allowedBrains, evidence }) {
157
161
  return null
158
162
  }
159
163
 
160
- /** Propose, gate, verify. Writes nothing. `readPage(name, brain)` gives {name, brain, tier, version, text} or null. */
161
- export async function proposeWikiEdits({ segments, read, facts, raw, log = '', call, readPage, search = async () => [], asOf }) {
162
- 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 }) {
163
186
  const pages = []
164
187
  // Manual close-outs also fix pages the session never opened, like a package's status page: in the two longest
165
188
  // sessions of the 2026-11-02 test, 17 of 22 such pages. Searching each workstream finds those.
@@ -171,11 +194,32 @@ export async function proposeWikiEdits({ segments, read, facts, raw, log = '', c
171
194
  const page = await readPage(name, allowedBrains)
172
195
  if (page) pages.push(page)
173
196
  }
174
- if (!pages.length) return { proposed: [], accepted: [], refused: [] }
197
+ if (!pages.length) return { proposed: [], pages }
175
198
  // A few pages per call: one call over all of them stopped at 10 edits where a manual close-out made 31.
176
199
  const batches = []
177
200
  for (let i = 0; i < pages.length; i += PAGES_PER_CALL) batches.push(pages.slice(i, i + PAGES_PER_CALL))
178
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: [] }
179
223
  const evidence = `${facts}\n${raw}`
180
224
  const refused = []
181
225
  const passed = []
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theronap/agnoclast-mcp",
3
- "version": "0.9.303",
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": {