@theronap/agnoclast-mcp 0.9.286 → 0.9.287
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/bin/cortex-mcp.mjs +8 -0
- package/lib/closeout.mjs +186 -0
- package/package.json +1 -1
package/bin/cortex-mcp.mjs
CHANGED
|
@@ -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()
|
package/lib/closeout.mjs
ADDED
|
@@ -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
|
+
}
|
package/package.json
CHANGED