CJR61 commited on
Commit
c8a5df5
·
verified ·
1 Parent(s): 4c84d94

today-and-farm-records + local-gate-manual-fallback + guardrail-registry a/b/c (worktree 383b4c6) (prompt_source 3b3474b2)

Browse files
app/account.py CHANGED
@@ -23,7 +23,8 @@ import httpx
23
  from sqlalchemy import func, insert, select, update
24
 
25
  from app import db
26
- from app.db import account_otp_tries, account_otps, accounts, cases, devices, feedback, images, messages, next_seq, now_iso
 
27
 
28
  log = logging.getLogger("drpig.account")
29
 
@@ -141,7 +142,8 @@ def _reissue_seq(conn, device_id: str) -> None:
141
  """A device joining an account: its rows get fresh seqs so the devices ALREADY on the account pull them —
142
  their cursors are past the old seqs (final review 2026-10-21 #7). Order kept; the joining device re-pulls
143
  from 0 anyway."""
144
- for table, pk in ((cases, "case_id"), (images, "img_id"), (messages, "msg_id"), (feedback, "fb_id")):
 
145
  ids = [r[0] for r in conn.execute(select(table.c[pk]).where(table.c.device_id == device_id, table.c.seq.is_not(None))
146
  .order_by(table.c.seq))]
147
  for i in ids:
 
23
  from sqlalchemy import func, insert, select, update
24
 
25
  from app import db
26
+ from app.db import (account_otp_tries, account_otps, accounts, cases, devices, feedback, images, medications, messages, mortality,
27
+ next_seq, now_iso)
28
 
29
  log = logging.getLogger("drpig.account")
30
 
 
142
  """A device joining an account: its rows get fresh seqs so the devices ALREADY on the account pull them —
143
  their cursors are past the old seqs (final review 2026-10-21 #7). Order kept; the joining device re-pulls
144
  from 0 anyway."""
145
+ for table, pk in ((cases, "case_id"), (images, "img_id"), (messages, "msg_id"), (feedback, "fb_id"),
146
+ (medications, "med_id"), (mortality, "mort_id")): # farm records too (2026-11-18)
147
  ids = [r[0] for r in conn.execute(select(table.c[pk]).where(table.c.device_id == device_id, table.c.seq.is_not(None))
148
  .order_by(table.c.seq))]
149
  for i in ids:
app/admin_stats.py CHANGED
@@ -52,9 +52,49 @@ def _props(raw) -> dict:
52
  "local_kind": p.get("local_kind") if p.get("local_kind") in LOCAL_KINDS else None,
53
  "lite_guard_tripped": isinstance(p.get("lite_guard"), dict) and p["lite_guard"].get("tripped") is True,
54
  "last_resort": p.get("last_resort") is True,
 
 
 
55
  }
56
 
57
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
  def _events(conn, names: tuple[str, ...], since: str | None = None) -> list[dict]:
59
  stmt = (select(telemetry_events.c.device_id, telemetry_events.c.event, telemetry_events.c.props,
60
  telemetry_events.c.received_at)
@@ -133,6 +173,8 @@ def device_summary(days: int = 30, now: datetime | None = None) -> dict:
133
  "downgrade_top": [{"reason": r, "n": n} for r, n in reasons.most_common(5)],
134
  "download": {"started": len(started), "done": len(done),
135
  "rate": round(len(done) / len(started), 3) if started else None},
 
 
136
  }
137
 
138
 
 
52
  "local_kind": p.get("local_kind") if p.get("local_kind") in LOCAL_KINDS else None,
53
  "lite_guard_tripped": isinstance(p.get("lite_guard"), dict) and p["lite_guard"].get("tripped") is True,
54
  "last_resort": p.get("last_resort") is True,
55
+ # openspec today-and-farm-records (2026-11-18): which card / which record kind — never the content
56
+ "card": p.get("card") if p.get("card") in FEATURE_CARDS else None,
57
+ "kind": p.get("kind") if p.get("kind") in FEATURE_KINDS else None,
58
  }
59
 
60
 
61
+ FEATURE_CARDS = ("price", "alert", "reminder_withdrawal", "reminder_followup", "ask")
62
+ FEATURE_KINDS = ("medication", "mortality")
63
+ WITHDRAWAL_ACTIONS = ("schedule", "cancel", "denied")
64
+ FEATURE_EVENTS = ("today_open", "today_card_tap", "farm_record", "withdrawal_reminder")
65
+
66
+
67
+ def _feature_window(events: list[dict], starts: list[dict], since: str) -> dict:
68
+ """Counts for one window: per feature event the number of events and of distinct devices (today_card_tap
69
+ also by card, farm_record by kind), plus the share of devices that started the App in the window and opened
70
+ 今日 at least once (the retention signal the pilot watches, proposal §對 KPI 的影響)."""
71
+ rows = [e for e in events if e["at"] >= since and e["device_id"]]
72
+ out: dict = {}
73
+ for name in FEATURE_EVENTS:
74
+ mine = [e for e in rows if e["event"] == name]
75
+ entry = {"n": len(mine), "devices": len({e["device_id"] for e in mine})}
76
+ if name == "today_card_tap":
77
+ entry["by_card"] = {c: sum(1 for e in mine if e["props"].get("card") == c) for c in FEATURE_CARDS}
78
+ if name == "farm_record":
79
+ entry["by_kind"] = {k: sum(1 for e in mine if e["props"].get("kind") == k) for k in FEATURE_KINDS}
80
+ if name == "withdrawal_reminder":
81
+ entry["by_action"] = {a: sum(1 for e in mine if e["props"].get("action") == a) for a in WITHDRAWAL_ACTIONS}
82
+ out[name] = entry
83
+ app_devices = {e["device_id"] for e in starts if e["at"] >= since and e["device_id"]}
84
+ today_devices = {e["device_id"] for e in rows if e["event"] == "today_open"}
85
+ out["app_devices"] = len(app_devices)
86
+ out["today_open_ratio"] = round(len(app_devices & today_devices) / len(app_devices), 3) if app_devices else None
87
+ return out
88
+
89
+
90
+ def feature_usage(now: datetime | None = None) -> dict:
91
+ """`feature_usage` for /admin/devices/summary: the four 今日 / 豬場 events over 7 and 30 days."""
92
+ with db.read_connection() as conn:
93
+ events = _events(conn, FEATURE_EVENTS, _since(30, now))
94
+ starts = _events(conn, ("app_start",), _since(30, now))
95
+ return {"7d": _feature_window(events, starts, _since(7, now)), "30d": _feature_window(events, starts, _since(30, now))}
96
+
97
+
98
  def _events(conn, names: tuple[str, ...], since: str | None = None) -> list[dict]:
99
  stmt = (select(telemetry_events.c.device_id, telemetry_events.c.event, telemetry_events.c.props,
100
  telemetry_events.c.received_at)
 
173
  "downgrade_top": [{"reason": r, "n": n} for r, n in reasons.most_common(5)],
174
  "download": {"started": len(started), "done": len(done),
175
  "rate": round(len(done) / len(started), 3) if started else None},
176
+ # 2026-11-18: is anyone using 今日 / 豬場? (fixed 7 / 30-day windows, independent of `days`)
177
+ "feature_usage": feature_usage(now),
178
  }
179
 
180
 
app/db.py CHANGED
@@ -165,6 +165,39 @@ images = Table(
165
  Column("seq", Integer, index=True),
166
  )
167
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
168
  sync_ops = Table(
169
  "sync_ops", metadata,
170
  Column("op_id", String, primary_key=True),
 
165
  Column("seq", Integer, index=True),
166
  )
167
 
