@theronap/agnoclast-mcp 0.9.300 → 0.9.302

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.
@@ -204,6 +204,11 @@ if (cmd === 'login') {
204
204
  const { healConfidentialGuard } = await import('../lib/editors/claude.mjs')
205
205
  healConfidentialGuard()
206
206
  } catch { /* never fail session start over this */ }
207
+ // Same for the session file-capture hook (lib/file_capture.mjs).
208
+ try {
209
+ const { healFileCapture } = await import('../lib/editors/claude.mjs')
210
+ healFileCapture()
211
+ } catch { /* never fail session start over this */ }
207
212
  } else if (cmd === 'closeout-sweep') {
208
213
  const { runCloseoutSweep } = await import('../lib/closeout.mjs')
209
214
  await runCloseoutSweep(process.argv.slice(3))
@@ -115,6 +115,42 @@ export function healConfidentialGuard({ home = homedir() } = {}) {
115
115
  return true
116
116
  }
117
117
 
118
+ export const FILE_CAPTURE_MATCHER = 'Write|Edit|MultiEdit|NotebookEdit|Read'
119
+ export const FILE_CAPTURE_COMMAND =
120
+ `[ -f "$HOME/.cortex/hooks/file-capture.mjs" ] && node "$HOME/.cortex/hooks/file-capture.mjs" --agnoclast-managed || true`
121
+
122
+ /** Copy the file-capture hook (lib/file_capture.mjs, self-contained) to where its hook runs it. Rewrites only on change. */
123
+ export function installFileCapture({ home = homedir() } = {}) {
124
+ const src = readFileSync(new URL('../file_capture.mjs', import.meta.url), 'utf8')
125
+ const dir = join(home, '.cortex', 'hooks')
126
+ const dest = join(dir, 'file-capture.mjs')
127
+ let cur = null
128
+ try { cur = readFileSync(dest, 'utf8') } catch { /* not installed yet */ }
129
+ if (cur === src) return false
130
+ mkdirSync(dir, { recursive: true, mode: 0o700 })
131
+ writeFileSync(dest, src, { mode: 0o600 })
132
+ return true
133
+ }
134
+
135
+ /** True when a settings.json object already carries the file-capture hook. */
136
+ export function hasFileCapture(settings) {
137
+ return (settings?.hooks?.PostToolUse ?? []).some((g) => (g.hooks ?? []).some((h) => h.command === FILE_CAPTURE_COMMAND))
138
+ }
139
+
140
+ /** SessionStart self-heal (`status`), as healConfidentialGuard: refresh the copy, add ONLY its hook when missing. */
141
+ export function healFileCapture({ home = homedir() } = {}) {
142
+ installFileCapture({ home })
143
+ const file = join(home, '.claude', 'settings.json')
144
+ if (!existsSync(file)) return false
145
+ const s = JSON.parse(readFileSync(file, 'utf8'))
146
+ if (hasFileCapture(s)) return false
147
+ s.hooks = s.hooks ?? {}
148
+ s.hooks.PostToolUse = Array.isArray(s.hooks.PostToolUse) ? s.hooks.PostToolUse : []
149
+ s.hooks.PostToolUse.push({ matcher: FILE_CAPTURE_MATCHER, hooks: [{ type: 'command', command: FILE_CAPTURE_COMMAND }] })
150
+ writeFileSync(file, JSON.stringify(s, null, 2))
151
+ return true
152
+ }
153
+
118
154
  /** Merge Agnoclast's Claude Code hooks into a ~/.claude/settings.json object. Pure + idempotent: drops
119
155
  * any prior cortex entry (old token/path/version) from each hook array before appending the current
120
156
  * one — capture (Stop), status + skills-repair + snapshot-context (SessionStart), hydrate
@@ -183,11 +219,16 @@ export function mergeClaudeSettings(existing, spec) {
183
219
  // settings.json.
184
220
  s.hooks.PostToolUse = Array.isArray(s.hooks.PostToolUse) ? s.hooks.PostToolUse : []
185
221
  for (const pg of s.hooks.PostToolUse) {
186
- if (Array.isArray(pg.hooks)) pg.hooks = pg.hooks.filter((h) => !isManagedSubcommand(h.command, 'arrivals-notice'))
222
+ if (Array.isArray(pg.hooks)) pg.hooks = pg.hooks.filter((h) => !isManagedSubcommand(h.command, 'arrivals-notice') && !isManagedSubcommand(h.command, 'file-capture'))
187
223
  }
188
224
  // Drop any group this emptied, so retirement does not leave a bare {matcher:'',hooks:[]} behind.
189
225
  s.hooks.PostToolUse = s.hooks.PostToolUse.filter((g) => (g.hooks ?? []).length)
190
- if (!s.hooks.PostToolUse.length) delete s.hooks.PostToolUse
226
+
227
+ // PostToolUse — file-capture (lib/file_capture.mjs; Theron, 2026-11-02): a file the session makes or works on gets
228
+ // stored on the page the work is about, during the session. Plain `node` on a copied file, like the confidential
229
+ // guard below, because it runs after every Write / Edit / Read. It answers through additionalContext — the
230
+ // PostToolUse channel that IS injected, unlike the stdout that sank the arrivals hook above.
231
+ s.hooks.PostToolUse.push({ matcher: FILE_CAPTURE_MATCHER, hooks: [{ type: 'command', command: FILE_CAPTURE_COMMAND }] })
191
232
 
192
233
  // 🔴 THIS HOOK DOES NOT FOLLOW `spec`, AND THE REASON IS A DEFECT THIS FILE SHIPPED ONCE.
193
234
  //
@@ -344,6 +385,7 @@ export default {
344
385
  ensureDir(settingsJson)
345
386
  writeJson(settingsJson, mergeClaudeSettings(s, spec))
346
387
  installConfidentialGuard({ home })
388
+ installFileCapture({ home })
347
389
  wrote.push(settingsJson)
348
390
  log(` ✓ Capture + hydrate hooks + status line → ${settingsJson}${bak ? ' (backup saved)' : ''}`)
349
391
  } catch (e) {
@@ -0,0 +1,188 @@
1
+ #!/usr/bin/env node
2
+ // SESSION FILE CAPTURE (Theron, 2026-11-02). A session that makes or works on a real file stores it in Agnoclast while
3
+ // the work is happening, on the page the work is about.
4
+ //
5
+ // Before this, nothing did. attach_document existed, but only an agent that thought of it called it, and none did:
6
+ // a session could write report.docx, mention it in its record, and leave the file on one laptop (or in a scratch
7
+ // folder deleted with the session). The background close-out was not the answer either, because it is being retired.
8
+ // So this runs IN the session: Claude Code calls it after every Write / Edit / Read (a PostToolUse hook, wired by
9
+ // setup and healed by `status`), and when the file is one worth keeping it tells the session, through
10
+ // additionalContext, to store it. The session picks the page, because only it knows what the work is about.
11
+ //
12
+ // ⚠ additionalContext, NOT stdout. Plain PostToolUse stdout never reaches the model (measured 2026-09-21, the
13
+ // arrivals hook). The JSON additionalContext channel does — verified 2026-11-02 with a headless session that wrote a
14
+ // file and repeated a codeword only the hook had given it.
15
+ //
16
+ // What counts as worth keeping, deliberately narrow so the nudge stays rare enough to be acted on:
17
+ // · a document (Word, Excel, PowerPoint, PDF…) the session created or edited — anywhere;
18
+ // · a text deliverable (Markdown, HTML, CSV, images…) the session created or edited OUTSIDE a git repo. Inside a repo
19
+ // it is code or docs, and those already reach Agnoclast through commits;
20
+ // · a document or spreadsheet the session OPENED outside a repo — what the person handed it to work on.
21
+ // Never: anything under node_modules, .git, ~/.claude, ~/.cortex, temp folders, dotfiles, or over 50 MB.
22
+ //
23
+ // It says nothing unless Agnoclast answers that this person's AI may store files: a paid brain plan, the feature on,
24
+ // and "Let assistants upload files" turned on (ADR-0108; /api/stored-files/capture-status). No answer is silence too,
25
+ // so a free account is never prompted. Its words are facts and options marked "Agnoclast note:", like every other
26
+ // note since 0.9.299.
27
+ //
28
+ // ⚠ SELF-CONTAINED ON PURPOSE: setup copies this one file to ~/.cortex/hooks/ and Claude Code runs it with plain
29
+ // `node` after every Write / Edit / Read, so it may import only Node built-ins (no npx start-up on the hot path).
30
+
31
+ import { readFileSync, writeFileSync, existsSync, statSync, mkdirSync } from 'node:fs'
32
+ import { homedir } from 'node:os'
33
+ import { join, dirname, basename, extname, resolve } from 'node:path'
34
+ import { createHash } from 'node:crypto'
35
+
36
+ export const MAX_BYTES = 50 * 1024 * 1024
37
+ export const RENUDGE_MS = 10 * 60 * 1000
38
+
39
+ const DOCUMENTS = new Set(['docx', 'doc', 'dotx', 'xlsx', 'xlsm', 'xls', 'pptx', 'ppt', 'potx', 'pdf', 'odt', 'ods', 'odp', 'rtf', 'pages', 'numbers', 'key'])
40
+ const DELIVERABLES = new Set(['md', 'markdown', 'html', 'htm', 'csv', 'tsv', 'txt', 'ipynb', 'png', 'jpg', 'jpeg', 'gif', 'webp', 'svg'])
41
+ const OPENED = new Set([...DOCUMENTS, 'csv', 'tsv'])
42
+ const MADE_TOOLS = new Set(['Write', 'Edit', 'MultiEdit', 'NotebookEdit'])
43
+
44
+ /** PURE. Is this path one we never store, whatever its type? */
45
+ export function isExcludedPath(path, home) {
46
+ const p = resolve(path)
47
+ const parts = p.split('/')
48
+ if (parts.includes('node_modules') || parts.includes('.git')) return true
49
+ if (basename(p).startsWith('.')) return true
50
+ const roots = [join(home, '.claude'), join(home, '.cortex'), '/tmp', '/private/tmp', '/var/folders', '/private/var/folders']
51
+ return roots.some((r) => p === r || p.startsWith(`${r}/`))
52
+ }
53
+
54
+ /** True when a folder at or above `dir` holds a .git (a checkout or a worktree). */
55
+ export function inGitRepo(dir, exists = existsSync) {
56
+ let d = resolve(dir)
57
+ for (;;) {
58
+ if (exists(join(d, '.git'))) return true
59
+ const up = dirname(d)
60
+ if (up === d) return false
61
+ d = up
62
+ }
63
+ }
64
+
65
+ /**
66
+ * PURE. What to tell the session about one tool call, or null. `kind` is 'created' | 'edited' | 'opened'.
67
+ * `size` is null when the file is gone.
68
+ */
69
+ export function fileDecision({ tool, path, created, home, inRepo, size }) {
70
+ if (!path || typeof path !== 'string') return null
71
+ const ext = extname(path).slice(1).toLowerCase()
72
+ let kind
73
+ if (MADE_TOOLS.has(tool)) {
74
+ if (!DOCUMENTS.has(ext) && !(DELIVERABLES.has(ext) && !inRepo)) return null
75
+ kind = tool === 'Write' && created ? 'created' : 'edited'
76
+ } else if (tool === 'Read') {
77
+ if (!OPENED.has(ext) || inRepo) return null
78
+ kind = 'opened'
79
+ } else return null
80
+ if (isExcludedPath(path, home)) return null
81
+ if (size == null || size === 0 || size > MAX_BYTES) return null
82
+ return { kind, path: resolve(path), name: basename(path) }
83
+ }
84
+
85
+ /** PURE. The words the session reads. */
86
+ // Facts and options, not orders (0.9.299): runtimes that screen tool output for prompt injection refuse imperatives.
87
+ // The permission is stated as a fact, because it is one — the person turned the setting on.
88
+ const PERMITTED = 'The person turned on "Let assistants upload files", so storing it needs no further OK from them.'
89
+
90
+ export function nudgeText({ kind, path, name }) {
91
+ const find = `find_documents with "${name}"`
92
+ if (kind === 'created') {
93
+ return `Agnoclast note: this session created ${path}. Files a session makes are kept in Agnoclast on the page the work is about: attach_document with that path and the page (grep and read_page find it; the person's own page is rarely the right one). ${PERMITTED} Scratch or throwaway output does not need storing. A later change to the file goes up as a new version with upload_document_version.`
94
+ }
95
+ if (kind === 'edited') {
96
+ return `Agnoclast note: this session changed ${path}. If Agnoclast already holds it (${find}), upload_document_version adds this as a new version. If it does not and the file is real work rather than scratch, attach_document stores it on the page the work is about. ${PERMITTED}`
97
+ }
98
+ return `Agnoclast note: this session opened ${path}. If the work here is about this file and Agnoclast does not hold it yet (${find}), attach_document stores it on the page it belongs to. ${PERMITTED} A file that was only a passing reference does not need storing.`
99
+ }
100
+
101
+ /** The token and base the local Agnoclast server was wired with. */
102
+ export function agnoclastCredentials({ home, env = process.env, read = readFileSync } = {}) {
103
+ let token = env.CORTEX_TOKEN || null
104
+ let base = env.CORTEX_URL || null
105
+ if (!token) {
106
+ try {
107
+ const cfg = JSON.parse(read(join(home, '.claude.json'), 'utf8'))
108
+ const s = cfg?.mcpServers?.agnoclast ?? cfg?.mcpServers?.cortex
109
+ token = s?.env?.CORTEX_TOKEN ?? null
110
+ base = base ?? s?.env?.CORTEX_URL ?? null
111
+ } catch { /* not wired */ }
112
+ }
113
+ return { token, base: (base || 'https://agnoclast.com').replace(/\/+$/, '') }
114
+ }
115
+
116
+ /** true / false from the server's capture-status, or null when it could not be asked. */
117
+ async function uploadsAllowed({ home, fetchImpl = globalThis.fetch }) {
118
+ const { token, base } = agnoclastCredentials({ home })
119
+ if (!token || !fetchImpl) return null
120
+ try {
121
+ const res = await fetchImpl(`${base}/api/stored-files/capture-status`, { headers: { Authorization: `Bearer ${token}` }, signal: AbortSignal.timeout(4000) })
122
+ if (!res.ok) return null
123
+ const view = await res.json()
124
+ return typeof view?.store === 'boolean' ? view.store : null
125
+ } catch { return null }
126
+ }
127
+
128
+ const statePath = (home, sessionId) =>
129
+ join(home, '.cortex', 'file-capture', createHash('sha256').update(String(sessionId)).digest('hex').slice(0, 32) + '.json')
130
+
131
+ /**
132
+ * Run as a hook: read Claude Code's PostToolUse payload, answer with additionalContext or nothing. Per session it
133
+ * asks the server about the upload setting once, and names each file at most once every ten minutes.
134
+ */
135
+ export async function runFileCapture({ input, home = homedir(), now = Date.now(), fetchImpl, exists = existsSync, stat = statSync } = {}) {
136
+ let p
137
+ try { p = JSON.parse(input) } catch { return null }
138
+ const path = p?.tool_input?.file_path ?? p?.tool_input?.notebook_path
139
+ if (!path || !p?.session_id) return null
140
+ let size = null
141
+ try { size = stat(path).size } catch { /* gone */ }
142
+ const d = fileDecision({
143
+ tool: p.tool_name,
144
+ path,
145
+ created: p?.tool_response?.type === 'create',
146
+ home,
147
+ inRepo: inGitRepo(dirname(resolve(p.cwd ?? '.', path)), exists),
148
+ size,
149
+ })
150
+ if (!d) return null
151
+
152
+ const file = statePath(home, p.session_id)
153
+ let state = { uploads: undefined, nudged: {} }
154
+ try { state = { ...state, ...JSON.parse(readFileSync(file, 'utf8')) } } catch { /* first file this session */ }
155
+ const last = state.nudged?.[d.path]
156
+ if (last && now - last < RENUDGE_MS) return null
157
+ // Asked again after ten minutes, so turning the setting on mid-session takes effect in that session.
158
+ if (state.uploads == null || now - (state.uploadsAt ?? 0) >= RENUDGE_MS) {
159
+ state.uploads = await uploadsAllowed({ home, fetchImpl })
160
+ state.uploadsAt = now
161
+ }
162
+ // Only a yes is a yes: not paid, uploads off, offline or an old server all say nothing.
163
+ if (state.uploads !== true) { save(file, state); return null }
164
+ state.nudged = { ...state.nudged, [d.path]: now }
165
+ save(file, state)
166
+ return { hookSpecificOutput: { hookEventName: 'PostToolUse', additionalContext: nudgeText(d) } }
167
+ }
168
+
169
+ function save(file, state) {
170
+ try {
171
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 })
172
+ writeFileSync(file, JSON.stringify(state), { mode: 0o600 })
173
+ } catch { /* a hook never fails the session */ }
174
+ }
175
+
176
+ // Run directly (the hook), never on import (setup and tests import it).
177
+ if (process.argv[1] && import.meta.url === new URL(`file://${process.argv[1]}`).href) {
178
+ let input = ''
179
+ process.stdin.setEncoding('utf8')
180
+ process.stdin.on('data', (c) => { input += c })
181
+ process.stdin.on('end', async () => {
182
+ try {
183
+ const out = await runFileCapture({ input })
184
+ if (out) process.stdout.write(JSON.stringify(out))
185
+ } catch { /* never fail the session */ }
186
+ process.exit(0)
187
+ })
188
+ }
@@ -22,7 +22,7 @@ export const REGULAR_ONLY_TOOLS = [
22
22
  'list_records', 'read_record', 'timeline_pull', 'record_status', 'set_record_notes', 'set_record_privacy',
23
23
  'relabel_record_people', 'supersede_record', 'move_record', 'contain_record', 'pending_records', 'claim_record',
24
24
  'route_record', 'unroute_record', 'request_file', 'get_file', 'create_custom_source', 'search_spam_email',
25
- 'gmail_modify', 'draft_email_reply', 'request_send_email', 'send_imessage', 'add_to_brain',
25
+ 'gmail_modify', 'draft_email_reply', 'request_send_email', 'send_imessage',
26
26
  ]
