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:
co-authored by
Claude Opus 4.8
parent
72424cfdb2
commit
b92328837e
@@ -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()
|
||||||
|
}
|
||||||
|
|||||||
+51
-17
@@ -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)
|
||||||
const hash = await sha256(file)
|
// Per-file isolation: one file's recognition failure must NEVER break the
|
||||||
if (cache[hash]) continue
|
// others. Any throw here is contained — the file stays in inbox for a retry.
|
||||||
const text = await extract(file)
|
try {
|
||||||
if (!hasUsableExtraction(text)) {
|
const hash = await sha256(file)
|
||||||
const record = await writeExtractCache(file, hash, text, 'needs_manual_context')
|
if (cache[hash]) continue
|
||||||
cache[hash] = { status: record.status, source_ref: record.source_ref, cache: path.relative(ROOT, path.join(EXTRACTS, `${hash}.json`)) }
|
// Local-first recognition (0 tokens): Apple Vision OCR / markitdown / whisper.
|
||||||
toArchive.push({ file, hash })
|
let text = await extract(file)
|
||||||
cachedOnly += 1
|
// Only if local produced nothing usable AND deep is on: LLM recognition.
|
||||||
if (PROGRESS_EVERY > 0 && (index + 1) % PROGRESS_EVERY === 0) {
|
if (!hasUsableExtraction(text) && canLlmExtract && (isImage(file) || isVideo(file) || isMarkitdownDocument(file))) {
|
||||||
console.error(JSON.stringify({ progress: index + 1, total: entries.length, processed, cached_only: cachedOnly }))
|
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) }))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
continue
|
if (!hasUsableExtraction(text)) {
|
||||||
|
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`)) }
|
||||||
|
toArchive.push({ file, hash })
|
||||||
|
cachedOnly += 1
|
||||||
|
} else {
|
||||||
|
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`)) }
|
||||||
|
toArchive.push({ file, hash })
|
||||||
|
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) }))
|
||||||
}
|
}
|
||||||
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`)) }
|
|
||||||
toArchive.push({ file, hash })
|
|
||||||
processed += 1
|
|
||||||
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 => {
|
||||||
|
|||||||
Reference in New Issue
Block a user