@alexgreensh/token-optimizer 5.13.69 → 5.13.71

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 (148) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/PRIVACY.md +4 -0
  4. package/hooks/hooks.json +11 -1
  5. package/hooks/module_runner.py +4 -1
  6. package/hooks/posttooluse_runner.py +44 -48
  7. package/hooks/sessionstart_runner.py +24 -5
  8. package/hooks/stop_runner.py +6 -6
  9. package/package.json +1 -1
  10. package/skills/token-optimizer/assets/dashboard.html +729 -767
  11. package/skills/token-optimizer/assets/savings_story.js +765 -0
  12. package/skills/token-optimizer/pricing/prices.json +1 -0
  13. package/skills/token-optimizer/references/cli-reference.md +1 -1
  14. package/skills/token-optimizer/references/implementation-playbook.md +3 -0
  15. package/skills/token-optimizer/scripts/_measure/__init__.py +3 -1
  16. package/skills/token-optimizer/scripts/_measure/archive_health.py +14 -0
  17. package/skills/token-optimizer/scripts/_measure/archive_void_codex.py +163 -0
  18. package/skills/token-optimizer/scripts/_measure/archive_void_evidence.py +165 -0
  19. package/skills/token-optimizer/scripts/_measure/audit.py +27 -135
  20. package/skills/token-optimizer/scripts/_measure/baseline_provenance.py +339 -0
  21. package/skills/token-optimizer/scripts/_measure/cache_policy.py +261 -581
  22. package/skills/token-optimizer/scripts/_measure/checkpoint_direction.py +97 -0
  23. package/skills/token-optimizer/scripts/_measure/checkpoint_retention.py +20 -0
  24. package/skills/token-optimizer/scripts/_measure/cli.py +12 -8
  25. package/skills/token-optimizer/scripts/_measure/codex_quality.py +246 -0
  26. package/skills/token-optimizer/scripts/_measure/compaction_survival.py +158 -0
  27. package/skills/token-optimizer/scripts/_measure/compression_fixture_void.py +147 -0
  28. package/skills/token-optimizer/scripts/_measure/compression_scan_checkpoint.py +72 -0
  29. package/skills/token-optimizer/scripts/_measure/context_reset_marker.py +66 -0
  30. package/skills/token-optimizer/scripts/_measure/continuity.py +64 -118
  31. package/skills/token-optimizer/scripts/_measure/cost_per_message_trend.py +40 -0
  32. package/skills/token-optimizer/scripts/_measure/counted_cap.py +30 -0
  33. package/skills/token-optimizer/scripts/_measure/counted_orphans.py +190 -0
  34. package/skills/token-optimizer/scripts/_measure/counted_position.py +20 -0
  35. package/skills/token-optimizer/scripts/_measure/counted_pricing_v5.py +267 -0
  36. package/skills/token-optimizer/scripts/_measure/counted_subagents.py +371 -0
  37. package/skills/token-optimizer/scripts/_measure/coverage_report.py +295 -0
  38. package/skills/token-optimizer/scripts/_measure/daemon.py +53 -74
  39. package/skills/token-optimizer/scripts/_measure/dashboard.py +90 -151
  40. package/skills/token-optimizer/scripts/_measure/dashboard_heal_claim.py +36 -0
  41. package/skills/token-optimizer/scripts/_measure/evidence_parallel.py +95 -0
  42. package/skills/token-optimizer/scripts/_measure/feature_health.py +256 -0
  43. package/skills/token-optimizer/scripts/_measure/file_refetch.py +250 -0
  44. package/skills/token-optimizer/scripts/_measure/first_call_context.py +216 -0
  45. package/skills/token-optimizer/scripts/_measure/first_read_outcomes.py +261 -0
  46. package/skills/token-optimizer/scripts/_measure/first_read_revive.py +137 -0
  47. package/skills/token-optimizer/scripts/_measure/fixture_context.py +65 -0
  48. package/skills/token-optimizer/scripts/_measure/headline.py +100 -0
  49. package/skills/token-optimizer/scripts/_measure/holdout_fallback.py +96 -0
  50. package/skills/token-optimizer/scripts/_measure/holdout_report.py +129 -0
  51. package/skills/token-optimizer/scripts/_measure/keepwarm_economics.py +201 -0
  52. package/skills/token-optimizer/scripts/_measure/keepwarm_linux.py +121 -0
  53. package/skills/token-optimizer/scripts/_measure/keepwarm_safety.py +260 -0
  54. package/skills/token-optimizer/scripts/_measure/lean_resume_receivers.py +260 -0
  55. package/skills/token-optimizer/scripts/_measure/lean_resume_threshold.py +76 -0
  56. package/skills/token-optimizer/scripts/_measure/lease_candidate_cleanup.py +82 -0
  57. package/skills/token-optimizer/scripts/_measure/lifecycle.py +54 -162
  58. package/skills/token-optimizer/scripts/_measure/mcp_archive_tripwire.py +120 -0
  59. package/skills/token-optimizer/scripts/_measure/mod_action_booking.py +178 -0
  60. package/skills/token-optimizer/scripts/_measure/mod_compaction_booking.py +276 -0
  61. package/skills/token-optimizer/scripts/_measure/mod_fresh_booking.py +105 -0
  62. package/skills/token-optimizer/scripts/_measure/output_reread.py +629 -0
  63. package/skills/token-optimizer/scripts/_measure/own_price_card.py +268 -0
  64. package/skills/token-optimizer/scripts/_measure/periphery_exposure.py +85 -0
  65. package/skills/token-optimizer/scripts/_measure/pricing.py +152 -87
  66. package/skills/token-optimizer/scripts/_measure/quality_archive.py +159 -215
  67. package/skills/token-optimizer/scripts/_measure/quality_checkpoint.py +174 -0
  68. package/skills/token-optimizer/scripts/_measure/quality_continuity.py +43 -0
  69. package/skills/token-optimizer/scripts/_measure/rework_metrics.py +194 -0
  70. package/skills/token-optimizer/scripts/_measure/routing_period.py +48 -0
  71. package/skills/token-optimizer/scripts/_measure/savings.py +439 -864
  72. package/skills/token-optimizer/scripts/_measure/savings_headline.py +130 -0
  73. package/skills/token-optimizer/scripts/_measure/savings_story.py +187 -0
  74. package/skills/token-optimizer/scripts/_measure/session_best.py +24 -0
  75. package/skills/token-optimizer/scripts/_measure/session_effect.py +557 -0
  76. package/skills/token-optimizer/scripts/_measure/session_flush_lock.py +75 -0
  77. package/skills/token-optimizer/scripts/_measure/session_store_spool.py +220 -0
  78. package/skills/token-optimizer/scripts/_measure/sessions.py +103 -196
  79. package/skills/token-optimizer/scripts/_measure/setup_attachment_counter.py +196 -0
  80. package/skills/token-optimizer/scripts/_measure/setup_budget_monitor.py +180 -0
  81. package/skills/token-optimizer/scripts/_measure/setup_connector_ledger.py +126 -0
  82. package/skills/token-optimizer/scripts/_measure/setup_step.py +220 -0
  83. package/skills/token-optimizer/scripts/_measure/status_bar_lock.py +117 -0
  84. package/skills/token-optimizer/scripts/_measure/structural_archives.py +79 -0
  85. package/skills/token-optimizer/scripts/_measure/structural_dedupe.py +91 -0
  86. package/skills/token-optimizer/scripts/_measure/structural_ledger.py +418 -0
  87. package/skills/token-optimizer/scripts/_measure/structural_listing.py +163 -0
  88. package/skills/token-optimizer/scripts/_measure/structural_report.py +339 -0
  89. package/skills/token-optimizer/scripts/_measure/structural_seed.py +164 -0
  90. package/skills/token-optimizer/scripts/_measure/structural_value.py +248 -0
  91. package/skills/token-optimizer/scripts/_measure/structure_funnel.py +97 -0
  92. package/skills/token-optimizer/scripts/_measure/timestamp_cache.py +11 -0
  93. package/skills/token-optimizer/scripts/_measure/token_type_split.py +29 -0
  94. package/skills/token-optimizer/scripts/_measure/transcript_backfill.py +419 -0
  95. package/skills/token-optimizer/scripts/_measure/transcript_product.py +228 -0
  96. package/skills/token-optimizer/scripts/_measure/transcript_stream.py +279 -0
  97. package/skills/token-optimizer/scripts/_measure/trends.py +44 -185
  98. package/skills/token-optimizer/scripts/_measure/ttl_period.py +6 -0
  99. package/skills/token-optimizer/scripts/_measure/upgrade_drain_control.py +287 -0
  100. package/skills/token-optimizer/scripts/activity_tracker.py +4 -33
  101. package/skills/token-optimizer/scripts/antigravity_install.py +2 -0
  102. package/skills/token-optimizer/scripts/archive_result.py +15 -19
  103. package/skills/token-optimizer/scripts/archive_verify.py +165 -0
  104. package/skills/token-optimizer/scripts/bash_compress.py +14 -43
  105. package/skills/token-optimizer/scripts/bash_compress_hook.py +132 -2
  106. package/skills/token-optimizer/scripts/checkpoint_state.py +2 -2
  107. package/skills/token-optimizer/scripts/cloud_kit.py +3 -6
  108. package/skills/token-optimizer/scripts/codemap.py +274 -0
  109. package/skills/token-optimizer/scripts/codemap_hint.py +153 -0
  110. package/skills/token-optimizer/scripts/codemap_index.py +656 -0
  111. package/skills/token-optimizer/scripts/codemap_ledger.py +309 -0
  112. package/skills/token-optimizer/scripts/codemap_reread.py +161 -0
  113. package/skills/token-optimizer/scripts/codex_doctor.py +9 -1
  114. package/skills/token-optimizer/scripts/codex_log_index.py +34 -15
  115. package/skills/token-optimizer/scripts/codex_session.py +16 -216
  116. package/skills/token-optimizer/scripts/compression_backfill.py +4 -35
  117. package/skills/token-optimizer/scripts/context_intel.py +5 -3
  118. package/skills/token-optimizer/scripts/copilot_install.py +2 -0
  119. package/skills/token-optimizer/scripts/coverage_funnel.py +261 -0
  120. package/skills/token-optimizer/scripts/cursor_install.py +12 -0
  121. package/skills/token-optimizer/scripts/cursor_quality.py +16 -64
  122. package/skills/token-optimizer/scripts/dashboard_assets.py +21 -0
  123. package/skills/token-optimizer/scripts/deterministic_candidates.py +2 -10
  124. package/skills/token-optimizer/scripts/devin_source.py +8 -3
  125. package/skills/token-optimizer/scripts/devin_verify.py +7 -1
  126. package/skills/token-optimizer/scripts/grok_install.py +2 -0
  127. package/skills/token-optimizer/scripts/heal_report.py +7 -6
  128. package/skills/token-optimizer/scripts/hermes_doctor.py +9 -1
  129. package/skills/token-optimizer/scripts/hermes_install.py +7 -1
  130. package/skills/token-optimizer/scripts/hermes_session.py +14 -136
  131. package/skills/token-optimizer/scripts/hint_paths.py +21 -0
  132. package/skills/token-optimizer/scripts/holdout.py +136 -0
  133. package/skills/token-optimizer/scripts/hook_runtime.py +1 -0
  134. package/skills/token-optimizer/scripts/hook_skip_log.py +89 -0
  135. package/skills/token-optimizer/scripts/large_transcripts.py +31 -0
  136. package/skills/token-optimizer/scripts/lean_resume_carry.py +518 -0
  137. package/skills/token-optimizer/scripts/measure.py +34 -76
  138. package/skills/token-optimizer/scripts/post_run_classify.py +349 -0
  139. package/skills/token-optimizer/scripts/preserved_reinject.py +54 -0
  140. package/skills/token-optimizer/scripts/read_cache.py +99 -100
  141. package/skills/token-optimizer/scripts/reset_epoch.py +3 -3
  142. package/skills/token-optimizer/scripts/session_store.py +49 -99
  143. package/skills/token-optimizer/scripts/session_store_guard.py +75 -0
  144. package/skills/token-optimizer/scripts/settings_backup.py +379 -0
  145. package/skills/token-optimizer/scripts/shipped_hook_templates.py +1 -0
  146. package/skills/token-optimizer/scripts/statusline.js +144 -30
  147. package/skills/token-optimizer/scripts/structural.py +25 -0
  148. package/skills/token-optimizer/scripts/structure_map.py +4 -26
