cctally 1.101.0 → 1.102.0

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.
@@ -20,10 +20,60 @@ from __future__ import annotations
20
20
 
21
21
  import datetime as dt
22
22
  from dataclasses import dataclass
23
+ from enum import Enum
23
24
 
24
25
  from _lib_budget import project_linear
25
26
 
26
27
 
28
+ class ForecastConfidenceCause(str, Enum):
29
+ """The closed set of reasons a forecast is low-confidence.
30
+
31
+ The four values are a wire contract `--json` consumers read, so they are
32
+ the exact strings `_assess_forecast_confidence` has always emitted.
33
+ """
34
+
35
+ ELAPSED_HOURS = "elapsed_hours<24"
36
+ PERCENT = "percent<2"
37
+ SNAPSHOTS = "snapshots<3"
38
+ NO_SAMPLE_GE_24H = "no_sample_ge_24h"
39
+
40
+
41
+ @dataclass(frozen=True)
42
+ class ForecastConfidenceAssessment:
43
+ confidence: str # "high" | "low"
44
+ reasons: tuple[str, ...]
45
+
46
+
47
+ def assess_forecast_confidence(
48
+ elapsed_hours: float,
49
+ percent: float,
50
+ snapshot_count: int,
51
+ *,
52
+ has_sample_ge_24h: bool,
53
+ ) -> ForecastConfidenceAssessment:
54
+ """The complete confidence predicate, including the fourth trigger.
55
+
56
+ `no_sample_ge_24h` used to be appended by `_load_forecast_inputs` after
57
+ it called the three-trigger predicate, which meant glue could add reasons
58
+ the predicate did not know about (#620 S2 E3, closes F19). Reason order
59
+ is `elapsed_hours<24`, `percent<2`, `snapshots<3`, `no_sample_ge_24h` —
60
+ the order the old call-plus-append produced.
61
+ """
62
+ reasons: list[str] = []
63
+ if elapsed_hours < 24:
64
+ reasons.append(ForecastConfidenceCause.ELAPSED_HOURS.value)
65
+ if percent < 2:
66
+ reasons.append(ForecastConfidenceCause.PERCENT.value)
67
+ if snapshot_count < 3:
68
+ reasons.append(ForecastConfidenceCause.SNAPSHOTS.value)
69
+ if not has_sample_ge_24h:
70
+ reasons.append(ForecastConfidenceCause.NO_SAMPLE_GE_24H.value)
71
+ return ForecastConfidenceAssessment(
72
+ confidence="low" if reasons else "high",
73
+ reasons=tuple(reasons),
74
+ )
75
+
76
+
27
77
  @dataclass
28
78
  class ForecastInputs:
29
79
  now_utc: dt.datetime
package/bin/_lib_perf.py CHANGED
@@ -244,6 +244,18 @@ def current_root():
244
244
  return getattr(_tls, "root", None)
245
245
 
246
246
 
247
+ def in_phase() -> bool:
248
+ """Whether a phase is currently OPEN on this thread.
249
+
250
+ `current_root()` answers a different question — it names the last root
251
+ that CLOSED — so a caller deciding whether to open a root of its own
252
+ cannot use it. A pure fold that opens child phases needs this one: with no
253
+ root open its children would be emitted into whatever phase happens to be
254
+ on the stack, or into none at all.
255
+ """
256
+ return bool(_stack())
257
+
258
+
247
259
  def reset_thread():
248
260
  """Start a fresh root scope on this thread, capturing the armed state.
249
261
 
@@ -8,7 +8,9 @@ implementation:
8
8
  1. ``extract_highlights`` — pull up to N lint-clean highlight bullets from a
9
9
  specific ``## [X.Y.Z] - YYYY-MM-DD`` CHANGELOG section (exact version match,
10
10
  Added > Changed > Fixed priority, multiline flattening, terminal issue-ref
11
- stripping, fenced-code skipping).
11
+ stripping, fenced-code skipping). ``render_latest_stable_block`` keeps that
12
+ compact target-section sample honest by naming and linking the complete
13
+ previous-stable-to-target upgrade span.
12
14
  2. ``normalize_highlight`` — deterministically rewrite a bullet so it satisfies
13
15
  the copy lint by construction (em/en dashes with surrounding spaces become
14
16
  ``, ``; doubled separators collapse; leading/trailing separators trim).
@@ -297,14 +299,33 @@ def extract_highlights(
297
299
 
298
300
 
299
301
  def render_latest_stable_block(
300
- version: str, date: str, bullets: "list[str]"
302
+ version: str,
303
+ date: str,
304
+ bullets: "list[str]",
305
+ *,
306
+ previous_stable: "str | None" = None,
307
+ release_url: "str | None" = None,
301
308
  ) -> str:
302
309
  """Render the auto-maintained latest-stable block (no trailing newline
303
- after the last bullet; version+date only when *bullets* is empty)."""
310
+ after the last line; initial baselines retain the single-release shape)."""
304
311
  base = f"**Latest stable: v{version}** ({date})\n"
