Commit History
-
Improve diagram layout, relationship correctness and validation; patch dependencies Running
DONG-WEI-YANG6ec5c72 -
fix: harden privacy, access limits, drafts and graceful shutdown
DONG-WEI-YANGf609b94
-
docs: document the raw-SQL DB init gotcha in feedback.ts and ragStore.ts
DONG-WEI-YANG +1: Claude Sonnet 5Investigated the "3 incompatible DB init strategies" backlog item. src/db/index.ts (main app.db) tracks real drizzle-kit migrations plus one idempotent runtime patch (ensureKeyPrefixColumn) for the column that predates migration tracking. feedback.ts and ragStore.ts instead create their tables via raw `CREATE TABLE IF NOT EXISTS` — a second, separately-maintained copy of feedback-schema.ts/rag-schema.ts's shape, currently in sync but with nothing enforcing that it stays that way. Deliberately not doing either of the two more invasive options: - Migrating these onto real drizzle-kit migrations now would mean generating a first migration against tables that already exist from raw SQL in already-deployed databases — the same "risky first migration against live data" class of problem as the key_prefix situation already deferred pending explicit user sign-off. - Building idempotent ALTER TABLE scaffolding preemptively would be speculative future-proofing for a column addition tha…720b4c5 -
docs(security): document sharp/adm-zip vulnerability reachability analysis
DONG-WEI-YANG +1: Claude Sonnet 5npm audit flags @huggingface/transformers as high-severity via two transitive deps with no available fix — sharp (libvips CVEs) and onnxruntime-node -> adm-zip (ZIP-parsing DoS). Traced both call graphs to determine real exploitability rather than just accepting the audit severity label at face value: - sharp's vulnerable image-decoding path is never reached: this app only calls transformers.js's feature-extraction pipeline for text embeddings (ragEmbedder.ts), and separately, the app's own OCR endpoints send images straight to a cloud vision API rather than processing them locally with sharp. - adm-zip is only referenced in onnxruntime-node's postinstall script (extracting its prebuilt native binary at `npm install` time) — never imported by code that runs during normal server operation. Recorded this as a code comment next to where @huggingface/transformers is actually used, so a future `npm audit` run doesn't require re-deriving the reachability analysis from scratch, …64365fc -
fix(react): resolve stale-closure bugs surfaced by exhaustive-deps
DONG-WEI-YANG +1: Claude Sonnet 5The react-hooks/exhaustive-deps lint rule (just added in the previous commit) caught two real bugs, not just style nitpicks: 1. NewSOAP.tsx, NewNursingNote.tsx, NewNursingPlan.tsx: handleConfirm's useCallback read `orgName` state (org_name: orgName) but didn't list it as a dependency. Since the callback's other dependencies don't change every time orgName does, React can reuse a stale memoized closure — if a user fills in 機構名稱 last, without touching any other field afterward, the submitted record's org_name reflects whatever it was BEFORE that edit, not what they just typed. Reproduced and verified the fix in a real browser: filled every field, typed 機構名稱 last, submitted immediately, and confirmed via the network response that org_name now correctly matches what was actually typed (a prior row in the same table, created before this fix, has org_name permanently blank from hitting exactly this bug). 2. VoiceWizard.tsx's step-2 AI-extract handler read t…c61e606 -
chore(lint): add ESLint, fix mechanical violations, remove dead code
DONG-WEI-YANG +1: Claude Sonnet 5No lint tooling existed in this project at all. Added ESLint 9 flat config (eslint.config.js) with typescript-eslint, eslint-plugin-react, and only the two classic eslint-plugin-react-hooks rules (rules-of-hooks, exhaustive-deps) rather than its full v7 "recommended" preset — that preset bundles the entire React Compiler rule set (set-state-in-effect, immutability, purity, etc.) as errors, which flags common existing patterns (e.g. syncing a tRPC query's error into local state via useEffect) that are safe today since this codebase doesn't use the Compiler. Adopting those is a deliberate future decision, not a side effect of adding lint tooling. `npm run lint` / `lint:fix` added. Ran eslint --fix for the mechanically-safe violations (useless escapes, useless try/catch, prefer-const, unused eslint-disable directives), then fixed the rest by hand: - target="_blank" without rel="noreferrer" on 3 external links (Home.tsx, Privacy.tsx x2) — real reverse-tabnabbing risk in older browsers.…01fbb71 -
perf(rag): cache the BM25 index instead of rebuilding it on every search
DONG-WEI-YANG +1: Claude Sonnet 5search()/searchBM25Only() called buildBM25Index() from scratch on every invocation — tokenizing every document's full content and recomputing document-frequency stats for the whole corpus, every single call. This cost scales with corpus size and now matters more than it used to: the earlier wantsDiagrams fix made every voice-to-form call across all 7 record types hit getGenogramRagContext/getEcomapRagContext, multiplying search() call volume. Documents are immutable once inserted — ragStore.ts's addDocument always assigns a fresh crypto.randomUUID() and nothing ever updates a row's content in place, only inserts or deletes (deleteExpired, deleteByCategory). That makes a cache keyed by the exact SET of document ids in the filtered corpus a safe, simple staleness check: if the id set matches exactly, the cached index is guaranteed still correct, no explicit invalidation hooks needed anywhere documents get written. Cache key is `${role}:${source}: ${category}` — the same tuple that alrea…f72e57d -
test: add coverage for cmsQuota, complianceRules, crawlTargets, wordExport
DONG-WEI-YANG +1: Claude Sonnet 5Four files had zero test coverage despite being real, used product logic (flagged in the original audit backlog): - src/server/services/cmsQuota.ts: CMS-level quota math driving the usage bar in NewCareTracking.tsx (ai.getQuotaSummary). 21 tests covering frequency-string parsing across all supported formats, unknown/invalid CMS levels, unknown service codes falling back to the default price, and the remaining/utilizationPercent math (including the over-quota case where remaining floors at 0). No bugs found — all pass as written. - src/lib/complianceRules.ts: the LTC rule-hint lookup actually rendered in supervisor/NewQualityCheck.tsx. 5 tests covering known/unknown codes and case sensitivity. - src/server/services/complianceRules.ts: turned out to be a dead byte-for-byte duplicate of the lib version's data, plus two more functions (checkCompliance, getAllComplianceRules) that were never imported anywhere in the server — confirmed via grep before deleting. Same …80f80eb
-
fix(security): derive consent-log IP from tRPC context, never client input
DONG-WEI-YANG +1: Claude Sonnet 5consent.log accepted an optional client-supplied `ipAddress` field and stored it verbatim into consent_logs — a table the app's own privacy notice describes as retained as legal evidence of consent. Any caller hitting the public endpoint directly (bypassing the frontend, which never even populated this field) could write an arbitrary IP into that record. Separately, record.create's automatic consent logging never captured an IP at all — the column was always left null. Added a real tRPC context: trpc.ts now uses initTRPC.context<Context>() with `{ ip: string | null }`, and a new context.ts derives it from Express's req.ip via createExpressMiddleware's createContext option. index.ts already sets `trust proxy` (for express-rate-limit), so req.ip correctly resolves through X-Forwarded-For behind Cloud Run/HF Spaces' reverse proxy rather than returning the proxy's own address. Removed the client-supplied ipAddress field from consent.log's input schema entirely and wired ctx.ip into both c…beda5a1 -
fix(ai): inject genogram/ecomap RAG context for all 7 record types
DONG-WEI-YANG +1: Claude Sonnet 5structureFromVoice gated RAG context injection behind a wantsDiagrams check that only fired for recordType 'visit'/'social_assessment', with a comment claiming "SOAP/nursing_*/care_tracking/quality_check are pure formData — no diagrams, no RAG context." That comment was wrong: reading prompts/nurse.ts, prompts/caseManager.ts, and prompts/supervisor.ts shows all three response schemas include genogram+ecomap fields and their system prompts embed GENOGRAM_PROMPT_FRAGMENT/ECOMAP_PROMPT_FRAGMENT — the AI is already instructed to extract genogram/ecomap data for SOAP, nursing_note, nursing_plan, care_tracking, and quality_check. They just never got the domain-knowledge RAG context (coding-guide chunks, LTC service codes, crawled care-resource docs) that visit/social_assessment did, so extraction quality for those 5 record types was worse without a code reason for it. Removed the wantsDiagrams gate — RAG context now injects for all 7 record types. TDD: tests/aiRouter.test.ts asserts getGeno…4650a6f -
refactor(backend): extract shared findRecordByKey helper
DONG-WEI-YANG +1: Claude Sonnet 5record.retrieve and export.word each had an identical copy-pasted block: pre-filter candidate records by keyPrefix, then bcrypt.compare against each to find the real match. Any future fix to this logic (timing-attack hardening, legacy-prefix cleanup) risked landing in only one copy. Extracted to src/server/services/recordLookup.ts. Pure refactor, no behavior change — standardized on the "金鑰錯誤或紀錄已過期" message (record.ts's version; export.ts previously said "金鑰錯誤或紀錄不存在" for the identical condition). Verified via the existing test suite, which already exercises both procedures extensively (no new tests needed for a same-behavior extraction). Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>8c43020 -
fix(backend): cap ltc3.match/search input length
DONG-WEI-YANG +1: Claude Sonnet 5Every other free-text input in the app caps at 50,000 chars (voice.ts, ai.ts) — ltc3.match's transcript and ltc3.search's query had no upper bound at all, despite matchServiceCodes() running hundreds of string scans per call, protected only by the generic 100/min rate limiter. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>fcd5907 -
fix(backend): wire up crawl scheduler + RAG expiry purge; add missing test coverage
DONG-WEI-YANG +1: Claude Sonnet 5initCrawlSchedule() (weekly regulatory-doc crawl) and deleteExpired() (90-day RAG doc purge) were both fully implemented and exported but had zero callers anywhere — the LTC regulation RAG knowledge base never actually refreshed in production, and expired documents never got purged. Wires both into src/server/index.ts, mirroring the existing initCleanupJob() pattern (cleanup.ts): immediate purge at startup + a recurring cron job, errors caught and logged per-role, never propagated. initCrawlSchedule() only registers cron callbacks (the first real crawl waits for its weekly tick), so it's safe to call unconditionally at every boot. Also closes two previously-flagged, completely untested code paths found along the way: - tests/cleanup.test.ts: purgeExpiredRecords() (the mechanism behind the "7-day auto-delete" privacy promise) had zero test coverage. Covers expiry filtering, cascade-delete of genograms/ecomaps/ encrypted_files, and that consent_logs are correctly retained. - tests…0da068d -
fix(security): mount retrieveLimiter/createLimiter; make batch matching robust
DONG-WEI-YANG +1: Claude Sonnet 5retrieveLimiter (key-guessing protection) and createLimiter (storage abuse protection) were fully defined but never app.use()'d anywhere — record.retrieve/export.word/record.create only ever got the generic 100/min limiter. Generalizes the aiLimiter path-matching fix from an earlier commit into a reusable limiterForProcedure() helper that parses tRPC's `/trpc/proc1,proc2` batch path into individual procedure names and matches against any of them — closing the batch-ordering bypass for ALL per-procedure limiters at once (a plain path-prefix mount only ever inspects the start of the combined path, so a targeted procedure anywhere but first in a batch silently skipped the limiter). retrieveLimiter's original value (3/min, apparently never load-tested since it was dead code) turned out too strict once actually wired in — even the integration test suite's realistic call volume, sharing one IP across many test cases, tripped it and broke unrelated tests with garbled non-tRPC-shaped 429 res…fa1fd00 -
fix(feedback): log when the Google Sheets sync fails instead of swallowing it
DONG-WEI-YANG +1: Claude Sonnet 5The fire-and-forget POST to FEEDBACK_SHEETS_URL used `.catch(() => {})` with no logging at all -- if the webhook URL ever broke, there was no way to notice short of the team independently realizing the sheet stopped updating. The sync stays fire-and-forget (correctly doesn't block the user's response), but failures now go through pino at warn level. Adds FEEDBACK_DB_URL to vitest.config.ts's test env (matching the existing RAG_DATA_DIR pattern) so tests/feedback.test.ts doesn't write into the real local dev feedback.db. The test calls appRouter's tRPC caller directly rather than spinning a subprocess server, since pino needs to be mocked at the module level to be spy-able (it writes straight to stdout, not console.*) -- something only possible when the router code runs in the same process as the test. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>5010774 -
fix(ai): nlpCorrector HF request format was broken; remove dead AI modules
DONG-WEI-YANG +1: Claude Sonnet 5Layer 4 ("AI 深度校正") of the voice-transcript correction pipeline sent {inputs: '', parameters: {model, messages, ...}} to the HF text-generation endpoint -- inputs was always empty and the real prompt was buried inside parameters.messages, a shape that endpoint never reads. Every single voice recording paid a wasted 15s HTTP round trip for zero effect, and the failure was swallowed by a bare catch{}. Rewritten to use llmProviders.ts's existing callOpenAICompat against the correct HF router chat-completions endpoint, with logger.warn (not .debug -- pino defaults to level 'info' and this repo never sets LOG_LEVEL, so a debug log here would've been silently dropped, reproducing the exact silent-failure bug this fix removes). Also deletes aiRouter.ts, confidenceGate.ts, codeMapper.ts, soapClassifier.ts, and contextManager.ts -- confirmed via grep to have zero callers anywhere outside each other, and zero test coverage. tinyNlp.ts is deleted too since its only real consumer was this dead cl…faec29b -
fix(security): patch critical vulnerabilities from full-app audit
DONG-WEI-YANG +1: Claude Sonnet 5- record.retrieve/genogram.load/ecomap.load now travel via POST body instead of GET, so the record access key never lands in URL query strings, proxy logs, browser history, or Referer headers (httpBatchLink methodOverride + allowMethodOverride) - express.json body limit 2mb -> 20mb, and ai.ts's imageBase64 gets an explicit .max() -- the old 2mb cap silently 413'd realistic photo uploads and multi-file record attachments before Zod ever ran - app.use('/trpc/ai.', aiLimiter) never actually matched in Express 5 (a path-prefix mount only matches when followed by '/' or EOS, never a procedure name) -- every paid AI call was silently running under only the generic 100/min limiter instead of the intended 10/min. Fixed via explicit req.path.startsWith() check; also caps tRPC batch size so one HTTP request can't smuggle dozens of AI calls past the per-request limiter - genogram.save/ecomap.save never verified the caller's key against the record's keyHash before encryptin…b81c93f
-
fix(offline-ai): 2 more bugs found via live browser inference (CSP wasm-eval, OPFS cache reporting)
DONG-WEI-YANG +1: Claude Fable 5Continuing the T11 smoke test after the prior 3-bug fix, live inference in Chromium surfaced two more real bugs: 1. CSP script-src lacked 'wasm-unsafe-eval', so WebAssembly.instantiate() itself was blocked ("Compiling or instantiating WebAssembly module violates CSP") — this only surfaces after the model finishes downloading, which is why it wasn't caught by the earlier connect-src/worker-src fix. Verified: with this added, a full download + WASM inference round-trip now succeeds end-to-end (confirmed via a real Qwen2.5-0.5B GGUF producing correct Traditional Chinese output in Chromium). 2. getCacheSize()/clearCache() checked the browser Cache API, but wllama 2.x actually persists downloaded models via OPFS through a CacheManager — Cache API was always empty, so the Privacy page permanently showed "未下載" (not cached) and the "清除模型快取" button stayed disabled even with a fully downloaded, working model. CacheManager has no standalone named export (only `e…03d636e -
fix(offline-ai): wllama never actually worked in production (3 bugs)
DONG-WEI-YANG +1: Claude Fable 5T11 cross-browser smoke test surfaced that the offline-AI feature shipped in the browser-wasm-wllama plan was completely non-functional end-to-end, with every failure silently swallowed (empty catch blocks / no banner update), so it looked done in code review but never ran in a real browser: 1. wllamaProvider.ts called `new Wllama()` with no arguments. The library requires an AssetsPathConfig as the first constructor arg and throws synchronously without it ("AssetsPathConfig is required"). Fixed by importing the single/multi-thread wasm files via Vite `?url` so they're bundled as static assets and passed to the constructor. Also added src/vite-env.d.ts to tsconfig.server.json's include so tsc recognizes the `*?url` ambient module type Vite declares. 2. CSP connect-src only allowed `https://*.huggingface.co`, which does NOT match the bare `https://huggingface.co` apex domain the default GGUF model URL points to (CSP wildcard subdomains never match the parent …2258f1d -
fix(db): repair key_prefix column after migrations on fresh databases
DONG-WEI-YANG +1: Claude Fable 5Migration 0000 creates records without key_prefix; the import-time ALTER in src/db/index.ts runs before migrate() on first boot, so it silently no-ops against the missing table and every records query then fails (health check: 'no such column: key_prefix'). Broke all fresh deploys. ensureKeyPrefixColumn() distinguishes added/exists/no-table instead of swallowing all errors; the server re-runs it right after migrate(). Verified: fresh data dir + production server → /health now returns ok. 287/287 tests green (4 new regression tests). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>a8dc994
-
fix(deploy): run DB migrations on server startup + copy drizzle to image
DONG-WEI-YANG +1: Claude Opus 4.7 (1M context)The HF Spaces live deploy fails with /health returning "no such table: records" on fresh container boots. Root cause: the Dockerfile never copied the drizzle/ migration SQL files to the production image, and the server never ran migrations on startup. This was latent — the persistent HF Spaces volume kept the schema across deploys until the volume was reset. Two changes: - Dockerfile: COPY drizzle ./drizzle in the production stage - src/server/index.ts: migrate(db, { migrationsFolder: './drizzle' }) before app.listen. Idempotent — drizzle tracks applied migrations in __drizzle_migrations meta table. Wrapped in try/catch so a migration failure logs but doesn't crash boot (health check will still fail, but the process stays up for debugging). Smoke-tested locally: fresh data dir + node dist/server/index.js produces 'Database migrations applied' log line before 'Server running on port' line. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>3861e0f -
fix(rag): test isolation + hasFailed() semantic accuracy
DONG-WEI-YANG +1: Claude Opus 4.7 (1M context)Two fixes from final code review: 1. Integration test now uses its own RAG_DATA_DIR (./data/test-integration) instead of inheriting ./data/test-ragSearch from vitest's global env. Previously the integration server's auto-seeded chunks could be raced/deleted by ragSearch.test.ts's beforeEach cleanup, making the 堂哥失智 assertion potentially pass for the wrong reason (LLM produced 'mental' without RAG). 2. hasFailed() in ragEmbedder.ts now correctly returns true only AFTER the load has settled with null — was previously returning true the moment loadPromise was assigned, which could be 3-10 seconds before the model finished loading. Adds a loadSettled flag set in finally. No production hot path uses hasFailed() so this is a latent semantic fix, not a behavior change. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>c17e2b9 -
feat(server): auto-seed genogram RAG on first startup
DONG-WEI-YANG +1: Claude Opus 4.7 (1M context)Adds maybeAutoSeedGenogramRag() in src/server/index.ts that runs after app.listen (non-blocking). If rag_social_worker.db has zero rows with (source='manual', category='genogram'), imports the seed script and seeds the 18 coding-guide chunks. Wrapped in try/catch — any failure logs a warning but does NOT kill server startup. Worst case: RAG returns empty until manual `npm run db:seed:rag-genogram` runs. Critical for HF Spaces deploys: fresh containers boot with an empty rag_social_worker.db; this removes the need for a manual docker exec to seed. 2 new unit tests verify seed() is reusable from imports + idempotent. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>f84a165 -
feat(ai): inject genogram/ecomap RAG context into 3 endpoints
DONG-WEI-YANG +1: Claude Opus 4.7 (1M context)Wires getGenogramRagContext + getEcomapRagContext into: - structureFromVoice (both, when recordType=visit or social_assessment) - supplementGenogram (genogram only) - supplementEcomap (ecomap only, default role=social_worker) Other recordTypes (SOAP/nursing_*/care_tracking/quality_check) skip RAG entirely — they're pure formData, no diagrams. Each caller appends RAG_TRAILING_NOTICE exactly once after combining context blocks. This prevents the double-notice bug that would otherwise occur in structureFromVoice when both helpers return content. Adds the 'RAG content is reference only, transcript is the truth' rule to all 4 affected prompts (SOCIAL_WORKER, SOCIAL_ASSESSMENT, GENOGRAM_SUPPLEMENT, ECOMAP_SUPPLEMENT) to reinforce the trailing notice. Integration test with '堂哥失智' transcript verifies the mental disambiguation works end-to-end. Test warn-and-skips if no API key is configured. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>330eb07 -
feat(ai): ragContext.ts — genogram + ecomap RAG helpers
DONG-WEI-YANG +1: Claude Opus 4.7 (1M context)Two functions to build system-prompt-injectable RAG context blocks: - getGenogramRagContext(transcript) — pulls hand-authored coding guide chunks from rag_social_worker.db (source='manual', category='genogram'), top-4 via ragSearch. - getEcomapRagContext(transcript, role) — combines matchServiceCodes() LTC keyword match (synchronous, no failure) with top-3 crawled care-resource chunks (source='crawl'). Both helpers wrap retrieval in try/catch and return '' on any error — RAG unavailable degrades to current pre-RAG behavior. Trailing notice instructs LLM to treat content as format/term reference only, never as case facts. 8 unit tests cover all combinations: search success/empty/throw, matchServiceCodes match/no-match, both-empty fallback, codes-only fallback when search throws. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>3cdaead -
feat(rag): genogram coding-guide seed + ragStore helpers
DONG-WEI-YANG +1: Claude Opus 4.7 (1M context)Adds: - deleteByCategory(role, category, source) — scoped DELETE for safe re-seeding without touching unrelated rows - countDocuments(role, opts?) — gate for auto-seed-if-empty (T6) - src/db/seeds/rag-genogram-guide.ts — 18 hand-authored chunks covering kinship decomposition (父系/母系/姻親/後代/直系/領養/ 同父異母/雙胞胎/離婚/同居), relationship quality enum mapping, health-status disambiguation (失智→mental, 中風→disabled, priority order), and McGoldrick schema conventions - 'db:seed:rag-genogram' package.json script Seeder is idempotent: deletes (source='manual', category='genogram') before inserting, scoped only to social_worker's rag store. 4 new unit tests covering count/delete behavior. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>ba6cdcd -
feat(rag): add source+category filters to ragSearch.search
DONG-WEI-YANG +1: Claude Opus 4.7 (1M context)Adds optional SearchOptions { source?, category? } to search() and searchBM25Only(). Both filters AND-combined. Enables the two-RAG pattern: genogram queries scoped to source='manual'+ category='genogram', ecomap queries scoped to source='crawl'. Backward-compatible: opts defaults to {}; no-arg callers behave identically. 6 new unit tests in tests/ragSearch.test.ts cover all filter combinations. Tests use a throwaway data dir set via vitest's env config (RAG_DATA_DIR=./data/test-ragSearch) so the production const DATA_DIR is captured correctly at module load. Local beforeEach() calls closeStores() to release Windows SQLite file locks before re-creating the dir. No production code changes outside ragSearch.ts. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>53962cc -
fix(ai): offline ecomap extraction uses institution-keyword dictionary, not substring slicing
DONG-WEI-YANG +1: Claude Opus 4.7 (1M context)Twin of the genogram fix (41b1465): the no-AI fallback extractor was slicing transcript chunks for ecomap system names too, producing garbage like '案主常去醫院看診' instead of '醫院'. Now a closed dictionary of institution/role keywords (醫院/診所/居服員/日照中心/社區關懷據點/里長/ 教會/朋友/鄰居/老農年金/...) maps each to an ecomap system type; each keyword found becomes a system NAMED BY THE KEYWORD, with connection strength and flow direction inferred from nearby context words. The clause containing the keyword becomes the system's notes. Type detection was already correct (it used the keyword dict); only the name was broken. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>c07e5f3 -
fix(ai): offline genogram extraction uses relation-word dictionary, not substring slicing
DONG-WEI-YANG +1: Claude Opus 4.7 (1M context)The no-AI fallback extractor was doing naive n-gram substring slicing on Chinese text, producing garbage 'names' like 媽媽和一 / 有糖尿病. Chinese has no word boundaries — naive substring extraction can't work as NER. Now: the closed KINSHIP dictionary (~40 family-relation words: 爸爸/媽媽/哥哥/弟弟/ 兒子/女兒/先生/太太/爺爺/奶奶/...) is iterated directly against the transcript. Each matched relation word becomes a member NAMED BY THE RELATION; the user renames in the GenogramEditor. Dedup by identity key (generation|gender|relType) so synonyms like 爸爸/父親 resolve to a single member (longest term wins via KINSHIP_TERMS sort). Health is detected clause-by-clause around each term occurrence — preventing cross-clause condition bleeding between family members. analyzeHealthRisks (familial pattern detection) unchanged — it now gets cleaner input. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>41b1465 -
fix(ai): tighten supplementGenogram prompt — gender/health from relation+condition words, relationship.from = named person
DONG-WEI-YANG +1: Claude Opus 4.7 (1M context)Fixes 3 accuracy errors observed: gender 'other' for '弟弟' (should be male), health 'healthy' for '有憂鬱症' (should be mental), and linking a new member to the wrong existing person ('案主的弟弟X' was attached to another existing name instead of the case subject). Prompt now gives explicit gender/health inference tables and requires relationship.from to be the person the transcript explicitly names. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>714d323
-
feat(llm): add DeepInfra provider to cloud-llama tier
DONG-WEI-YANG +1: Claude Opus 4.7 (1M context)DeepInfra is OpenAI-compat — slots into the cloud-llama tier reusing CloudLlamaProvider. ~14-line buildRegistry addition, zero orchestrator changes, zero router changes (except one line in apiStatus's hasCloudLlama). Default model meta-llama/Llama-3.3-70B-Instruct-Turbo, overridable via DEEPINFRA_MODEL. Env: DEEPINFRA_API_KEY/_API2/_API3. Demonstrates the 'Nth provider ≈ free' property of the #0 abstraction: #1 added Groq+OpenRouter in ~310 lines (building CloudLlamaProvider); #2 added local-server in 14 lines; this adds DeepInfra in ~14 lines. 257 -> 259 tests. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>4fae6d6 -
fix(api): apiStatus reports cloud-llama / local-server tiers
DONG-WEI-YANG +1: Claude Opus 4.7 (1M context)apiStatus only checked GEMINI/HF env vars — so the frontend showed 'no AI' even when GROQ_API_KEY (cloud-llama tier) was configured. Now reports hasCloudLlama / hasLocalServer, and hasAny is authoritative (getRegistry().length > 0, covering all tiers). Multimodal flags stay Gemini-gated (hfInference.ts retained those). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>bb6dec8 -
test(device-ai): concurrent getWllamaSession dedup test; fix stale buildRegistry comment
DONG-WEI-YANG +1: Claude Opus 4.7 (1M context)Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>42e62a0 -
fix(deps): migrate @xenova /transformers v2 -> @huggingface/transformers v4
DONG-WEI-YANG +1: Claude Opus 4.7 (1M context)Eliminates the 4 critical dependabot vulns — v4's onnxruntime-web (1.26+) no longer pulls in the vulnerable onnx-proto -> protobufjs chain. Only 2 files import the package directly (tinyNlp.ts, ragEmbedder.ts). Model IDs unchanged (Xenova/ HF Hub models still work in v4 — confirmed by pre-flight spike). Type adaptation: v4 renamed `quantized: true` -> `dtype: 'q8'` in PretrainedModelOptions (ragEmbedder.ts line 57). npm audit --omit=dev: 0 critical. 255 tests green. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>eafa87d
-
feat(llm): register local-server llama provider from LLAMA_SERVER_URL env
DONG-WEI-YANG +1: Claude Sonnet 4.6Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>bde8c5f -
feat(llm): register OpenRouter cloud-llama providers from env vars
DONG-WEI-YANGdd470e4 -
feat(llm): register Groq cloud-llama providers from env vars
DONG-WEI-YANG0312753 -
feat(llm): _clearCircuitBreaker resets all provider families
DONG-WEI-YANG2a2a1b2 -
feat(llm): CloudLlamaProvider class for OpenAI-compat endpoints
DONG-WEI-YANG +1: Claude Sonnet 4.6Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>7055a3a -
fix(llm): cooldown last-resort loop bails on non-retryable 4xx
DONG-WEI-YANG104ee08 -
docs(llm): explain magic-number constants in provider configs
DONG-WEI-YANGdf78735 -
refactor(llm): export callOpenAICompat for sibling provider modules
DONG-WEI-YANGe84b08c -
feat(llm): add cloud-llama tier with JSDoc on Tier type
DONG-WEI-YANG0eaa75b -
refactor(llm): extract shared extractJson to utils.ts (DRY fix)
DONG-WEI-YANG4292060 -
fix(llm): race-batch prioritizes non-retryable in AggregateError flattening
DONG-WEI-YANG +1: Claude Sonnet 4.6Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>4673bbe -
refactor(llm): hfInference.ts retains multimodal, re-exports chat from llmProviders
DONG-WEI-YANG300ae55 -
feat(llm): move chatAndReturn and chatAndParse to llmProviders.ts
DONG-WEI-YANG20655a4 -
feat(llm): buildRegistry from env vars (Gemini x3 keys, HF 8 models x3 keys)
DONG-WEI-YANGf20a677 -
feat(llm): HFProvider with 120s circuit breaker per provider name
DONG-WEI-YANG +1: Claude Sonnet 4.6Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>d15e911 -
feat(llm): GeminiProvider with model override and 4xx status preservation
DONG-WEI-YANG +1: Claude Sonnet 4.6Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>5e63838