@@ -0,0 +1,268 @@
1
+ """Price the work-normalized transformation at the user's own current prices.
2
+
3
+ The transformation compares cost per unit of work in a baseline window with
4
+ the same figure now, both priced on ONE card so a vendor price change or a
5
+ model switch cannot count as a saving. That card used to be a fixed Opus 4.x
6
+ card for every user, which put a Sonnet, Haiku or other-provider user's result
7
+ in dollars two to five times their own. Here the card is the user's own: for
8
+ each token class, what they actually paid per million tokens this period,
9
+ averaged over the models they ran.
10
+
11
+ A baseline pinned before per-class token sums were kept cannot be re-priced
12
+ until those sums are rebuilt from its transcripts; until then the fixed card
13
+ stays in use and is named as such on the page.
14
+ """
15
+
16
+ CLASSES = ("input", "output", "cache_read", "cache_write")
17
+ _ZERO = {"sessions": 0, "usd": 0.0, "tokens": 0.0, "flat_usd": 0.0, "api_calls": 0, "messages": 0}
18
+ # A rebuilt baseline may differ this much from the pinned one and still lend it
19
+ # its class split; beyond that the transcripts are no longer the same window.
20
+ _REBUILD_TOLERANCE = 0.02
21
+
22
+
23
+ def price_rows(facade, rows, tier, api_calls_unknown=None):
24
+ """Sum parent rows: engine-priced USD, fixed-card USD, class tokens, work units."""
25
+ if not rows:
26
+ return None
27
+ default_model = facade._default_model_for_runtime()
28
+ fr = facade._WEIGHT_POOL_FLAT_RATES
29
+ usd = flat_usd = tokens = 0.0
30
+ api_calls = messages = 0
31
+ classes = dict.fromkeys(CLASSES, 0.0)
32
+ for r in rows:
33
+ fi, cw, cr, out = facade._session_token_vector(r[:5])
34
+ tokens += fi + cw + cr + out
35
+ for key, value in zip(CLASSES, (fi, out, cr, cw)):
36
+ classes[key] += value
37
+ flat_usd += (fi * fr["input"] + out * fr["output"]
38
+ + cr * fr["cache_read"] + cw * fr["cache_write"]) / 1_000_000
39
+ api_calls += int(r[7] or 0)
40
+ messages += int(r[8] or 0)
41
+ usage = facade._safe_json_dict(r[5]) or facade._safe_json_dict(r[6]) or {}
42
+ grand = sum(int(v or 0) for v in usage.values() if v)
43
+ if len(r) > 9 and facade._safe_json_dict(r[9]):
44
+ cost = facade._cost_from_model_breakdown(facade._safe_json_dict(r[9]), tier=tier)
45
+ elif grand > 0:
46
+ # Share denominator is the session TOTAL, so an unpriced (non-Claude, local)
47
+ # model is proxy-priced at the runtime default rather than letting a small
48
+ # priced sliver stand for the whole session. Same rule as _cost_per_session.
49
+ cost = 0.0
50
+ for model, toks in usage.items():
51
+ share = int(toks or 0) / grand
52
+ if share <= 0:
53
+ continue
54
+ cost += share * facade._get_model_cost(
55
+ model if facade._is_priced_model(model, tier) else default_model,
56
+ int(fi), int(out), int(cr), int(cw), tier=tier)
57
+ else:
58
+ cost = facade._get_model_cost(default_model, int(fi), int(out), int(cr), int(cw), tier=tier)
59
+ usd += cost
60
+ return {"sessions": len(rows), "usd": usd, "tokens": tokens,
61
+ "flat_usd": flat_usd, "api_calls": api_calls, "messages": messages,
62
+ "classes": classes,
63
+ # Sessions whose dated per-day call evidence was never recorded.
64
+ # api_calls is then a lower bound, not a measured total.
65
+ "api_calls_unknown": int(api_calls_unknown or 0)}
66
+
67
+
68
+ def classes_of(metrics):
69
+ """The arm's class token sums, or None when it was priced before they were kept."""
70
+ try:
71
+ classes = metrics.get("classes")
72
+ if not isinstance(classes, dict):
73
+ return None
74
+ out = {k: float(classes[k]) for k in CLASSES}
75
+ return out if all(v == v and v >= 0 for v in out.values()) and sum(out.values()) > 0 else None
76
+ except (AttributeError, KeyError, TypeError, ValueError):
77
+ return None
78
+
79
+
80
+ def lend_classes(frozen, fresh):
81
+ """Give a frozen month its class split from the same month re-read from the
82
+ ledger, when the two still agree. True when `frozen` was changed."""
83
+ try:
84
+ if classes_of(frozen) or not fresh:
85
+ return False
86
+ split = classes_of(fresh)
87
+ old, new = float(frozen["flat_usd"]), float(fresh["flat_usd"])
88
+ if not split or not (old > 0 and new > 0) or abs(new - old) > _REBUILD_TOLERANCE * old:
89
+ return False
90
+ frozen["classes"] = {k: split[k] * old / new for k in CLASSES}
91
+ return True
92
+ except (KeyError, TypeError, ValueError):
93
+ return False
94
+
95
+
96
+ def card(facade, days):
97
+ """{class: $/MTok} the user paid this period, or None with no priced usage.
98
+
99
+ Each class rate is the token-weighted average of the exact cards of the
100
+ models that ran. Cache writes blend the 5-minute and 1-hour rates as used.
101
+ A class with no tokens takes the average card of the models that ran.
102
+ """
103
+ try:
104
+ usage = facade._routing_usage_by_model(days=days) or {}
105
+ spent = dict.fromkeys(CLASSES, 0.0)
106
+ used = dict.fromkeys(CLASSES, 0.0)
107
+ weights = []
108
+ for model, parts in usage.items():
109
+ rates = facade._routing_class_rates(model)
110
+ if not rates:
111
+ continue # unpriced or free: its price is not known, so it sets none
112
+ split = {"input": [("fresh_input", "fresh_input")], "output": [("output", "output")],
113
+ "cache_read": [("cache_read", "cache_read")],
114
+ "cache_write": [("cache_create_5m", "cache_create_5m"), ("cache_create_1h", "cache_create_1h")]}
115
+ total = 0.0
116
+ for name, pairs in split.items():
117
+ for bucket, rate in pairs:
118
+ tokens = float(parts.get(bucket) or 0)
119
+ if tokens > 0:
120
+ spent[name] += tokens * rates[rate]
121
+ used[name] += tokens
122
+ total += tokens
123
+ if total > 0:
124
+ weights.append((total, {"input": rates["fresh_input"], "output": rates["output"],
125
+ "cache_read": rates["cache_read"], "cache_write": rates["cache_create_5m"]}))
126
+ whole = sum(w for w, _ in weights)
127
+ if whole <= 0:
128
+ return None
129
+ out = {}
130
+ for name in CLASSES:
131
+ rate = spent[name] / used[name] if used[name] > 0 else sum(w * r[name] for w, r in weights) / whole
132
+ if not (rate == rate and rate > 0):
133
+ return None
134
+ out[name] = round(rate, 6)
135
+ return out
136
+ except Exception:
137
+ return None
138
+
139
+
140
+ def apply(facade, before, now, days):
141
+ """Both arms on the user's own card: {"basis", "rates", "before_usd", "now_usd"}.
142
+
143
+ None when either arm lacks class sums or no priced usage exists; the caller
144
+ then keeps the fixed card.
145
+ """
146
+ b, n = classes_of(before or {}), classes_of(now or {})
147
+ if not b or not n:
148
+ return None
149
+ rates = card(facade, days)
150
+ if not rates:
151
+ return None
152
+
153
+ def value(classes):
154
+ return sum(classes[k] * rates[k] for k in CLASSES) / 1_000_000
155
+
156
+ before_usd, now_usd = value(b), value(n)
157
+ if not (before_usd > 0 and now_usd > 0):
158
+ return None
159
+ return {"basis": "own_prices", "rates": rates, "before_usd": before_usd, "now_usd": now_usd}
160
+
161
+
162
+ def _blank():
163
+ return dict(_ZERO, classes=dict.fromkeys(CLASSES, 0.0))
164
+
165
+
166
+ def _walk(facade, progress, start, end, budget_seconds, tier):
167
+ """Price a few more transcripts into `progress`. True when every file is done."""
168
+ files = sorted(str(f) for f, _mtime, _proj in facade._find_all_jsonl_files(None))
169
+ seen = set(progress.get("seen") or [])
170
+ metrics = progress["metrics"]
171
+ metrics.setdefault("classes", dict.fromkeys(CLASSES, 0.0))
172
+ deadline = facade.time.monotonic() + budget_seconds
173
+ cursor = int(progress.get("cursor") or 0)
174
+ while cursor < len(files) and facade.time.monotonic() < deadline:
175
+ fp = files[cursor]
176
+ cursor += 1
177
+ uuid = facade._canonical_session_uuid(fp) or fp
178
+ if uuid in seen:
179
+ continue # another copy of a session already priced
180
+ seen.add(uuid)
181
+ row = facade._pretool_session_row(fp, start, end, progress.setdefault("requests", {}))
182
+ priced = facade._price_parent_rows([row], tier) if row else None
183
+ if priced:
184
+ for key in _ZERO:
185
+ metrics[key] += priced[key]
186
+ for key in CLASSES:
187
+ metrics["classes"][key] += priced["classes"][key]
188
+ progress["cursor"], progress["seen"] = cursor, sorted(seen)
189
+ return cursor >= len(files)
190
+
191
+
192
+ def _usable(facade, metrics):
193
+ return (metrics["sessions"] >= facade._SESSION_WEIGHT_MIN_ANCHOR_SESSIONS
194
+ and metrics["api_calls"] > 0 and metrics["flat_usd"] > 0)
195
+
196
+
197
+ def _fill_classes(facade, state, budget_seconds, tier):
198
+ """Rebuild the class split of an already pinned baseline, without unpinning it.
199
+
200
+ The pinned figures stay as they are. The rebuilt split is adopted only when
201
+ the transcripts still reproduce the pinned total; otherwise the baseline
202
+ keeps the fixed card for good.
203
+ """
204
+ window = state.get("window")
205
+ if not (isinstance(window, list) and len(window) == 2):
206
+ state["classes_status"] = "unavailable"
207
+ return
208
+ fill = state.get("class_fill")
209
+ if not isinstance(fill, dict) or not isinstance(fill.get("metrics"), dict):
210
+ fill = {"cursor": 0, "seen": [], "metrics": _blank()}
211
+ if not _walk(facade, fill, window[0], window[1], budget_seconds, tier):
212
+ state["class_fill"] = fill
213
+ return
214
+ state.pop("class_fill", None)
215
+ old, new = float(state["metrics"]["flat_usd"]), float(fill["metrics"]["flat_usd"])
216
+ if old > 0 and new > 0 and abs(new - old) <= _REBUILD_TOLERANCE * old:
217
+ scale = old / new
218
+ state["metrics"]["classes"] = {k: fill["metrics"]["classes"][k] * scale for k in CLASSES}
219
+ state["classes_filled_at"] = facade.datetime.now().isoformat()
220
+ else:
221
+ state["classes_status"] = "unavailable"
222
+
223
+
224
+ def anchor_step(facade, budget_seconds=None, tier=None):
225
+ """Build the pinned pre-install anchor a few transcripts at a time.
226
+
227
+ The ledger keeps a rolling window, so the months before install age out of
228
+ it; their transcripts usually remain on disk. Each call prices up to
229
+ `budget_seconds` of them with the same ruler as the live pool and banks
230
+ running sums, then pins the result once the window is done. A window with
231
+ too few surviving transcripts is marked unavailable, so the check stops.
232
+ An anchor pinned before class sums were kept gets them rebuilt the same way.
233
+ Returns the state string. Never raises.
234
+ """
235
+ path = facade.SNAPSHOT_DIR / facade._PRETOOL_ANCHOR_FILE
236
+ try:
237
+ state = facade.json.loads(path.read_text(encoding="utf-8")) if path.exists() else {}
238
+ if not isinstance(state, dict) or state.get("activity_basis") != 1:
239
+ # State written before activity dating (or surviving an archive
240
+ # collision) was computed on session-date windows; rebuild it.
241
+ state = {}
242
+ if state.get("status") == "unavailable":
243
+ return "unavailable"
244
+ if tier is None:
245
+ tier = facade._load_pricing_tier()
246
+ if state.get("status") == "pinned":
247
+ if classes_of(state.get("metrics") or {}) or state.get("classes_status") == "unavailable":
248
+ return "pinned"
249
+ _fill_classes(facade, state, budget_seconds, tier)
250
+ facade._write_baseline_state(path, state)
251
+ return "pinned"
252
+ window = facade._pretool_window()
253
+ if not window:
254
+ return "no_baseline"
255
+ start, end = window
256
+ if state.get("window") != [start, end] or state.get("rates") != facade._WEIGHT_POOL_FLAT_RATES:
257
+ state = {"status": "building", "window": [start, end], "rates": facade._WEIGHT_POOL_FLAT_RATES,
258
+ "activity_basis": 1, "cursor": 0, "seen": [], "metrics": _blank()}
259
+ if _walk(facade, state, start, end, budget_seconds, tier):
260
+ m = state["metrics"]
261
+ state = {"status": "pinned" if _usable(facade, m) else "unavailable", "window": [start, end],
262
+ "rates": facade._WEIGHT_POOL_FLAT_RATES, "activity_basis": 1, "metrics": m,
263
+ "label": f"your earliest tracked month ({start} to {end})",
264
+ "pinned_at": facade.datetime.now().isoformat()}
265
+ facade._write_baseline_state(path, state)
266
+ return state["status"]
267
+ except Exception:
268
+ return "error"
@@ -0,0 +1,85 @@
1
+ """Build bounded periphery maps and return the paths actually included."""
2
+ from pathlib import Path
3
+ import hashlib
4
+ import json
5
+ import os
6
+ import time
7
+
8
+
9
+ def build(paths, limit, budget, summarize, shown_paths=None):
10
+ parts = []
11
+ total = 0
12
+ for raw in paths:
13
+ if len(parts) >= limit or total >= budget:
14
+ break
15
+ path = Path(raw)
16
+ try:
17
+ result = summarize(path)
18
+ except Exception:
19
+ continue
20
+ if not result.replacement_text:
21
+ continue
22
+ chunk = f"# periphery: {path.name} ({result.replacement_type})\n{result.replacement_text}"
23
+ if total + len(chunk) > budget:
24
+ break
25
+ parts.append(chunk)
26
+ total += len(chunk)
27
+ if shown_paths is not None:
28
+ shown_paths.append(str(raw))
29
+ return "\n\n".join(parts)
30
+
31
+
32
+ def _hash(value):
33
+ return hashlib.sha256(str(value).encode("utf-8", "replace")).hexdigest()
34
+
35
+
36
+ def exposure_rows(session_id, tool_id, shown, language, band):
37
+ """Stable unique IDs for shown paths; no source paths or content persisted."""
38
+ return _rows(session_id, tool_id, shown, language, band, "map")
39
+
40
+
41
+ def control_rows(session_id, tool_id, path, language, band):
42
+ return _rows(session_id, tool_id, [path], language, band, "no_map")
43
+
44
+
45
+ def _rows(session_id, tool_id, shown, language, band, arm):
46
+ if not session_id or not tool_id:
47
+ return []
48
+ rows, seen = [], set()
49
+ for path in shown:
50
+ identity = json.dumps([session_id, tool_id, str(path), arm], separators=(",", ":"))
51
+ exposure_id = _hash(identity)
52
+ if exposure_id in seen:
53
+ continue
54
+ seen.add(exposure_id)
55
+ rows.append({"exposure_id": exposure_id, "session_id": _hash(session_id),
56
+ "tool_use_id": _hash(tool_id),
57
+ "path_id": _hash(json.dumps([session_id, str(path)], separators=(",", ":"))),
58
+ "language": language, "band": band, "timestamp": time.time(),
59
+ "arm": arm, "read_confirmed": False})
60
+ return rows
61
+
62
+
63
+ def record_exposures(snapshot_dir, session_id, tool_id, shown, language, band):
64
+ _record(snapshot_dir, exposure_rows(session_id, tool_id, shown, language, band))
65
+
66
+
67
+ def record_control(snapshot_dir, session_id, tool_id, path, language, band):
68
+ _record(snapshot_dir, control_rows(session_id, tool_id, path, language, band))
69
+
70
+
71
+ def record_target_outline(snapshot_dir, session_id, tool_id, path, language, band):
72
+ """Keep target substitutions distinct from periphery-map treatments."""
73
+ rows = _rows(session_id, tool_id, [path], language, band, "legacy_skeleton")
74
+ _record(snapshot_dir, rows)
75
+ return rows
76
+
77
+
78
+ def _record(snapshot_dir, rows):
79
+ if not rows:
80
+ return
81
+ directory = snapshot_dir / "diagnostics"
82
+ directory.mkdir(parents=True, exist_ok=True, mode=0o700)
83
+ fd = os.open(str(directory / "periphery_exposures.jsonl"), os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600)
84
+ with os.fdopen(fd, "a", encoding="utf-8") as fh:
85
+ fh.write("".join(json.dumps(row, separators=(",", ":")) + "\n" for row in rows))