312
+ if previous_stable is None:
313
+ if bullets:
314
+ return base + "\n" + "\n".join(f"- {b}" for b in bullets)
315
+ return base
316
+ if release_url is None:
317
+ raise ValueError("stable-span README block requires a release URL")
318
+ blocks = [
319
+ base.rstrip("\n"),
320
+ f"Highlights from the `v{previous_stable}` to `v{version}` "
321
+ "stable upgrade:",
322
+ ]
305
323
  if bullets:
306
- return base + "\n" + "\n".join(f"- {b}" for b in bullets)
307
- return base
324
+ blocks.append("\n".join(f"- {b}" for b in bullets))
325
+ blocks.append(
326
+ f"[See every change in this stable upgrade]({release_url})"
327
+ )
328
+ return "\n\n".join(blocks)
308
329
 
309
330
 
310
331
  # --------------------------------------------------------------------------
package/bin/cctally CHANGED
@@ -93,8 +93,10 @@ def _load_sibling(name: str):
93
93
  `_lib_transcript_access.transcripts_allowed`), then self-heal once the body
94
94
  finished. `_SIBLING_LOCK` serializes the load so a concurrent caller blocks
95
95
  until the body completes; `_LOADED_SIBLINGS` gates a lock-free fast path for
96
- already-loaded siblings. Fail-closed by construction — a race waits, it never
97
- returns a partial module early.
96
+ already-loaded siblings and retains the completed object owned by this
97
+ cctally module generation. Fail-closed by construction — a race waits, it
98
+ never returns a partial module early or adopts one registered by a newer
99
+ test-loader generation.
98
100
 
99
101
  For `_cctally_*.py` siblings that back-reference `cctally`, the sibling
100
102
  module exposes a `_cctally()` accessor that reads `sys.modules['cctally']`
@@ -115,19 +117,23 @@ def _load_sibling(name: str):
115
117
  # _load_sibling closure — regardless of pytest re-imports.
116
118
  sys.modules["cctally"] = _THIS_MODULE
117
119
  # Fast path: a sibling whose body has FULLY executed is returned without
118
- # contending on the load lock. `_LOADED_SIBLINGS` is only ever added to,
119
- # after a successful exec_module (below), so its membership is a stable
120
- # "complete" signal — keeping the hot path lock-free for the ~50 sequential
121
- # sibling loads at CLI startup and every warm request-thread lazy-load.
122
- if name in _LOADED_SIBLINGS:
123
- return sys.modules[name]
120
+ # contending on the load lock. The mapping is populated only after a
121
+ # successful exec_module (below), so its value is both a stable "complete"
122
+ # signal and the exact module object this cctally generation completed.
123
+ # Tests deliberately replace sys.modules entries between load_script()
124
+ # generations while older request threads may still run; consulting the
125
+ # process-global entry here would let an old loader adopt a newer partial.
126
+ loaded = _LOADED_SIBLINGS.get(name)
127
+ if loaded is not None:
128
+ return loaded
124
129
  # Slow path — serialize the actual load (#306). Any concurrent caller blocks
125
130
  # here until the owning thread finishes exec_module and records the name
126
131
  # complete, so it can never observe the half-initialized module.
127
132
  with _SIBLING_LOCK:
128
133
  # Completed while we waited for the lock.
129
- if name in _LOADED_SIBLINGS:
130
- return sys.modules[name]
134
+ loaded = _LOADED_SIBLINGS.get(name)
135
+ if loaded is not None:
136
+ return loaded
131
137
  cached = sys.modules.get(name)
132
138
  if cached is not None:
133
139
  # Registered but not yet recorded complete. Under the lock this is
@@ -159,7 +165,7 @@ def _load_sibling(name: str):
159
165
  # broken module is never recorded complete (mirrors importlib).
160
166
  sys.modules.pop(name, None)
161
167
  raise
162
- _LOADED_SIBLINGS.add(name)
168
+ _LOADED_SIBLINGS[name] = mod
163
169
  return mod
164
170
 
165
171
 
@@ -185,12 +191,12 @@ _THIS_MODULE = sys.modules.get(__name__) or sys.modules.get("cctally")
185
191
  # conversation-path siblings are lazy-loaded on those threads. `_SIBLING_LOCK`
