File size: 14,485 Bytes
46f490b
 
 
 
 
 
 
66f16a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46f490b
 
 
 
 
66f16a0
46f490b
 
 
 
66f16a0
 
 
 
46f490b
 
66f16a0
46f490b
 
 
 
66f16a0
 
 
 
 
46f490b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66f16a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46f490b
 
66f16a0
 
 
46f490b
 
 
 
 
66f16a0
 
 
 
 
 
 
46f490b
66f16a0
 
 
 
 
 
 
46f490b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66f16a0
46f490b
 
 
 
 
 
66f16a0
 
 
 
46f490b
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
// BudgetBench system: PULSE LOCAL, the app's own chat pipeline (answerPipeline), wired as
// app/electron/state/llmState.ts wires it and as bench/chat-eval.mjs runs it, on a household loaded from its SOURCE
// files the way a person loads them (a bank file through the importer, a connected bank through the Plaid page
// ingest). Two variants:
//   rules        the shipped rules with the tuned 0.6B chat model, "Better understanding" OFF (the default at 16 GB)
//   reader       "Better understanding" ON (the default above 16 GB): Qwen3-4B-Instruct-2507 reads every message
//                too, policy "strict" (agree or not sure), with the shipped example bank
//   reader3      EVAL ONLY (PREREG-small-checker.md, step 1, 2026-10-20): the same strict check, with the fine-tuned 0.6B
//                reader (Qwen3-0.6B-reader3, eval-synth, 2026-10-02) as the second reader in place of the 4B. It gets the
//                prompt it was trained on: `readerSystem` (no field guide), `readerUser` (the message with the last two
//                messages and their reads), no retrieved examples, the grammar of this household's names. The pipeline
//                already takes that path when no example bank is given, so nothing in the app changes; the reading goes
//                through the same `readerWorksheet` and the same agreement check as the 4B's. The packaged app never
//                runs this file. BB_READER3_MODEL overrides the GGUF's path.
//   reader4      EVAL ONLY (PREREG-small-checker-step2.md, step 2, 2026-10-21): the reader3 mechanism unchanged (same prompt,
//                no examples, same grammar, same strict check) with the step-2 fine-tune (Qwen3-0.6B-reader4, trained on
//                many authors' gold-verified readings plus refusal rows). The GGUF is BB_READER3_MODEL, which must be set.
//   reader5      EVAL ONLY (PREREG-small-checker-v2sealed.md, 2026-10-22): the same mechanism with the 0.4.19 fine-tune
//                (Qwen3-0.6B-reader5: reader4's data plus the new_merchants field, ledgers in other currencies and
//                exclusions said as a noun phrase). The GGUF is BB_READER3_MODEL, which must be set.
//   shipped      (0.4.19, 2026-10-22) the second reader EXACTLY as the app wires it: opened, called and handed to the
//                pipeline by the app's own module, app/electron/llm/secondReader.ts (no example bank, policy strict). With
//                BB_READER3_MODEL = reader5's GGUF it must give the reader5 variant's reader output and answer on every
//                turn of the same tree: that is the proof that the app ships the measured checker. The reader5 code
//                above stays as measured and is never changed.
// The runner gives every system the same interface: open(household) -> {ask(history, message)}.
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import {fileURLToPath} from "node:url";
import {createHash} from "node:crypto";

const APP = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../app");
const MODEL_FILE = process.env.BB_PULSE_MODEL ?? path.join(APP, "models/Qwen3-0.6B-pulse-v4-Q4_K_M.gguf");
const READER_FILE = path.join(APP, "models/hf_unsloth_Qwen3-4B-Instruct-2507-Q4_K_M.gguf");
const READER3_FILE = process.env.BB_READER3_MODEL ?? path.resolve(APP, "../models/Qwen3-0.6B-reader3-Q4_K_M.gguf");
const READER4_FILE = process.env.BB_READER3_MODEL ?? null;
const readerFileOf = (variant) => (variant === "reader" ? READER_FILE : variant === "reader3" ? READER3_FILE : variant === "reader4" || variant === "reader5" || variant === "shipped" ? READER4_FILE : null);
const learnedVariant = (variant) => variant === "reader3" || variant === "reader4" || variant === "reader5" || variant === "shipped";

export const name = "pulse-local";
export const variants = ["rules", "reader", "reader3", "reader4", "reader5", "shipped"];
// the budget ledger is one per process: one household per process
export const processPerHousehold = true;

export async function describe(variant) {
    const rf = readerFileOf(variant);
    if ((variant === "reader4" || variant === "reader5" || variant === "shipped") && rf == null) throw new Error(`${variant} needs BB_READER3_MODEL set to its GGUF`);
    return {system: "Pulse Local", variant, model: path.basename(MODEL_FILE), reader: rf != null ? path.basename(rf) : null,
        ...(learnedVariant(variant) ? {reader_sha256: createHash("sha256").update(fs.readFileSync(rf)).digest("hex"), reader_prompt: "readerSystem + readerUser, no examples"} : {}),
        ...(variant === "shipped" ? {reader_wiring: "app/electron/llm/secondReader.ts"} : {}),
        version: JSON.parse(fs.readFileSync(path.join(APP, "package.json"), "utf8")).version};
}

