@theronap/agnoclast-mcp 0.9.306 → 0.9.308

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.
@@ -209,6 +209,11 @@ if (cmd === 'login') {
209
209
  const { healFileCapture } = await import('../lib/editors/claude.mjs')
210
210
  healFileCapture()
211
211
  } catch { /* never fail session start over this */ }
212
+ // And the page nudge (lib/page_nudge.mjs).
213
+ try {
214
+ const { healPageNudge } = await import('../lib/editors/claude.mjs')
215
+ healPageNudge()
216
+ } catch { /* never fail session start over this */ }
212
217
  } else if (cmd === 'closeout-sweep') {
213
218
  const { runCloseoutSweep } = await import('../lib/closeout.mjs')
214
219
  await runCloseoutSweep(process.argv.slice(3))
package/lib/closeout.mjs CHANGED
@@ -25,8 +25,10 @@ import { edgeSafeEnv } from './edge_extract.mjs'
25
25
  import { redactSecrets } from './redact.mjs'
26
26
  import { channelSpec } from './channel.mjs'
27
27
  import { proposeWikiEdits, applyWikiEdits, parseGrepPages, withPageProposals } from './closeout_wiki.mjs'
28
+ import { nudgeDecision } from './page_nudge.mjs'
28
29
 
29
30
  const QUIET_MS = 45 * 60 * 1000
31
+ const WIKI_PASS_WORK = 20
30
32
  const MAX_AGE_MS = 3 * 24 * 60 * 60 * 1000
31
33
  const MIN_PROMPTS = 3
32
34
  const MAX_ATTEMPTS = 2
@@ -158,6 +160,10 @@ export function readSessionLog(text, { stopAtLog = false } = {}) {
158
160
  const obligationCalls = new Map()
159
161
  let firstAt = null
160
162
  let lastAt = null
163
+ let summary = null
164
+ let summaryAt = 0
165
+ // For needsWikiPass: work done since the session last wrote a page, and whether something shipped after it.
166
+ const since = { work: 0, shipped: false, pagesWritten: 0 }
161
167
  const addPr = (repo, number) => { if (!prs.has(`${repo ?? ''}#${number}`)) prs.set(`${repo ?? ''}#${number}`, { repo: repo ?? null, number }) }
162
168
  const scan = (t) => { for (const m of t.matchAll(PR_URL)) addPr(m[1], m[2]) }
163
169
  lines: for (const line of text.split('\n')) {
@@ -167,6 +173,13 @@ export function readSessionLog(text, { stopAtLog = false } = {}) {
167
173
  if (d.isSidechain) continue
168
174
  const content = d.message?.content
169
175
  if (d.timestamp && (d.type === 'user' || d.type === 'assistant')) { firstAt ??= d.timestamp; lastAt = d.timestamp }
176
+ // Claude Code's own summary at a compaction covers everything before it, so what came earlier need not be read
177
+ // again. It was once a USER line cut to 3,000 of its ~12,000 characters.
178
+ if (d.type === 'user' && d.isCompactSummary) {
179
+ summary = typeof content === 'string' ? content : Array.isArray(content) ? content.map((b) => b.text ?? '').join('\n') : ''
180
+ summaryAt = out.length
181
+ continue
182
+ }
170
183
  if (d.type === 'user' && !d.isMeta) {
171
184
  const blocks = typeof content === 'string' ? [{ type: 'text', text: content }] : Array.isArray(content) ? content : []
172
185
  for (const b of blocks) {
@@ -194,7 +207,11 @@ export function readSessionLog(text, { stopAtLog = false } = {}) {
194
207
  const name = bareTool(b.name)
195
208
  const input = b.input ?? {}
196
209
  if (name === 'log_session' && stopAtLog) break lines
197
- if ((name === 'edit_page' || name === 'author') && input.name) pages.add(input.name)
210
+ if ((name === 'edit_page' || name === 'author') && input.name) { pages.add(input.name); since.work = 0; since.shipped = false; since.pagesWritten += 1 }
211
+ else if (['Edit', 'Write', 'MultiEdit', 'NotebookEdit', 'Bash'].includes(b.name)) {
212
+ since.work += 1
213
+ if (nudgeDecision({ tool: b.name, input })?.kind === 'ship') since.shipped = true
214
+ }
198
215
  if (name === 'read_page' && input.name && !input.history) pagesRead[input.name] = (pagesRead[input.name] ?? 0) + 1
199
216
  if (b.name === 'Bash' && PR_COMMAND.test(input.command ?? '')) {
200
217
  prCalls.set(b.id, true)
@@ -208,7 +225,19 @@ export function readSessionLog(text, { stopAtLog = false } = {}) {
208
225
  }
209
226
  // A number from `gh pr merge` names no repo. Drop it when a URL already carries that number.
210
227
  for (const [key, pr] of prs) if (!pr.repo && [...prs.values()].some((p) => p.repo && p.number === pr.number)) prs.delete(key)
211
- return { log: redactSecrets(out.join('\n')), pages: [...pages], pagesRead, prs: [...prs.values()], obligations: [...obligations.entries()].map(([id, o]) => ({ id, ...o })), firstAt, lastAt }
228
+ return { since, log: redactSecrets(out.join('\n')), summary: summary && redactSecrets(summary), sinceSummary: redactSecrets(out.slice(summaryAt).join('\n')), pages: [...pages], pagesRead, prs: [...prs.values()], obligations: [...obligations.entries()].map(([id, o]) => ({ id, ...o })), firstAt, lastAt }
229
+ }
230
+
231
+ /**
232
+ * PURE. Whether the close-out should look for pages at all. Pages are written during the work (ADR-0107, 2026-11-04),
233
+ * so a session that wrote one after its last ship, and is not a long run of work with no page, has nothing to clean up.
234
+ */
235
+ export function needsWikiPass(read) {
236
+ const s = read?.since
237
+ if (!s) return true
238
+ if (s.shipped) return true
239
+ if (!s.pagesWritten) return s.work >= WIKI_PASS_WORK
240
+ return s.work >= WIKI_PASS_WORK * 2
212
241
  }
213
242
 
214
243
  /** PURE. Fixed-size chunks. */
@@ -427,10 +456,12 @@ export async function digestSession(text, { brains, brainNames, privateBrain, en
427
456
  let cost = 0
428
457
  const call = async (prompt, model, system) => { const r = await llm(prompt, model, system, env); cost += r.cost; onCost(cost); return r.text }
429
458
  const read = readSessionLog(text, { stopAtLog })
430
- if (!read.log.trim()) throw new Error('empty transcript')
459
+ if (!read.log.trim() && !read.summary) throw new Error('empty transcript')
431
460
  const prs = prStates(read.prs, read.lastAt, env)
432
- const parts = await mapLimit(chunk(read.log), CONCURRENCY, (c) => call(wrapChunk(c), 'haiku', MAP_SYSTEM))
433
- const facts = parts.join('\n')
461
+ // Only what came after the last compaction is read in chunks; its summary stands for everything before it.
462
+ const fresh = read.summary ? read.sinceSummary : read.log
463
+ const parts = fresh.trim() ? await mapLimit(chunk(fresh), CONCURRENCY, (c) => call(wrapChunk(c), 'haiku', MAP_SYSTEM)) : []
464
+ const facts = [read.summary && `EARLIER IN THE SESSION, as its own summary at the last compaction recorded it:\n${read.summary}\n\nAFTER THAT:`, ...parts].filter(Boolean).join('\n')
434
465
  const tail = read.log.slice(-TAIL_CHARS)
435
466
  const written = await call(writerPrompt({ brains, prs, pages: read.pages, obligations: read.obligations, firstAt: read.firstAt, lastAt: read.lastAt, facts, tail }), 'sonnet')
436
467
  const checked = await call(checkPrompt(written, rawForCheck(read.log)), 'sonnet')
@@ -575,7 +606,8 @@ async function closeSession(session, { env, home, stopAtLog = false, write = tru
575
606
  let cost = digest.cost
576
607
  const call = async (prompt, model) => { const r = await llm(prompt, model, undefined, env); cost += r.cost; return r.text }
577
608
  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 })
609
+ // Skipped when the session kept its pages current as it worked: nothing to clean up, nothing spent.
610
+ const wiki = noWiki || !needsWikiPass(digest.read) ? 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 })
579
611
  if (!write) return { ok: true, cost, digest, wiki }
580
612
  const accepted = wiki?.accepted ?? []
581
613
  // Pages first, so the record that follows has them attached: the server attaches what this session wrote.
@@ -11,7 +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
+ const MAX_EXPLORED_EDITS = 40
15
15
  const EVIDENCE_WINDOW = 1_500
16
16
  const MAX_EVIDENCE = 60_000
17
17
  const MAX_PAGE_CHARS = 24_000
@@ -168,11 +168,11 @@ export function gateEdit(edit, { page, allowedBrains, evidence }) {
168
168
  export function explorePrompt({ segments, read, facts, asOf }) {
169
169
  const seen = [...new Set([...segments.flatMap((s) => s.pages), ...read.pages, ...Object.keys(read.pagesRead ?? {})])]
170
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}.
171
+ First list what the session established that a wiki reader needs: for each workstream, every status that changed, every result, and every rule, preference or decision a person stated ("never list connectors in public copy" is one). Then find the page each item belongs on.
172
+ 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, 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'}.
173
+ Bring each page fully current: every item that belongs on it, not only the first. Several edits to one page are normal. A stated rule or decision goes on the page it governs, with who stated it and the date.
174
+ ${RULES(segments, asOf)}
175
+ Finish with JSON only: {"items": [{"item": one short phrase, "page": the page it went on, or null}], "edits": [at most ${MAX_EXPLORED_EDITS} objects ${EDIT_SHAPE}]}.
176
176
 
177
177
  SESSION RECORD:
178
178
  ${segments.map((s) => `[${s.brain}]\n${s.summary}`).join('\n\n')}
@@ -181,6 +181,43 @@ FACT NOTES:
181
181
  ${facts.slice(-40_000)}`
182
182
  }
183
183
 
184
+ /**
185
+ * PURE. The second exploring run: only the items the first left without a page. In the 2026-11-03 test the first run
186
+ * proposed nothing at all for 2 of 8 sessions whose manual close-out fixed a page each.
187
+ */
188
+ export function gapPrompt({ segments, facts, asOf, open, done }) {
189
+ return `A work session has just closed, and the team wiki has been partly updated for it. These items it established have no page yet:
190
+ ${open.map((i) => `- ${i.item}`).join('\n')}
191
+ For each one, search the wiki (grep with names, identifiers and phrases, then follow [[links]]) for an existing page it belongs on, and read the page. An item may truly belong nowhere; then leave it. Pages already being edited, which you need not repeat: ${[...new Set(done.map((e) => e.page))].join(', ') || 'none'}.
192
+ ${RULES(segments, asOf)}
193
+ Finish with JSON only: an array of at most ${MAX_EXPLORED_EDITS} objects ${EDIT_SHAPE}.
194
+
195
+ SESSION RECORD:
196
+ ${segments.map((s) => `[${s.brain}]\n${s.summary}`).join('\n\n')}
197
+
198
+ FACT NOTES:
199
+ ${facts.slice(-40_000)}`
200
+ }
201
+
202
+ const EDIT_SHAPE = '{"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}'
203
+ const RULES = (segments, asOf) => `Only pages in these brains: ${segments.map((s) => s.brain).join(', ')}. Never a confidential page.
204
+ 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. Promised or still owed is not done. Propose an edit only for something this session established first-hand.
205
+ Prefer correcting the sentence that went stale over adding a new paragraph, and never drop a warning or reason that still holds. 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.`
206
+
207
+ /** PURE. The exploring run's reply: its checklist and edits, or a bare array of edits. */
208
+ export function parseExplore(text) {
209
+ const fenced = [...text.matchAll(/```(?:json)?\s*\n([\s\S]*?)```/g)].map((m) => m[1].trim())
210
+ const start = text.indexOf('{"items"') >= 0 ? text.indexOf('{"items"') : text.search(/\{\s*"items"/)
211
+ for (const t of [...fenced.reverse(), start >= 0 ? text.slice(start, text.lastIndexOf('}') + 1) : '']) {
212
+ try {
213
+ const o = JSON.parse(t)
214
+ if (o && Array.isArray(o.edits)) return { items: Array.isArray(o.items) ? o.items : [], edits: o.edits }
215
+ if (Array.isArray(o)) return { items: [], edits: o }
216
+ } catch {}
217
+ }
218
+ return { items: [], edits: parseJsonArray(text) }
219
+ }
220
+
184
221
  /** The fixed proposer: search, read a set of pages, and propose over them a few at a time. */
185
222
  async function proposeFromPages({ segments, read, facts, call, readPage, search, asOf, allowedBrains }) {
186
223
  const pages = []
@@ -209,7 +246,13 @@ async function proposeFromPages({ segments, read, facts, call, readPage, search,
209
246
  */
210
247
  export async function proposeWikiEdits({ segments, read, facts, raw, log = '', call, readPage, search = async () => [], asOf, explore }) {
211
248
  const allowedBrains = segments.map((s) => s.brain)
212
- let proposed = explore ? parseJsonArray(await explore(explorePrompt({ segments, read, facts, asOf })) ?? '').slice(0, MAX_EXPLORED_EDITS) : []
249
+ let proposed = []
250
+ if (explore) {
251
+ const first = parseExplore((await explore(explorePrompt({ segments, read, facts, asOf }))) ?? '')
252
+ proposed = first.edits.slice(0, MAX_EXPLORED_EDITS)
253
+ const open = first.items.filter((i) => i && typeof i.item === 'string' && !i.page)
254
+ if (open.length) proposed.push(...parseExplore((await explore(gapPrompt({ segments, facts, asOf, open, done: proposed }))) ?? '').edits.slice(0, MAX_EXPLORED_EDITS))
255
+ }
213
256
  let pages = []
214
257
  if (proposed.length) {
215
258
  for (const name of new Set(proposed.map((e) => e.page))) {
@@ -151,6 +151,42 @@ export function healFileCapture({ home = homedir() } = {}) {
151
151
  return true
152
152
  }
153
153
 
154
+ export const PAGE_NUDGE_MATCHER = 'Bash|Write|Edit|MultiEdit|mcp__.*__(edit_page|author)'
155
+ export const PAGE_NUDGE_COMMAND =
156
+ `[ -f "$HOME/.cortex/hooks/page-nudge.mjs" ] && node "$HOME/.cortex/hooks/page-nudge.mjs" --agnoclast-managed || true`
157
+
158
+ /** Copy the page-nudge hook (lib/page_nudge.mjs, self-contained) to where its hook runs it. Rewrites only on change. */
159
+ export function installPageNudge({ home = homedir() } = {}) {
160
+ const src = readFileSync(new URL('../page_nudge.mjs', import.meta.url), 'utf8')
161
+ const dir = join(home, '.cortex', 'hooks')
162
+ const dest = join(dir, 'page-nudge.mjs')
163
+ let cur = null
164
+ try { cur = readFileSync(dest, 'utf8') } catch { /* not installed yet */ }
165
+ if (cur === src) return false
166
+ mkdirSync(dir, { recursive: true, mode: 0o700 })
167
+ writeFileSync(dest, src, { mode: 0o600 })
168
+ return true
169
+ }
170
+
171
+ /** True when a settings.json object already carries the page-nudge hook. */
172
+ export function hasPageNudge(settings) {
173
+ return (settings?.hooks?.PostToolUse ?? []).some((g) => (g.hooks ?? []).some((h) => h.command === PAGE_NUDGE_COMMAND))
174
+ }
175
+
176
+ /** SessionStart self-heal (`status`), as healFileCapture: refresh the copy, add ONLY its hook when missing. */
177
+ export function healPageNudge({ home = homedir() } = {}) {
178
+ installPageNudge({ home })
179
+ const file = join(home, '.claude', 'settings.json')
180
+ if (!existsSync(file)) return false
181
+ const s = JSON.parse(readFileSync(file, 'utf8'))
182
+ if (hasPageNudge(s)) return false
183
+ s.hooks = s.hooks ?? {}
184
+ s.hooks.PostToolUse = Array.isArray(s.hooks.PostToolUse) ? s.hooks.PostToolUse : []
185
+ s.hooks.PostToolUse.push({ matcher: PAGE_NUDGE_MATCHER, hooks: [{ type: 'command', command: PAGE_NUDGE_COMMAND }] })
186
+ writeFileSync(file, JSON.stringify(s, null, 2))
187
+ return true
188
+ }
189
+
154
190
  /** Merge Agnoclast's Claude Code hooks into a ~/.claude/settings.json object. Pure + idempotent: drops
155
191
  * any prior cortex entry (old token/path/version) from each hook array before appending the current
156
192
  * one — capture (Stop), status + skills-repair + snapshot-context (SessionStart), hydrate
@@ -219,7 +255,7 @@ export function mergeClaudeSettings(existing, spec) {
219
255
  // settings.json.
220
256
  s.hooks.PostToolUse = Array.isArray(s.hooks.PostToolUse) ? s.hooks.PostToolUse : []
221
257
  for (const pg of s.hooks.PostToolUse) {
222
- if (Array.isArray(pg.hooks)) pg.hooks = pg.hooks.filter((h) => !isManagedSubcommand(h.command, 'arrivals-notice') && !isManagedSubcommand(h.command, 'file-capture'))
258
+ if (Array.isArray(pg.hooks)) pg.hooks = pg.hooks.filter((h) => !isManagedSubcommand(h.command, 'arrivals-notice') && !isManagedSubcommand(h.command, 'file-capture') && !isManagedSubcommand(h.command, 'page-nudge'))
223
259
  }
224
260
  // Drop any group this emptied, so retirement does not leave a bare {matcher:'',hooks:[]} behind.
225
261
  s.hooks.PostToolUse = s.hooks.PostToolUse.filter((g) => (g.hooks ?? []).length)
@@ -230,6 +266,10 @@ export function mergeClaudeSettings(existing, spec) {
230
266
  // PostToolUse channel that IS injected, unlike the stdout that sank the arrivals hook above.
231
267
  s.hooks.PostToolUse.push({ matcher: FILE_CAPTURE_MATCHER, hooks: [{ type: 'command', command: FILE_CAPTURE_COMMAND }] })
232
268
 
269
+ // PostToolUse — page nudge (lib/page_nudge.mjs; Theron, 2026-11-04): pages are written during the work, so after a
270
+ // ship, a spec written to disk, or a long stretch with no page, the session gets one line saying so.
271
+ s.hooks.PostToolUse.push({ matcher: PAGE_NUDGE_MATCHER, hooks: [{ type: 'command', command: PAGE_NUDGE_COMMAND }] })
272
+
233
273
  // 🔴 THIS HOOK DOES NOT FOLLOW `spec`, AND THE REASON IS A DEFECT THIS FILE SHIPPED ONCE.
234
274
  //
235
275
  // `spec` pins @stable, which is what desktop-wired seats deliberately follow. But a hook wired at
@@ -386,6 +426,7 @@ export default {
386
426
  writeJson(settingsJson, mergeClaudeSettings(s, spec))
387
427
  installConfidentialGuard({ home })
388
428
  installFileCapture({ home })
429
+ installPageNudge({ home })
389
430
  wrote.push(settingsJson)
390
431
  log(` ✓ Capture + hydrate hooks + status line → ${settingsJson}${bak ? ' (backup saved)' : ''}`)
391
432
  } catch (e) {
@@ -0,0 +1,94 @@
1
+ // THE PAGE NUDGE (PostToolUse). Pages are meant to be written while the work happens, not at the close: over 138
2
+ // sessions that ran /agnoclast-log, 72% of page writes already came during the work, but 28 sessions wrote nothing
3
+ // until the close (measured 2026-11-04). So at the moments a hook can see, it tells the session in one line:
4
+ // - something shipped (a PR merged, a package published, a deploy),
5
+ // - a plan or spec was written to disk, where only the repo can see it,
6
+ // - a long stretch of edits and commands went by with no page written.
7
+ // It never writes anything to Agnoclast and never blocks: it only adds a line of context, at most once per thing.
8
+ //
9
+ // Self-contained (Node built-ins only): setup copies it to ~/.cortex/hooks/page-nudge.mjs and the hook runs it with
10
+ // plain `node`, since it fires on every Bash and edit call.
11
+ import { readFileSync, writeFileSync, mkdirSync } from 'node:fs'
12
+ import { homedir } from 'node:os'
13
+ import { join, dirname, basename } from 'node:path'
14
+ import { createHash } from 'node:crypto'
15
+
16
+ export const STRETCH = 40
17
+
18
+ const SHIP = [
19
+ [/\bgh\s+pr\s+merge\b/, 'a pull request merged'],
20
+ [/\bnpm\s+publish\b/, 'a package was published'],
21
+ [/\bvercel\b[^\n;&|]*\s--prod\b/, 'a production deploy ran'],
22
+ [/\bwrangler\s+(?:deploy|publish)\b/, 'a deploy ran'],
23
+ [/\bfly(?:ctl)?\s+deploy\b/, 'a deploy ran'],
24
+ ]
25
+ const SPEC_DIR = /\/(?:docs|specs?|plans?|designs?|rfcs?)\/(?:[^/]+\/)*[^/]+\.md$/i
26
+ const NOT_SPEC = /^(?:readme|changelog|claude|agents|license|contributing|security|code_of_conduct)\.md$/i
27
+ const PAGE_WRITE = /__(?:edit_page|author)$/
28
+ const WORK = new Set(['Bash', 'Write', 'Edit', 'MultiEdit'])
29
+
30
+ /** PURE. What, if anything, this one tool call is worth a line about. `state.sinceWrite` counts work since a page. */
31
+ export function nudgeDecision({ tool, input = {}, state = {} }) {
32
+ if (PAGE_WRITE.test(tool)) return { reset: true }
33
+ if (!WORK.has(tool)) return null
34
+ if (tool === 'Bash') {
35
+ const cmd = String(input.command ?? '')
36
+ if (!/--dry-run\b/.test(cmd)) for (const [re, what] of SHIP) if (re.test(cmd)) return { kind: 'ship', key: `ship:${cmd.slice(0, 200)}`, what, cmd }
37
+ } else {
38
+ const path = String(input.file_path ?? '')
39
+ if (SPEC_DIR.test(path) && !NOT_SPEC.test(basename(path)) && !/\/node_modules\//.test(path)) return { kind: 'spec', key: `spec:${path}`, path }
40
+ }
41
+ if ((state.sinceWrite ?? 0) + 1 >= STRETCH) return { kind: 'stretch', key: `stretch:${state.stretches ?? 0}`, count: (state.sinceWrite ?? 0) + 1 }
42
+ return { count: true }
43
+ }
44
+
45
+ /** PURE. The line the session reads: facts and options, never orders. */
46
+ export function nudgeLine(d) {
47
+ if (d.kind === 'ship') return `Agnoclast note: ${d.what} (\`${d.cmd.trim().slice(0, 80)}\`). The page about this work may now be behind what this session knows; it can be brought current with edit_page now, while the details are in front of it.`
48
+ if (d.kind === 'spec') return `Agnoclast note: ${basename(d.path)} looks like a plan or spec, and on disk only this repo can see it. If it is one, it can live on a page (author), or the page it belongs to can link it, so teammates and later sessions find it.`
49
+ return `Agnoclast note: ${d.count} edits and commands since this session last wrote a page. If any of it changed what a page says (a status, a decision, a result), this is a natural point to edit that page.`
50
+ }
51
+
52
+ const statePath = (home, sessionId) =>
53
+ join(home, '.cortex', 'page-nudge', createHash('sha256').update(String(sessionId)).digest('hex').slice(0, 32) + '.json')
54
+
55
+ /** The hook: reads the PostToolUse payload, keeps a small per-session state, returns the output or null. */
56
+ export function runPageNudge({ input, home = homedir(), env = process.env }) {
57
+ if (env.CORTEX_SUMMARIZING) return null
58
+ let p
59
+ try { p = JSON.parse(input) } catch { return null }
60
+ if (!p?.session_id || !p.tool_name) return null
61
+ const file = statePath(home, p.session_id)
62
+ let state = {}
63
+ try { state = JSON.parse(readFileSync(file, 'utf8')) } catch { /* first call this session */ }
64
+ const d = nudgeDecision({ tool: p.tool_name, input: p.tool_input ?? {}, state })
65
+ if (!d) return null
66
+ if (d.reset) { save(file, { ...state, sinceWrite: 0 }); return null }
67
+ const sinceWrite = (state.sinceWrite ?? 0) + 1
68
+ if (!d.kind || state.nudged?.[d.key]) { save(file, { ...state, sinceWrite }); return null }
69
+ const next = { ...state, sinceWrite: d.kind === 'stretch' ? 0 : sinceWrite, nudged: { ...state.nudged, [d.key]: true } }
70
+ if (d.kind === 'stretch') next.stretches = (state.stretches ?? 0) + 1
71
+ save(file, next)
72
+ return { hookSpecificOutput: { hookEventName: 'PostToolUse', additionalContext: nudgeLine(d) } }
73
+ }
74
+
75
+ function save(file, state) {
76
+ try {
77
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 })
78
+ writeFileSync(file, JSON.stringify(state), { mode: 0o600 })
79
+ } catch { /* a hook never fails the session */ }
80
+ }
81
+
82
+ // Run directly (the hook), never on import (setup and tests import it).
83
+ if (process.argv[1] && import.meta.url === new URL(`file://${process.argv[1]}`).href) {
84
+ let input = ''
85
+ process.stdin.setEncoding('utf8')
86
+ process.stdin.on('data', (c) => { input += c })
87
+ process.stdin.on('end', () => {
88
+ try {
89
+ const out = runPageNudge({ input })
90
+ if (out) process.stdout.write(JSON.stringify(out))
91
+ } catch { /* never fail the session */ }
92
+ process.exit(0)
93
+ })
94
+ }
package/lib/setup.mjs CHANGED
@@ -6,7 +6,7 @@ import { resolveChannel } from './channel.mjs'
6
6
  import { installSkills } from './skills.mjs'
7
7
  // Pure config-merge functions live in the editor adapters; setup imports (and re-exports) THE SAME
8
8
  // functions the `cortex install` path uses, so both write byte-identical config.
9
- import { mergeClaudeMcp, mergeClaudeSettings, installConfidentialGuard, installFileCapture } from './editors/claude.mjs'
9
+ import { mergeClaudeMcp, mergeClaudeSettings, installConfidentialGuard, installFileCapture, installPageNudge } from './editors/claude.mjs'
10
10
  import { mergeCodexToml, mergeCodexHooks } from './editors/codex.mjs'
11
11
 
12
12
  // One-command employee onboarding. Wires both:
@@ -156,6 +156,7 @@ export async function runSetup(argv, version) {
156
156
  s = mergeClaudeSettings(s, spec)
157
157
  installConfidentialGuard()
158
158
  installFileCapture()
159
+ installPageNudge()
159
160
 
160
161
  ensureDir(settingsJson)
161
162
  writeFileSync(settingsJson, JSON.stringify(s, null, 2))
package/lib/uninstall.mjs CHANGED
@@ -31,7 +31,7 @@ const CORTEX_DIR = join(HOME, '.cortex')
31
31
  const LAUNCH_AGENTS = join(HOME, 'Library', 'LaunchAgents')
32
32
  // Hook events the installer writes (editors/claude.mjs). UserPromptSubmit was MISSING here until
33
33
  // 2026-08-19, so every uninstall left the `hydrate` hook behind while reporting success.
34
- export const MANAGED_HOOK_EVENTS = ['Stop', 'SessionStart', 'UserPromptSubmit', 'PreCompact', 'PreToolUse']
34
+ export const MANAGED_HOOK_EVENTS = ['Stop', 'SessionStart', 'UserPromptSubmit', 'PreCompact', 'PreToolUse', 'PostToolUse']
35
35
 
36
36
  export function runUninstall(argv = []) {
37
37
  const dry = argv.includes('--dry-run') || argv.includes('-n')
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theronap/agnoclast-mcp",
3
- "version": "0.9.306",
3
+ "version": "0.9.308",
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": {
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: agnoclast-log
3
- description: Close out a work session into Agnoclast — summarize what happened, confirm it reached the org, and surface anything teammates should know. Run at or near the end of any working session.
3
+ description: Close out a work session into Agnoclast now — summarize what happened, confirm it reached the org, and surface anything teammates should know. Run it when the person asks, or at the end of a session on a machine without the automatic close-out; pages and arrivals belong in the work itself, not here.
4
4
  ---
5
5
 
6
6
  > **Agnoclast-managed skill.** This file is installed and kept up to date by Agnoclast. Local edits are
@@ -16,10 +16,19 @@ personal `/log` skill follows the same shape against the local brain.
16
16
 
17
17
  ## When to use
18
18
 
19
- At the end of a Claude Code session, or after finishing a meaningful phase of work. Agnoclast keeps a
20
- background auto-capture as a fallback, but this skill is the *authoritative* close-out: it composes a
21
- clean, structured summary and persists THAT as the session's durable record (superseding the
22
- auto-capture's raw-transcript re-derivation).
19
+ **Pages and arrivals are work, not close-out.** Edit the page a change made stale when you make the change, and
20
+ file what arrives while it is in front of you; anything you cannot place, release for another session. Over 138
21
+ sessions measured 2026-11-04, 72% of page writes already happened during the work, and the sessions that left them
22
+ all to the end are what this skill was mostly mopping up.
23
+
24
+ So run this skill when:
25
+ - **the person asks** for the session to be closed out now, or
26
+ - **this machine has no automatic close-out** and the session is ending. Check with
27
+ `ls ~/Library/LaunchAgents/com.agnoclast.closeout.plist`: if it exists, a background job logs the session about
28
+ 45 minutes after it goes quiet (ADR-0107), so do not run this out of habit.
29
+
30
+ When it does run, it is the *authoritative* close-out: it composes a clean, structured summary and persists THAT as
31
+ the session's durable record (superseding the background re-derivation).
23
32
 
24
33
  ## Inputs
25
34