@alexgreensh/token-optimizer 5.13.74 → 5.13.76

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 (84) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/hooks/module_runner.py +1 -1
  4. package/hooks/posttooluse_runner.py +7 -9
  5. package/hooks/run.py +5 -1
  6. package/hooks/stop_runner.py +15 -56
  7. package/hooks/userpromptsubmit_runner.py +29 -4
  8. package/package.json +1 -1
  9. package/skills/token-optimizer/assets/dashboard.html +30 -14
  10. package/skills/token-optimizer/assets/savings_story.js +103 -27
  11. package/skills/token-optimizer/references/agent-prompts.md +2 -0
  12. package/skills/token-optimizer/references/implementation-playbook.md +1 -0
  13. package/skills/token-optimizer/scripts/_measure/__init__.py +1 -1
  14. package/skills/token-optimizer/scripts/_measure/apply_safe.py +512 -0
  15. package/skills/token-optimizer/scripts/_measure/audit.py +9 -20
  16. package/skills/token-optimizer/scripts/_measure/autocompact_advice.py +455 -0
  17. package/skills/token-optimizer/scripts/_measure/cache_policy.py +82 -127
  18. package/skills/token-optimizer/scripts/_measure/cli.py +10 -24
  19. package/skills/token-optimizer/scripts/_measure/cold_guard.py +777 -0
  20. package/skills/token-optimizer/scripts/_measure/continuity.py +45 -4
  21. package/skills/token-optimizer/scripts/_measure/counted_closes.py +398 -0
  22. package/skills/token-optimizer/scripts/_measure/counted_headline.py +112 -0
  23. package/skills/token-optimizer/scripts/_measure/dashboard.py +14 -6
  24. package/skills/token-optimizer/scripts/_measure/feature_health.py +6 -0
  25. package/skills/token-optimizer/scripts/_measure/keepwarm_auto.py +452 -0
  26. package/skills/token-optimizer/scripts/_measure/keepwarm_economics.py +8 -4
  27. package/skills/token-optimizer/scripts/_measure/keepwarm_safety.py +548 -24
  28. package/skills/token-optimizer/scripts/_measure/limit_units.py +463 -0
  29. package/skills/token-optimizer/scripts/_measure/local_adapt.py +192 -0
  30. package/skills/token-optimizer/scripts/_measure/mod_action_booking.py +71 -14
  31. package/skills/token-optimizer/scripts/_measure/next_actions.py +420 -0
  32. package/skills/token-optimizer/scripts/_measure/poc_commands.py +44 -0
  33. package/skills/token-optimizer/scripts/_measure/prefix_cost.py +215 -0
  34. package/skills/token-optimizer/scripts/_measure/pt_resume_cues.py +46 -0
  35. package/skills/token-optimizer/scripts/_measure/quality_archive.py +7 -10
  36. package/skills/token-optimizer/scripts/_measure/savings.py +80 -82
  37. package/skills/token-optimizer/scripts/_measure/savings_headline.py +17 -21
  38. package/skills/token-optimizer/scripts/_measure/savings_story.py +8 -1
  39. package/skills/token-optimizer/scripts/_measure/session_store_spool.py +119 -78
  40. package/skills/token-optimizer/scripts/_measure/status_bar_refresh.py +38 -3
  41. package/skills/token-optimizer/scripts/_measure/structural_ledger.py +1 -1
  42. package/skills/token-optimizer/scripts/_measure/subscription_audits.py +725 -0
  43. package/skills/token-optimizer/scripts/_measure/transcript_backfill.py +1 -1
  44. package/skills/token-optimizer/scripts/_measure/transcript_stream.py +8 -2
  45. package/skills/token-optimizer/scripts/antigravity_install.py +3 -0
  46. package/skills/token-optimizer/scripts/archive_result.py +16 -28
  47. package/skills/token-optimizer/scripts/archive_verify.py +1 -1
  48. package/skills/token-optimizer/scripts/bash_compress.py +156 -176
  49. package/skills/token-optimizer/scripts/bash_compress_hook.py +218 -174
  50. package/skills/token-optimizer/scripts/bash_search_results.py +189 -9
  51. package/skills/token-optimizer/scripts/bash_whitelist.py +6 -1
  52. package/skills/token-optimizer/scripts/benchmark.py +11 -13
  53. package/skills/token-optimizer/scripts/big_noncode_read.py +998 -0
  54. package/skills/token-optimizer/scripts/build_output_compress.py +103 -8
  55. package/skills/token-optimizer/scripts/builtin_tool_compress.py +716 -0
  56. package/skills/token-optimizer/scripts/cloud_kit.py +1 -1
  57. package/skills/token-optimizer/scripts/codex_doctor.py +1 -1
  58. package/skills/token-optimizer/scripts/command_compress_extra.py +955 -0
  59. package/skills/token-optimizer/scripts/compact_markers.py +129 -0
  60. package/skills/token-optimizer/scripts/copilot_install.py +3 -0
  61. package/skills/token-optimizer/scripts/cursor_install.py +7 -0
  62. package/skills/token-optimizer/scripts/devin_source.py +5 -5
  63. package/skills/token-optimizer/scripts/emit_safety_gate.py +518 -0
  64. package/skills/token-optimizer/scripts/fixtures/b2_more_commands.json +142 -0
  65. package/skills/token-optimizer/scripts/fixtures/b5_more_savings.json +26 -0
  66. package/skills/token-optimizer/scripts/fixtures/builtin_tools.json +103 -0
  67. package/skills/token-optimizer/scripts/fixtures/c7_review_ratchet.json +52 -0
  68. package/skills/token-optimizer/scripts/fixtures/large_output_policy.json +55 -0
  69. package/skills/token-optimizer/scripts/go_cargo_test_compress.py +493 -0
  70. package/skills/token-optimizer/scripts/grok_install.py +3 -0
  71. package/skills/token-optimizer/scripts/hermes_doctor.py +4 -1
  72. package/skills/token-optimizer/scripts/hermes_install.py +10 -1
  73. package/skills/token-optimizer/scripts/hook_fastpath.py +94 -0
  74. package/skills/token-optimizer/scripts/hook_runtime.py +6 -2
  75. package/skills/token-optimizer/scripts/large_output_policy.py +431 -0
  76. package/skills/token-optimizer/scripts/measure.py +10 -12
  77. package/skills/token-optimizer/scripts/pipe_file_compress.py +900 -0
  78. package/skills/token-optimizer/scripts/pipeline_analyzer.py +15 -1
  79. package/skills/token-optimizer/scripts/post_run_classify.py +2 -2
  80. package/skills/token-optimizer/scripts/preserved_reinject.py +20 -3
  81. package/skills/token-optimizer/scripts/process_identity.py +66 -0
  82. package/skills/token-optimizer/scripts/read_cache.py +51 -60
  83. package/skills/token-optimizer/scripts/statusline.js +21 -3
  84. package/skills/token-optimizer/scripts/visibility_rule.py +536 -0
