@theronap/agnoclast-mcp 0.9.286 → 0.9.288

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.
@@ -124,6 +124,8 @@ if (cmd === '--help' || cmd === '-h' || cmd === 'help') {
124
124
  ` use-brain [<brain>] where your session captures are saved — no arg shows the current setting\n` +
125
125
  ` skills install/repair the managed Agnoclast skills — bundled + org-published (also wired by setup)\n` +
126
126
  ` skills push <file> publish a SKILL.md to your org (owner/manager/admin)\n` +
127
+ ` closeout-sweep close out one quiet Claude Code session in the background (--dry-run to preview)\n` +
128
+ ` closeout-install run closeout-sweep every 30 minutes on this Mac (--remove to stop)\n` +
127
129
  ` docs-scan detect new/changed local docs pending Agnoclast authoring (used by /cortex-author-docs)\n` +
128
130
  ` graphify-sync [path] [--brain <name-or-id>] rebuild the local code graph + log a timeline event\n` +
129
131
  ` snapshot-context save the exact startup context Agnoclast served to a local snapshot\n` +
@@ -202,6 +204,12 @@ if (cmd === 'login') {
202
204
  const { healConfidentialGuard } = await import('../lib/editors/claude.mjs')
203
205
  healConfidentialGuard()
204
206
  } catch { /* never fail session start over this */ }
207
+ } else if (cmd === 'closeout-sweep') {
208
+ const { runCloseoutSweep } = await import('../lib/closeout.mjs')
209
+ await runCloseoutSweep(process.argv.slice(3))
210
+ } else if (cmd === 'closeout-install') {
211
+ const { installCloseout } = await import('../lib/closeout.mjs')
212
+ installCloseout(process.argv.slice(3))
205
213
  } else if (cmd === 'capture') {
206
214
  const { runCapture } = await import('../lib/capture.mjs')
207
215
  await runCapture()
@@ -0,0 +1,186 @@
1
+ // THE BACKGROUND CLOSE-OUT: a quiet Claude Code session closes itself out, so nobody has to remember
2
+ // /agnoclast-log (Theron, 2026-11-01). A launchd job runs `closeout-sweep`, which finds substantive sessions
3
+ // that have gone quiet and resumes one, in a throwaway fork, to run the real close-out.
4
+ //
5
+ // ⚠ NEVER FROM A HOOK. A slow `claude -p` in the Stop hook locked the input box for up to 90 seconds a turn
6
+ // (2026-07-08), and why it hung was never found. So this is a separate process with a hard timeout.
7
+ //
8
+ // ⚠ COST. Resuming re-reads a session's whole context, so only substantive sessions qualify, one runs per sweep,
9
+ // and DAILY_LIMIT caps a day. A session too large to resume sensibly is reported, not run.
10
+ import { readdirSync, readFileSync, statSync, writeFileSync, mkdirSync, existsSync, rmSync } from 'node:fs'
11
+ import { spawn, spawnSync } from 'node:child_process'
12
+ import { createHash } from 'node:crypto'
13
+ import { homedir } from 'node:os'
14
+ import { basename, dirname, join } from 'node:path'
15
+
16
+ const QUIET_MS = 45 * 60 * 1000
17
+ const MAX_AGE_MS = 3 * 24 * 60 * 60 * 1000
18
+ const MAX_TRANSCRIPT_BYTES = 12 * 1000 * 1000
19
+ const MIN_PROMPTS = 3
20
+ const MAX_ATTEMPTS = 2
21
+ const DAILY_LIMIT = 6
22
+ const RUN_TIMEOUT_MS = 15 * 60 * 1000
23
+ const MAX_BUDGET_USD = '3'
24
+ const CLOSED_LINE = /^CLOSED: record ([0-9a-f-]{36})/m
25
+
26
+ const WORK_TOOLS = new Set(['Edit', 'Write', 'NotebookEdit', 'mcp__agnoclast__author', 'mcp__agnoclast__edit_page'])
27
+ const COMMITTED = /\bgit\b[^\n]*\b(commit|push)\b|\bgh pr (create|merge)\b/
28
+ const HUMAN_ENTRYPOINTS = new Set(['claude-desktop', 'cli'])
29
+
30
+ /** PURE. What a transcript says about itself. Tolerates partial or foreign lines. */
31
+ export function summarizeTranscript(text) {
32
+ const s = { entrypoint: null, cwd: null, prompts: 0, work: 0, logged: false }
33
+ for (const line of text.split('\n')) {
34
+ if (!line) continue
35
+ let d
36
+ try { d = JSON.parse(line) } catch { continue }
37
+ if (d.entrypoint) s.entrypoint ??= d.entrypoint
38
+ if (d.cwd) s.cwd ??= d.cwd
39
+ if (d.isSidechain) continue
40
+ const content = d.message?.content
41
+ if (d.type === 'user' && !d.isMeta) {
42
+ const typed = typeof content === 'string' || (Array.isArray(content) && content.some((c) => c.type === 'text'))
43
+ if (typed) s.prompts += 1
44
+ }
45
+ if (d.type !== 'assistant' || !Array.isArray(content)) continue
46
+ for (const c of content) {
47
+ if (c.type !== 'tool_use') continue
48
+ if (c.name === 'mcp__agnoclast__log_session') s.logged = true
49
+ if (WORK_TOOLS.has(c.name) || (c.name === 'Bash' && COMMITTED.test(c.input?.command ?? ''))) s.work += 1
50
+ }
51
+ }
52
+ return s
53
+ }
54
+
55
+ /** PURE. Why this session gets no close-out, or null when it qualifies. */
56
+ export function skipReason(session, state, now) {
57
+ const quiet = now - session.mtimeMs
58
+ if (quiet < QUIET_MS) return 'active'
59
+ if (quiet > MAX_AGE_MS) return 'too_old'
60
+ if (state.closed?.[session.id]) return 'closed'
61
+ if ((state.attempts?.[session.id] ?? 0) >= MAX_ATTEMPTS) return 'gave_up'
62
+ if (session.confidential) return 'confidential'
63
+ if (!HUMAN_ENTRYPOINTS.has(session.entrypoint)) return 'not_a_person'
64
+ if (session.logged) return 'already_logged'
65
+ if (session.prompts < MIN_PROMPTS || !session.work) return 'not_substantive'
66
+ if (session.bytes > MAX_TRANSCRIPT_BYTES) return 'too_large'
67
+ return null
68
+ }
69
+
70
+ /** PURE. Most work first, so a capped day spends itself on what matters. */
71
+ export function pickNext(sessions, state, now) {
72
+ return sessions.filter((s) => !skipReason(s, state, now)).sort((a, b) => b.work - a.work)[0] ?? null
73
+ }
74
+
75
+ export function closeoutPrompt(sessionId) {
76
+ return [
77
+ 'This session has gone quiet, and you are running unattended to close it out. The person is not here.',
78
+ 'Run the agnoclast-log skill now, with these changes:',
79
+ `- Call log_session with sessionId "${sessionId}", the brain the work was in, and pages naming the pages it was about.`,
80
+ '- When work could belong to several brains, use the more private one.',
81
+ '- Only update a wiki page for something this session established first-hand. Never send, delete or change who can see anything.',
82
+ '- If you cannot read the skill, still call log_session with a concrete summary of what changed, what was decided and what is open.',
83
+ 'End with one line, exactly: CLOSED: record <the record id log_session returned>. If nothing landed, end with: NOT CLOSED: <why>.',
84
+ ].join('\n')
85
+ }
86
+
87
+ const stateFile = (home) => join(home, '.cortex', 'closeout', 'state.json')
88
+
89
+ function readState(home) {
90
+ try { return JSON.parse(readFileSync(stateFile(home), 'utf8')) } catch { return { closed: {}, attempts: {}, runs: {} } }
91
+ }
92
+
93
+ function writeState(home, state) {
94
+ mkdirSync(dirname(stateFile(home)), { recursive: true })
95
+ writeFileSync(stateFile(home), JSON.stringify(state, null, 2))
96
+ }
97
+
98
+ function findSessions(home) {
99
+ const root = join(home, '.claude', 'projects')
100
+ const out = []
101
+ const now = Date.now()
102
+ for (const dir of existsSync(root) ? readdirSync(root) : []) {
103
+ let names
104
+ try { names = readdirSync(join(root, dir)) } catch { continue }
105
+ for (const name of names) {
106
+ if (!name.endsWith('.jsonl')) continue
107
+ const path = join(root, dir, name)
108
+ const st = statSync(path)
109
+ if (now - st.mtimeMs > MAX_AGE_MS) continue
110
+ const id = basename(name, '.jsonl')
111
+ const marker = join(home, '.cortex', 'confidential-sessions', createHash('sha256').update(id).digest('hex'))
112
+ out.push({ id, path, mtimeMs: st.mtimeMs, bytes: st.size, confidential: existsSync(marker), ...summarizeTranscript(readFileSync(path, 'utf8')) })
113
+ }
114
+ }
115
+ return out
116
+ }
117
+
118
+ function runCloseout(session, env) {
119
+ return new Promise((resolve) => {
120
+ const args = ['-p', closeoutPrompt(session.id), '--resume', session.id, '--fork-session', '--no-session-persistence',
121
+ '--model', 'sonnet', '--max-budget-usd', MAX_BUDGET_USD, '--tools', 'Read,Skill,ToolSearch',
122
+ '--allowedTools', 'Read', 'Skill', 'ToolSearch', 'mcp__agnoclast__*']
123
+ // CORTEX_SUMMARIZING: the capture hook's own recursion guard, so this run is never captured as a session.
124
+ const child = spawn('claude', args, { cwd: existsSync(session.cwd ?? '') ? session.cwd : homedir(), env: { ...env, CORTEX_SUMMARIZING: '1' }, stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true })
125
+ let out = ''
126
+ child.stdout.on('data', (b) => { out += b })
127
+ child.stderr.on('data', (b) => { out += b })
128
+ const timer = setTimeout(() => { out += '\n[timed out]'; child.kill('SIGKILL') }, RUN_TIMEOUT_MS)
129
+ child.on('error', (e) => { clearTimeout(timer); resolve({ ok: false, out: e.message }) })
130
+ child.on('close', () => { clearTimeout(timer); resolve({ ok: CLOSED_LINE.test(out), recordId: out.match(CLOSED_LINE)?.[1] ?? null, out: out.slice(-1500) }) })
131
+ })
132
+ }
133
+
134
+ const LABEL = 'com.agnoclast.closeout'
135
+
136
+ /** PURE. A launchd job every 30 minutes; login shell so `claude` and `npx` are on PATH. */
137
+ export function closeoutPlist(home) {
138
+ const command = `npx -y @theronap/agnoclast-mcp@latest closeout-sweep >> "${home}/.cortex/closeout/sweep.log" 2>&1`
139
+ return `<?xml version="1.0" encoding="UTF-8"?>
140
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
141
+ <plist version="1.0"><dict>
142
+ <key>Label</key><string>${LABEL}</string>
143
+ <key>ProgramArguments</key><array><string>/bin/zsh</string><string>-lc</string><string>${command}</string></array>
144
+ <key>StartInterval</key><integer>1800</integer>
145
+ <key>RunAtLoad</key><false/>
146
+ </dict></plist>
147
+ `
148
+ }
149
+
150
+ /** Install or remove the job on this Mac. Off by default: it runs models on the person's own account. */
151
+ export function installCloseout(argv = [], { home = homedir(), log = console.log } = {}) {
152
+ const path = join(home, 'Library', 'LaunchAgents', `${LABEL}.plist`)
153
+ spawnSync('launchctl', ['unload', path], { stdio: 'ignore', windowsHide: true })
154
+ if (argv.includes('--remove')) {
155
+ rmSync(path, { force: true })
156
+ log('Background close-out removed.')
157
+ return
158
+ }
159
+ mkdirSync(join(home, '.cortex', 'closeout'), { recursive: true })
160
+ writeFileSync(path, closeoutPlist(home))
161
+ const loaded = spawnSync('launchctl', ['load', path], { windowsHide: true })
162
+ log(loaded.status === 0 ? `Background close-out installed: ${path}` : `Wrote ${path}, but launchctl failed: ${loaded.stderr}`)
163
+ }
164
+
165
+ /** One sweep. `--dry-run` prints what qualifies and spends nothing; `--session <id>` runs one named session. */
166
+ export async function runCloseoutSweep(argv = [], { home = homedir(), env = process.env, log = console.log } = {}) {
167
+ if (env.CORTEX_SUMMARIZING) return
168
+ const now = Date.now()
169
+ const today = new Date(now).toISOString().slice(0, 10)
170
+ const state = readState(home)
171
+ const sessions = findSessions(home)
172
+ const named = argv.includes('--session') ? argv[argv.indexOf('--session') + 1] : null
173
+ const reasons = {}
174
+ for (const s of sessions) { const r = skipReason(s, state, now) ?? 'qualifies'; reasons[r] = (reasons[r] ?? 0) + 1 }
175
+ log(JSON.stringify({ at: new Date(now).toISOString(), runsToday: state.runs?.[today] ?? 0, reasons }))
176
+ if (argv.includes('--dry-run')) return
177
+ if (!named && (state.runs?.[today] ?? 0) >= DAILY_LIMIT) return
178
+ const next = named ? sessions.find((s) => s.id === named) : pickNext(sessions, state, now)
179
+ if (!next) return
180
+ state.attempts = { ...state.attempts, [next.id]: (state.attempts?.[next.id] ?? 0) + 1 }
181
+ state.runs = { [today]: (state.runs?.[today] ?? 0) + 1 }
182
+ writeState(home, state)
183
+ const result = await runCloseout(next, env)
184
+ if (result.ok) writeState(home, { ...state, closed: { ...state.closed, [next.id]: result.recordId } })
185
+ log(JSON.stringify({ session: next.id, closed: result.recordId, tail: result.ok ? undefined : result.out }))
186
+ }
@@ -40,7 +40,7 @@ export function mergeClaudeMcp(existing, spec, token) {
40
40
  export const ALLOWED_TOOL_NAMES = [
41
41
  // read surface
42
42
  'grep', 'read_page', 'my_context', 'project_status', 'session_context', 'search_org',
43
- 'list_records', 'read_record', 'page_history', 'page_diff', 'timeline_pull', 'my_brains', 'my_sessions', 'token_activity', 'hand_task', 'my_tasks', 'finish_task', 'handed_tasks', 'writing_style',
43
+ 'list_records', 'read_record', 'page_history', 'page_diff', 'timeline_pull', 'my_brains', 'my_sessions', 'token_activity', 'hand_task', 'my_tasks', 'tasks_waiting', 'finish_task', 'handed_tasks', 'writing_style',
44
44
  'code_graph_query', 'my_retier_notices', 'list_page_grants', 'list_project_members', 'file_requests',
45
45
  // the questions agents used to answer with SQL (2026-10-07) — read-only, the caller's own view
46
46
  'record_status', 'my_connectors', 'brain_stats', 'my_sends', 'find_arrivals',
@@ -5,7 +5,7 @@
5
5
  // that web/lib/engine/release.test.ts pins to the server's registry.
6
6
 
7
7
  /** Tools any release flag gates — hidden when the server cannot be asked. Mirror of allGatedTools(). */
8
- 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', 'import_document_as_page', 'intake_shadow', 'list_documents', 'my_messages', 'my_tasks', 'pin_document', 'read_conversation', 'read_document', 'send_message', 'set_manager', 'upload_document_version']
8
+ 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', '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
9
 
10
10
  export const RELEASE_FETCH_TIMEOUT_MS = 2500
11
11
 
package/lib/server.mjs CHANGED
@@ -543,7 +543,7 @@ export async function runServer(version) {
543
543
  // The header stamps page revisions, so a new id here keeps a log joined to the pages it wrote.
544
544
  if (rotated) setSessionKey(rotated)
545
545
  const result = await handler(...args)
546
- const taskLine = name === 'my_tasks' || name === 'handed_tasks' ? null : await taskNotice()
546
+ const taskLine = name === 'my_tasks' || name === 'handed_tasks' || name === 'tasks_waiting' ? null : await taskNotice()
547
547
  if (taskLine && Array.isArray(result?.content)) result.content = [...result.content, { type: 'text', text: taskLine }]
548
548
  if (!result?.isError) {
549
549
  if (name === 'log_session') {
@@ -6286,6 +6286,21 @@ function renderNudge(payload) {
6286
6286
  },
6287
6287
  )
6288
6288
 
6289
+ server.registerTool(
6290
+ 'tasks_waiting',
6291
+ {
6292
+ title: 'How many tasks are waiting',
6293
+ description: 'Just the count of open tasks handed to this token, as `waiting: N`. It marks nothing as picked up, so a cheap poller can call it as often as it likes and wake an agent only when N is above zero. To read the tasks, use my_tasks.',
6294
+ inputSchema: {},
6295
+ },
6296
+ async () => {
6297
+ try {
6298
+ const { waiting } = await tasksCall('?box=count')
6299
+ return { content: [{ type: 'text', text: `waiting: ${waiting}` }] }
6300
+ } catch (e) { return toolError(`Could not count your tasks: ${e.message}`) }
6301
+ },
6302
+ )
6303
+
6289
6304
  server.registerTool(
6290
6305
  'finish_task',
6291
6306
  {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theronap/agnoclast-mcp",
3
- "version": "0.9.286",
3
+ "version": "0.9.288",
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": {