27
27
 
28
28
  /** What a locked tool answers when the check itself could not be made. Nothing was run. */
@@ -11,7 +11,7 @@
11
11
  // That is safe because hiding a tool is a courtesy, and every gated route checks its own flag on the server.
12
12
 
13
13
  /** Tools any release flag gates — hidden when the server cannot be asked. Mirror of allGatedTools(). */
14
- 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', 'hold_task', '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']
14
+ 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', 'hold_task', 'import_document_as_page', 'intake_shadow', 'list_documents', 'my_messages', 'my_tasks', 'pin_document', 'read_conversation', 'read_document', 'send_message', 'set_manager', 'store_file', 'tasks_waiting', 'upload_document_version']
15
15
 
16
16
  export const RELEASE_FETCH_TIMEOUT_MS = 2500
17
17
  /** A remembered answer older than this is not trusted: a week covers a quiet weekend without hiding tools for long. */
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 } from './editors/claude.mjs'
9
+ import { mergeClaudeMcp, mergeClaudeSettings, installConfidentialGuard, installFileCapture } from './editors/claude.mjs'
10
10
  import { mergeCodexToml, mergeCodexHooks } from './editors/codex.mjs'
11
11
 
12
12
  // One-command employee onboarding. Wires both:
@@ -155,6 +155,7 @@ export async function runSetup(argv, version) {
155
155
  // PreCompact reminder from seats that still carry it.
156
156
  s = mergeClaudeSettings(s, spec)
157
157
  installConfidentialGuard()
158
+ installFileCapture()
158
159
 
159
160
  ensureDir(settingsJson)
160
161
  writeFileSync(settingsJson, JSON.stringify(s, null, 2))
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theronap/agnoclast-mcp",
3
- "version": "0.9.300",
3
+ "version": "0.9.302",
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": {