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
-
feat(a11y): keyboard navigation for genogram/ecomap canvas editors
DONG-WEI-YANG +1: Claude Sonnet 5Canvas has no native focusable sub-elements, so members/systems in GenogramEditor and EcomapEditor were only reachable by clicking exact pixel coordinates — completely unusable for keyboard-only or screen-reader users, and one of the accessibility gaps flagged in the original audit. Added an additive keyboard interaction layer that reuses the exact same selectedId state and mutation logic mouse clicks already drive, so no existing rendering or pointer-interaction code changed: - Canvas is now tabIndex={0} + role="application" with an aria-label and aria-describedby pointing at the existing mode-hint text (now updated to mention the keyboard controls). - ArrowRight/ArrowDown and ArrowLeft/ArrowUp cycle selection through members (sorted by generation then x — genogram's natural reading order) or systems (array order — ecomap has no hierarchy), wrapping at both ends. Works identically in read-only mode, since navigating without mutating is always safe. - Escape clears select…ad1dd60 -
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 -
fix(retrieve): add QR-scan retrieval to nurse/case-manager/supervisor
DONG-WEI-YANG +1: Claude Sonnet 5Only social-worker/Retrieve.tsx used the shared RetrieveForm component (html5-qrcode-based camera scanning). The other three roles each had their own local RetrieveForm with text-only key entry — camera QR scanning was never wired up for them, even though every role's KeyDisplay generates a scannable QR code alongside the plaintext key. A nurse/case-manager/ supervisor user who only has the QR code (e.g. printed on paper, or a photo) had no way to retrieve a record without manually retyping the 28-character key. case-manager and supervisor's local forms already matched the shared component's prop shape (onRetrieve/loading/error, no key-mangling logic), so swapping them was a straightforward replacement. nurse's local form was structured differently — it owned the tRPC query itself instead of the parent, so retrieval logic had to be lifted up to the page component first (mirroring the query-in-parent pattern the other three roles already use) before the shared form could be dropped in.…47cb614 -
fix(a11y): associate labels with form controls in genogram/ecomap modals
DONG-WEI-YANG +1: Claude Sonnet 5MemberFormModal and RelationshipFormModal (GenogramEditor.tsx) and SystemPopup (EcomapEditor.tsx) all had <label> elements as siblings of their inputs/selects/textareas/button-groups, with no htmlFor/id or aria-labelledby connecting them. Visually fine, but a screen reader has no way to know which label describes which control — every field in these three modals was effectively unlabeled to assistive tech. Real inputs/selects/textareas get id + matching htmlFor (姓名, 出生年, 死亡年, 疾病/狀況, 特殊狀態, 世代, 系統名稱, 類型, 連結強度, 資源流向, 備註). The 此人為個案本人 checkbox was already correctly wrapped inside its <label> and needed no change. Button-group fields that don't map to a single labelable element (性別, 健康狀態, 關係類型, 關係品質) instead get a role="group" wrapper with aria-labelledby pointing at the existing heading text, converted from <label> to <span> since it isn't labeling one control. Verified in a real browser: opened all three modals via the actual add-member/add-relationship/add-system flows and confirmed vi…c3c9539 -
refactor(ui): extract shared RoleWorkspaceIndex for case-manager/supervisor landing pages
DONG-WEI-YANG +1: Claude Sonnet 5The original audit flagged all 4 role Index.tsx pages as ~400 lines of duplicated RoleCard logic, safe to unify. That was only half right — a lesson repeated from the LTC3CodePicker false-positive earlier this session: verify audit findings against the actual code before acting. nurse/Index.tsx and social-worker/Index.tsx each use a genuinely different layout (horizontal card list vs a 2-card grid built on the shared ui Card component) — those are deliberate design differences, not duplication, and were left alone. case-manager/Index.tsx and supervisor/Index.tsx, however, were byte-for-byte identical in structure, varying only by accent color (amber/purple), copy, icons, and hrefs — a genuine, safe duplication. Extracted that shared shape into RoleWorkspaceIndex.tsx, parametrized by an accentColor color-token map (following the same full-literal-classname pattern already used in RoleCard.tsx, required since Tailwind can't see dynamically interpolated class names). Both pages are now …4bd76fd -
fix(genogram,ecomap): add real readOnly mode instead of fake no-op onChange
DONG-WEI-YANG +1: Claude Sonnet 5social-worker/Retrieve.tsx and VoiceWizard.tsx's final-preview step passed onChange={() => {}} to GenogramEditor/EcomapEditor to fake read-only viewing. This didn't work: pointer/double-click handlers still ran fully (opening add/edit modals, allowing drag-to-move, selection, delete), they just failed to persist since onChange was swallowed — so a viewer could interact with a supposedly read-only diagram and see modals with no way to actually save, a confusing dead-end UI. Added a proper `readOnly` prop to both editors. When set, pointer handlers only allow selection and canvas panning, double-click is a no-op, the mutating toolbar buttons (新增成員/建立關係/刪除/自動排列 and their ecomap equivalents) are hidden and replaced with a "唯讀檢視" badge, and the selected-member info bar's 編輯 button is hidden. Non-mutating toolbar actions (reset view, export PNG) remain available. Verified via real browser: created a test record with a genogram member, retrieved it through social-worker/Retrieve.tsx, confir…bc0709a -
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(db): add missing indexes on hot lookup paths
DONG-WEI-YANG +1: Claude Sonnet 5SQLite does not auto-index foreign key columns. genograms.record_id, ecomaps.record_id, and encrypted_files.record_id were all unindexed, so every genogram/ecomap load and every daily cleanup cascade-delete did a full table scan. Adds a real drizzle migration (0001) for these three — safe since nothing has ever manually patched them, unlike key_prefix. records(key_prefix, expires_at) needed the same treatment but can't go through a normal drizzle migration: key_prefix itself was never captured by a real migration (see ensureColumns.ts), so drizzle-kit's diff against the last snapshot always wants to re-propose `ALTER TABLE records ADD key_prefix` alongside any new migration touching that table -- which would throw "duplicate column name" on every already-deployed database that already has the column via the existing runtime patch. Manually stripped that line out of the generated 0001 migration (with a comment explaining why, plus a test asserting no migration file ever reintroduces it…601f85f -
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): log deviceAI runBuiltIn/runWasm failures instead of failing silently
DONG-WEI-YANG +1: Claude Sonnet 5Both catch blocks returned null with zero console output on failure. Falling back to the server is correct behavior; being silent about why is not -- this exact silent-catch shape (fail, return null, no log) is what let the offline-AI feature stay completely broken in production for months with no signal anywhere. Adds console.warn in both, verified with a test asserting the warning actually fires on a wllama init failure. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>130817c -
fix(feedback): FeedbackWidget silently reported success on server errors
DONG-WEI-YANG +1: Claude Sonnet 5fetch() only rejects on network failure -- a 4xx/5xx response still resolves normally, so the missing response.ok check meant any server-side validation error or 500 still showed "感謝您的寶貴建議!" while the feedback was never actually saved. Also replaces the alert() fallback with an inline error message matching the rest of the app's error-display style. First real use of the jsdom + RTL component-test harness added earlier this session -- FeedbackWidget needed no providers (no trpc client, no router), making it a clean first case. Also fixes a gap in the harness itself: RTL's cleanup() wasn't wired into afterEach, so multiple render() calls across tests in one file piled up in the same jsdom document instead of unmounting. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>44c3303 -
fix(nurse): render missing ecomap editor on nursing plan page
DONG-WEI-YANG +1: Claude Sonnet 5NewNursingPlan.tsx tracked ecomap state and included it when submitting the record (AI-fill could populate it from a voice transcript), but never rendered any UI for it -- users had no way to see or edit ecomap data on this page, unlike every other section (genogram included). Adds the same collapsible EcomapEditor section already used by genogram on this page and by both editors on nurse/NewSOAP.tsx. Verified via tsc --noEmit, the full test suite, and a real-browser check confirming the ecomap canvas renders with no console errors. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>a607fdf -
refactor(frontend): unify genogram/ecomap/key-display on shared components
DONG-WEI-YANG +1: Claude Sonnet 5case-manager/NewCareTracking.tsx, supervisor/NewQualityCheck.tsx, and nurse/{NewSOAP,NewNursingPlan}.tsx each hand-rolled their own plain table-row-form genogram/ecomap editor (~130-460 duplicated lines per page) instead of using the real canvas-based GenogramEditor/ EcomapEditor components already running in production on the social-worker pages -- same Genogram/Ecomap data shape, purely a UI duplication. case-manager and supervisor also had their own static KeyDisplay reimplementation lacking the shared component's live 7-day countdown. Swapped all four pages onto the shared components. KeyDisplay gains an optional onReset prop (backward compatible -- other callers are unaffected) to preserve case-manager/supervisor's "建立新紀錄" button, which the shared component didn't previously offer. Along the way, case-manager/NewCareTracking.tsx and supervisor/NewQualityCheck.tsx also gain a createRecord.isError error banner (mirroring nurse/NewSOAP.tsx's existing pattern) -- both pages previous…668ce24 -
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 -
refactor(ui): extract shouldOfferOfflineAI() helper, DRY the modal guard
DONG-WEI-YANG +1: Claude Opus 4.7 (1M context)Replaces 4 inline copies (3 in AiFillButton, 1 in SmartTranscript) of the enabled/declined check with a single helper in deviceAI.ts. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>dbfa411 -
refactor(device-ai): make Privacy dynamic-import wllamaProvider, eliminate Vite warning
DONG-WEI-YANG +1: Claude Opus 4.7 (1M context)DEFAULT_MODEL_URL moved to the lightweight wllamaProgress.ts (re-exported from wllamaProvider for back-compat). Privacy.tsx now dynamic-imports the wllama lifecycle functions inside event handlers instead of statically. With no static importers, wllamaProvider code-splits cleanly — the INEFFECTIVE_DYNAMIC_IMPORT warning is gone. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>394cdce -
refactor(device-ai): extract wllamaProgress pub-sub, fix Vite chunk warning
DONG-WEI-YANG +1: Claude Opus 4.7 (1M context)OfflineAIBanner now imports download-progress from the lightweight wllamaProgress.ts instead of the heavy wllamaProvider.ts — removing the static-import edge that prevented wllamaProvider from code-splitting. wllamaProvider re-exports onDownloadProgress/getDownloadProgress so existing importers (tests) are unchanged. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>a70fc1e -
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(ui): wire offline-AI modal trigger + banner mount at App level
DONG-WEI-YANGa752482 -
feat(ui): Privacy page — offline AI toggle, model URL, cache controls
DONG-WEI-YANGba8602b -
feat(ui): OfflineAIBanner — sticky download progress with cancel
DONG-WEI-YANG88ee8cf