/** load a household from its source files into a fresh ledger, then build the pipeline's dependencies */
export async function open(hhDir, setup, variant = "rules") {
    if (process.env.PULSE_TODAY !== setup.today) throw new Error("PULSE_TODAY must be set to the household's today before the app loads");
    process.env.VITE_PUBLIC ??= path.join(APP, "public");
    const {getLlama, LlamaLogLevel, LlamaChatSession} = await import("node-llama-cpp");
    const {openBudgetDb, ledgerDb} = await import(path.join(APP, "electron/budget/db.ts"));
    const {importCsv} = await import(path.join(APP, "electron/budget/importer.ts"));
    const {applyPage, accountNamesFor} = await import(path.join(APP, "electron/connected/ingest.ts"));
    const {upsertAccount} = await import(path.join(APP, "electron/budget/runway.ts"));
    const {setRegion} = await import(path.join(APP, "electron/budget/currency.ts"));
    const {setAccountCurrency} = await import(path.join(APP, "electron/budget/accountCurrency.ts"));
    const {chatFacts, planContext, budgetApi, readerContext: ledgerReaderContext} = await import(path.join(APP, "electron/budget/api.ts"));
    const {categoryBreakdown, ledgerSummary, recentMonths, searchTransactions} = await import(path.join(APP, "electron/ledger/db.ts"));
    const {answerQuery} = await import(path.join(APP, "electron/budget/query.ts"));
    const {buildSystemPrompt} = await import(path.join(APP, "electron/llm/systemPrompt.ts"));
    const {modelFunctions} = await import(path.join(APP, "electron/llm/modelFunctions.ts"));
    const {CONTEXT_SIZE, MAX_ANSWER_TOKENS, TEMPERATURE} = await import(path.join(APP, "electron/llm/modelConfig.ts"));
    const {getNote, notesShown} = await import(path.join(APP, "electron/llm/narrator.ts"));
    const {trimHistory} = await import(path.join(APP, "electron/llm/rawChat.ts"));
    const router = await import(path.join(APP, "electron/llm/router.ts"));
    const pipeline = await import(path.join(APP, "electron/llm/pipeline.ts"));

    // the ledger, as a person in this household would have it
    openBudgetDb(fs.mkdtempSync(path.join(os.tmpdir(), `bb-pulse-${setup.id}-`)));
    if (setup.region && setup.region !== "US") setRegion(setup.region);
    let loaded = 0;
    for (const f of setup.load) {
        const text = fs.readFileSync(path.join(hhDir, f.file), "utf8");
        if (f.kind === "plaid") {
            const p = JSON.parse(text);
            const names = accountNamesFor(p.institution, p.accounts);
            ledgerDb().prepare("INSERT INTO connected_items (connection_id, institution, accounts, cursor, last_pulled_at, created_at) VALUES (?, ?, ?, NULL, NULL, ?)")
                .run(p.connection_id, p.institution, JSON.stringify(names), setup.today);
            applyPage(p.connection_id, p.institution, p.page, names);
            for (const a of p.accounts) if (a.balance_current != null) upsertAccount(names[a.account_id], a.type === "credit" ? "credit" : "checking", a.balance_current, null);
            loaded += p.page.added.length;
        } else {
            const r = importCsv(path.basename(f.file), text, f.account ?? "Checking");
            loaded += r.inserted ?? r.imported ?? 0;
            // (the import's currency card, answered "keep this account in <currency>" for an account in another currency)
            if (f.currency && f.currency !== setup.currency) setAccountCurrency([f.account], f.currency);
        }
    }

    const llama = await getLlama({logLevel: LlamaLogLevel.error});
    const model = await llama.loadModel({modelPath: MODEL_FILE});
    const context = await model.createContext({contextSize: CONTEXT_SIZE, sequences: 1});
    const seq = context.getSequence();
    await router.loadRouter(llama, path.join(APP, "models"));
    const facts = ledgerSummary(), months = recentMonths();
    const tools = Object.entries(modelFunctions).map(([n, f]) => ({name: n, description: f.description ?? "", params: f.params ?? {type: "object", properties: {}}, handler: (args) => f.handler(args)}));
    const systemPrompt = buildSystemPrompt(setup.today, months, facts);
    let reader = {};
    // (per ask: each reader call's milliseconds and whether it gave JSON, for the latency and "no reading" counts)
    let readerCalls = [];
    if (variant === "shipped") {
        // the app's own module, as electron/state/llmState.ts uses it; only the timing and the raw output are recorded
        const {openSecondReader, secondReaderDeps} = await import(path.join(APP, "electron/llm/secondReader.ts"));
        const {readQuery: appRead} = await openSecondReader(llama, readerFileOf(variant));
        const readQuery = async (system, user, schema, shots) => {
            const t0 = Date.now();
            const out = await appRead(system, user, schema, shots);
            let json = false;
            try { json = out != null && JSON.parse(out) != null; } catch { json = false; }
            readerCalls.push({ms: Date.now() - t0, json, raw: out});
            return out;
        };
        reader = secondReaderDeps(readQuery, () => ledgerReaderContext(setup.today));
    } else if (variant === "reader" || learnedVariant(variant)) {
        const rmodel = await llama.loadModel({modelPath: readerFileOf(variant)});
        const rseq = (await rmodel.createContext({contextSize: 8192, sequences: 1})).getSequence();
        const grammars = new Map();
        // the app's readQueryLocal (electron/state/llmState.ts), as bench/shapes-check.mjs runs it; with no shots it is
        // eval-synth/reader-ft.mjs's call of the fine-tuned reader (system prompt, one user turn, the grammar, 260 tokens,
        // temperature 0, no thinking)
        const readQuery = async (system, user, schema, shots) => {
            const key = JSON.stringify(schema);
            if (!grammars.has(key)) grammars.set(key, await llama.createGrammarForJsonSchema(schema));
            const session = new LlamaChatSession({contextSequence: rseq, autoDisposeSequence: false, systemPrompt: system});
            if (shots != null && shots.length > 0) session.setChatHistory([{type: "system", text: system}, ...shots.flatMap((x) => [{type: "user", text: x.user}, {type: "model", response: [x.json]}])]);
            const t0 = Date.now();
            let out = null;
            try { out = await session.prompt(user, {grammar: grammars.get(key), maxTokens: 260, temperature: 0, budgets: {thoughtTokens: 0}}); } catch { out = null; } finally { session.dispose({disposeSequence: false}); }
            let json = false;
            try { json = out != null && JSON.parse(out) != null; } catch { json = false; }
            readerCalls.push({ms: Date.now() - t0, json, raw: out});
            return out;
        };
        reader = {readQuery, readerContext: () => ledgerReaderContext(setup.today), readerPolicy: "strict"};
        if (variant === "reader") {
            const {ExampleBank, parseBank} = await import(path.join(APP, "electron/llm/worksheet/bank.ts"));
            const bank = new ExampleBank(parseBank(fs.readFileSync(path.join(APP, "public/reader-bank.jsonl"), "utf8")), (t) => router.embedText(t));
            await bank.init();
            reader.readerExamples = (u, cur) => bank.nearest(u, 8, cur);
        }
    }
    const deps = {
        model, seq, systemPrompt, tools,
        route: router.routeTools, embed: router.embedText, embedStatus: router.routerStatus, embedFault: router.routerFault,
        searchLedger: (w) => { try { return searchTransactions(w).matches.map((m) => ({date: String(m.date), amount: Number(m.amount)})); } catch { return []; } },
        ledgerFacts: facts, ledgerMonths: months, todayIso: setup.today,
        budgetFactsFor: (m) => { try { return chatFacts(m); } catch { return null; } },
        categoryBreakdown: (m, c) => { try { return categoryBreakdown(m, c); } catch { return null; } },
        planContext, runQuery: answerQuery,
        briefing: (m, c) => { try { return budgetApi.briefing(m, c); } catch { return null; } },
        noteFor: (kind, subject) => (notesShown() ? getNote(kind, subject)?.text ?? null : null),
        modelName: path.basename(MODEL_FILE), mode: "local", prefillNoThink: false,
        maxTokens: MAX_ANSWER_TOKENS, temperature: TEMPERATURE,
        ...reader
    };
    return {
        loaded,
        model: path.basename(MODEL_FILE),
        /** one message: {text, choice?: {labels}, history (after), meta} */
        async ask(history, message) {
            const t0 = Date.now();
            readerCalls = [];
            const r = await pipeline.answerPipeline(deps, history, message);
            const text = (r.text + (r.tables ? "\n" + r.tables : "")).trim();
            const after = trimHistory([...history, {role: "user", text: message}, ...(r.newTurns ?? [])], 6);
            const pend = [...(r.newTurns ?? [])].reverse().find((t) => t.state?.pending != null)?.state?.pending;
            const choice = r.path === "clarify" && pend?.kind === "choice" && Array.isArray(pend.options) && pend.options.length ? {labels: pend.options.map((o) => o.label)} : null;
            return {text, choice, history: after, meta: {path: r.path, kind: r.kind ?? null, readBy: r.readBy ?? null, agreement: r.agreement ?? null, tokens: r.tokens ?? 0, ms: Date.now() - t0,
                strip: (r.worksheet?.chips ?? []).map((c) => c.label).join(" · ") || null,
                // (the process memory for every variant since 2026-10-22, so a 4B run reports it beside a 0.6B one)
                rssMB: Math.round(process.memoryUsage().rss / 1048576),
                ...(learnedVariant(variant) ? {reader: readerCalls.map((c) => ({ms: c.ms, json: c.json, raw: c.raw}))} : {})}};
        }
    };
}