168
+ # ── farm records (openspec today-and-farm-records, FR-FARM-06 / FR-MORT-04, 2026-11-18) ───────────
169
+ # Same sync shape as `cases`: device_id from the header, client_ts LWW, seq cursor, hide = hidden=1. Withdrawal days
170
+ # are what the farmer typed from the drug label — the server never supplies or corrects them (D-45).
171
+ medications = Table(
172
+ "medications", metadata,
173
+ Column("med_id", String, primary_key=True),
174
+ Column("device_id", String, nullable=False, index=True),
175
+ Column("drug_name", String), Column("target", String),
176
+ Column("given_on", String), # YYYY-MM-DD, last dose
177
+ Column("withdrawal_days", Integer), # 0..365, farmer-entered
178
+ Column("note", Text),
179
+ Column("created_at", String), Column("updated_at", String),
180
+ Column("hidden", Integer, default=0),
181
+ Column("client_ts", String), Column("server_received_at", String),
182
+ Column("seq", Integer, index=True),
183
+ )
184
+
185
+ mortality = Table(
186
+ "mortality", metadata,
187
+ Column("mort_id", String, primary_key=True),
188
+ Column("device_id", String, nullable=False, index=True),
189
+ Column("day", String, index=True), # YYYY-MM-DD
190
+ Column("kind", String), # death | cull
191
+ Column("stage", String), # piglet | nursery | grower | breeder | other
192
+ Column("count", Integer), # 1..9999 (whole farm, that day)
193
+ Column("reason", String), # illness | diarrhea | respiratory | crushed | weak | injury | heat | unknown | other
194
+ Column("note", Text),
195
+ Column("created_at", String), Column("updated_at", String),
196
+ Column("hidden", Integer, default=0),
197
+ Column("client_ts", String), Column("server_received_at", String),
198
+ Column("seq", Integer, index=True),
199
+ )
200
+
201
  sync_ops = Table(
202
  "sync_ops", metadata,
203
  Column("op_id", String, primary_key=True),
app/generated/prompt_source.py CHANGED
@@ -3,7 +3,7 @@
3
  import re
4
  from typing import Any
5
 
6
- PROMPT_SOURCE_VERSION = "aa8c9807"
7
 
8
  SYSTEM_PROMPT = """你是一位專業的畜牧臨床與豬場管理顧問 Dr. Pig。
9
  專注於豬場管理、豬隻疾病、生物安全及防疫相關問題。
@@ -83,10 +83,16 @@ FIXED_REPLIES: dict[str, str] = {
83
  "error_image_service": "圖片分析服務暫時無法使用,請稍後再試。",
84
  "daily_cap": "今日雲端查詢已達上限,請改用本機 AI,或於明日再試。",
85
  "cloud_off": "目前未提供雲端 AI 問答。請於 Dr. Pig App「我的」頁下載本機 AI,即可在手機上問答(離線亦可使用)。",
 
86
  "local_refuse": "離線資料未收錄此問題,無法提供答案,建議洽詢獸醫師。",
87
  "lite_guard_notice": "為避免數字錯誤,以下直接顯示資料原文:",
88
  "manual_only_notice": "離線資料的相關段落(僅供參考):",
89
  "report_notice": "疑似非洲豬瘟、口蹄疫、豬瘟等重大疫病時,請立即通報當地動物防疫機關或特約獸醫,病死豬不要移動或自行處理。通報電話如下:",
 
 
 
 
 
90
  "legacy_local_refuse_v1": "內建手冊沒有提到這件事,我不確定答案。建議連上網路後再問一次,或直接請教獸醫師。",
91
  "legacy_lite_guard_notice_v1": "AI 整理的內容可能有誤,以下是手冊原文:",
92
  "legacy_local_refuse_v2": "離線手冊未收錄此問題,無法提供答案。請於連線後再次查詢,或洽詢獸醫師。",
@@ -387,6 +393,613 @@ FOLLOWUP_DAYS_MAX = 30
387
  FOLLOWUP_DEDUPE_DAYS = 7
388
  FOLLOWUP_CARD = "{n} 天後提醒我:{text}"
389
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
390
  QUESTIONNAIRE: dict[str, Any] = {
391
  "version": 1,
392
  "status": "待獸醫確認(D-34);2026-10-19 依證據報告調整 age A / stool A 權重與 spread C red_flag(docs/grill/questionnaire_evidence_2026-10-16.md)",
 
3
  import re
4
  from typing import Any
5
 
6
+ PROMPT_SOURCE_VERSION = "3b3474b2"
7
 
8
  SYSTEM_PROMPT = """你是一位專業的畜牧臨床與豬場管理顧問 Dr. Pig。
9
  專注於豬場管理、豬隻疾病、生物安全及防疫相關問題。
 
83
  "error_image_service": "圖片分析服務暫時無法使用,請稍後再試。",
84
  "daily_cap": "今日雲端查詢已達上限,請改用本機 AI,或於明日再試。",
85
  "cloud_off": "目前未提供雲端 AI 問答。請於 Dr. Pig App「我的」頁下載本機 AI,即可在手機上問答(離線亦可使用)。",
86
+ "cloud_off_unsupported": "目前未提供雲端 AI 問答,此裝置也不支援本機 AI 問答。您可以查閱 App 內的衛教資料;疑似重大疫病請立即通報當地動物防疫機關或特約獸醫。",
87
  "local_refuse": "離線資料未收錄此問題,無法提供答案,建議洽詢獸醫師。",
88
  "lite_guard_notice": "為避免數字錯誤,以下直接顯示資料原文:",
89
  "manual_only_notice": "離線資料的相關段落(僅供參考):",
90
  "report_notice": "疑似非洲豬瘟、口蹄疫、豬瘟等重大疫病時,請立即通報當地動物防疫機關或特約獸醫,病死豬不要移動或自行處理。通報電話如下:",
91
+ "local_rule_rx": "用藥種類、劑量與廠牌需由獸醫師診斷後開立,Dr. Pig 不提供處方或產品推薦,請洽詢獸醫師。",
92
+ "local_rule_species": "Dr. Pig 只回答豬隻相關問題,其他動物的疾病請洽詢該動物的獸醫師;若懷疑禽流感等重大疫病,請立即通報當地動物防疫機關。",
93
+ "local_rule_pet": "Dr. Pig 以經濟豬場的飼養與疫病為主,寵物豬的照護請洽詢寵物醫院。",
94
+ "local_rule_human": "這個問題涉及人的健康,請洽詢醫師;若接觸病豬或病死豬後身體不適,就醫時請告知醫師有豬隻接觸史。",
95
+ "local_rule_price": "Dr. Pig 不提供豬價或市場行情,請參考官方公布的毛豬交易行情。",
96
  "legacy_local_refuse_v1": "內建手冊沒有提到這件事,我不確定答案。建議連上網路後再問一次,或直接請教獸醫師。",
97
  "legacy_lite_guard_notice_v1": "AI 整理的內容可能有誤,以下是手冊原文:",
98
  "legacy_local_refuse_v2": "離線手冊未收錄此問題,無法提供答案。請於連線後再次查詢,或洽詢獸醫師。",
 
393
  FOLLOWUP_DEDUPE_DAYS = 7
394
  FOLLOWUP_CARD = "{n} 天後提醒我:{text}"
395
 
396
+ # FR-RAIL-05 檢索常數單一定義(shared/prompt_source/retrieval.yaml;不進 PROMPT_SOURCE_VERSION)
397
+ RETRIEVAL: dict[str, Any] = {
398
+ "k": 2,
399
+ "close_gap": 0.03,
400
+ "lite_threshold": 0.6,
401
+ "manual_threshold_full": 0.45,
402
+ "rag_max_chars": 1200,
403
+ "lite_passage_chars": 300,
404
+ "manual_max_passages": 3,
405
+ "report_extra_hits": 2,
406
+ }
407
+
408
+ # FR-RAIL-03 防線登錄表(shared/prompt_source/rails.yaml;不進 PROMPT_SOURCE_VERSION)
409
+ RAILS: list[dict[str, Any]] = [
410
+ {
411
+ "id": "be-ratelimit",
412
+ "stage": "input",
413
+ "routes": [
414
+ "API",
415
+ "WEB",
416
+ "LINE",
417
+ "LEGACY_APP",
418
+ "PARTNER",
419
+ ],
420
+ "owner": "backend",
421
+ "action": "surface_error",
422
+ "http": 429,
423
+ "trace": False,
424
+ "fr": "驗收 7",
425
+ },
426
+ {
427
+ "id": "be-cloud-off",
428
+ "stage": "route",
429
+ "routes": [
430
+ "API",
431
+ "WEB",
432
+ "LINE",
433
+ "LEGACY_APP",
434
+ "PARTNER",
435
+ ],
436
+ "owner": "backend",
437
+ "action": "fixed",
438
+ "notice": "cloud_off",
439
+ "trace": True,
440
+ "fr": "FR-CLOUD-02/05/08",
441
+ },
442
+ {
443
+ "id": "be-device-cap",
444
+ "stage": "input",
445
+ "routes": [
446
+ "API",
447
+ "WEB",
448
+ "LINE",
449
+ "LEGACY_APP",
450
+ "PARTNER",
451
+ ],
452
+ "owner": "backend",
453
+ "action": "fixed",
454
+ "notice": "daily_cap",
455
+ "trace": True,
456
+ "fr": "docs/16",
457
+ },
458
+ {
459
+ "id": "be-global-cap",
460
+ "stage": "route",
461
+ "routes": [
462
+ "API",
463
+ "WEB",
464
+ "LINE",
465
+ "LEGACY_APP",
466
+ "PARTNER",
467
+ ],
468
+ "owner": "backend",
469
+ "action": "fixed",
470
+ "notice": "error_llm_unavailable",
471
+ "trace": True,
472
+ "fr": "docs/16",
473
+ },
474
+ {
475
+ "id": "be-clean",
476
+ "stage": "input",
477
+ "routes": [
478
+ "API",
479
+ "WEB",
480
+ "LINE",
481
+ "LEGACY_APP",
482
+ "PARTNER",
483
+ ],
484
+ "owner": "backend",
485
+ "action": "strip",
486
+ "trace": False,
487
+ "fr": "P4 H-1",
488
+ },
489
+ {
490
+ "id": "be-jailbreak",
491
+ "stage": "input",
492
+ "routes": [
493
+ "API",
494
+ "WEB",
495
+ "LINE",
496
+ "LEGACY_APP",
497
+ "PARTNER",
498
+ ],
499
+ "owner": "both",
500
+ "action": "fixed",
501
+ "notice": "jailbreak",
502
+ "trace": True,
503
+ "fr": "FR-GUARD-01~05",
504
+ },
505
+ {
506
+ "id": "be-should-rag",
507
+ "stage": "retrieval",
508
+ "routes": [
509
+ "API",
510
+ "WEB",
511
+ "LINE",
512
+ "LEGACY_APP",
513
+ "PARTNER",
514
+ ],
515
+ "owner": "backend",
516
+ "action": "strip",
517
+ "trace": False,
518
+ "fr": "docs/03 §7.3",
519
+ },
520
+ {
521
+ "id": "be-internal",
522
+ "stage": "route",
523
+ "routes": [
524
+ "API",
525
+ "WEB",
526
+ "LEGACY_APP",
527
+ ],
528
+ "owner": "backend",
529
+ "action": "fixed",
530
+ "notice": "error_internal",
531
+ "trace": True,
532
+ "fr": "docs/03 §7.1",
533
+ },
534
+ {
535
+ "id": "be-llm-fail",
536
+ "stage": "route",
537
+ "routes": [
538
+ "API",
539
+ "WEB",
540
+ "LEGACY_APP",
541
+ ],
542
+ "owner": "backend",
543
+ "action": "fixed",
544
+ "notice": "error_llm_unavailable",
545
+ "trace": True,
546
+ "fr": "docs/03 §7.1",
547
+ },
548
+ {
549
+ "id": "be-chips",
550
+ "stage": "output",
551
+ "routes": [
552
+ "API",
553
+ "WEB",
554
+ "LINE",
555
+ "LEGACY_APP",
556
+ "PARTNER",
557
+ "LOCAL_FULL",
558
+ ],
559
+ "owner": "both",
560
+ "action": "strip",
561
+ "trace": False,
562
+ "fr": "docs/03 §8",
563
+ },
564
+ {
565
+ "id": "be-prompt-self",
566
+ "stage": "output",
567
+ "routes": [
568
+ "API",
569
+ "LOCAL_FULL",
570
+ ],
571
+ "owner": "both",
572
+ "action": "fixed",
573
+ "notice": "identity",
574
+ "trace": False,
575
+ "fr": "FR-GUARD-02/03",
576
+ "note": "模型自律;identity / out_of_scope / jailbreak 三句皆可能",
577
+ },
578
+ {
579
+ "id": "be-line-image",
580
+ "stage": "route",
581
+ "routes": [
582
+ "LINE",
583
+ ],
584
+ "owner": "backend",
585
+ "action": "fixed",
586
+ "notice": "error_image_service",
587
+ "trace": False,
588
+ "fr": "docs/03 §3",
589
+ },
590
+ {
591
+ "id": "app-fallback",
592
+ "stage": "route",
593
+ "routes": [
594
+ "API",
595
+ "LOCAL_FULL",
596
+ "LITE",
597
+ ],
598
+ "owner": "app",
599
+ "action": "fallback",
600
+ "reason": "primary_failed",
601
+ "trace": True,
602
+ "fr": "FR-ROUTE-04",
603
+ },
604
+ {
605
+ "id": "app-canfallback",
606
+ "stage": "route",
607
+ "routes": [
608
+ "API",
609
+ "LOCAL_FULL",
610
+ "LITE",
611
+ "MANUAL",
612
+ ],
613
+ "owner": "app",
614
+ "action": "surface_error",
615
+ "error_type": "DeviceSecretLost|RecordsError",
616
+ "trace": False,
617
+ "fr": "review 2026-11-05 H2",
618
+ },
619
+ {
620
+ "id": "app-both-fail",
621
+ "stage": "route",
622
+ "routes": [
623
+ "API",
624
+ "LOCAL_FULL",
625
+ "LITE",
626
+ ],
627
+ "owner": "app",
628
+ "action": "surface_error",
629
+ "error_type": "cloud_error",
630
+ "trace": True,
631
+ "fr": "FR-ROUTE-04",
632
+ },
633
+ {
634
+ "id": "app-last-resort",
635
+ "stage": "route",
636
+ "routes": [
637
+ "MANUAL",
638
+ ],
639
+ "owner": "app",
640
+ "action": "fallback",
641
+ "reason": "offline",
642
+ "trace": True,
643
+ "fr": "FR-LITE-10",
644
+ },
645
+ {
646
+ "id": "app-service-error-local",
647
+ "stage": "route",
648
+ "routes": [
649
+ "API",
650
+ "LOCAL_FULL",
651
+ "LITE",
652
+ ],
653
+ "owner": "app",
654
+ "action": "fallback",
655
+ "reason": "service_error",
656
+ "trace": True,
657
+ "fr": "FR-CLOUD-06",
658
+ },
659
+ {
660
+ "id": "app-service-error-manual",
661
+ "stage": "route",
662
+ "routes": [
663
+ "API",
664
+ "MANUAL",
665
+ ],
666
+ "owner": "app",
667
+ "action": "fallback",
668
+ "reason": "service_error",
669
+ "trace": True,
670
+ "fr": "FR-CLOUD-06",
671
+ },
672
+ {
673
+ "id": "app-cloud-off-unsupported",
674
+ "stage": "route",
675
+ "routes": [
676
+ "API",
677
+ ],
678
+ "owner": "app",
679
+ "action": "fixed",
680
+ "notice": "cloud_off_unsupported",
681
+ "trace": True,
682
+ "fr": "FR-CLOUD-07/08",
683
+ },
684
+ {
685
+ "id": "gate-1-static",
686
+ "stage": "route",
687
+ "routes": [
688
+ "LOCAL_FULL",
689
+ "LITE",
690
+ ],
691
+ "owner": "app",
692
+ "action": "fallback",
693
+ "reason": "spec_fail",
694
+ "trace": False,
695
+ "fr": "FR-DEV-01/02/06",
696
+ },
697
+ {
698
+ "id": "gate-2-bench",
699
+ "stage": "route",
700
+ "routes": [
701
+ "LOCAL_FULL",
702
+ "LITE",
703
+ ],
704
+ "owner": "app",
705
+ "action": "fallback",
706
+ "reason": "bench_fail",
707
+ "trace": False,
708
+ "fr": "FR-DEV-04",
709
+ },
710
+ {
711
+ "id": "gate-3-runtime",
712
+ "stage": "route",
713
+ "routes": [
714
+ "LOCAL_FULL",
715
+ "LITE",
716
+ ],
717
+ "owner": "app",
718
+ "action": "fallback",
719
+ "reason": "runtime_gate",
720
+ "trace": True,
721
+ "fr": "FR-DEV-05",
722
+ },
723
+ {
724
+ "id": "gate-3-lock",
725
+ "stage": "route",
726
+ "routes": [
727
+ "LOCAL_FULL",
728
+ "LITE",
729
+ ],
730
+ "owner": "app",
731
+ "action": "fallback",
732
+ "reason": "locked",
733
+ "trace": True,
734
+ "fr": "FR-DEV-05",
735
+ },
736
+ {
737
+ "id": "loc-jailbreak",
738
+ "stage": "input",
739
+ "routes": [
740
+ "LOCAL_FULL",
741
+ "LITE",
742
+ "MANUAL",
743
+ ],
744
+ "owner": "both",
745
+ "action": "fixed",
746
+ "notice": "jailbreak",
747
+ "trace": True,
748
+ "fr": "FR-GUARD;驗收 14",
749
+ },
750
+ {
751
+ "id": "loc-chatml-sanitize",
752
+ "stage": "input",
753
+ "routes": [
754
+ "LOCAL_FULL",
755
+ "LITE",
756
+ ],
757
+ "owner": "app",
758
+ "action": "strip",
759
+ "trace": False,
760
+ "fr": "docs/03 Layer 1",
761
+ },
762
+ {
763
+ "id": "loc-retrieve-skip-opener",
764
+ "stage": "retrieval",
765
+ "routes": [
766
+ "LOCAL_FULL",
767
+ ],
768
+ "owner": "app",
769
+ "action": "strip",
770
+ "trace": False,
771
+ "fr": "review 2026-10-13 #1",
772
+ },
773
+ {
774
+ "id": "loc-retrieve-fail-open",
775
+ "stage": "retrieval",
776
+ "routes": [
777
+ "LOCAL_FULL",
778
+ ],
779
+ "owner": "app",
780
+ "action": "strip",
781
+ "trace": False,
782
+ "fr": "FR-LOCAL-02",
783
+ },
784
+ {
785
+ "id": "loc-threshold",
786
+ "stage": "retrieval",
787
+ "routes": [
788
+ "LOCAL_FULL",
789
+ ],
790
+ "owner": "app",
791
+ "action": "strip",
792
+ "min_score": "manual_threshold_full",
793
+ "trace": True,
794
+ "fr": "FR-LOCAL-04",
795
+ },
796
+ {
797
+ "id": "loc-fit",
798
+ "stage": "retrieval",
799
+ "routes": [
800
+ "LOCAL_FULL",
801
+ ],
802
+ "owner": "app",
803
+ "action": "strip",
804
+ "trace": False,
805
+ "fr": "FR-LOCAL-06",
806
+ },
807
+ {
808
+ "id": "loc-report",
809
+ "stage": "input",
810
+ "routes": [
811
+ "LOCAL_FULL",
812
+ "LITE",
813
+ "MANUAL",
814
+ ],
815
+ "owner": "both",
816
+ "action": "fixed_plus_sources",
817
+ "notice": "report_notice",
818
+ "min_score": "none",
819
+ "trace": True,
820
+ "fr": "FR-KB-07",
821
+ "note": "釘選電話段全部 + 檢索 covered 的 ≤ report_extra_hits 段(門檻 = 該路線 retriever 的門檻)",
822
+ },
823
+ {
824
+ "id": "loc-rule",
825
+ "stage": "input",
826
+ "routes": [
827
+ "LOCAL_FULL",
828
+ ],
829
+ "owner": "both",
830
+ "action": "fixed_plus_sources",
831
+ "notice_from": "flows.local_guard.rules.reply",
832
+ "min_score": "lite_threshold",
833
+ "trace": True,
834
+ "fr": "FR-LOCAL-09①",
835
+ },
836
+ {
837
+ "id": "loc-mem-load",
838
+ "stage": "generation",
839
+ "routes": [
840
+ "LOCAL_FULL",
841
+ "LITE",
842
+ ],
843
+ "owner": "app",
844
+ "action": "fallback",
845
+ "reason": "low_mem|oom",
846
+ "trace": True,
847
+ "fr": "FR-DEV-05",
848
+ },
849
+ {
850
+ "id": "loc-ttft",
851
+ "stage": "generation",
852
+ "routes": [
853
+ "LOCAL_FULL",
854
+ "LITE",
855
+ ],
856
+ "owner": "app",
857
+ "action": "fallback",
858
+ "reason": "ttft_timeout",
859
+ "trace": True,
860
+ "fr": "FR-DEV-05、FR-LUX-10",
861
+ },
862
+ {
863
+ "id": "loc-engine-error",
864
+ "stage": "generation",
865
+ "routes": [
866
+ "LOCAL_FULL",
867
+ "LITE",
868
+ ],
869
+ "owner": "app",
870
+ "action": "fallback",
871
+ "reason": "local_error",
872
+ "trace": True,
873
+ "fr": "2026-10-13",
874
+ },
875
+ {
876
+ "id": "loc-prompt-budget",
877
+ "stage": "input",
878
+ "routes": [
879
+ "LOCAL_FULL",
880
+ ],
881
+ "owner": "app",
882
+ "action": "strip",
883
+ "trace": False,
884
+ "fr": "FR-LOCAL-06、FR-UDOC-09",
885
+ },
886
+ {
887
+ "id": "loc-zhtw",
888
+ "stage": "output",
889
+ "routes": [
890
+ "LOCAL_FULL",
891
+ "LITE",
892
+ ],
893
+ "owner": "app",
894
+ "action": "strip",
895
+ "trace": False,
896
+ "fr": "docs/11 §3.7c",
897
+ },
898
+ {
899
+ "id": "loc-number-guard",
900
+ "stage": "output",
901
+ "routes": [
902
+ "LOCAL_FULL",
903
+ ],
904
+ "owner": "both",
905
+ "action": "show_sources",
906
+ "notice": "lite_guard_notice",
907
+ "min_score": "lite_threshold",
908
+ "fallback_notice": "local_refuse",
909
+ "trace": True,
910
+ "fr": "FR-LOCAL-09②",
911
+ },
912
+ {
913
+ "id": "loc-lowrel",
914
+ "stage": "output",
915
+ "routes": [
916
+ "LOCAL_FULL",
917
+ ],
918
+ "owner": "app",
919
+ "action": "prepend",
920
+ "notice_ref": "flows.local_guard.lowrel_note",
921
+ "trace": True,
922
+ "fr": "FR-LOCAL-09③",
923
+ },
924
+ {
925
+ "id": "lite-no-rag",
926
+ "stage": "retrieval",
927
+ "routes": [
928
+ "LITE",
929
+ ],
930
+ "owner": "app",
931
+ "action": "fallback",
932
+ "reason": "local_error",
933
+ "trace": True,
934
+ "fr": "D-40",
935
+ },
936
+ {
937
+ "id": "lite-threshold",
938
+ "stage": "retrieval",
939
+ "routes": [
940
+ "LITE",
941
+ "MANUAL",
942
+ ],
943
+ "owner": "app",
944
+ "action": "fixed",
945
+ "notice": "local_refuse",
946
+ "min_score": "lite_threshold",
947
+ "trace": True,
948
+ "fr": "FR-LITE-05、FR-KB-05",
949
+ },
950
+ {
951
+ "id": "lite-fit",
952
+ "stage": "retrieval",
953
+ "routes": [
954
+ "LITE",
955
+ ],
956
+ "owner": "app",
957
+ "action": "strip",
958
+ "trace": False,
959
+ "fr": "FR-LITE-04",
960
+ },
961
+ {
962
+ "id": "lite-refusal",
963
+ "stage": "output",
964
+ "routes": [
965
+ "LITE",
966
+ ],
967
+ "owner": "app",
968
+ "action": "fixed",
969
+ "notice": "local_refuse",
970
+ "trace": True,
971
+ "fr": "FR-LITE-05",
972
+ },
973
+ {
974
+ "id": "lite-number-guard",
975
+ "stage": "output",
976
+ "routes": [
977
+ "LITE",
978
+ ],
979
+ "owner": "both",
980
+ "action": "show_sources",
981
+ "notice": "lite_guard_notice",
982
+ "min_score": "lite_threshold",
983
+ "fallback_notice": "local_refuse",
984
+ "trace": True,
985
+ "fr": "FR-LITE-06",
986
+ },
987
+ {
988
+ "id": "man-all",
989
+ "stage": "output",
990
+ "routes": [
991
+ "MANUAL",
992
+ ],
993
+ "owner": "app",
994
+ "action": "show_sources",
995
+ "notice": "manual_only_notice",
996
+ "min_score": "lite_threshold",
997
+ "fallback_notice": "local_refuse",
998
+ "trace": True,
999
+ "fr": "FR-LITE-07/10/13、FR-KB-07",
1000
+ },
1001
+ ]
1002
+
1003
  QUESTIONNAIRE: dict[str, Any] = {
1004
  "version": 1,
1005
  "status": "待獸醫確認(D-34);2026-10-19 依證據報告調整 age A / stool A 權重與 spread C red_flag(docs/grill/questionnaire_evidence_2026-10-16.md)",
app/main.py CHANGED
@@ -37,6 +37,7 @@ from app.feed import MAX_RELAY_BYTES, MAX_RELAY_FEEDS, fetch_all as feed_fetch_a
37
  from app import line
38
  from app.line import router as line_router
39
  from app.models import manifest_response
 
40
  from app.prompts import FIXED_REPLIES, NON_ANSWER_REPLIES, PROMPT_SOURCE_VERSION, parse_chips, parse_followups
41
  from app.ratelimit import client_ip, rate_account, rate_chat, rate_classify, rate_feed, rate_feed_ingest, rate_feedback, rate_partner, rate_register, legacy_scope, rate_sync, request_ip_debug
42
  from app.storage import (bump_chat_usage, find_reply_after, get_image, get_messages_by_conv, get_service_errors, get_sessions,
@@ -995,6 +996,18 @@ async def admin_openai_passthrough(path: str, request: Request):
995
  return Response(content=r.content, status_code=r.status_code, headers=passthrough)
996
 
997
 
 
 
 
 
 
 
 
 
 
 
 
 
998
  @app.get("/api/models/manifest")
999
  async def api_models_manifest(request: Request):
1000
  """FR-MODEL-01 (docs/02 §1.15): public catalogue of on-device models. The App caches the last copy
 
37
  from app import line
38
  from app.line import router as line_router
39
  from app.models import manifest_response
40
+ from app import price
41
  from app.prompts import FIXED_REPLIES, NON_ANSWER_REPLIES, PROMPT_SOURCE_VERSION, parse_chips, parse_followups
42
  from app.ratelimit import client_ip, rate_account, rate_chat, rate_classify, rate_feed, rate_feed_ingest, rate_feedback, rate_partner, rate_register, legacy_scope, rate_sync, request_ip_debug
43
  from app.storage import (bump_chat_usage, find_reply_after, get_image, get_messages_by_conv, get_service_errors, get_sessions,
 
996
  return Response(content=r.content, status_code=r.status_code, headers=passthrough)
997
 
998
 
999
+ @app.get("/api/price/pig")
1000
+ async def api_price_pig(request: Request):
1001
+ """FR-TODAY-03 (openspec today-and-farm-records, 2026-11-18): 毛豬交易行情 relayed from 農業部, county-aggregated,
1002
+ cached 1 h server-side (stale ≤ 48 h on upstream failure, else 503). Public read-only on the feed bucket."""
1003
+ rate_feed(client_ip(request))
1004
+ try:
1005
+ body = await asyncio.to_thread(price.get_pig_price)
1006
+ except price.PriceUnavailable:
1007
+ raise HTTPException(status_code=503, detail="pig price unavailable")
1008
+ return JSONResponse(body, headers={"Cache-Control": "public, max-age=600"})
1009
+
1010
+
1011
  @app.get("/api/models/manifest")
1012
  async def api_models_manifest(request: Request):
1013
  """FR-MODEL-01 (docs/02 §1.15): public catalogue of on-device models. The App caches the last copy
app/price.py ADDED
@@ -0,0 +1,223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ price.py — 毛豬交易行情 relay for the 今日頁 (openspec today-and-farm-records, FR-TODAY-03 / FR-TODAY-11, design D7).
3
+
4
+ The App never calls data.gov.tw itself: `GET /api/price/pig` serves a 1-hour cached, county-aggregated view of the
5
+ 農業部 AnimalTransData feed (data.gov.tw 7296, UnitId=026). The full feed is 15.7 MB / 9,999 rows; `$top=30` returns
6
+ the newest ~two trading days (47 KB on 2026-11-18, fixture tests/fixtures/moa_pig_top30_2026-11-18.json).
7
+
8
+ Shape: {date, counties:[{county, head, avg_kg, avg_price, markets}], national:{head, avg_kg, avg_price}, fetched_at, stale, server_time}
9
+ - date = the newest 交易日期 (ROC yyymmdd → ISO); only that day's rows are used.
10
+ - county = market name → county by MARKET_COUNTY (台 → 臺 first; unknown names fall through as-is, never dropped).
11
+ - weights: 規格豬-頭數 weighs 規格豬-平均價格 and 規格豬-平均重量 (per county and nationally).
12
+ Cache: process dict + server_meta `price_pig` (survives a restart). TTL 1 h; on upstream failure the last good
13
+ payload is served with stale=true for up to 48 h, after that 503. Every failure is one service_errors `price_fetch` row
14
+ and a 10-minute back-off; only one request fetches at a time and nobody waits for it (review M1).
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import json
19
+ import logging
20
+ import threading
21
+ from datetime import date, datetime, timedelta, timezone
22
+ from typing import Callable
23
+
24
+ import httpx
25
+ from sqlalchemy import insert, select
26
+
27
+ from app.db import engine, now_iso, server_meta
28
+ from app.storage import save_service_error
29
+
30
+ log = logging.getLogger("price")
31
+
32
+ UPSTREAM = "https://data.moa.gov.tw/Service/OpenData/FromM/AnimalTransData.aspx?IsTransData=1&UnitId=026&$top=30"
33
+ MAX_BYTES = 512 * 1024 # design D7: anything bigger is treated as a failed fetch (the `$top` guard was lost)
34
+ FETCH_TIMEOUT = httpx.Timeout(20.0)
35
+ TTL = timedelta(hours=1)
36
+ STALE_MAX = timedelta(hours=48)
37
+ META_KEY = "price_pig"
38
+ SOURCE_LABEL = "農業部 毛豬交易行情"
39
+
40
+ # Upstream column names (full-width hyphen-less; they are what the JSON carries on 2026-11-18)
41
+ COL_DATE, COL_MARKET = "交易日期", "市場名稱"
42
+ COL_HEAD, COL_KG, COL_PRICE = "規格豬-頭數", "規格豬-平均重量", "規格豬-平均價格"
43
+
44
+ # FR-TODAY-11: market name → county, compared after 台 → 臺. Names not listed: "X縣 / X市" stay as they are.
45
+ MARKET_COUNTY: dict[str, str] = {
46
+ "高雄旗山": "高雄市", "高雄鳳山": "高雄市", "高雄岡山": "高雄市", "高雄市": "高雄市",
47
+ "臺南市": "臺南市", "臺南安南": "臺南市",
48
+ "臺中大安": "臺中市",
49
+ "臺東縣": "臺東縣",
50
+ "嘉義市": "嘉義市",
51
+ }
52
+
53
+ Fetcher = Callable[[], bytes]
54
+ RETRY_AFTER = timedelta(minutes=10) # review M1: after a failed fetch, no upstream call for this long
55
+ _lock = threading.Lock() # held only by the one request that fetches; others never wait on it
56
+ _cache: dict | None = None # the last good payload (without server_time / stale)
57
+ _next_try: datetime | None = None # earliest time the upstream may be tried again after a failure
58
+
59
+
60
+ class PriceUnavailable(Exception):
61
+ """No fresh data and no usable cache → 503."""
62
+
63
+
64
+ def norm_county(name: str) -> str:
65
+ return (name or "").strip().replace("台", "臺")
66
+
67
+
68
+ def county_of(market: str) -> str:
69
+ n = norm_county(market)
70
+ return MARKET_COUNTY.get(n, n)
71
+
72
+
73
+ def roc_to_iso(s: str) -> str | None:
74
+ """'1151116' → '2026-11-16'. None when the field is not a 7-digit ROC date."""
75
+ s = str(s or "").strip()
76
+ if len(s) != 7 or not s.isdigit():
77
+ return None
78
+ try:
79
+ return date(int(s[:3]) + 1911, int(s[3:5]), int(s[5:7])).isoformat()
80
+ except ValueError:
81
+ return None
82
+
83
+
84
+ def _num(v) -> float:
85
+ try:
86
+ return float(v)
87
+ except (TypeError, ValueError):
88
+ return 0.0
89
+
90
+
91
+ def _weighted(rows: list[dict]) -> dict:
92
+ head = sum(int(_num(r.get(COL_HEAD))) for r in rows)
93
+ if head <= 0:
94
+ return {"head": 0, "avg_kg": None, "avg_price": None}
95
+ kg = sum(_num(r.get(COL_KG)) * _num(r.get(COL_HEAD)) for r in rows) / head
96
+ price = sum(_num(r.get(COL_PRICE)) * _num(r.get(COL_HEAD)) for r in rows) / head
97
+ return {"head": head, "avg_kg": round(kg, 2), "avg_price": round(price, 2)}
98
+
99
+
100
+ def aggregate(raw: object) -> dict:
101
+ """Upstream JSON list → {date, counties, national}. Raises ValueError when nothing usable is in it."""
102
+ if not isinstance(raw, list):
103
+ raise ValueError("upstream payload is not a list")
104
+ dated = [(roc_to_iso(r.get(COL_DATE)), r) for r in raw if isinstance(r, dict)]
105
+ dated = [(d, r) for d, r in dated if d]
106
+ if not dated:
107
+ raise ValueError("no dated rows")
108
+ newest = max(d for d, _ in dated)
109
+ rows = [r for d, r in dated if d == newest and int(_num(r.get(COL_HEAD))) > 0]
110
+ if not rows:
111
+ raise ValueError("newest day has no 規格豬 rows")
112
+ by_county: dict[str, list[dict]] = {}
113
+ for r in rows:
114
+ by_county.setdefault(county_of(str(r.get(COL_MARKET, ""))), []).append(r)
115
+ counties = [
116
+ {"county": c, **_weighted(rs), "markets": [str(r.get(COL_MARKET, "")) for r in rs]}
117
+ for c, rs in by_county.items()
118
+ ]
119
+ counties.sort(key=lambda x: -x["head"])
120
+ return {"date": newest, "counties": counties, "national": _weighted(rows), "source": SOURCE_LABEL}
121
+
122
+
123
+ def _default_fetcher() -> bytes:
124
+ """Streams the body and aborts as soon as it passes MAX_BYTES (review S1: never buffer a 15 MB answer)."""
125
+ with httpx.Client(timeout=FETCH_TIMEOUT, follow_redirects=True, headers={"User-Agent": "DrPig/2.0 price"}) as c:
126
+ with c.stream("GET", UPSTREAM) as r:
127
+ r.raise_for_status()
128
+ buf = bytearray()
129
+ for chunk in r.iter_bytes():
130
+ buf += chunk
131
+ if len(buf) > MAX_BYTES:
132
+ raise ValueError(f"upstream response too large: > {MAX_BYTES} bytes")
133
+ return bytes(buf)
134
+
135
+
136
+ def _load_meta() -> dict | None:
137
+ with engine().begin() as conn:
138
+ raw = conn.execute(select(server_meta.c.value).where(server_meta.c.key == META_KEY)).scalar()
139
+ if not raw:
140
+ return None
141
+ try:
142
+ v = json.loads(raw)
143
+ return v if isinstance(v, dict) and "fetched_at" in v else None
144
+ except ValueError:
145
+ return None
146
+
147
+
148
+ def _save_meta(payload: dict) -> None:
149
+ value = json.dumps(payload, ensure_ascii=False)
150
+ with engine().begin() as conn:
151
+ if conn.execute(select(server_meta.c.key).where(server_meta.c.key == META_KEY)).first():
152
+ conn.execute(server_meta.update().where(server_meta.c.key == META_KEY).values(value=value))
153
+ else:
154
+ conn.execute(insert(server_meta).values(key=META_KEY, value=value))
155
+
156
+
157
+ def _age(payload: dict, now: datetime) -> timedelta:
158
+ try:
159
+ return now - datetime.fromisoformat(payload["fetched_at"])
160
+ except (KeyError, ValueError, TypeError):
161
+ return STALE_MAX + timedelta(seconds=1)
162
+
163
+
164
+ def fetch_once(fetcher: Fetcher | None = None, now: datetime | None = None) -> dict:
165
+ """One upstream round trip → aggregated payload. Raises on any failure (size, HTTP, JSON, shape)."""
166
+ body = (fetcher or _default_fetcher)()
167
+ if len(body) > MAX_BYTES:
168
+ raise ValueError(f"upstream response too large: {len(body)} bytes")
169
+ payload = aggregate(json.loads(body))
170
+ payload["fetched_at"] = (now or datetime.now(timezone.utc)).replace(tzinfo=None).isoformat()
171
+ return payload
172
+
173
+
174
+ def _serve_cached(now: datetime) -> dict:
175
+ """What a request gets without calling upstream: the fresh copy, a stale copy (≤ 48 h), or PriceUnavailable."""
176
+ cache = _cache
177
+ if cache is not None:
178
+ age = _age(cache, now)
179
+ if age <= TTL:
180
+ return {**cache, "stale": False, "server_time": now_iso()}
181
+ if age <= STALE_MAX:
182
+ return {**cache, "stale": True, "server_time": now_iso()}
183
+ raise PriceUnavailable("no usable cache")
184
+
185
+
186
+ def get_pig_price(fetcher: Fetcher | None = None, now: datetime | None = None) -> dict:
187
+ """The endpoint body (review M1). Fresh cache → no upstream call. Expired → at most ONE request fetches
188
+ (non-blocking lock); concurrent requests do not queue behind it but get the current cache / stale / 503. A failed
189
+ fetch backs off RETRY_AFTER (10 min): until then every request is served from cache / stale / 503 without
190
+ touching upstream."""
191
+ global _cache, _next_try
192
+ now = (now or datetime.now(timezone.utc)).replace(tzinfo=None)
193
+ if _cache is None:
194
+ _cache = _load_meta()
195
+ if _cache is not None and _age(_cache, now) <= TTL:
196
+ return {**_cache, "stale": False, "server_time": now_iso()}
197
+ if _next_try is not None and now < _next_try:
198
+ return _serve_cached(now) # backing off after a failure
199
+ if not _lock.acquire(blocking=False):
200
+ return _serve_cached(now) # someone else is fetching: never wait
201
+ try:
202
+ if _cache is not None and _age(_cache, now) <= TTL: # filled while we checked
203
+ return {**_cache, "stale": False, "server_time": now_iso()}
204
+ try:
205
+ fresh = fetch_once(fetcher, now)
206
+ except Exception as e: # noqa: BLE001 — every failure mode degrades the same way
207
+ log.warning("price fetch failed: %s", e)
208
+ _next_try = now + RETRY_AFTER
209
+ save_service_error("price", "pig", "price_fetch", f"{type(e).__name__}: {e}")
210
+ return _serve_cached(now)
211
+ _cache, _next_try = fresh, None
212
+ try:
213
+ _save_meta(fresh)
214
+ except Exception as e: # noqa: BLE001 — the in-memory copy still serves
215
+ log.warning("price meta save failed: %s", e)
216
+ return {**fresh, "stale": False, "server_time": now_iso()}
217
+ finally:
218
+ _lock.release()
219
+
220
+
221
+ def reset_cache_for_tests() -> None:
222
+ global _cache, _next_try
223
+ _cache, _next_try = None, None
app/prompts.py CHANGED
@@ -17,7 +17,7 @@ from app.generated.prompt_source import ( # noqa: F401 (re-exported for caller
17
 
18
  # Stored replies that are not answers: an outage or the daily cap. A 重送 asks the LLM again instead of replaying them,
19
  # and KPI-2a does not count them as use (2026-11-02; docs/02 chat replay, docs/19 KPI-2a). Defined once, here.
20
- NON_ANSWER_REPLIES: tuple[str, ...] = tuple(FIXED_REPLIES[k].strip() for k in ("error_internal", "error_llm_unavailable", "daily_cap", "cloud_off",
21
  "legacy_daily_cap_v1")) # replies stored before 2026-11-06
22
 
23
 
 
17
 
18
  # Stored replies that are not answers: an outage or the daily cap. A 重送 asks the LLM again instead of replaying them,
19
  # and KPI-2a does not count them as use (2026-11-02; docs/02 chat replay, docs/19 KPI-2a). Defined once, here.
20
+ NON_ANSWER_REPLIES: tuple[str, ...] = tuple(FIXED_REPLIES[k].strip() for k in ("error_internal", "error_llm_unavailable", "daily_cap", "cloud_off", "cloud_off_unsupported", # the App stores the latter on a phone with no local backend (FR-CLOUD-07)
21
  "legacy_daily_cap_v1")) # replies stored before 2026-11-06
22
 
23
 
app/static/admin.html CHANGED
@@ -209,6 +209,12 @@ tr:hover td{background:#fafafa;cursor:pointer}
209
  <div class="card"><div class="card-label">降級原因 Top 5</div><div class="kv" id="dv-down">—</div></div>
210
  <div class="card"><div class="card-label">模型下載完成率</div><div class="card-val" id="dv-dl">—</div><div class="card-sub" id="dv-dlsub">—</div></div>
211
  </div>
 
 
 
 
 
 
212
  <div class="filters">搜尋
213
  <input id="dv-q" placeholder="裝置編號開頭或機型" oninput="clearTimeout(_dvT); _dvT = setTimeout(loadDeviceList, 250)">
214
  Tier
@@ -638,8 +644,31 @@ async function loadDevices() {
638
  document.getElementById('dv-down').innerHTML = d.downgrade_top.map(x => `${escHtml(x.reason)}:${x.n}`).join('<br>') || '—';
639
  document.getElementById('dv-dl').textContent = fmtPct(d.download.rate);
640
  document.getElementById('dv-dlsub').textContent = `完成 ${d.download.done} / 開始 ${d.download.started} 台`;
 
641
  loadDeviceList();
642
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
643
  let _dvSeq = 0, _dvT;
644
  async function loadDeviceList() {
645
  const seq = ++_dvSeq;
 
209
  <div class="card"><div class="card-label">降級原因 Top 5</div><div class="kv" id="dv-down">—</div></div>
210
  <div class="card"><div class="card-label">模型下載完成率</div><div class="card-val" id="dv-dl">—</div><div class="card-sub" id="dv-dlsub">—</div></div>
211
  </div>
212
+ <!-- 2026-11-18 今日頁 + 豬場紀錄:有沒有人用(固定 7 / 30 天窗) -->
213
+ <div class="tbl-head"><span>新功能使用(事件數 / 不重複裝置)</span></div>
214
+ <div class="tbl-wrap"><table>
215
+ <thead><tr><th>功能</th><th>近 7 天</th><th>近 30 天</th></tr></thead>
216
+ <tbody id="dv-feature"><tr><td colspan="3" class="empty">載入中…</td></tr></tbody>
217
+ </table></div>
218
  <div class="filters">搜尋
219
  <input id="dv-q" placeholder="裝置編號開頭或機型" oninput="clearTimeout(_dvT); _dvT = setTimeout(loadDeviceList, 250)">
220
  Tier
 
644
  document.getElementById('dv-down').innerHTML = d.downgrade_top.map(x => `${escHtml(x.reason)}:${x.n}`).join('<br>') || '—';
645
  document.getElementById('dv-dl').textContent = fmtPct(d.download.rate);
646
  document.getElementById('dv-dlsub').textContent = `完成 ${d.download.done} / 開始 ${d.download.started} 台`;
647
+ renderFeatureUsage(d.feature_usage);
648
  loadDeviceList();
649
  }
650
+ // 新功能使用: one row per event (numbers only; the server never stores card / kind content beyond the enum)
651
+ function renderFeatureUsage(fu) {
652
+ const el = document.getElementById('dv-feature');
653
+ if (!fu || !fu['7d'] || !fu['30d']) { el.innerHTML = '<tr><td colspan="3" class="empty">—</td></tr>'; return; }
654
+ const cardLabel = {price: '行情', alert: '公告', reminder_withdrawal: '停藥提醒', reminder_followup: '追蹤提醒', ask: '拍照問'};
655
+ const kindLabel = {medication: '用藥', mortality: '死亡/淘汰'};
656
+ const actionLabel = {schedule: '排程', cancel: '取消', denied: '無權限'};
657
+ const cell = (w, k, sub) => {
658
+ const e = w[k]; if (!e) return '—';
659
+ let t = `${e.n} / ${e.devices} 台`;
660
+ if (sub === 'card' && e.by_card) t += '<br><small>' + Object.entries(e.by_card).filter(([,n]) => n).map(([c,n]) => `${cardLabel[c] || escHtml(c)} ${n}`).join(' · ') + '</small>';
661
+ if (sub === 'kind' && e.by_kind) t += '<br><small>' + Object.entries(e.by_kind).map(([c,n]) => `${kindLabel[c] || escHtml(c)} ${n}`).join(' · ') + '</small>';
662
+ if (sub === 'action' && e.by_action) t += '<br><small>' + Object.entries(e.by_action).map(([c,n]) => `${actionLabel[c] || escHtml(c)} ${n}`).join(' · ') + '</small>';
663
+ return t;
664
+ };
665
+ const rows = [
666
+ ['打開今日頁', 'today_open'], ['點今日卡片', 'today_card_tap', 'card'], ['豬場紀錄(新增 / 編輯 / 刪除)', 'farm_record', 'kind'], ['停藥期提醒', 'withdrawal_reminder', 'action'],
667
+ ].map(([label, k, sub]) => `<tr><td>${label}</td><td>${cell(fu['7d'], k, sub)}</td><td>${cell(fu['30d'], k, sub)}</td></tr>`);
668
+ const ratio = w => w.today_open_ratio == null ? '—' : `${fmtPct(w.today_open_ratio)}(${w.app_devices} 台開過 App)`;
669
+ rows.push(`<tr><td>開 App 的裝置中有開今日頁</td><td>${ratio(fu['7d'])}</td><td>${ratio(fu['30d'])}</td></tr>`);
670
+ el.innerHTML = rows.join('');
671
+ }
672
  let _dvSeq = 0, _dvT;
673
  async function loadDeviceList() {
674
  const seq = ++_dvSeq;
app/sync.py CHANGED
@@ -32,7 +32,7 @@ from sqlalchemy import insert, select, update
32
  from sqlalchemy.exc import OperationalError
33
 
34
  from app import db
35
- from app.db import cases, devices, engine, feedback, images, messages, next_seq, now_iso, sync_ops
36
 
37
  log = logging.getLogger("sync")
38
 
@@ -44,7 +44,19 @@ _ENTITIES: dict[str, tuple[Any, str]] = { # entity → (table, pk colum
44
  "image": (images, "img_id"),
45
  "message": (messages, "msg_id"),
46
  "feedback": (feedback, "fb_id"), # App: fb_id == msg_id (one vote per message)
 
 
47
  }
 
 
 
 
 
 
 
 
 
 
48
  _PROTECTED = {"device_id", "server_received_at", "ts", "session_id", "conv_id", "origin",
49
  "hidden", "legacy", "seq", "client_ts", "case_id_owner"}
50
  _JSON_FIELDS = {"questionnaire_answers", "rapid_test", "quality_flags"}
@@ -150,10 +162,51 @@ def _validate_row(entity: str, row: dict) -> None:
150
  raise OpError("status must be open|archived")
151
  if row.get("verdict_class") not in (None, "bacteria", "virus"):
152
  raise OpError("verdict_class must be bacteria|virus")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
153
 
154
 
155
  def _prepare_insert(entity: str, device_id: str, entity_id: str, vals: dict, client_ts: str) -> dict:
156
- """Fill legacy columns so Admin views keep working; validate required fields (#4, #21)."""
 
157
  if entity == "message":
158
  vals.update(session_id=device_id, conv_id=vals.get("case_id") or "", ts=client_ts, origin="app")
159
  vals.setdefault("route", "API")
@@ -167,6 +220,9 @@ def _prepare_insert(entity: str, device_id: str, entity_id: str, vals: dict, cli
167
  vals.setdefault("status", "open")
168
  vals.setdefault("created_at", client_ts)
169
  vals.setdefault("last_activity_at", client_ts)
 
 
 
170
  return vals
171
 
172
 
@@ -300,7 +356,7 @@ def pull(device_id: str, since: int | None) -> dict:
300
  rows = [dict(r._mapping) for r in conn.execute(stmt)]
301
  truncated = len(rows) > PULL_LIMIT
302
  rows = rows[:PULL_LIMIT]
303
- out[entity + "s"] = rows
304
  if rows:
305
  maxima_all.append(rows[-1]["seq"])
306
  if truncated:
 
32
  from sqlalchemy.exc import OperationalError
33
 
34
  from app import db
35
+ from app.db import cases, devices, engine, feedback, images, medications, messages, mortality, next_seq, now_iso, sync_ops
36
 
37
  log = logging.getLogger("sync")
38
 
 
44
  "image": (images, "img_id"),
45
  "message": (messages, "msg_id"),
46
  "feedback": (feedback, "fb_id"), # App: fb_id == msg_id (one vote per message)
47
+ "medication": (medications, "med_id"), # farm records (FR-FARM-05, 2026-11-18): no case, no legacy columns
48
+ "mortality": (mortality, "mort_id"), # FR-MORT-03
49
  }
50
+ # pull key per entity: entity + "s", except the one irregular plural (FR-MORT-03: `mortalities`)
51
+ _PULL_KEYS = {e: ("mortalities" if e == "mortality" else e + "s") for e in _ENTITIES}
52
+
53
+ # FR-FARM-05 / FR-MORT-03 limits — the App's farm_records/lib/src/validation.dart carries the same numbers.
54
+ MED_DRUG_MAX, MED_TARGET_MAX, MED_NOTE_MAX = 80, 40, 200
55
+ WITHDRAWAL_DAYS_MAX = 365
56
+ MORT_COUNT_MAX = 9999
57
+ MORT_KINDS = ("death", "cull")
58
+ MORT_STAGES = ("piglet", "nursery", "grower", "breeder", "other")
59
+ MORT_REASONS = ("illness", "diarrhea", "respiratory", "crushed", "weak", "injury", "heat", "unknown", "other")
60
  _PROTECTED = {"device_id", "server_received_at", "ts", "session_id", "conv_id", "origin",
61
  "hidden", "legacy", "seq", "client_ts", "case_id_owner"}
62
  _JSON_FIELDS = {"questionnaire_answers", "rapid_test", "quality_flags"}
 
162
  raise OpError("status must be open|archived")
163
  if row.get("verdict_class") not in (None, "bacteria", "virus"):
164
  raise OpError("verdict_class must be bacteria|virus")
165
+ elif entity == "medication":
166
+ _text_len(row, "drug_name", 1, MED_DRUG_MAX)
167
+ _text_len(row, "target", 1, MED_TARGET_MAX)
168
+ _date(row, "given_on")
169
+ d = row.get("withdrawal_days")
170
+ if not isinstance(d, int) or isinstance(d, bool) or not (0 <= d <= WITHDRAWAL_DAYS_MAX):
171
+ raise OpError(f"withdrawal_days must be 0..{WITHDRAWAL_DAYS_MAX}")
172
+ _text_len(row, "note", 0, MED_NOTE_MAX)
173
+ elif entity == "mortality":
174
+ _date(row, "day")
175
+ _enum(row, "kind", MORT_KINDS)
176
+ _enum(row, "stage", MORT_STAGES)
177
+ _enum(row, "reason", MORT_REASONS)
178
+ n = row.get("count")
179
+ if not isinstance(n, int) or isinstance(n, bool) or not (1 <= n <= MORT_COUNT_MAX):
180
+ raise OpError(f"count must be 1..{MORT_COUNT_MAX}")
181
+ _text_len(row, "note", 0, MED_NOTE_MAX)
182
+
183
+
184
+ def _text_len(row: dict, field: str, lo: int, hi: int) -> None:
185
+ v = row.get(field)
186
+ if v is None:
187
+ v = ""
188
+ if not isinstance(v, str) or not (lo <= len(v.strip() if lo else v) <= hi):
189
+ raise OpError(f"{field} must be {lo}..{hi} chars")
190
+
191
+
192
+ def _date(row: dict, field: str) -> None:
193
+ v = row.get(field)
194
+ try:
195
+ if not isinstance(v, str) or len(v) != 10:
196
+ raise ValueError
197
+ datetime.strptime(v, "%Y-%m-%d")
198
+ except ValueError as e:
199
+ raise OpError(f"{field} must be YYYY-MM-DD") from e
200
+
201
+
202
+ def _enum(row: dict, field: str, allowed: tuple[str, ...]) -> None:
203
+ if row.get(field) not in allowed:
204
+ raise OpError(f"{field} must be {'|'.join(allowed)}")
205
 
206
 
207
  def _prepare_insert(entity: str, device_id: str, entity_id: str, vals: dict, client_ts: str) -> dict:
208
+ """Fill legacy columns so Admin views keep working; validate required fields (#4, #21).
209
+ medication / mortality have no legacy columns (no session_id / conv_id / case_id): nothing to map."""
210
  if entity == "message":
211
  vals.update(session_id=device_id, conv_id=vals.get("case_id") or "", ts=client_ts, origin="app")
212
  vals.setdefault("route", "API")
 
220
  vals.setdefault("status", "open")
221
  vals.setdefault("created_at", client_ts)
222
  vals.setdefault("last_activity_at", client_ts)
223
+ elif entity in ("medication", "mortality"):
224
+ vals.setdefault("created_at", client_ts)
225
+ vals.setdefault("updated_at", client_ts)
226
  return vals
227
 
228
 
 
356
  rows = [dict(r._mapping) for r in conn.execute(stmt)]
357
  truncated = len(rows) > PULL_LIMIT
358
  rows = rows[:PULL_LIMIT]
359
+ out[_PULL_KEYS[entity]] = rows
360
  if rows:
361
  maxima_all.append(rows[-1]["seq"])
362
  if truncated: