feat(run): per-file recognition isolation + LLM extraction fallback (deep)

E1: each file's extraction is isolated — a recognition failure logs extract_error, leaves the file in inbox, and never breaks the rest of the batch (failed count surfaced). E2: local-first recognition stays 0 tokens (Apple Vision OCR / markitdown / whisper); only when local yields nothing usable AND --deep is on does a vision-capable LLM (llmText, Read tool) transcribe the file. New llmText() in the provider bridge (Claude primary, Codex parity).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Зарубин Филипп
2026-06-18 17:29:34 +03:00
co-authored by Claude Opus 4.8
parent 72424cfdb2
commit b92328837e
2 changed files with 77 additions and 17 deletions
+26
View File
@@ -137,3 +137,29 @@ export async function llmJson(prompt, schema, opts = {}) {
const provider = activeProvider(opts) const provider = activeProvider(opts)
return provider === 'codex' ? codexJsonCall(prompt, schema, opts) : claudeJsonCall(prompt, schema, opts) return provider === 'codex' ? codexJsonCall(prompt, schema, opts) : claudeJsonCall(prompt, schema, opts)
} }
// Plain-text call (no schema) — used for vision/extraction fallback where the
// agent reads a local file (image/PDF) and transcribes it. Tools opt-in; for
// file reading pass tools:['Read']. Returns raw text. Claude primary; Codex at
// parity (runs in the file's directory so it can open it).
export async function llmText(prompt, opts = {}) {
const provider = activeProvider(opts)
if (provider === 'codex') {
if (!binExists(CODEX_BIN)) throw new Error(`codex binary not found: ${CODEX_BIN}`)
const res = spawnSync(CODEX_BIN, [
'exec', '-C', opts.cwd || process.cwd(), '--skip-git-repo-check',
'--dangerously-bypass-approvals-and-sandbox', '-'
], { input: prompt, encoding: 'utf8', timeout: opts.timeoutMs || TIMEOUT_MS, maxBuffer: 64 * 1024 * 1024 })
if (res.status !== 0) throw new Error(`codex exec failed (status ${res.status}): ${String(res.stderr || '').slice(-400)}`)
return String(res.stdout || '').trim()
}
const bin = resolveClaudeBin()
if (!binExists(bin)) throw new Error('claude binary not found: set MNEMAZINE_CLAUDE_BIN')
const args = ['-p', '--output-format', 'json']
if (opts.tools?.length) args.push('--allowedTools', opts.tools.join(','))
const res = spawnSync(bin, args, { input: prompt, encoding: 'utf8', timeout: opts.timeoutMs || TIMEOUT_MS, maxBuffer: 64 * 1024 * 1024 })
if (res.status !== 0) throw new Error(`claude -p failed (status ${res.status}): ${String(res.stderr || '').slice(-400)}`)
let envelope
try { envelope = JSON.parse(res.stdout) } catch { envelope = null }
return (envelope && typeof envelope.result === 'string' ? envelope.result : res.stdout).trim()
}
+42 -8
View File
@@ -4,6 +4,7 @@ import { existsSync } from 'node:fs'
import path from 'node:path' import path from 'node:path'
import crypto from 'node:crypto' import crypto from 'node:crypto'
import { spawnSync } from 'node:child_process' import { spawnSync } from 'node:child_process'
import { llmAvailable, llmText } from './mnemazine-llm.mjs'
const ROOT = process.env.MNEMAZINE_ROOT || path.resolve(process.cwd()) const ROOT = process.env.MNEMAZINE_ROOT || path.resolve(process.cwd())
const INBOX = process.env.MNEMAZINE_INBOX || path.join(ROOT, 'inbox') const INBOX = process.env.MNEMAZINE_INBOX || path.join(ROOT, 'inbox')
@@ -242,6 +243,22 @@ async function extract(file) {
return '' return ''
} }
// LLM recognition fallback (deep only). Used ONLY when local engines (Apple
// Vision OCR / markitdown / whisper) produced nothing usable — keeps the default
// path at 0 tokens. A vision-capable agent reads the file and transcribes it.
async function llmExtract(file) {
const ext = path.extname(file).toLowerCase()
const kind = isImage(file) ? 'image' : isVideo(file) ? 'video frame still' : 'document'
const prompt = `Read the local ${kind} file and output ALL of its information as plain text: transcribe every readable word verbatim, then add a short factual description of any non-text content (diagrams, charts, UI). No commentary, no preamble.\n\nFILE: ${file}`
// Claude reads via the Read tool; Codex reads files in its working dir.
const text = await llmText(prompt, {
tools: ['Read'],
cwd: path.dirname(file),
timeoutMs: COMMAND_TIMEOUT_MS
})
return text || ''
}
async function writeExtractCache(source, hash, text, status) { async function writeExtractCache(source, hash, text, status) {
await ensureDir(EXTRACTS) await ensureDir(EXTRACTS)
const ext = path.extname(source).toLowerCase().replace('.', '') || 'file' const ext = path.extname(source).toLowerCase().replace('.', '') || 'file'
@@ -281,27 +298,44 @@ async function main() {
let processed = 0 let processed = 0
let cachedOnly = 0 let cachedOnly = 0
const toArchive = [] const toArchive = []
let failed = 0
const canLlmExtract = DEEP && llmAvailable()
for (const [index, entry] of entries.entries()) { for (const [index, entry] of entries.entries()) {
const file = path.join(INBOX, entry.name) const file = path.join(INBOX, entry.name)
// Per-file isolation: one file's recognition failure must NEVER break the
// others. Any throw here is contained — the file stays in inbox for a retry.
try {
const hash = await sha256(file) const hash = await sha256(file)
if (cache[hash]) continue if (cache[hash]) continue
const text = await extract(file) // Local-first recognition (0 tokens): Apple Vision OCR / markitdown / whisper.
let text = await extract(file)
// Only if local produced nothing usable AND deep is on: LLM recognition.
if (!hasUsableExtraction(text) && canLlmExtract && (isImage(file) || isVideo(file) || isMarkitdownDocument(file))) {
try {
const llmText = await llmExtract(file)
if (hasUsableExtraction(llmText)) text = llmText
} catch (err) {
console.error(JSON.stringify({ file: entry.name, llm_extract_error: String(err.message).slice(0, 200) }))
}
}
if (!hasUsableExtraction(text)) { if (!hasUsableExtraction(text)) {
const record = await writeExtractCache(file, hash, text, 'needs_manual_context') const record = await writeExtractCache(file, hash, text, 'needs_manual_context')
cache[hash] = { status: record.status, source_ref: record.source_ref, cache: path.relative(ROOT, path.join(EXTRACTS, `${hash}.json`)) } cache[hash] = { status: record.status, source_ref: record.source_ref, cache: path.relative(ROOT, path.join(EXTRACTS, `${hash}.json`)) }
toArchive.push({ file, hash }) toArchive.push({ file, hash })
cachedOnly += 1 cachedOnly += 1
if (PROGRESS_EVERY > 0 && (index + 1) % PROGRESS_EVERY === 0) { } else {
console.error(JSON.stringify({ progress: index + 1, total: entries.length, processed, cached_only: cachedOnly }))
}
continue
}
await writeExtractCache(file, hash, text, 'extracted_for_note') await writeExtractCache(file, hash, text, 'extracted_for_note')
cache[hash] = { status: 'extracted_for_note', source_ref: sourceRef(hash), cache: path.relative(ROOT, path.join(EXTRACTS, `${hash}.json`)) } cache[hash] = { status: 'extracted_for_note', source_ref: sourceRef(hash), cache: path.relative(ROOT, path.join(EXTRACTS, `${hash}.json`)) }
toArchive.push({ file, hash }) toArchive.push({ file, hash })
processed += 1 processed += 1
}
} catch (err) {
// Isolated failure: log, leave file in inbox, keep going.
failed += 1
console.error(JSON.stringify({ file: entry.name, extract_error: String(err.message).slice(0, 200) }))
}
if (PROGRESS_EVERY > 0 && (index + 1) % PROGRESS_EVERY === 0) { if (PROGRESS_EVERY > 0 && (index + 1) % PROGRESS_EVERY === 0) {
console.error(JSON.stringify({ progress: index + 1, total: entries.length, processed, cached_only: cachedOnly })) console.error(JSON.stringify({ progress: index + 1, total: entries.length, processed, cached_only: cachedOnly, failed }))
} }
} }
await fs.writeFile(CACHE, JSON.stringify(cache, null, 2), 'utf8') await fs.writeFile(CACHE, JSON.stringify(cache, null, 2), 'utf8')
@@ -325,7 +359,7 @@ async function main() {
if (DEEP) { if (DEEP) {
spawnSync(process.execPath, [path.join(ROOT, 'scripts/mnemazine-digest.mjs')], { stdio: 'inherit', env: process.env }) spawnSync(process.execPath, [path.join(ROOT, 'scripts/mnemazine-digest.mjs')], { stdio: 'inherit', env: process.env })
} }
console.log(JSON.stringify({ inbox: entries.length, processed, cached_only: cachedOnly, archived: archived.length, deep: DEEP, vault: VAULT }, null, 2)) console.log(JSON.stringify({ inbox: entries.length, processed, cached_only: cachedOnly, failed, archived: archived.length, deep: DEEP, vault: VAULT }, null, 2))
} }
main().catch(err => { main().catch(err => {