Commit History
-
Improve diagram layout, relationship correctness and validation; patch dependencies Running
DONG-WEI-YANG6ec5c72
-
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 -
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
-
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(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(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(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(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: complete Group B+C+D — full system implementation
DONG-WEI-YANG +1: Claude Opus 4.6 (1M context)Backend (Group B): - tRPC routers: record, genogram, ecomap, voice, ltc3, consent, export, rag - Services: crypto (AES-256-GCM+HKDF), Word export, voice structuring, LTC3 matching, cleanup cron, crawl targets - Middleware: rate limiter per endpoint Frontend (Group C): - Role selection home page with 9 shared UI components - Social worker workspace: visit record + social assessment forms - Nurse workspace: SOAP + nursing note + nursing plan forms - Case manager workspace: care tracking with LTC3 code mapping - Supervisor workspace: quality check with compliance review - Canvas editors: genogram (1422 lines, McGoldrick) + ecomap (865 lines) - Voice recorder (Web Speech API) + LTC3 code suggestions - Consent dialog + key/QR display + retrieve form with QR scanner RAG + AI (Group D): - Per-role distributed SQLite RAG stores (4 databases) - Embedder (Transformers.js all-MiniLM-L6-v2) - Hybrid search (0.7*vector + 0.3*BM25) - Record ingester with PII anonymization - Auto-crawler (9 LTC r…7c280c7