@@ -1,6 +1,6 @@
1
1
  """Definition-only implementations; mutable state belongs to measure."""
2
2
  from __future__ import annotations
3
- from . import _compat, transcript_stream, checkpoint_direction, checkpoint_retention, upgrade_drain_control
3
+ from . import _compat, transcript_stream, checkpoint_direction, checkpoint_retention, upgrade_drain_control, pt_resume_cues
4
4
 
5
5
 
6
6
  def _iter_tail_lines(filepath, tail_lines, chunk_size=None):
@@ -2472,11 +2472,16 @@ def _extract_session_id_from_prompt(text):
2472
2472
  return (m.group(1) or m.group(2)).lower()
2473
2473
 
2474
2474
 
2475
+
2475
2476
  def _resume_intent(text):
2476
2477
  """True when the prompt asks to continue/recall prior work (Latin or CJK cue)."""
2477
2478
  _measure_facade = _compat.facade()
2478
2479
  t = text or ""
2479
- return bool(_measure_facade._RESUME_INTENT_RE.search(t) or _measure_facade._CJK_RESUME_CUE_RE.search(t))
2480
+ return bool(
2481
+ _measure_facade._RESUME_INTENT_RE.search(t)
2482
+ or _measure_facade._CJK_RESUME_CUE_RE.search(t)
2483
+ or pt_resume_cues.pt_resume_cue_re().search(t)
2484
+ )
2480
2485
 
2481
2486
 
2482
2487
  def _in_ranges(cp, ranges):
@@ -2517,6 +2522,7 @@ def _resume_topic_score(text, checkpoint_path):
2517
2522
  """
2518
2523
  _measure_facade = _compat.facade()
2519
2524
  residual = _measure_facade._RESUME_INTENT_RE.sub(" ", str(text or "").lower())
2525
+ residual = pt_resume_cues.pt_resume_cue_re().sub(" ", residual)
2520
2526
  topic_tokens = _measure_facade._topic_tokens(residual, _measure_facade._RESUME_TOPIC_STOPWORDS)
2521
2527
  if not topic_tokens:
2522
2528
  return 0.0
@@ -4293,6 +4299,37 @@ def keyword_relevance_score(text, checkpoint_path):
4293
4299
  every checkpoint ties at 1.0 and the most RECENT one wins, surfacing the
4294
4300
  wrong parallel session instead of the one the user named.
4295
4301
  """
