@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.
- package/.claude-plugin/marketplace.json +2 -2
- package/.claude-plugin/plugin.json +1 -1
- package/hooks/module_runner.py +1 -1
- package/hooks/posttooluse_runner.py +7 -9
- package/hooks/run.py +5 -1
- package/hooks/stop_runner.py +15 -56
- package/hooks/userpromptsubmit_runner.py +29 -4
- package/package.json +1 -1
- package/skills/token-optimizer/assets/dashboard.html +30 -14
- package/skills/token-optimizer/assets/savings_story.js +103 -27
- package/skills/token-optimizer/references/agent-prompts.md +2 -0
- package/skills/token-optimizer/references/implementation-playbook.md +1 -0
- package/skills/token-optimizer/scripts/_measure/__init__.py +1 -1
- package/skills/token-optimizer/scripts/_measure/apply_safe.py +512 -0
- package/skills/token-optimizer/scripts/_measure/audit.py +9 -20
- package/skills/token-optimizer/scripts/_measure/autocompact_advice.py +455 -0
- package/skills/token-optimizer/scripts/_measure/cache_policy.py +82 -127
- package/skills/token-optimizer/scripts/_measure/cli.py +10 -24
- package/skills/token-optimizer/scripts/_measure/cold_guard.py +777 -0
- package/skills/token-optimizer/scripts/_measure/continuity.py +45 -4
- package/skills/token-optimizer/scripts/_measure/counted_closes.py +398 -0
- package/skills/token-optimizer/scripts/_measure/counted_headline.py +112 -0
- package/skills/token-optimizer/scripts/_measure/dashboard.py +14 -6
- package/skills/token-optimizer/scripts/_measure/feature_health.py +6 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_auto.py +452 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_economics.py +8 -4
- package/skills/token-optimizer/scripts/_measure/keepwarm_safety.py +548 -24
- package/skills/token-optimizer/scripts/_measure/limit_units.py +463 -0
- package/skills/token-optimizer/scripts/_measure/local_adapt.py +192 -0
- package/skills/token-optimizer/scripts/_measure/mod_action_booking.py +71 -14
- package/skills/token-optimizer/scripts/_measure/next_actions.py +420 -0
- package/skills/token-optimizer/scripts/_measure/poc_commands.py +44 -0
- package/skills/token-optimizer/scripts/_measure/prefix_cost.py +215 -0
- package/skills/token-optimizer/scripts/_measure/pt_resume_cues.py +46 -0
- package/skills/token-optimizer/scripts/_measure/quality_archive.py +7 -10
- package/skills/token-optimizer/scripts/_measure/savings.py +80 -82
- package/skills/token-optimizer/scripts/_measure/savings_headline.py +17 -21
- package/skills/token-optimizer/scripts/_measure/savings_story.py +8 -1
- package/skills/token-optimizer/scripts/_measure/session_store_spool.py +119 -78
- package/skills/token-optimizer/scripts/_measure/status_bar_refresh.py +38 -3
- package/skills/token-optimizer/scripts/_measure/structural_ledger.py +1 -1
- package/skills/token-optimizer/scripts/_measure/subscription_audits.py +725 -0
- package/skills/token-optimizer/scripts/_measure/transcript_backfill.py +1 -1
- package/skills/token-optimizer/scripts/_measure/transcript_stream.py +8 -2
- package/skills/token-optimizer/scripts/antigravity_install.py +3 -0
- package/skills/token-optimizer/scripts/archive_result.py +16 -28
- package/skills/token-optimizer/scripts/archive_verify.py +1 -1
- package/skills/token-optimizer/scripts/bash_compress.py +156 -176
- package/skills/token-optimizer/scripts/bash_compress_hook.py +218 -174
- package/skills/token-optimizer/scripts/bash_search_results.py +189 -9
- package/skills/token-optimizer/scripts/bash_whitelist.py +6 -1
- package/skills/token-optimizer/scripts/benchmark.py +11 -13
- package/skills/token-optimizer/scripts/big_noncode_read.py +998 -0
- package/skills/token-optimizer/scripts/build_output_compress.py +103 -8
- package/skills/token-optimizer/scripts/builtin_tool_compress.py +716 -0
- package/skills/token-optimizer/scripts/cloud_kit.py +1 -1
- package/skills/token-optimizer/scripts/codex_doctor.py +1 -1
- package/skills/token-optimizer/scripts/command_compress_extra.py +955 -0
- package/skills/token-optimizer/scripts/compact_markers.py +129 -0
- package/skills/token-optimizer/scripts/copilot_install.py +3 -0
- package/skills/token-optimizer/scripts/cursor_install.py +7 -0
- package/skills/token-optimizer/scripts/devin_source.py +5 -5
- package/skills/token-optimizer/scripts/emit_safety_gate.py +518 -0
- package/skills/token-optimizer/scripts/fixtures/b2_more_commands.json +142 -0
- package/skills/token-optimizer/scripts/fixtures/b5_more_savings.json +26 -0
- package/skills/token-optimizer/scripts/fixtures/builtin_tools.json +103 -0
- package/skills/token-optimizer/scripts/fixtures/c7_review_ratchet.json +52 -0
- package/skills/token-optimizer/scripts/fixtures/large_output_policy.json +55 -0
- package/skills/token-optimizer/scripts/go_cargo_test_compress.py +493 -0
- package/skills/token-optimizer/scripts/grok_install.py +3 -0
- package/skills/token-optimizer/scripts/hermes_doctor.py +4 -1
- package/skills/token-optimizer/scripts/hermes_install.py +10 -1
- package/skills/token-optimizer/scripts/hook_fastpath.py +94 -0
- package/skills/token-optimizer/scripts/hook_runtime.py +6 -2
- package/skills/token-optimizer/scripts/large_output_policy.py +431 -0
- package/skills/token-optimizer/scripts/measure.py +10 -12
- package/skills/token-optimizer/scripts/pipe_file_compress.py +900 -0
- package/skills/token-optimizer/scripts/pipeline_analyzer.py +15 -1
- package/skills/token-optimizer/scripts/post_run_classify.py +2 -2
- package/skills/token-optimizer/scripts/preserved_reinject.py +20 -3
- package/skills/token-optimizer/scripts/process_identity.py +66 -0
- package/skills/token-optimizer/scripts/read_cache.py +51 -60
- package/skills/token-optimizer/scripts/statusline.js +21 -3
- package/skills/token-optimizer/scripts/visibility_rule.py +536 -0
|
@@ -70,6 +70,28 @@ def _enqueue(store, data):
|
|
|
70
70
|
raise
|
|
71
71
|
|
|
72
72
|
|
|
73
|
+
def _sweep_stranded_receipts(conn, directory, already_unlinked=()):
|
|
74
|
+
"""Delete receipts for already-unlinked events and any stranded receipts
|
|
75
|
+
whose matching ``.pending`` file no longer exists."""
|
|
76
|
+
to_delete = list(already_unlinked)
|
|
77
|
+
seen = set(to_delete)
|
|
78
|
+
try:
|
|
79
|
+
rows = conn.execute("SELECT id FROM spool_receipts").fetchall()
|
|
80
|
+
except sqlite3.OperationalError:
|
|
81
|
+
rows = ()
|
|
82
|
+
for (rid,) in rows:
|
|
83
|
+
if rid not in seen and not (directory / (rid + ".pending")).exists():
|
|
84
|
+
to_delete.append(rid)
|
|
85
|
+
seen.add(rid)
|
|
86
|
+
if not to_delete:
|
|
87
|
+
return
|
|
88
|
+
try:
|
|
89
|
+
conn.executemany("DELETE FROM spool_receipts WHERE id = ?", [(eid,) for eid in to_delete])
|
|
90
|
+
conn.commit()
|
|
91
|
+
except sqlite3.OperationalError:
|
|
92
|
+
conn.rollback()
|
|
93
|
+
|
|
94
|
+
|
|
73
95
|
def drain(store, conn, limit=64, deadline=None):
|
|
74
96
|
if conn.in_transaction:
|
|
75
97
|
return
|
|
@@ -80,89 +102,108 @@ def drain(store, conn, limit=64, deadline=None):
|
|
|
80
102
|
paths = []
|
|
81
103
|
with os.scandir(directory) as entries:
|
|
82
104
|
for entry in entries:
|
|
83
|
-
if len(paths) >= limit or time.monotonic() >= deadline:
|
|
105
|
+
if len(paths) >= limit or (paths and time.monotonic() >= deadline):
|
|
84
106
|
break
|
|
85
107
|
if entry.name.endswith(".pending") and entry.is_file(follow_symlinks=False):
|
|
86
108
|
paths.append(directory / entry.name)
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
conn.execute(
|
|
104
|
-
"INSERT INTO context_intel_events (tool_name, tool_use_id, summary, output_chars, timestamp) "
|
|
105
|
-
"SELECT ?, ?, ?, ?, ? WHERE ? = '' OR NOT EXISTS "
|
|
106
|
-
"(SELECT 1 FROM context_intel_events WHERE tool_use_id = ?)",
|
|
107
|
-
(data["tool_name"], data["tool_use_id"], data["summary"],
|
|
108
|
-
data["output_chars"], data["timestamp"], data["tool_use_id"], data["tool_use_id"]),
|
|
109
|
-
)
|
|
110
|
-
elif receipt.rowcount and data.get("kind") == "tool_output":
|
|
111
|
-
conn.execute(
|
|
112
|
-
"INSERT OR IGNORE INTO tool_outputs (tool_use_id, tool_name, tool_type, command_or_path, "
|
|
113
|
-
"output_hash, output_chars, output_tokens_est, compressed_preview, timestamp, source_file_path, "
|
|
114
|
-
"language, archived_from, output_text, truncated, index_truncated) "
|
|
115
|
-
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", data["values"])
|
|
116
|
-
elif receipt.rowcount and data.get("kind") == "activity":
|
|
117
|
-
from activity_tracker import detect_mode, _WINDOW_SIZE, _PRUNE_THRESHOLD, _PRUNE_KEEP
|
|
118
|
-
conn.execute("INSERT INTO activity_log (tool_name, tool_bucket, has_error, timestamp) VALUES (?, ?, ?, ?)",
|
|
119
|
-
(data["tool_name"], data["bucket"], data["has_error"], data["timestamp"]))
|
|
120
|
-
rows = conn.execute("SELECT tool_bucket, has_error FROM activity_log ORDER BY timestamp DESC, id DESC LIMIT ?", (_WINDOW_SIZE,)).fetchall()
|
|
121
|
-
if conn.execute("SELECT COUNT(*) FROM activity_log").fetchone()[0] > _PRUNE_THRESHOLD:
|
|
122
|
-
conn.execute("DELETE FROM activity_log WHERE id NOT IN (SELECT id FROM activity_log ORDER BY timestamp DESC, id DESC LIMIT ?)", (_PRUNE_KEEP,))
|
|
123
|
-
mode = detect_mode([row[0] for row in rows], any(row[1] for row in rows))
|
|
124
|
-
conn.execute("INSERT OR REPLACE INTO session_meta (key, value) VALUES ('current_mode', ?)", (mode,))
|
|
125
|
-
elif receipt.rowcount and data.get("kind") == "hint_serves":
|
|
126
|
-
row = conn.execute("SELECT value FROM session_meta WHERE key='reset_epoch'").fetchone()
|
|
127
|
-
current = int(row[0]) if row else 0
|
|
128
|
-
if current == data["reset_epoch"]:
|
|
129
|
-
conn.executemany(
|
|
130
|
-
"INSERT INTO hint_serves (file_path, served_at, credited) VALUES (?, ?, 0) "
|
|
131
|
-
"ON CONFLICT(file_path) DO NOTHING",
|
|
132
|
-
[(path, data["timestamp"]) for path in data["paths"]],
|
|
133
|
-
)
|
|
134
|
-
elif receipt.rowcount and data.get("kind") == "file_edit":
|
|
135
|
-
conn.execute("INSERT OR REPLACE INTO session_meta (key, value) VALUES (?, '1')",
|
|
136
|
-
("checkpoint_edit:" + data["fingerprint"],))
|
|
137
|
-
elif receipt.rowcount and data.get("kind") == "decisions":
|
|
138
|
-
from context_intel import _MAX_DECISIONS
|
|
139
|
-
row = conn.execute("SELECT value FROM session_meta WHERE key='session_decisions'").fetchone()
|
|
140
|
-
existing = json.loads(row[0]) if row and row[0] else []
|
|
141
|
-
if not isinstance(existing, list):
|
|
142
|
-
raise ValueError("invalid decision state")
|
|
143
|
-
for decision in data["decisions"]:
|
|
144
|
-
if decision not in existing and len(existing) < _MAX_DECISIONS:
|
|
145
|
-
existing.append(decision)
|
|
146
|
-
conn.execute("INSERT OR REPLACE INTO session_meta (key, value) VALUES ('session_decisions', ?)",
|
|
147
|
-
(json.dumps(existing, ensure_ascii=False),))
|
|
148
|
-
elif receipt.rowcount:
|
|
149
|
-
raise ValueError("unknown spool record")
|
|
150
|
-
conn.commit()
|
|
109
|
+
if not paths:
|
|
110
|
+
_sweep_stranded_receipts(conn, directory)
|
|
111
|
+
return
|
|
112
|
+
try:
|
|
113
|
+
conn.execute("CREATE TABLE IF NOT EXISTS spool_receipts (id TEXT PRIMARY KEY)")
|
|
114
|
+
conn.commit()
|
|
115
|
+
except sqlite3.OperationalError as exc:
|
|
116
|
+
conn.rollback()
|
|
117
|
+
if "locked" in str(exc).lower() or "busy" in str(exc).lower():
|
|
118
|
+
return
|
|
119
|
+
raise
|
|
120
|
+
unlinked_ids = []
|
|
121
|
+
try:
|
|
122
|
+
for idx, path in enumerate(paths):
|
|
123
|
+
if idx > 0 and time.monotonic() >= deadline:
|
|
124
|
+
break
|
|
151
125
|
try:
|
|
152
|
-
path.
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
126
|
+
data = json.loads(path.read_text(encoding="utf-8"))
|
|
127
|
+
if data["id"] != path.stem:
|
|
128
|
+
continue
|
|
129
|
+
if data.get("kind") == "hint_serves" and data.get("reset_epoch") is None:
|
|
130
|
+
continue
|
|
131
|
+
conn.execute("BEGIN IMMEDIATE")
|
|
132
|
+
if not path.is_file():
|
|
133
|
+
conn.rollback()
|
|
134
|
+
continue
|
|
135
|
+
receipt = conn.execute("INSERT OR IGNORE INTO spool_receipts (id) VALUES (?)", (data["id"],))
|
|
136
|
+
if receipt.rowcount and data.get("kind", "intel") == "intel":
|
|
137
|
+
conn.execute(
|
|
138
|
+
"INSERT INTO context_intel_events (tool_name, tool_use_id, summary, output_chars, timestamp) "
|
|
139
|
+
"SELECT ?, ?, ?, ?, ? WHERE ? = '' OR NOT EXISTS "
|
|
140
|
+
"(SELECT 1 FROM context_intel_events WHERE tool_use_id = ?)",
|
|
141
|
+
(data["tool_name"], data["tool_use_id"], data["summary"],
|
|
142
|
+
data["output_chars"], data["timestamp"], data["tool_use_id"], data["tool_use_id"]),
|
|
143
|
+
)
|
|
144
|
+
elif receipt.rowcount and data.get("kind") == "tool_output":
|
|
145
|
+
conn.execute(
|
|
146
|
+
"INSERT OR IGNORE INTO tool_outputs (tool_use_id, tool_name, tool_type, command_or_path, "
|
|
147
|
+
"output_hash, output_chars, output_tokens_est, compressed_preview, timestamp, source_file_path, "
|
|
148
|
+
"language, archived_from, output_text, truncated, index_truncated) "
|
|
149
|
+
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", data["values"])
|
|
150
|
+
elif receipt.rowcount and data.get("kind") == "activity":
|
|
151
|
+
from activity_tracker import detect_mode, _WINDOW_SIZE, _PRUNE_THRESHOLD, _PRUNE_KEEP
|
|
152
|
+
conn.execute("INSERT INTO activity_log (tool_name, tool_bucket, has_error, timestamp) VALUES (?, ?, ?, ?)",
|
|
153
|
+
(data["tool_name"], data["bucket"], data["has_error"], data["timestamp"]))
|
|
154
|
+
rows = conn.execute("SELECT tool_bucket, has_error FROM activity_log ORDER BY timestamp DESC, id DESC LIMIT ?", (_WINDOW_SIZE,)).fetchall()
|
|
155
|
+
if conn.execute("SELECT COUNT(*) FROM activity_log").fetchone()[0] > _PRUNE_THRESHOLD:
|
|
156
|
+
conn.execute("DELETE FROM activity_log WHERE id NOT IN (SELECT id FROM activity_log ORDER BY timestamp DESC, id DESC LIMIT ?)", (_PRUNE_KEEP,))
|
|
157
|
+
mode = detect_mode([row[0] for row in rows], any(row[1] for row in rows))
|
|
158
|
+
conn.execute("INSERT OR REPLACE INTO session_meta (key, value) VALUES ('current_mode', ?)", (mode,))
|
|
159
|
+
elif receipt.rowcount and data.get("kind") == "hint_serves":
|
|
160
|
+
row = conn.execute("SELECT value FROM session_meta WHERE key='reset_epoch'").fetchone()
|
|
161
|
+
current = int(row[0]) if row else 0
|
|
162
|
+
if current == data["reset_epoch"]:
|
|
163
|
+
conn.executemany(
|
|
164
|
+
"INSERT INTO hint_serves (file_path, served_at, credited) VALUES (?, ?, 0) "
|
|
165
|
+
"ON CONFLICT(file_path) DO NOTHING",
|
|
166
|
+
[(path, data["timestamp"]) for path in data["paths"]],
|
|
167
|
+
)
|
|
168
|
+
elif receipt.rowcount and data.get("kind") == "file_edit":
|
|
169
|
+
conn.execute("INSERT OR REPLACE INTO session_meta (key, value) VALUES (?, '1')",
|
|
170
|
+
("checkpoint_edit:" + data["fingerprint"],))
|
|
171
|
+
elif receipt.rowcount and data.get("kind") == "decisions":
|
|
172
|
+
from context_intel import _MAX_DECISIONS
|
|
173
|
+
row = conn.execute("SELECT value FROM session_meta WHERE key='session_decisions'").fetchone()
|
|
174
|
+
existing = json.loads(row[0]) if row and row[0] else []
|
|
175
|
+
if not isinstance(existing, list):
|
|
176
|
+
raise ValueError("invalid decision state")
|
|
177
|
+
for decision in data["decisions"]:
|
|
178
|
+
if decision not in existing and len(existing) < _MAX_DECISIONS:
|
|
179
|
+
existing.append(decision)
|
|
180
|
+
conn.execute("INSERT OR REPLACE INTO session_meta (key, value) VALUES ('session_decisions', ?)",
|
|
181
|
+
(json.dumps(existing, ensure_ascii=False),))
|
|
182
|
+
elif receipt.rowcount:
|
|
183
|
+
raise ValueError("unknown spool record")
|
|
184
|
+
conn.commit()
|
|
185
|
+
try:
|
|
186
|
+
path.unlink()
|
|
187
|
+
except FileNotFoundError:
|
|
188
|
+
pass
|
|
189
|
+
except OSError:
|
|
190
|
+
continue
|
|
191
|
+
unlinked_ids.append(data["id"])
|
|
192
|
+
except sqlite3.OperationalError as exc:
|
|
193
|
+
conn.rollback()
|
|
194
|
+
if "locked" in str(exc).lower() or "busy" in str(exc).lower():
|
|
195
|
+
break
|
|
196
|
+
raise
|
|
197
|
+
except (OSError, ValueError, KeyError, TypeError):
|
|
198
|
+
conn.rollback()
|
|
199
|
+
finally:
|
|
200
|
+
# An exception outside the caught set (KeyboardInterrupt, IntegrityError,
|
|
201
|
+
# ImportError) can leave an item's BEGIN IMMEDIATE open with its receipt
|
|
202
|
+
# inserted. Roll it back first, or the sweep's commit would persist that
|
|
203
|
+
# receipt and the next drain would unlink the event without recording it.
|
|
204
|
+
if conn.in_transaction:
|
|
165
205
|
conn.rollback()
|
|
206
|
+
_sweep_stranded_receipts(conn, directory, unlinked_ids)
|
|
166
207
|
|
|
167
208
|
|
|
168
209
|
def drain_collect(snapshot_dir, seconds=0.5, max_sessions=8):
|
|
@@ -25,6 +25,25 @@ def retry_delay(failures):
|
|
|
25
25
|
return min(600, 60 * 2 ** min(max(0, int(failures) - 1), 6))
|
|
26
26
|
|
|
27
27
|
|
|
28
|
+
TIE_WINDOW_S = 1.0
|
|
29
|
+
STAMP_STEP_S = 0.000001
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def fresh_stamp(facade, prior):
|
|
33
|
+
"""Strictly increasing computed_at for a fresh write inside the tie window: a
|
|
34
|
+
coarse timer tick or sub-second rollback must never let an older cached
|
|
35
|
+
result shadow the newest write. A stamp further in the future belongs to a
|
|
36
|
+
clock-skewed writer and keeps winning until real time catches up."""
|
|
37
|
+
now = facade.time.time()
|
|
38
|
+
try:
|
|
39
|
+
previous = float((prior or {}).get('computed_at'))
|
|
40
|
+
except (TypeError, ValueError):
|
|
41
|
+
previous = None
|
|
42
|
+
if previous is not None and now <= previous < now + TIE_WINDOW_S:
|
|
43
|
+
return previous + STAMP_STEP_S
|
|
44
|
+
return now
|
|
45
|
+
|
|
46
|
+
|
|
28
47
|
def write_cache(facade, session_id, savings, reason):
|
|
29
48
|
# One failure is routine (a hook writing): the retry note needs two in a row.
|
|
30
49
|
directory = facade._status_bar_dir()
|
|
@@ -37,10 +56,15 @@ def write_cache(facade, session_id, savings, reason):
|
|
|
37
56
|
savings = prior['savings']
|
|
38
57
|
friendly = 'no savings recorded yet' if reason == 'no savings recorded yet' else 'still counting savings'
|
|
39
58
|
data = {
|
|
40
|
-
'schema': facade._STATUS_BAR_SCHEMA, 'computed_at': prior['computed_at'] if stale else facade
|
|
59
|
+
'schema': facade._STATUS_BAR_SCHEMA, 'computed_at': prior['computed_at'] if stale else fresh_stamp(facade, prior),
|
|
41
60
|
'savings': savings, 'reason': friendly if savings is None else None, 'stale': stale,
|
|
42
61
|
'last_attempt': facade.time.time() if failed else 0, 'failures': failures, 'refresh_failed': failed and failures >= 2 and reason != 'no savings recorded yet',
|
|
43
62
|
}
|
|
63
|
+
try:
|
|
64
|
+
from . import poc_commands
|
|
65
|
+
data.update(poc_commands.status_extras(facade, session_id))
|
|
66
|
+
except Exception:
|
|
67
|
+
pass
|
|
44
68
|
try:
|
|
45
69
|
atomic_write(facade, facade._status_bar_cache_path(session_id), data)
|
|
46
70
|
except PermissionError:
|
|
@@ -88,11 +112,22 @@ def read_cache(facade, session_id):
|
|
|
88
112
|
try:
|
|
89
113
|
data = facade.json.loads(candidate.read_text(encoding='utf-8'))
|
|
90
114
|
if isinstance(data, dict) and isinstance(data.get('computed_at'), (int, float)):
|
|
91
|
-
|
|
115
|
+
try:
|
|
116
|
+
written = candidate.stat().st_mtime_ns
|
|
117
|
+
except OSError:
|
|
118
|
+
written = 0
|
|
119
|
+
valid.append((data, written))
|
|
92
120
|
except (OSError, ValueError):
|
|
93
121
|
pass
|
|
94
122
|
if valid:
|
|
95
|
-
|
|
123
|
+
# Equal stamps cannot be ordered causally from the payload; fall back
|
|
124
|
+
# to physical write order (file mtime) so a later write never loses
|
|
125
|
+
# to an earlier one just because their stamps tied.
|
|
126
|
+
return max(valid, key=lambda item: (
|
|
127
|
+
item[0]['computed_at'],
|
|
128
|
+
item[0].get('last_attempt', 0) if isinstance(item[0].get('last_attempt', 0), (int, float)) else 0,
|
|
129
|
+
item[1],
|
|
130
|
+
))[0]
|
|
96
131
|
except OSError:
|
|
97
132
|
pass
|
|
98
133
|
return seed_legacy(facade, session_id)
|
|
@@ -45,7 +45,7 @@ SCHEMA = 1
|
|
|
45
45
|
TRIMS_FILE = "structural_trims.jsonl"
|
|
46
46
|
HISTORY_FILE = "prefix_history.jsonl"
|
|
47
47
|
BASELINE_FILE = "structural_baseline.json"
|
|
48
|
-
TIER_BY_SOURCE = {"audit_action": "measured", "attested": "estimated", "dated_archive": "estimated", "detected": "unattributed"}
|
|
48
|
+
TIER_BY_SOURCE = {"audit_action": "measured", "apply_safe": "estimated", "attested": "estimated", "dated_archive": "estimated", "detected": "unattributed"}
|
|
49
49
|
SUMMED_TIERS = ("measured", "estimated")
|
|
50
50
|
MIN_TRIM_TOKENS = 20 # below this a shrink is estimator noise, not a trim
|
|
51
51
|
SNAPSHOT_INTERVAL_S = 6 * 3600
|