cctally 1.116.1 → 1.117.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/CHANGELOG.md +47 -0
  2. package/README.md +4 -6
  3. package/bin/_cctally_account.py +57 -3
  4. package/bin/_cctally_cache.py +5720 -885
  5. package/bin/_cctally_claude_attribution.py +997 -0
  6. package/bin/_cctally_completion.py +101 -28
  7. package/bin/_cctally_core.py +235 -12
  8. package/bin/_cctally_dashboard.py +263 -17
  9. package/bin/_cctally_dashboard_conversation.py +107 -21
  10. package/bin/_cctally_dashboard_envelope.py +44 -0
  11. package/bin/_cctally_db.py +928 -80
  12. package/bin/_cctally_diagnosis_sources.py +78 -13
  13. package/bin/_cctally_doctor.py +211 -86
  14. package/bin/_cctally_five_hour.py +446 -22
  15. package/bin/_cctally_forecast.py +302 -6
  16. package/bin/_cctally_journal.py +2418 -158
  17. package/bin/_cctally_milestone_history.py +379 -91
  18. package/bin/_cctally_oauth_samples.py +185 -7
  19. package/bin/_cctally_parser.py +38 -0
  20. package/bin/_cctally_project.py +34 -8
  21. package/bin/_cctally_quarantine.py +821 -343
  22. package/bin/_cctally_quota.py +69 -4
  23. package/bin/_cctally_quota_calibration.py +677 -3
  24. package/bin/_cctally_quota_model.py +927 -127
  25. package/bin/_cctally_record.py +922 -445
  26. package/bin/_cctally_rederive.py +119 -15
  27. package/bin/_cctally_statusline.py +1048 -176
  28. package/bin/_cctally_store.py +544 -110
  29. package/bin/_cctally_tui.py +455 -42
  30. package/bin/_cctally_update.py +77 -14
  31. package/bin/_lib_account_protocol.py +227 -19
  32. package/bin/_lib_claude_attribution.py +421 -0
  33. package/bin/_lib_clone_copy.py +30 -0
  34. package/bin/_lib_codex_conversation_query.py +45 -9
  35. package/bin/_lib_codex_conversation_watch.py +72 -13
  36. package/bin/_lib_codex_rollout_container.py +234 -19
  37. package/bin/_lib_codex_worker_lifecycle.py +374 -0
  38. package/bin/_lib_credit.py +22 -13
  39. package/bin/_lib_dashboard_sources.py +257 -18
  40. package/bin/_lib_detector_access_registry.py +1335 -166
  41. package/bin/_lib_doctor.py +276 -92
  42. package/bin/_lib_ingest_frontier.py +269 -36
  43. package/bin/_lib_journal.py +273 -22
  44. package/bin/_lib_jsonl.py +12 -0
  45. package/bin/_lib_meter_rate_change.py +72 -0
  46. package/bin/_lib_outcome_quarantine.py +917 -554
  47. package/bin/_lib_provider_activity.py +24 -6
  48. package/bin/_lib_quota_calibration.py +57 -3
  49. package/bin/_lib_quota_copy.py +7 -2
  50. package/bin/_lib_quota_lineage.py +613 -0
  51. package/bin/_lib_quota_model.py +464 -33
  52. package/bin/_lib_rate_change_delivery.py +16 -0
  53. package/bin/_lib_reclaim_planner.py +6 -4
  54. package/bin/_lib_rederive.py +2046 -21
  55. package/bin/_lib_selector_state.py +131 -3
  56. package/bin/_lib_snapshot_cache.py +8 -0
  57. package/bin/_lib_stale_proof.py +113 -4
  58. package/bin/_lib_statusline.py +72 -3
  59. package/bin/_lib_statusline_candidates.py +246 -42
  60. package/bin/_lib_tick_stats.py +10 -5
  61. package/bin/_lib_write_io.py +419 -6
  62. package/bin/cctally +28 -11
  63. package/dashboard/static/assets/{ConversationsView-Dflb_myA.js → ConversationsView-oqNsWzWV.js} +1 -1
  64. package/dashboard/static/assets/{DoctorModal-DFX5CfIs.js → DoctorModal-B0DnU9d9.js} +1 -1
  65. package/dashboard/static/assets/ModalRoot-CYua2wP_.js +1 -0
  66. package/dashboard/static/assets/{ProjectsDrillPanel-C3PJy1xx.js → ProjectsDrillPanel-DSxXQSa-.js} +1 -1
  67. package/dashboard/static/assets/{SourceDetailModal-BczsWKhD.js → SourceDetailModal-BleDpQqG.js} +1 -1
  68. package/dashboard/static/assets/{UpdateModal-Os-Lo5cs.js → UpdateModal-CMqaAkSK.js} +1 -1
  69. package/dashboard/static/assets/{index-CYZ3NLqF.js → index-BjQV-0-D.js} +3 -3
  70. package/dashboard/static/assets/index-D34eYhAc.css +1 -0
  71. package/dashboard/static/assets/{outlineNavigation-k-zIif6W.js → outlineNavigation-CO-VWBm7.js} +1 -1
  72. package/dashboard/static/assets/{useKeymap-CW7Up0Ay.js → useKeymap-CUgEnnua.js} +1 -1
  73. package/dashboard/static/dashboard.html +3 -3
  74. package/package.json +5 -1
  75. package/dashboard/static/assets/ModalRoot-HlxoagIa.js +0 -1
  76. package/dashboard/static/assets/index-BKITk1CT.css +0 -1