4302
+ # Function words (EN + PT, len>3 so they would survive _topic_token_kept) that carry no
4303
+ # topic. Only the PROMPT side of keyword_relevance_score drops them: a prompt such as
4304
+ # "would this benchmark spend our tokens" must not match an unrelated checkpoint on
4305
+ # "this"/"would" alone. Content words ("tokens", "build", "test") are deliberately absent.
4306
+ # Lives inside this function: this provider must stay definitions-only
4307
+ # (scripts/check_measure_split.py) and the measure.py facade may not grow
4308
+ # (scripts/check_file_size.py).
4309
+ _PROMPT_FUNCTION_WORDS = frozenset({
4310
+ # English
4311
+ "this", "that", "these", "those", "them", "they", "their", "theirs", "there",
4312
+ "then", "than", "what", "when", "where", "which", "while", "whom", "whose",
4313
+ "with", "without", "within", "would", "should", "could", "shall", "might",
4314
+ "must", "have", "been", "being", "were", "does", "done",
4315
+ "your", "yours", "ours", "ourselves", "myself", "yourself", "itself",
4316
+ "also", "just", "very", "more", "most", "some", "such", "only", "into",
4317
+ "from", "about", "over", "here", "really", "still", "even", "each", "other",
4318
+ "both", "same", "will", "because", "though", "although", "whether",
4319
+ "much", "many", "ever", "never", "maybe", "again", "once",
4320
+ # Portuguese (accented and unaccented forms)
4321
+ "esse", "esses", "essa", "essas", "isso", "este", "estes", "esta", "estas",
4322
+ "isto", "aquele", "aquela", "aqueles", "aquelas", "aquilo", "nosso", "nossa",
4323
+ "nossos", "nossas", "seus", "suas", "meus", "minha",
4324
+ "minhas", "para", "como", "temos", "tenho", "tinha", "tenha", "tambem",
4325
+ "também", "está", "estou", "estão", "estao", "estamos", "mais",
4326
+ "muito", "muita", "muitos", "muitas", "pois", "porque", "porém", "porem",
4327
+ "entao", "então", "quando", "onde", "qual", "quais", "quem", "aqui", "ainda",
4328
+ "apenas", "sobre", "entre", "sido", "será", "sera", "seria", "deve", "devem",
4329
+ "pode", "podem", "poderia", "havia", "mesmo", "nunca", "sempre", "depois",
4330
+ "agora", "tudo", "toda", "todos", "todas",
4331
+ })
4332
+
4296
4333
  _measure_facade = _compat.facade()
4297
4334
  text_lower = text.lower()
4298
4335
 
@@ -4302,7 +4339,10 @@ def keyword_relevance_score(text, checkpoint_path):
4302
4339
  _measure_facade = _compat.facade()
4303
4340
  return _measure_facade._topic_tokens(s)
4304
4341
 
4305
- text_tokens = content_words(text)
4342
+ # Function words never count as topic (neither denominator nor hits), and a
4343
+ # resume cue followed only by them ("continue where we left off with these")
4344
+ # stays a vague resume.
4345
+ text_tokens = {w for w in content_words(text) if w not in _PROMPT_FUNCTION_WORDS}
4306
4346
 
4307
4347
  # Continuation cue present? (phrase OR strong single word)