186
192
  # serializes the actual load so a concurrent caller can never observe a module
187
193
  # that is registered in sys.modules but whose exec_module is still mid-body (the
188
- # pre-registration window below), and `_LOADED_SIBLINGS` records the names whose
189
- # bodies have fully executed, gating a lock-free fast path. RLock (not Lock) so a
190
- # circular import that re-enters _load_sibling on the SAME thread during
191
- # exec_module cannot self-deadlock.
194
+ # pre-registration window below), and `_LOADED_SIBLINGS` records the completed
195
+ # module objects, gating a lock-free and generation-local fast path. RLock (not
196
+ # Lock) lets a circular import re-enter _load_sibling on the SAME thread during
197
+ # exec_module without self-deadlocking.
192
198
  _SIBLING_LOCK = threading.RLock()
193
- _LOADED_SIBLINGS: set[str] = set()
199
+ _LOADED_SIBLINGS: dict[str, object] = {}
194
200
 
195
201
 
196
202
  # Hook-tick non-path constants (Section 1 of onboarding spec).
@@ -204,6 +210,7 @@ SETUP_SYMLINK_NAMES = (
204
210
  "cctally-budget",
205
211
  "cctally-dashboard",
206
212
  "cctally-dollar-per-percent",
213
+ "cctally-explain",
207
214
  "cctally-five-hour-blocks",
208
215
  "cctally-five-hour-breakdown",
209
216
  "cctally-forecast",
@@ -404,6 +411,40 @@ project_linear = _lib_budget.project_linear
404
411
  calendar_month_window = _lib_budget.calendar_month_window
405
412
  calendar_week_window = _lib_budget.calendar_week_window
406
413
 
414
+ # Diagnosis kernel (#620 S2): the pure classification layer behind
415
+ # `cctally explain` and `GET /api/diagnosis`. Re-exported like the other
416
+ # _lib_* kernels; the store adapter and the renderer are separate siblings.
417
+ _lib_diagnosis = _load_sibling("_lib_diagnosis")
418
+ DIAGNOSIS_CONTRACT_VERSION = _lib_diagnosis.DIAGNOSIS_CONTRACT_VERSION
419
+ DIAGNOSIS_CONTRIBUTOR_SHARE_FLOOR = _lib_diagnosis.DIAGNOSIS_CONTRIBUTOR_SHARE_FLOOR
420
+ DIAGNOSIS_SHARE_FLOOR_EPSILON = _lib_diagnosis.DIAGNOSIS_SHARE_FLOOR_EPSILON
421
+ DIAGNOSIS_TIE_EPSILON_USD = _lib_diagnosis.DIAGNOSIS_TIE_EPSILON_USD
422
+ CONTRIBUTOR_REGISTRY = _lib_diagnosis.CONTRIBUTOR_REGISTRY
423
+ ContributorSpec = _lib_diagnosis.ContributorSpec
424
+ ContributorRow = _lib_diagnosis.ContributorRow
425
+ ClassResult = _lib_diagnosis.ClassResult
426
+ DiagnosisReport = _lib_diagnosis.DiagnosisReport
427
+ DiagnosisWindow = _lib_diagnosis.DiagnosisWindow
428
+ Denominator = _lib_diagnosis.Denominator
429
+ EvidenceField = _lib_diagnosis.EvidenceField
430
+ PopulationCoverage = _lib_diagnosis.PopulationCoverage
431
+ SubjectFacts = _lib_diagnosis.SubjectFacts
432
+ ProviderResult = _lib_diagnosis.ProviderResult
433
+ EstablishmentError = _lib_diagnosis.EstablishmentError
434
+ EstablishmentFailure = _lib_diagnosis.EstablishmentFailure
435
+ WithheldCause = _lib_diagnosis.WithheldCause
436
+ BaselineOutcome = _lib_diagnosis.BaselineOutcome
437
+ VerdictState = _lib_diagnosis.VerdictState
438
+ OverallVerdict = _lib_diagnosis.OverallVerdict
439
+ assess_confidence = _lib_diagnosis.assess_confidence
440
+ support_shortfall = _lib_diagnosis.support_shortfall
441
+ classify_class = _lib_diagnosis.classify_class
442
+ rank_rows = _lib_diagnosis.rank_rows
443
+ overall_verdict = _lib_diagnosis.overall_verdict
444
+ build_provider_result = _lib_diagnosis.build_provider_result
445
+ build_report = _lib_diagnosis.build_report
446
+ unreadable_store_is_terminal = _lib_diagnosis.unreadable_store_is_terminal
447
+
407
448
  # CLAUDE_MODEL_CONTEXT_WINDOWS / …_DEFAULT_FAMILY moved to _cctally_statusline.py (re-exported below).
408
449
 
409
450
  _lib_display_tz = _load_sibling("_lib_display_tz")
@@ -1119,6 +1160,12 @@ maybe_record_codex_budget_milestone = _cctally_record.maybe_record_codex_budget_
1119
1160
  maybe_record_projected_alert = _cctally_record.maybe_record_projected_alert
1120
1161
  _weekly_pct_week_avg_projection = _cctally_record._weekly_pct_week_avg_projection
1121
1162
  _compute_block_totals = _cctally_record._compute_block_totals
1163
+ # #620 S2 E2: the pure fold lifted out of _compute_block_totals, plus the
1164
+ # canonical priced record and bucket shapes it folds over.
1165
+ PricedEntry = _cctally_record.PricedEntry
1166
+ BlockBucket = _cctally_record.BlockBucket
1167
+ BlockTotals = _cctally_record.BlockTotals
1168
+ fold_block_totals = _cctally_record.fold_block_totals
1122
1169
  maybe_update_five_hour_block = _cctally_record.maybe_update_five_hour_block
1123
1170
  cmd_record_usage = _cctally_record.cmd_record_usage
1124
1171
  CreditPlan = _cctally_record.CreditPlan
@@ -2999,6 +3046,28 @@ cmd_diff = _cctally_diff.cmd_diff # parser: c.c
2999
3046
  _emit_diff_debug_samples = _cctally_diff._emit_diff_debug_samples # test_debug_sample_emission mod._emit_diff_debug_samples
3000
3047
 
3001
3048
 
3049
+ # Eager re-export of bin/_cctally_diagnosis.py — the `explain` handler, the
3050
+ # ONE wire adapter both surfaces serialize through, and the canonical
3051
+ # projection their equivalence is defined over (#620 S2). MUST load after the
3052
+ # _lib_diff_kernel block above, because `explain` resolves its window through
3053
+ # the same `_parse_diff_window` grammar. The store adapter it calls stays
3054
+ # lazily loaded, so an ordinary `cctally` invocation never opens a database
3055
+ # it does not need.
3056
+ #
3057
+ # Measured 2026-08-19: loading this sibling costs 20.5 ms of the median
3058
+ # `cctally --version`, which is compiling this module plus `_lib_diagnosis`.
3059
+ # It stays EAGER anyway, for the reason recorded at the `_lib_diff_kernel`
3060
+ # block below: the test surface reaches these symbols by dict-key access on
3061
+ # `mod.__dict__`, which no lazy binding can serve, and spec §4.8 makes the
3062
+ # eager pattern mandatory rather than preferred. Recovering the 20 ms belongs
3063
+ # to a change that shortens `cctally`'s import path as a whole.
3064
+ _cctally_diagnosis = _load_sibling("_cctally_diagnosis")
3065
+ cmd_explain = _cctally_diagnosis.cmd_explain # parser: c.cmd_explain
3066
+ diagnosis_to_wire = _cctally_diagnosis.diagnosis_to_wire
3067
+ canonical_projection = _cctally_diagnosis.canonical_projection
3068
+ render_diagnosis_terminal = _cctally_diagnosis.render_terminal
3069
+
3070
+
3002
3071
  # Provider-aware analytics deliberately wrap the established command entries
3003
3072
  # here, leaving their Claude implementation modules untouched below the branch.
3004
3073
  _cmd_project_claude = cmd_project
@@ -3577,6 +3646,14 @@ def _post_command_update_hooks(command: str | None, args) -> None:
3577
3646
  return
3578
3647
  if command == "doctor":
3579
3648
  return
3649
+ if command == "explain":
3650
+ # Read-only diagnostic by contract (#620 S3, spec 5.1): every store it
3651
+ # touches is opened `mode=ro`, and it must reach no update check, no
3652
+ # telemetry beat and no configuration write. Without this early return
3653
+ # `_spawn_background_update_check` writes `update-state.json` and
3654
+ # `update.log` into a data directory the command only read from. Same
3655
+ # rationale class as `doctor` and `pricing-check` below.
3656
+ return
3580
3657
  if command == "pricing-check":
3581
3658
  # Read-only diagnostic (same rationale as doctor): load_config() would
3582
3659
  # call ensure_dirs() and write a stub config.json on a fresh HOME, and
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env bash
2
+ # Thin wrapper: `cctally-explain` → `cctally explain`.
3
+ # Mirrors `cctally-forecast` / `cctally-project` pattern.
4
+ set -euo pipefail
5
+ exec "$(dirname "$0")/cctally" explain "$@"