@@ -52,6 +52,12 @@ from _cctally_core import (
52
52
  _BudgetConfigError, _get_budget_config,
53
53
  BUDGET_PERIODS as _CCTALLY_BUDGET_PERIODS,
54
54
  )
55
+ # #836: the decorated Current Week's owner and cycle identity read the reset
56
+ # chokepoint and the held-column guard directly; neither is ns-patched.
57
+ from _cctally_core import (
58
+ _canonicalize_optional_iso, _latest_reset_event_for_end,
59
+ weekly_held_exclusion,
60
+ )
55
61
 
56
62
  import importlib.util as _ilu
57
63
 
@@ -389,6 +395,272 @@ def _apply_midweek_reset_override(
389
395
  return week_start_at, samples
390
396
 
391
397
 
398
+ # === #836: the decorated Current Week — one owner, one cycle identity =======
399
+ #
400
+ # On a store with more than one REAL Claude account (`provider_is_decorated`)
401
+ # the Current Week card, its weekly milestones and the history index's current
402
+ # entry describe ONE account: the owner of the newest non-held weekly sample at
403
+ # the build's as-of instant (#839's contract, spec 5.2). The merged reads above
404
+ # stay unchanged for every undecorated store and every other caller.
405
+
406
+ #: Every subscription window that can contain an instant starts no more than
407
+ #: seven days (plus host-offset slack on `week_start_date`) before it, so this
408
+ #: leading `week_start_date` bound keeps every candidate read an
409
+ #: `idx_usage_week_time` range rather than a scan of the whole history.
410
+ _CLAUDE_CYCLE_CANDIDATE_DAYS = 8
411
+
412
+
413
+ @dataclass(frozen=True)
414
+ class ClaudeCycleScope:
415
+ """The decorated Current Week's cycle identity (#836, spec 5.2 step 2).
416
+
417
+ Resolved once per build by `_claude_current_cycle_scope` and shared by the
418
+ card, the weekly milestones and the scoped history index, so the three
419
+ readers of one cycle cannot choose it differently.
420
+
421
+ ``account_key``: the owner. ``as_of_utc``: the build instant (ISO-8601
422
+ ``Z``); reset events are admitted only at or before it.
423
+ ``week_start_date``: the storage key milestones are recorded under.
424
+ ``week_start_at``: the owner's stored boundary text (``None`` on the
425
+ date-only leg). ``week_end_at``: the canonical end
426
+ (`_canonicalize_optional_iso`, the `week_reset_events.new_week_end_at`
427
+ form; ``None`` on the date-only leg). ``effective_start_at``: the week
428
+ start, or the active reset's effective instant when later (ISO-8601 ``Z``;
429
+ ``None`` on the date-only leg). ``reset_event_id``: the active reset's id
430
+ (the milestone segment), ``0`` when none.
431
+ """
432
+ account_key: str
433
+ as_of_utc: str
434
+ week_start_date: str
435
+ week_start_at: "str | None"
436
+ week_end_at: "str | None"
437
+ effective_start_at: "str | None"
438
+ reset_event_id: int
439
+
440
+
441
+ def _claude_newest_weekly_sample(conn, now_utc: dt.datetime, *,
442
+ account_key: "str | None" = None):
443
+ """The newest non-held weekly sample captured at or before ``now_utc``
444
+ among windows containing it, or ``None`` (#836, spec 5.2 step 1).
445
+
446
+ Only non-held rows take part, so a newer held row of another account (a
447
+ copy of an older weekly value under a newer capture) never chooses the
448
+ window — the defect of the held-inclusive ``MAX(captured_at_utc)`` window
449
+ choice in `_fetch_current_week_snapshots` (spec D-C). Captures after
450
+ ``now_utc`` never participate. Boundaryful windows
451
+ (``[week_start_at, week_end_at)`` containing ``now_utc``) are preferred;
452
+ when none qualifies, the date-only leg (``week_start_date`` ..
453
+ ``week_end_date`` containing today's host-local date) applies, as in
454
+ `_fetch_current_week_snapshots`. Ties break by ``(captured_at_utc, id)``.
455
+
456
+ Returns a dict of the row's identity and boundary columns plus
457
+ ``boundaryful``: whether the CHOSEN row carries both parseable bounds,
458
+ never which pool it came from. On the window's end date, after its reset
459
+ instant and before any next-window sample, a bounded row reaches the
460
+ date-only pool; its scope is still built from its own bounds, so the
461
+ account's own reset stays in effect (#836 review F1).
462
+ """
463
+ floor_date = (now_utc.astimezone(dt.timezone.utc).date()
464
+ - dt.timedelta(days=_CLAUDE_CYCLE_CANDIDATE_DAYS)).isoformat()
465
+ acct_pred = "" if account_key is None else " AND account_key = ?"
466
+ acct_p: tuple = () if account_key is None else (account_key,)
467
+ rows = conn.execute(
468
+ "SELECT id, account_key, week_start_date, week_end_date, "
469
+ " week_start_at, week_end_at, captured_at_utc "
470
+ "FROM weekly_usage_snapshots "
471
+ "WHERE week_start_date >= ?" + acct_pred
472
+ + weekly_held_exclusion(conn),
473
+ (floor_date,) + acct_p,
474
+ ).fetchall()
475
+ # internal fallback: host-local intentional (the date-only leg's day,
476
+ # matching `_fetch_current_week_snapshots`)
477
+ today_local = now_utc.astimezone().date().isoformat()
478
+ boundaryful = []
479
+ date_only = []
480
+ for r in rows:
481
+ try:
482
+ cap = parse_iso_datetime(r[6], "captured_at_utc")
483
+ except (TypeError, ValueError):
484
+ continue
485
+ if cap > now_utc:
486
+ continue
487
+ rank = (cap, int(r[0]))
488
+ try:
489
+ ws = parse_iso_datetime(r[4], "week_start_at") if r[4] else None
490
+ we = parse_iso_datetime(r[5], "week_end_at") if r[5] else None
491
+ except ValueError:
492
+ ws = we = None
493
+ bounded = ws is not None and we is not None
494
+ if bounded and ws <= now_utc < we:
495
+ boundaryful.append((rank, r, True))
496
+ elif (r[2] is not None and r[3] is not None
497
+ and r[2] <= today_local <= r[3]):
498
+ date_only.append((rank, r, bounded))
499
+ pool = boundaryful or date_only
500
+ if not pool:
501
+ return None
502
+ _rank, r, bounded = max(pool, key=lambda item: item[0])
503
+ return {
504
+ "id": int(r[0]),
505
+ "account_key": r[1],
506
+ "week_start_date": r[2],
507
+ "week_end_date": r[3],
508
+ "week_start_at": r[4],
509
+ "week_end_at": r[5],
510
+ "captured_at_utc": r[6],
511
+ "boundaryful": bounded,
512
+ }
513
+
514
+
515
+ def _claude_select_current_owner(conn, now_utc: dt.datetime) -> "str | None":
516
+ """The displayed account: the owner of the newest non-held weekly sample
517
+ at ``now_utc`` (#836, spec 5.2 step 1), or ``None`` when there is none."""
518
+ sample = _claude_newest_weekly_sample(conn, now_utc)
519
+ return None if sample is None else sample["account_key"]
520
+
521
+
522
+ def _claude_current_cycle_scope(conn, now_utc: dt.datetime, *,
523
+ account_key: str) -> "ClaudeCycleScope | None":
524
+ """``account_key``'s current cycle identity at ``now_utc`` (#836, spec 5.2
525
+ step 2), or ``None`` when the account has no eligible non-held sample.
526
+
527
+ The window is the one holding the account's newest eligible non-held
528
+ sample. The active reset is `_latest_reset_event_for_end` for the
529
+ canonical end, scoped to the account and admitted only at or before
530
+ ``now_utc`` — the #750 S3 chokepoint's effective-instant order — so another
531
+ account's credit never re-anchors this cycle (spec D-A) and a reset that
532
+ takes effect later does not cut it yet. The effective start is that
533
+ reset's instant exactly when the history index cuts the account's storage
534
+ bucket there (`_claude_reset_cuts_cycle`, the one rule both use) — which
535
+ can be EARLIER than the nominal week start after a same-date early
536
+ re-anchor (#836 review F7). The date-only leg has no end text, so it
537
+ carries no reset.
538
+ """
539
+ sample = _claude_newest_weekly_sample(conn, now_utc, account_key=account_key)
540
+ if sample is None:
541
+ return None
542
+ as_of = _iso_z(now_utc)
543
+ if not sample["boundaryful"]:
544
+ return ClaudeCycleScope(
545
+ account_key=account_key, as_of_utc=as_of,
546
+ week_start_date=sample["week_start_date"],
547
+ week_start_at=None, week_end_at=None, effective_start_at=None,
548
+ reset_event_id=0)
549
+ week_start = parse_iso_datetime(sample["week_start_at"], "week_start_at")
550
+ canon_end = _canonicalize_optional_iso(sample["week_end_at"],
551
+ "claude.cycle.end")
552
+ effective_start = week_start
553
+ reset_event_id = 0
554
+ if canon_end:
555
+ event = _latest_reset_event_for_end(
556
+ conn, canon_end, account_key=account_key, as_of_utc=as_of)
557
+ if event is not None:
558
+ reset_event_id = int(event["id"])
559
+ if event["effective_reset_at_utc"]:
560
+ try:
561
+ reset_dt = parse_iso_datetime(
562
+ event["effective_reset_at_utc"], "reset_event.effective")
563
+ except ValueError:
564
+ reset_dt = None
565
+ if reset_dt is not None:
566
+ import _cctally_milestone_history as _mhist
567
+ outer = _mhist._claude_storage_boundaries(
568
+ conn, sample["week_start_date"],
569
+ account_key=account_key)
570
+ if _mhist._claude_reset_cuts_cycle(outer, reset_dt):
571
+ effective_start = reset_dt
572
+ return ClaudeCycleScope(
573
+ account_key=account_key, as_of_utc=as_of,
574
+ week_start_date=sample["week_start_date"],
575
+ week_start_at=sample["week_start_at"],
576
+ week_end_at=canon_end,
577
+ effective_start_at=_iso_z(effective_start),
578
+ reset_event_id=reset_event_id)
579
+
580
+
581
+ def _claude_cycle_scope_samples(conn, scope: ClaudeCycleScope,
582
+ now_utc: dt.datetime):
583
+ """The decorated card's held-inclusive samples for ``scope`` (#836).
584
+
585
+ The shape of ``_fetch_current_week_snapshots(include_held=True,
586
+ include_account=True, include_scope=True)`` — ``(week_start_at,
587
+ week_end_at, samples, week_scope)`` — restricted to the scope's account and
588
+ window, so the card reads the window its owner was chosen in rather than
589
+ one `_fetch_current_week_snapshots` would choose by its held-inclusive
590
+ ``MAX(captured_at_utc)``. ``week_start_at`` is the NOMINAL start; the
591
+ caller filters from ``scope.effective_start_at``. Samples are filtered to
592
+ ``captured_at <= now_utc``. Returns ``None`` when the window cannot be
593
+ resolved.
594
+ """
595
+ floor_date = (now_utc.astimezone(dt.timezone.utc).date()
596
+ - dt.timedelta(days=_CLAUDE_CYCLE_CANDIDATE_DAYS)).isoformat()
597
+ if scope.week_start_at is None:
598
+ drow = conn.execute(
599
+ "SELECT week_end_date FROM weekly_usage_snapshots "
600
+ "WHERE week_start_date = ? AND account_key = ? "
601
+ "AND week_end_date IS NOT NULL "
602
+ "ORDER BY captured_at_utc DESC, id DESC LIMIT 1",
603
+ (scope.week_start_date, scope.account_key),
604
+ ).fetchone()
605
+ if drow is None:
606
+ return None
607
+ # internal fallback: host-local intentional (the date-only leg)
608
+ local_tz = dt.datetime.now().astimezone().tzinfo
609
+ ws_date = dt.date.fromisoformat(scope.week_start_date)
610
+ we_date = dt.date.fromisoformat(drow[0])
611
+ week_start_at = dt.datetime.combine(
612
+ ws_date, dt.time(0, 0), local_tz).astimezone(dt.timezone.utc)
613
+ week_end_at = dt.datetime.combine(
614
+ we_date + dt.timedelta(days=1), dt.time(0, 0),
615
+ local_tz).astimezone(dt.timezone.utc)
616
+ rows = conn.execute(
617
+ "SELECT captured_at_utc, weekly_percent, five_hour_percent, "
618
+ " weekly_observation_held, account_key "
619
+ "FROM weekly_usage_snapshots "
620
+ "WHERE week_start_date = ? AND account_key = ? "
621
+ "ORDER BY captured_at_utc ASC, id ASC",
622
+ (scope.week_start_date, scope.account_key),
623
+ ).fetchall()
624
+ samples = _shape_week_samples(rows, include_held=True,
625
+ include_account=True)
626
+ samples = [s for s in samples if s[0] <= now_utc]
627
+ return (week_start_at, week_end_at, samples,
628
+ (scope.week_start_date, None))
629
+ week_start_at = parse_iso_datetime(scope.week_start_at, "week_start_at")
630
+ week_end_at = parse_iso_datetime(scope.week_end_at, "week_end_at")
631
+ # Every textual spelling of the same start instant, as the merged read
632
+ # gathers them for an upgrade-in-progress window.
633
+ matching_texts: list[str] = []
634
+ for (text,) in conn.execute(
635
+ "SELECT DISTINCT week_start_at FROM weekly_usage_snapshots "
636
+ "WHERE week_start_date >= ? AND account_key = ? "
637
+ "AND week_start_at IS NOT NULL AND week_end_at IS NOT NULL",
638
+ (floor_date, scope.account_key)).fetchall():
639
+ try:
640
+ if parse_iso_datetime(text, "week_start_at") == week_start_at:
641
+ matching_texts.append(text)
642
+ except ValueError:
643
+ continue
644
+ if scope.week_start_at not in matching_texts:
645
+ matching_texts.append(scope.week_start_at)
646
+ matching_texts.sort()
647
+ placeholders = ",".join("?" * len(matching_texts))
648
+ rows = _week_rows_by_capture(conn.execute(
649
+ f"SELECT captured_at_utc, weekly_percent, five_hour_percent, "
650
+ f" weekly_observation_held, account_key, id "
651
+ f"FROM weekly_usage_snapshots "
652
+ f"WHERE (week_start_at IN ({placeholders}) "
653
+ f" OR (week_start_at IS NULL AND week_start_date = ?)) "
654
+ f" AND account_key = ?",
655
+ tuple(matching_texts) + (scope.week_start_date, scope.account_key),
656
+ ), by_id=True)
657
+ samples = _shape_week_samples(rows, include_held=True,
658
+ include_account=True)
659
+ samples = [s for s in samples if s[0] <= now_utc]
660
+ return (week_start_at, week_end_at, samples,
661
+ (scope.week_start_date, tuple(matching_texts)))
662
+
663
+
392
664
  def _current_week_five_hour_percent(conn, now_utc, week_scope, *,
393
665
  account_key, week_start_at,
394
666
  week_start_before_override):
@@ -777,7 +1049,8 @@ def _snapshot_columns(conn) -> set:
777
1049
  return {str(row[1]) for row in rows}
778
1050
 
779
1051
 
780
- def _dpp_candidate_regime(current_week_start, *, account_key):
1052
+ def _dpp_candidate_regime(current_week_start, *, account_key,
1053
+ stats_conn=None):
781
1054
  """The S1 regime the TARGET week sits in, or None when there is none.
782
1055
 
783
1056
  None means "no regime restriction is knowable", which is the inert state
@@ -817,7 +1090,8 @@ def _dpp_candidate_regime(current_week_start, *, account_key):
817
1090
  c = _cctally()
818
1091
  try:
819
1092
  qcg = c._load_sibling("_cctally_quota_calibration")
820
- read = qcg.read_calibration_file(account_key=account_key)
1093
+ read = qcg.read_calibration_file(account_key=account_key,
1094
+ stats_conn=stats_conn)
821
1095
  except Exception: # noqa: BLE001
822
1096
  return None
823
1097
  regime = getattr(read, "regime", None)
@@ -1032,7 +1306,8 @@ def _select_dollars_per_percent(
1032
1306
  # marked `detection-only`, so on an install with no calibration there is
1033
1307
  # no regime information and the restriction is inert. Applying it anyway
1034
1308
  # would exclude every candidate rather than the incomparable ones.
1035
- regime = _dpp_candidate_regime(current_week_start, account_key=account_key)
1309
+ regime = _dpp_candidate_regime(current_week_start, account_key=account_key,
1310
+ stats_conn=conn)
1036
1311
  eligible: list[tuple[dt.datetime, dt.datetime, float]] = []
1037
1312
  drifted = False
1038
1313
  unverified = False
@@ -1250,6 +1525,11 @@ def _pick_p_24h_ago(
1250
1525
  _CALIBRATION_REJECTION_CODES: dict = {
1251
1526
  "calibration-fingerprint-mismatch": "stale",
1252
1527
  "calibration-revision-mismatch": "stale",
1528
+ # #1015 spec 5.4: a correction to the regime's inputs. Its attempt status
1529
+ # (when current) is stated instead, exactly as the detection-only branch
1530
+ # states the stored status. `calibration-lineage-unavailable` falls to
1531
+ # `unavailable` with every other rejection.
1532
+ "recalibration-needed": "recalibration-needed",
1253
1533
  }
1254
1534
 
1255
1535
  #: The cause a `detection-only` refusal states when the stored regime's own
@@ -1283,6 +1563,7 @@ def _calibrated_projection(
1283
1563
  week_end_at: dt.datetime,
1284
1564
  *,
1285
1565
  account_key: "str | None",
1566
+ stats_conn=None,
1286
1567
  ) -> "tuple[float | None, str | None]":
1287
1568
  """`(projected_end_of_week_percent, withheld_code)` from the S1 model.
1288
1569
 
@@ -1290,7 +1571,8 @@ def _calibrated_projection(
1290
1571
  `_calibrated_week_detail` is the one implementation.
1291
1572
  """
1292
1573
  detail = _calibrated_week_detail(
1293
- now_utc, week_start_at, week_end_at, account_key=account_key)
1574
+ now_utc, week_start_at, week_end_at, account_key=account_key,
1575
+ stats_conn=stats_conn)
1294
1576
  return detail.projection_pct, detail.code
1295
1577
 
1296
1578
 
@@ -1300,6 +1582,7 @@ def _calibrated_week_detail(
1300
1582
  week_end_at: dt.datetime,
1301
1583
  *,
1302
1584
  account_key: "str | None",
1585
+ stats_conn=None,
1303
1586
  ) -> CalibratedWeek:
1304
1587
  """The S1 model's view of THIS week, or the typed cause it has none.
1305
1588
 
@@ -1324,9 +1607,21 @@ def _calibrated_week_detail(
1324
1607
  # of the function. That function now returns THREE values, which is why
1325
1608
  # its unreadable-state path returns `None, (), ()`.
1326
1609
  return CalibratedWeek(code="unavailable")
1327
- read = qcg.read_calibration_file(account_key=account_key)
1610
+ # #1015: the stats connection the caller holds, when it holds one, so the
1611
+ # lineage assessment reads the same index; otherwise the reader's
1612
+ # fail-fast opener.
1613
+ read = qcg.read_calibration_file(account_key=account_key,
1614
+ stats_conn=stats_conn)
1328
1615
  if read.regime is None:
1329
1616
  rejection = getattr(read.rejection, "value", None)
1617
+ if rejection == "recalibration-needed":
1618
+ # #1015 spec 5.4: the sweep's withheld attempt over the current
1619
+ # basis names its own status; otherwise the refusal itself.
1620
+ qm = c._load_sibling("_lib_quota_model")
1621
+ stored = read.regime_status
1622
+ return CalibratedWeek(code=(
1623
+ stored if stored in qm.EVIDENCE_CODES
1624
+ else qm.RECALIBRATION_NEEDED))
1330
1625
  if rejection == "calibration-detection-only":
1331
1626
  # S1 held this successor fit below its prediction gate, and the
1332
1627
  # regime records which blocking status it carried. State that
@@ -1522,7 +1817,8 @@ def _load_forecast_inputs(
1522
1817
  p_24h_ago_corrected = corrected_percent_point(p_24h_ago)
1523
1818
  right_censored = p_now_corrected is None
1524
1819
  calibrated = _calibrated_week_detail(
1525
- now_utc, week_start_at, week_end_at, account_key=account_key)
1820
+ now_utc, week_start_at, week_end_at, account_key=account_key,
1821
+ stats_conn=conn)
1526
1822
 
1527
1823
  # Cache is warm for this invocation after the spent_usd lookup. Suppress
1528
1824
  # re-syncs in downstream cost lookups (trailing-4wk-median loop hits