4308
4348
  has_continuation = (
@@ -4325,6 +4365,7 @@ def keyword_relevance_score(text, checkpoint_path):
4325
4365
  residual = {
4326
4366
  w for w in content_words(residual_text)
4327
4367
  if w not in _measure_facade._RESUME_TOPIC_STOPWORDS and w not in _measure_facade._CONTINUATION_WORDS
4368
+ and w not in _PROMPT_FUNCTION_WORDS
4328
4369
  }
4329
4370
  if not residual:
4330
4371
  return 1.0
@@ -4535,7 +4576,7 @@ def _rotate_checkpoint_events():
4535
4576
 
4536
4577
 
4537
4578
  def _prune_trends_db():
4538
- """Remove session_log rows older than the retention threshold. No-op when unlimited (0)."""
4579
+ """Prune old source rows. Daily closes and corrections outlive retention."""
4539
4580
  _measure_facade = _compat.facade()
4540
4581
  if _measure_facade._TRENDS_RETENTION_DAYS <= 0:
4541
4582
  return
@@ -0,0 +1,398 @@
1
+ """Durable daily savings balances and the reasons for any downward revision."""
2
+ from collections import defaultdict
3
+ from contextlib import contextmanager
4
+ from datetime import date, datetime, timezone
5
+ import json
6
+ import math
7
+ import os
8
+ import sqlite3
9
+
10
+ _HELD_KEY = "counted_held_since"
11
+ _OVERALL_EVIDENCE_KEY = "overall_close_evidence"
12
+ _RECOUNT = "A recount could not reproduce the earlier figure for this day."
13
+ _EMPTY = {"usd": 0.0, "tokens": 0, "since": None, "held_days": 0, "last_correction": None}
14
+
15
+
16
+ def selected_rows(facade, conn):
17
+ """Share the lifetime cohort with the period summary before its date filter."""
18
+ excluded = set()
19
+ if facade._ensure_counted_views(conn):
20
+ for prefix, table in (("se", "savings_events"), ("ce", "compression_events")):
21
+ excluded.update(row[0] for row in conn.execute(
22
+ f"SELECT '{prefix}:'||id FROM main.{table} EXCEPT "
23
+ f"SELECT '{prefix}:'||id FROM counted_{table}"))
24
+ stored = facade._counted_stored_rows(conn)
25
+ candidates = facade._counted_candidate_events(conn)
26
+ orphaned = facade._counted_pricing_v5.orphaned_keys(
27
+ stored.values(), {event[0] for event in candidates}, conn)
28
+ rows = [row for key, row in stored.items() if key not in excluded and key not in orphaned]
29
+ return rows, stored, candidates, orphaned
30
+
31
+
32
+ def awaiting_rescore(facade, rows):
33
+ return [row for row in rows if row.get("session_uuid") and facade._counted_row_awaits_rescore(row)]
34
+
35
+
36
+ def _removal_day(row):
37
+ for value in (str(row["event_ts"] or "")[:10], f"{row['event_month']}-01"):
38
+ try:
39
+ return date.fromisoformat(value).isoformat()
40
+ except ValueError:
41
+ pass
42
+ # The lifetime rollup counts legacy rows that have no usable timestamp.
43
+ # Keep their value without claiming a start date.
44
+ return ""
45
+
46
+
47
+ def _per_day(facade, conn, rows):
48
+ groups = defaultdict(list)
49
+ for row in rows:
50
+ groups[_removal_day(row)].append(row)
51
+ memo = {}
52
+ totals = {}
53
+ for day, day_rows in groups.items():
54
+ rollup = facade._counted_rollup_rows(day_rows, conn, memo, for_close=True)
55
+ usd = rollup["total_usd"]
56
+ if not math.isfinite(usd):
57
+ raise ValueError("invalid counted amount")
58
+ totals[day] = usd, rollup["removed_tokens"] + rollup["reread_tokens"]
59
+ return totals
60
+
61
+
62
+ def per_day(facade, conn):
63
+ """Count initial removals and repeat reads on the original removal day."""
64
+ rows, *_ = selected_rows(facade, conn)
65
+ return _per_day(facade, conn, rows)
66
+
67
+
68
+ @contextmanager
69
+ def _transaction(conn):
70
+ """Close against a single snapshot and preserve the caller's transaction."""
71
+ nested = conn.in_transaction
72
+ conn.execute("SAVEPOINT savings_close" if nested else "BEGIN")
73
+ try:
74
+ yield
75
+ if nested:
76
+ conn.execute("RELEASE savings_close")
77
+ else:
78
+ conn.commit()
79
+ except Exception:
80
+ if nested:
81
+ conn.execute("ROLLBACK TO savings_close")
82
+ conn.execute("RELEASE savings_close")
83
+ else:
84
+ conn.rollback()
85
+ raise
86
+
87
+
88
+ def _create_counted(conn):
89
+ conn.execute("""CREATE TABLE IF NOT EXISTS counted_day_close (
90
+ day TEXT PRIMARY KEY, usd REAL NOT NULL, tokens INTEGER NOT NULL,
91
+ pricing_version TEXT, updated_at TEXT NOT NULL)""")
92
+ conn.execute("""CREATE TABLE IF NOT EXISTS counted_corrections (
93
+ id INTEGER PRIMARY KEY AUTOINCREMENT, day TEXT NOT NULL, applied_at TEXT NOT NULL,
94
+ from_usd REAL NOT NULL, to_usd REAL NOT NULL, reason_code TEXT NOT NULL, reason_text TEXT NOT NULL)""")
95
+ conn.execute("CREATE TABLE IF NOT EXISTS token_optimizer_meta (key TEXT PRIMARY KEY, value TEXT)")
96
+
97
+
98
+ def _decode_held(value):
99
+ held = json.loads(value or "{}")
100
+ if not isinstance(held, dict):
101
+ raise ValueError("invalid counted hold state")
102
+ return held
103
+
104
+
105
+ def _held(conn):
106
+ row = conn.execute("SELECT value FROM token_optimizer_meta WHERE key = ?", (_HELD_KEY,)).fetchone()
107
+ return _decode_held(row[0]) if row else {}
108
+
109
+
110
+ def _decrease(previous, current, old_version, version, pending, held_since, today, recount):
111
+ """Return the hold date and any correction that releases the lower value."""
112
+ if current >= previous - 0.005:
113
+ return None, None
114
+ if old_version != version and not pending:
115
+ return None, ("repricing",
116
+ f"Prices were updated (version {old_version} to {version}). Earlier days were re-priced.")
117
+ first = held_since or today.isoformat()
118
+ if (today - date.fromisoformat(first)).days >= 7:
119
+ return None, ("recount", recount)
120
+ return first, None
121
+
122
+
123
+ def _write_correction(conn, tier, day, stamp, before, after, reason):
124
+ conn.execute(f"""INSERT INTO {tier}_corrections
125
+ (day, applied_at, from_usd, to_usd, reason_code, reason_text)
126
+ VALUES (?, ?, ?, ?, ?, ?)""", (day, stamp, before, after, *reason))
127
+
128
+
129
+ def _refresh_counted(facade, conn, today, stamp, version):
130
+ rows, source_rows, *_ = selected_rows(facade, conn)
131
+ pending = bool(awaiting_rescore(facade, rows))
132
+ amounts = _per_day(facade, conn, rows)
133
+ _create_counted(conn)
134
+ stored = {day: (usd, tokens, pricing) for day, usd, tokens, pricing in conn.execute(
135
+ "SELECT day, usd, tokens, pricing_version FROM counted_day_close")}
136
+ held = _held(conn)
137
+ prior_held = held.copy()
138
+ # A filtered row can support a correction to zero. An absent row cannot.
139
+ missing = stored.keys() - {_removal_day(row) for row in source_rows.values()}
140
+ for day in missing:
141
+ held.pop(day, None)
142
+ written = 0
143
+ for day in sorted(amounts.keys() | (stored.keys() - missing)):
144
+ current, tokens = amounts.get(day, (0.0, 0))
145
+ saved_version = version
146
+ if day in stored:
147
+ previous, previous_tokens, old_version = stored[day]
148
+ first, correction = _decrease(previous, current, old_version, version, pending,
149
+ held.get(day), today, _RECOUNT)
150
+ if first:
151
+ held[day] = first
152
+ else:
153
+ held.pop(day, None)
154
+ if correction:
155
+ _write_correction(conn, "counted", day, stamp, previous, current, correction)
156
+ written += 1
157
+ elif current <= previous:
158
+ tokens = max(tokens, previous_tokens) if current == previous else previous_tokens
159
+ current = previous
160
+ if pending and not correction:
161
+ saved_version = old_version
162
+ if (current, tokens, saved_version) == stored[day]:
163
+ continue
164
+ elif current < 0:
165
+ _write_correction(conn, "counted", day, stamp, 0.0, current,
166
+ ("net_debit", "Recorded costs exceeded the savings for this day."))
167
+ written += 1
168
+ conn.execute("""INSERT INTO counted_day_close (day, usd, tokens, pricing_version, updated_at)
169
+ VALUES (?, ?, ?, ?, ?) ON CONFLICT(day) DO UPDATE SET
170
+ usd=excluded.usd, tokens=excluded.tokens, pricing_version=excluded.pricing_version,
171
+ updated_at=excluded.updated_at""", (day, current, tokens, saved_version, stamp))
172
+ if held != prior_held:
173
+ conn.execute("INSERT OR REPLACE INTO token_optimizer_meta(key, value) VALUES (?, ?)",
174
+ (_HELD_KEY, json.dumps(held, sort_keys=True)))
175
+ return written, pending, missing
176
+
177
+
178
+ def _recorded_costs(facade, conn, since, now):
179
+ """Read the cost evidence eligible for the same since-install summary."""
180
+ table = facade._counted_table(conn, "savings_events")
181
+ compaction = conn.execute(f"""SELECT COALESCE(-SUM(cost_saved_usd), 0)
182
+ FROM {table} WHERE event_type = 'autocompact_window_estimated'
183
+ AND timestamp >= ? AND cost_saved_usd < 0""", (since,)).fetchone()[0]
184
+ start = facade._keepwarm_iso_to_epoch(since)
185
+ warm = facade.keepwarm_spend_summary(days=max(0, now - start) / 86400, now=now)["spend_usd"]
186
+ return {"keepwarm": warm, "autocompact": compaction}
187
+
188
+
189
+ def _historical_sources(facade, conn, since, seen, *, recheck):
190
+ """Identify evidence that a fresh recount may no longer be able to read."""
191
+ from . import cold_guard
192
+
193
+ sources = set()
194
+ for key, path in conn.execute("""SELECT 'session:' || COALESCE(NULLIF(session_uuid, ''), id), jsonl_path
195
+ FROM session_log WHERE date >= ? AND jsonl_path IS NOT NULL""", (since,)):
196
+ if key not in sources and ((key in seen and not recheck) or os.path.isfile(path)):
197
+ sources.add(key)
198
+ start = facade._keepwarm_iso_to_epoch(since)
199
+ for _, marker in cold_guard._markers(facade):
200
+ for block in cold_guard._blocks(marker):
201
+ if block.get("choice") == "fresh" and block.get("fresh_session_id") and block["told_at"] >= start:
202
+ sources.add(f"cold_guard:{block['fresh_session_id']}:{block['told_at']}")
203
+ return sources
204
+
205
+
206
+ def _overall_evidence(facade, conn, since, now, current, previous):
207
+ row = conn.execute("SELECT value FROM token_optimizer_meta WHERE key = ?", (_OVERALL_EVIDENCE_KEY,)).fetchone()
208
+ prior = _decode_held(row[0]) if row else {}
209
+ costs = _recorded_costs(facade, conn, since, now)
210
+ debit = 0.0
211
+ if prior.get("since") == since:
212
+ new_costs = sum(costs.values()) - sum(prior["costs"].values())
213
+ # A fraction of a cent can move the displayed total by one cent.
214
+ debit_limit = math.ceil(round(new_costs * 100, 6)) / 100
215
+ debit = round(max(0.0, min(debit_limit, prior["usd"] - current, previous - current)), 2)
216
+ seen = set(prior.get("sources", ()))
217
+ sources = _historical_sources(facade, conn, since, seen, recheck=current < previous)
218
+ snapshot = {"since": since, "costs": costs, "usd": current, "sources": sorted(seen | sources)}
219
+ if snapshot != prior:
220
+ conn.execute("INSERT OR REPLACE INTO token_optimizer_meta(key, value) VALUES (?, ?)",
221
+ (_OVERALL_EVIDENCE_KEY, json.dumps(snapshot, separators=(",", ":"))))
222
+ return debit, bool(seen - sources)
223
+
224
+
225
+ def _refresh_overall(facade, conn, since_install, monthly, now, version, pending, missing):
226
+ # This sum includes lifetime estimates whose model mix spans the whole
227
+ # window. Store the balance observed each day. Adding daily balances (or
228
+ # pricing slices separately) would count the same savings more than once.
229
+ all_in = since_install.get("all_in") or {}
230
+ if all_in.get("total_usd") is None or not since_install.get("install_date"):
231
+ return
232
+ try:
233
+ current = float(all_in["total_usd"])
234
+ since = date.fromisoformat(since_install["install_date"]).isoformat()
235
+ except (TypeError, ValueError):
236
+ return
237
+ if not math.isfinite(current):
238
+ return
239
+ conn.execute("""CREATE TABLE IF NOT EXISTS overall_day_close (
240
+ day TEXT PRIMARY KEY, usd REAL NOT NULL, since TEXT NOT NULL, pricing_version TEXT,
241
+ held_since TEXT, estimated_usd REAL, last_30d_usd REAL)""")
242
+ conn.execute("""CREATE TABLE IF NOT EXISTS overall_corrections (
243
+ id INTEGER PRIMARY KEY AUTOINCREMENT, day TEXT NOT NULL, applied_at TEXT NOT NULL,
244
+ from_usd REAL NOT NULL, to_usd REAL NOT NULL, reason_code TEXT NOT NULL, reason_text TEXT NOT NULL)""")
245
+ prior = conn.execute("""SELECT day, usd, since, pricing_version, held_since, estimated_usd, last_30d_usd
246
+ FROM overall_day_close ORDER BY day DESC LIMIT 1""").fetchone()
247
+ today, stamp = now.date(), now.isoformat()
248
+ day, held_since = today.isoformat(), None
249
+ estimate, rolling = monthly
250
+ pending = pending or all_in.get("remeasuring") or all_in.get("routing_pending")
251
+ debit, missing_sources = _overall_evidence(
252
+ facade, conn, since, now.timestamp(), current, prior[1] if prior else current)
253
+ if prior:
254
+ old_day, previous, old_since, old_version, first, old_estimate, old_rolling = prior
255
+ estimate = old_estimate if estimate is None else estimate
256
+ rolling = old_rolling if rolling is None else rolling
257
+ # A wall-clock rollback must not make a later close unreachable.
258
+ day = max(day, old_day)
259
+ since = min(since, old_since)
260
+ if debit:
261
+ after_debit = round(previous - debit, 2)
262
+ _write_correction(conn, "overall", day, stamp, previous, after_debit,
263
+ ("net_debit", "New recorded costs reduced since-install savings."))
264
+ previous = after_debit
265
+ if missing_sources or any(day >= since for day in missing):
266
+ # Aging out of the source window is not evidence for a restatement.
267
+ current = max(previous, current)
268
+ version = old_version
269
+ else:
270
+ held_since, correction = _decrease(
271
+ previous, current, old_version, version, pending, first, today,
272
+ "A recount could not reproduce the earlier since-install savings total.")
273
+ if correction:
274
+ _write_correction(conn, "overall", day, stamp, previous, current, correction)
275
+ else:
276
+ current = max(previous, current)
277
+ if pending:
278
+ version = old_version
279
+ conn.execute("""INSERT OR REPLACE INTO overall_day_close
280
+ (day, usd, since, pricing_version, held_since, estimated_usd, last_30d_usd)
281
+ VALUES (?, ?, ?, ?, ?, ?, ?)""", (day, current, since, version, held_since, estimate, rolling))
282
+
283
+
284
+ def refresh(facade, conn, now=None, *, since_install=None, monthly=(None, None)):
285
+ """Close the counted days, and the overall balance when a full summary exists."""
286
+ written = 0
287
+ try:
288
+ now = (now or datetime.now(timezone.utc)).astimezone(timezone.utc)
289
+ version = str(facade._COUNTED_PRICING_VERSION)
290
+ with _transaction(conn):
291
+ written, pending, missing = _refresh_counted(facade, conn, now.date(), now.isoformat(), version)
292
+ if since_install:
293
+ _refresh_overall(facade, conn, since_install, monthly, now, version, pending, missing)
294
+ except Exception:
295
+ written = 0
296
+ return {k: v for k, v in total(conn).items() if k != "last_correction"} | {"corrections_written": written}
297
+
298
+
299
+ def _correction(date_applied, before, after, reason):
300
+ if not date_applied:
301
+ return None
302
+ return {"date": date_applied[:10], "delta_usd": round(after - before, 6), "reason": reason}
303
+
304
+
305
+ def total(conn):
306
+ """Read the counted balance and latest correction in one SQLite snapshot."""
307
+ try:
308
+ usd, tokens, since, held, stamp, before, after, reason = conn.execute("""
309
+ WITH totals AS (
310
+ SELECT SUM(usd) AS usd, SUM(tokens) AS tokens, MIN(NULLIF(day, '')) AS since
311
+ FROM counted_day_close
312
+ )
313
+ SELECT usd, tokens, since, (SELECT value FROM token_optimizer_meta WHERE key = ?),
314
+ applied_at, from_usd, to_usd, reason_text
315
+ FROM totals LEFT JOIN (
316
+ SELECT applied_at, from_usd, to_usd, reason_text
317
+ FROM counted_corrections ORDER BY applied_at DESC, id DESC LIMIT 1
318
+ ) ON 1 = 1""", (_HELD_KEY,)).fetchone()
319
+ try:
320
+ held_days = len(_decode_held(held))
321
+ except ValueError:
322
+ held_days = 0
323
+ return {"usd": round(usd or 0.0, 6), "tokens": tokens or 0, "since": since,
324
+ "held_days": held_days, "last_correction": _correction(stamp, before, after, reason)}
325
+ except (sqlite3.Error, AttributeError):
326
+ return dict(_EMPTY)
327
+
328
+
329
+ def total_overall(conn):
330
+ """Read the newest daily all-in balance, including its rolling context."""
331
+ try:
332
+ row = conn.execute("""
333
+ SELECT usd, since, held_since, estimated_usd, last_30d_usd, applied_at, from_usd, to_usd, reason_text
334
+ FROM (SELECT * FROM overall_day_close ORDER BY day DESC LIMIT 1)
335
+ LEFT JOIN (SELECT applied_at, from_usd, to_usd, reason_text
336
+ FROM overall_corrections ORDER BY applied_at DESC, id DESC LIMIT 1) ON 1 = 1""").fetchone()
337
+ except (sqlite3.Error, AttributeError):
338
+ return None
339
+ if row is None:
340
+ return None
341
+ usd, since, held, estimated, monthly, stamp, before, after, reason = row
342
+ return {"usd": usd, "tokens": 0, "since": since, "held_days": int(bool(held)),
343
+ "last_correction": _correction(stamp, before, after, reason),
344
+ "estimated_usd": estimated, "last_30d_usd": monthly}
345
+
346
+
347
+ def corrections(conn, now, *, overall=False):
348
+ table = "overall_corrections" if overall else "counted_corrections"
349
+ try:
350
+ rows = conn.execute(f"""SELECT applied_at, from_usd, to_usd, reason_text FROM {table}
351
+ WHERE substr(applied_at, 1, 10) BETWEEN date(?, '-90 days') AND ?
352
+ ORDER BY applied_at DESC, id DESC""", (now.isoformat(), now.isoformat()))
353
+ return [_correction(*row) for row in rows]
354
+ except (sqlite3.Error, AttributeError):
355
+ return []
356
+
357
+
358
+ def register_correction(conn, day, to_usd, reason_code, reason_text):
359
+ """Explicitly restate an existing counted day, atomically with the audit row."""
360
+ stamp = datetime.now(timezone.utc).isoformat()
361
+ to_usd = float(to_usd)
362
+ if not math.isfinite(to_usd) or not reason_code.strip() or not reason_text.strip():
363
+ raise ValueError("a correction needs a finite amount and a reason")
364
+ with _transaction(conn):
365
+ _create_counted(conn)
366
+ row = conn.execute("SELECT usd FROM counted_day_close WHERE day = ?", (day,)).fetchone()
367
+ if row is None or row[0] == to_usd:
368
+ return False
369
+ _write_correction(conn, "counted", day, stamp, row[0], to_usd, (reason_code, reason_text))
370
+ conn.execute("UPDATE counted_day_close SET usd = ?, updated_at = ? WHERE day = ?", (to_usd, stamp, day))
371
+ held = _held(conn)
372
+ if day in held:
373
+ del held[day]
374
+ conn.execute("UPDATE token_optimizer_meta SET value = ? WHERE key = ?",
375
+ (json.dumps(held, sort_keys=True), _HELD_KEY))
376
+ return True
377
+
378
+
379
+ def on_savings_refresh(facade, summary):
380
+ """Refresh at the scaffold's savings-only entry point, then publish both balances."""
381
+ from . import counted_headline
382
+ try:
383
+ if facade.TRENDS_DB.exists():
384
+ uri = facade.TRENDS_DB.resolve().as_uri() + "?mode=rw"
385
+ conn = facade.sqlite3.connect(uri, uri=True, timeout=0.25)
386
+ try:
387
+ action = summary.get("action_savings") or {}
388
+ since = summary.get("since_install") or {}
389
+ all_in = since.get("all_in") or {}
390
+ window_usd = action.get("total_usd") if summary.get("period_days") == 30 else None
391
+ refresh(facade, conn, since_install=since,
392
+ monthly=(all_in.get("estimated_usd"), window_usd))
393
+ finally:
394
+ conn.close()
395
+ except (OSError, sqlite3.Error):
396
+ pass
397
+ summary["counted_headline"] = counted_headline.build(facade)
398
+ summary["overall_headline"] = counted_headline.build_overall(facade)
@@ -0,0 +1,112 @@
1
+ """Read-only savings headlines for the dashboard, CLI and status cache."""
2
+ import argparse
3
+ from contextlib import contextmanager
4
+ from datetime import date, datetime, timezone
5
+ from decimal import Decimal, ROUND_HALF_UP
6
+ import json
7
+ import sqlite3
8
+
9
+ from . import counted_closes, savings_headline
10
+
11
+
12
+ @contextmanager
13
+ def _reader(facade, conn=None):
14
+ if conn is not None:
15
+ yield conn
16
+ return
17
+ try:
18
+ db = sqlite3.connect(facade.TRENDS_DB.resolve().as_uri() + "?mode=ro", uri=True, timeout=0.1)
19
+ except (AttributeError, OSError, sqlite3.Error):
20
+ yield None
21
+ return
22
+ try:
23
+ yield db
24
+ finally:
25
+ db.close()
26
+
27
+
28
+ def _today():
29
+ return datetime.now(timezone.utc).date()
30
+
31
+
32
+ def _money(value):
33
+ return "$" + format(Decimal(str(value)).quantize(Decimal("1"), rounding=ROUND_HALF_UP), ",")
34
+
35
+
36
+ def _signed_money(value, *, whole=False):
37
+ amount = _money(abs(value)) if whole else f"${abs(value):,.2f}"
38
+ return ("-" if value < 0 else "+") + amount
39
+
40
+
41
+ def _headline(balance, url, *, overall=False):
42
+ usd, tokens, since = balance["usd"], balance["tokens"], balance["since"]
43
+ day = date.fromisoformat(since) if since else None
44
+ correction = balance["last_correction"]
45
+ if correction and not 0 <= (_today() - date.fromisoformat(correction["date"])).days <= 14:
46
+ correction = None
47
+ if usd >= 1 or overall:
48
+ amount = "under $1" if 0 < usd < 1 else _money(usd)
49
+ short_since = day.strftime("%b %Y") if day and not overall else "install"
50
+ long_since = f"{day:%b} {day.day}, {day.year}" if day else "install"
51
+ long_verb = "saved" if overall else "counted"
52
+ display = {"kind": "since", "short": f"Saved {amount} since {short_since}",
53
+ "long": f"{amount} {long_verb} since {long_since}", "url": url}
54
+ else:
55
+ display = savings_headline._display(0, None, tokens, url)
56
+ if display and correction:
57
+ display["short"] += f" (corrected {_signed_money(correction['delta_usd'], whole=True)})"
58
+ display["long"] += f". {correction['reason']}"
59
+ return {"schema": 1, "usd": usd, "tokens": tokens, "since": since,
60
+ "rechecking": balance["held_days"] > 0, "held_days": balance["held_days"],
61
+ "last_correction": correction, "display": display}
62
+
63
+
64
+ def build(facade, conn=None, dashboard_url=None):
65
+ """Build the counted-only headline from stored daily balances."""
66
+ with _reader(facade, conn) as db:
67
+ return _headline(counted_closes.total(db), dashboard_url or savings_headline.DASHBOARD_SAVINGS_URL)
68
+
69
+
70
+ def build_overall(facade, conn=None, dashboard_url=None):
71
+ """Build the all-in since-install headline from the latest daily balance."""
72
+ with _reader(facade, conn) as db:
73
+ balance = counted_closes.total_overall(db)
74
+ if balance is None:
75
+ return None
76
+ return _headline(balance, dashboard_url or savings_headline.DASHBOARD_SAVINGS_URL, overall=True)
77
+
78
+
79
+ def cache_value(facade, session_id):
80
+ """Supply the status consumer's since-install headline, even after a timeout."""
81
+ with _reader(facade) as conn:
82
+ if conn is None:
83
+ return None
84
+ return build_overall(facade, conn) or build(facade, conn)
85
+
86
+
87
+ def correction_line(correction):
88
+ return f"{correction['date']} {_signed_money(correction['delta_usd'])} {correction['reason']}"
89
+
90
+
91
+ def main(facade, args):
92
+ parser = argparse.ArgumentParser(prog="measure.py counted-total")
93
+ parser.add_argument("--json", action="store_true", dest="as_json")
94
+ options = parser.parse_args(args)
95
+ with _reader(facade) as conn:
96
+ data = build(facade, conn)
97
+ overall = counted_closes.total_overall(conn) or {}
98
+ changes = counted_closes.corrections(conn, _today())
99
+ if options.as_json:
100
+ print(json.dumps(data | {"corrections": changes}, indent=2))
101
+ return 0
102
+ print((data["display"] or {}).get("long") or
103
+ f"${data['usd']:,.2f} counted since {data['since'] or 'install'}")
104
+ estimated = overall.get("estimated_usd")
105
+ last_30d = overall.get("last_30d_usd")
106
+ if estimated is not None:
107
+ print(f"Estimated on top (can move): ${estimated:,.2f}")
108
+ if last_30d is not None:
109
+ print(f"Last 30 days (moves as days roll off): ${last_30d:,.2f}")
110
+ for change in changes:
111
+ print(correction_line(change))
112
+ return 0