@alexgreensh/token-optimizer 5.13.63 → 5.13.65
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/sessionstart_runner.py +5 -0
- package/package.json +1 -1
- package/skills/fleet-auditor/SKILL.md +1 -1
- package/skills/token-coach/SKILL.md +49 -40
- package/skills/token-coach/references/deterministic-stages.md +1 -1
- package/skills/token-coach/references/keepwarm-consent.md +7 -7
- package/skills/token-dashboard/SKILL.md +30 -6
- package/skills/token-optimizer/SKILL.md +42 -44
- package/skills/token-optimizer/assets/dashboard.html +180 -44
- package/skills/token-optimizer/references/agent-prompts.md +4 -1
- package/skills/token-optimizer/references/codex-workflow.md +30 -12
- package/skills/token-optimizer/references/cursor-workflow.md +9 -7
- package/skills/token-optimizer/references/implementation-playbook.md +4 -4
- package/skills/token-optimizer/references/keepwarm-consent.md +7 -7
- package/skills/token-optimizer/references/opencode-workflow.md +4 -2
- package/skills/token-optimizer/references/optimization-checklist.md +9 -9
- package/skills/token-optimizer/references/phase0-setup.md +9 -9
- package/skills/token-optimizer/references/presentation-workflow.md +3 -3
- package/skills/token-optimizer/references/session-continuity.md +1 -1
- package/skills/token-optimizer/references/token-flow-architecture.md +2 -1
- package/skills/token-optimizer/scripts/archive_result.py +6 -1
- package/skills/token-optimizer/scripts/archive_window.py +274 -0
- package/skills/token-optimizer/scripts/checkpoint_state.py +385 -0
- package/skills/token-optimizer/scripts/codex_session.py +149 -1
- package/skills/token-optimizer/scripts/devin_source.py +2 -2
- package/skills/token-optimizer/scripts/measure.py +3498 -1111
- package/skills/token-optimizer/scripts/read_cache.py +20 -7
- package/skills/token-optimizer/scripts/recovery_output.py +67 -18
- package/skills/token-optimizer/scripts/session_activity.py +169 -0
- package/skills/token-optimizer/scripts/session_store.py +63 -9
- package/skills/token-optimizer/scripts/statusline.js +4 -6
|
@@ -333,9 +333,13 @@ DEFAULT_MODE = "soft_block"
|
|
|
333
333
|
MIN_STRUCTURE_CONFIDENCE = 0.75
|
|
334
334
|
MAX_CONSECUTIVE_DENIALS = 3
|
|
335
335
|
REASON_ONLY_TOKENS_EST = 10
|
|
336
|
-
# U-G3: conservative avoided-search
|
|
337
|
-
# straight to a file (~2 exploratory reads of ~2500 tokens it
|
|
338
|
-
# to locate it).
|
|
336
|
+
# U-G3: conservative avoided-search ESTIMATE credited when a proactive hint
|
|
337
|
+
# sends the agent straight to a file (~2 exploratory reads of ~2500 tokens it
|
|
338
|
+
# plausibly did not have to do to locate it). The hint->read trigger is
|
|
339
|
+
# observed; whether a search would otherwise have run is not, so the magnitude
|
|
340
|
+
# is a fixed estimate and _get_savings_summary files the event in the
|
|
341
|
+
# estimated tier, never the measured total. Deliberately small -- lean
|
|
342
|
+
# understated, claimed once per file.
|
|
339
343
|
_HINT_FOLLOW_AVOIDED_TOKENS = 5000
|
|
340
344
|
STRICT_CONTEXT_CAPS = {
|
|
341
345
|
"signatures": 350,
|
|
@@ -1126,7 +1130,7 @@ def _first_read_compress(
|
|
|
1126
1130
|
source_file_path=_safe_path,
|
|
1127
1131
|
language=language,
|
|
1128
1132
|
archived_from="first_read_skeleton",
|
|
1129
|
-
output_text=_safe_skel
|
|
1133
|
+
output_text=_safe_skel,
|
|
1130
1134
|
)
|
|
1131
1135
|
except Exception:
|
|
1132
1136
|
pass
|
|
@@ -1467,9 +1471,11 @@ def handle_read(hook_input: dict[str, Any], mode: str, quiet: bool) -> None:
|
|
|
1467
1471
|
return
|
|
1468
1472
|
|
|
1469
1473
|
# U-G3: if a proactive prior-session hint surfaced this exact file to this
|
|
1470
|
-
# session, the agent reading it is observed evidence the hint
|
|
1471
|
-
# exploratory search
|
|
1472
|
-
#
|
|
1474
|
+
# session, the agent reading it is observed evidence the hint was followed.
|
|
1475
|
+
# Whether it spared an exploratory search is counterfactual -- we see the
|
|
1476
|
+
# read, not the search that did not happen -- so the credit is a fixed
|
|
1477
|
+
# avoided-search ESTIMATE (claimed once: claim_hint_follow flips the flag),
|
|
1478
|
+
# filed in the estimated tier downstream. Best-effort.
|
|
1473
1479
|
try:
|
|
1474
1480
|
if store.claim_hint_follow(file_path):
|
|
1475
1481
|
_log_savings_event(
|
|
@@ -2205,6 +2211,13 @@ def handle_invalidate(hook_input: dict[str, Any], quiet: bool) -> None:
|
|
|
2205
2211
|
if store is None:
|
|
2206
2212
|
return
|
|
2207
2213
|
|
|
2214
|
+
# Checkpoints can predate this edit. Preserve its path independently of
|
|
2215
|
+
# cache entries, including edits to files that have never been read.
|
|
2216
|
+
try:
|
|
2217
|
+
store.record_file_edit(file_path)
|
|
2218
|
+
except Exception:
|
|
2219
|
+
pass
|
|
2220
|
+
|
|
2208
2221
|
# U5: resolve the first-read shadow quality proxy (edit-after-shadow-read).
|
|
2209
2222
|
_resolve_first_read_shadow_on_edit(
|
|
2210
2223
|
file_path, detect_structure_language(file_path), session_id, store
|
|
@@ -33,17 +33,67 @@ def is_recovery_tool(tool_name: str) -> bool:
|
|
|
33
33
|
return tool_name in _RECOVERY_TOOLS
|
|
34
34
|
|
|
35
35
|
|
|
36
|
-
#
|
|
37
|
-
#
|
|
38
|
-
#
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
36
|
+
# Bounded-read flags `expand` accepts after the key; each takes exactly one
|
|
37
|
+
# value token. --search/--list/--grep stay outside: their output is a result
|
|
38
|
+
# list, not the stored original, so it keeps the normal pipeline.
|
|
39
|
+
_EXPAND_VALUE_FLAGS = frozenset({
|
|
40
|
+
'--session', '--lines', '--start', '--chars',
|
|
41
|
+
'--match', '--context', '--skip',
|
|
42
|
+
})
|
|
43
43
|
# A printed hint may pin its runtime with a leading `--runtime NAME` (Hermes and
|
|
44
44
|
# Codex archives live under their own homes; see refetch_fingerprint.expand_command).
|
|
45
45
|
_RUNTIME_PIN = re.compile(r'--runtime [a-z][a-z0-9-]{0,31} ')
|
|
46
46
|
_RUNTIME_NAME = re.compile(r'[a-z][a-z0-9-]{0,31}')
|
|
47
|
+
# Shell operators that split a command even when glued to a word (`--match a;b`
|
|
48
|
+
# runs `b` as a second command). Quoted text keeps them inside the value token.
|
|
49
|
+
_EXPAND_PUNCT = ';&|<>()'
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _expand_split(text):
|
|
53
|
+
"""shlex.split, but unquoted ``;&|<>()`` surface as their own tokens.
|
|
54
|
+
|
|
55
|
+
Plain shlex keeps ``a;b`` inside one word, which would let a compound
|
|
56
|
+
command pass as a single ``--match`` value; the shell still splits on it.
|
|
57
|
+
"""
|
|
58
|
+
lex = shlex.shlex(text, posix=True, punctuation_chars=_EXPAND_PUNCT)
|
|
59
|
+
lex.whitespace_split = True
|
|
60
|
+
return list(lex)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _expand_tail_ok(tokens):
|
|
64
|
+
"""``expand`` tail tokens: <key> then --flag value pairs, nothing else.
|
|
65
|
+
|
|
66
|
+
One optional trailing ']' is tolerated on the key or the last value: pointers
|
|
67
|
+
shipped before the bracket moved to its own line ended "expand <id>]", and
|
|
68
|
+
those stale hints are still in live transcripts. No shell operator can pass —
|
|
69
|
+
every token must be the key, a known flag, or that flag's value.
|
|
70
|
+
"""
|
|
71
|
+
if not tokens:
|
|
72
|
+
return False
|
|
73
|
+
key = tokens[0]
|
|
74
|
+
if key.endswith(']'):
|
|
75
|
+
key = key[:-1]
|
|
76
|
+
if key.startswith('-') or not re.fullmatch(r'[a-zA-Z0-9_-]+', key):
|
|
77
|
+
return False
|
|
78
|
+
rest = list(tokens[1:])
|
|
79
|
+
if rest and rest[-1].endswith(']'):
|
|
80
|
+
rest[-1] = rest[-1][:-1]
|
|
81
|
+
i = 0
|
|
82
|
+
while i < len(rest):
|
|
83
|
+
flag = rest[i]
|
|
84
|
+
if flag not in _EXPAND_VALUE_FLAGS or i + 1 >= len(rest):
|
|
85
|
+
return False
|
|
86
|
+
value = rest[i + 1]
|
|
87
|
+
if flag == '--session':
|
|
88
|
+
# Same closed charset the recognizer used before bounded flags.
|
|
89
|
+
if not re.fullmatch(r'[a-zA-Z0-9_-]+', value):
|
|
90
|
+
return False
|
|
91
|
+
elif '$' in value or '`' in value:
|
|
92
|
+
# Quoting does not stop the shell from expanding $(...) or `...`
|
|
93
|
+
# inside a double-quoted value; keep recovery output to literal text.
|
|
94
|
+
return False
|
|
95
|
+
i += 2
|
|
96
|
+
return True
|
|
47
97
|
|
|
48
98
|
|
|
49
99
|
def _is_printed_hint(command: str) -> bool:
|
|
@@ -77,8 +127,13 @@ def _is_printed_hint(command: str) -> bool:
|
|
|
77
127
|
pinned = _RUNTIME_PIN.match(rest)
|
|
78
128
|
if pinned:
|
|
79
129
|
rest = rest[pinned.end():]
|
|
80
|
-
if rest.startswith('expand ')
|
|
81
|
-
|
|
130
|
+
if rest.startswith('expand '):
|
|
131
|
+
try:
|
|
132
|
+
tail = _expand_split(rest[len('expand '):])
|
|
133
|
+
except ValueError:
|
|
134
|
+
continue
|
|
135
|
+
if _expand_tail_ok(tail):
|
|
136
|
+
return True
|
|
82
137
|
return False
|
|
83
138
|
|
|
84
139
|
|
|
@@ -94,22 +149,16 @@ def is_expand_command(command: str) -> bool:
|
|
|
94
149
|
if _is_printed_hint(command):
|
|
95
150
|
return True
|
|
96
151
|
try:
|
|
97
|
-
tokens =
|
|
152
|
+
tokens = _expand_split(command)
|
|
98
153
|
if (len(tokens) >= 4 and tokens[2] == '--runtime'
|
|
99
154
|
and _RUNTIME_NAME.fullmatch(tokens[3])):
|
|
100
155
|
tokens = tokens[:2] + tokens[4:]
|
|
101
|
-
if len(tokens)
|
|
156
|
+
if len(tokens) < 4 or tokens[2] != 'expand':
|
|
102
157
|
return False
|
|
103
158
|
if not _PYTHON.fullmatch(Path(tokens[0]).name):
|
|
104
159
|
return False
|
|
105
|
-
|
|
106
|
-
key = tokens[3][:-1] if tokens[3].endswith(']') else tokens[3]
|
|
107
|
-
if key.startswith('-') or not re.fullmatch(r'[a-zA-Z0-9_-]+', key):
|
|
160
|
+
if not _expand_tail_ok(tokens[3:]):
|
|
108
161
|
return False
|
|
109
|
-
if len(tokens) == 6:
|
|
110
|
-
sid = tokens[5][:-1] if tokens[5].endswith(']') else tokens[5]
|
|
111
|
-
if tokens[4] != '--session' or not re.fullmatch(r'[a-zA-Z0-9_-]+', sid):
|
|
112
|
-
return False
|
|
113
162
|
expected = Path(__file__).resolve().parent / 'measure.py'
|
|
114
163
|
return Path(tokens[1]).is_absolute() and Path(tokens[1]).resolve() == expected
|
|
115
164
|
except (ValueError, OSError, RuntimeError):
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
"""Dated usage projections. Ingestion timestamps never supply activity dates."""
|
|
2
|
+
import json
|
|
3
|
+
import sqlite3
|
|
4
|
+
from datetime import date
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def activity_days(usage):
|
|
8
|
+
days = []
|
|
9
|
+
for day, models in usage.items():
|
|
10
|
+
try:
|
|
11
|
+
if date.fromisoformat(day).isoformat() == day and isinstance(models, dict):
|
|
12
|
+
days.append(day)
|
|
13
|
+
except (TypeError, ValueError):
|
|
14
|
+
pass
|
|
15
|
+
return sorted(days)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def activity_bounds(*maps):
|
|
19
|
+
"""Bound every retained source of dated usage or metadata."""
|
|
20
|
+
return sorted({day for usage in maps if isinstance(usage, dict)
|
|
21
|
+
for day in activity_days(usage)})
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def activity_coverage(conn):
|
|
25
|
+
columns = {r[1] for r in conn.execute("PRAGMA table_info(session_log)")}
|
|
26
|
+
if "daily_usage_json" not in columns:
|
|
27
|
+
return {"complete": False, "undated_sessions": 0}
|
|
28
|
+
parent_col = "parent_daily_usage_json" if "parent_daily_usage_json" in columns else "NULL"
|
|
29
|
+
incomplete = 0
|
|
30
|
+
for raw, parent in conn.execute(f"SELECT daily_usage_json,{parent_col} FROM session_log"):
|
|
31
|
+
try:
|
|
32
|
+
usage = json.loads(raw) if raw is not None else None
|
|
33
|
+
except (TypeError, ValueError):
|
|
34
|
+
usage = None
|
|
35
|
+
if not isinstance(usage, dict) or (not usage and parent is None) or len(activity_days(usage)) != len(usage):
|
|
36
|
+
incomplete += 1
|
|
37
|
+
return {"complete": incomplete == 0, "undated_sessions": incomplete}
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def ensure_activity_schema(conn):
|
|
41
|
+
columns = {r[1] for r in conn.execute("PRAGMA table_info(session_log)")}
|
|
42
|
+
for name, kind in (("first_activity_day", "TEXT"), ("last_activity_day", "TEXT"),
|
|
43
|
+
("transcript_mtime", "REAL"), ("parent_daily_usage_json", "TEXT"),
|
|
44
|
+
("daily_calls_json", "TEXT"), ("daily_metrics_json", "TEXT")):
|
|
45
|
+
if name not in columns:
|
|
46
|
+
try:
|
|
47
|
+
conn.execute(f"ALTER TABLE session_log ADD COLUMN {name} {kind}")
|
|
48
|
+
except sqlite3.OperationalError:
|
|
49
|
+
if name not in {r[1] for r in conn.execute("PRAGMA table_info(session_log)")}:
|
|
50
|
+
raise
|
|
51
|
+
conn.execute("CREATE TABLE IF NOT EXISTS schema_migrations (name TEXT PRIMARY KEY)")
|
|
52
|
+
if conn.execute("SELECT 1 FROM main.sqlite_master WHERE type='view' AND name='session_activity'").fetchone():
|
|
53
|
+
conn.execute("DROP VIEW main.session_activity")
|
|
54
|
+
ensure_activity_view(conn)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def ensure_activity_view(conn):
|
|
58
|
+
"""Connection-local projection, including legacy/read-only database shapes."""
|
|
59
|
+
if conn.execute("SELECT 1 FROM sqlite_temp_master WHERE type='view' AND name='session_activity'").fetchone():
|
|
60
|
+
return
|
|
61
|
+
columns = {r[1] for r in conn.execute("PRAGMA table_info(session_log)")}
|
|
62
|
+
def source(name, default="NULL"):
|
|
63
|
+
return "s." + name if name in columns else default
|
|
64
|
+
def total(field):
|
|
65
|
+
return f"COALESCE((SELECT SUM(COALESCE(json_extract(value, '$.{field}'),0)) FROM json_each(d.value)),0)"
|
|
66
|
+
fresh, read, write, output = [total(k) for k in ("fresh_input", "cache_read", "cache_create", "output")]
|
|
67
|
+
inp = f"({fresh}+{read}+{write})"
|
|
68
|
+
model_mix = "(SELECT json_group_object(key, COALESCE(json_extract(value,'$.fresh_input'),0)+COALESCE(json_extract(value,'$.cache_create'),0)+COALESCE(json_extract(value,'$.output'),0)+COALESCE(json_extract(value,'$.unsplit'),0)) FROM json_each(d.value))"
|
|
69
|
+
overrides = {
|
|
70
|
+
"date": "d.key", "input_tokens": inp, "output_tokens": output,
|
|
71
|
+
"cache_hit_rate": f"CASE WHEN {inp}>0 THEN 1.0*{read}/{inp} ELSE 0 END",
|
|
72
|
+
"cache_create_1h_tokens": total("cache_create_1h"),
|
|
73
|
+
"cache_create_5m_tokens": f"({write}-{total('cache_create_1h')})",
|
|
74
|
+
"model_usage_json": model_mix, "all_model_usage_json": model_mix,
|
|
75
|
+
"model_usage_breakdown_json": "d.value",
|
|
76
|
+
"daily_usage_json": "json_object(d.key, json(d.value))",
|
|
77
|
+
"api_calls": f"json_extract({source('daily_calls_json')}, '$.\"' || d.key || '\"')",
|
|
78
|
+
# 1 only when dated per-day call evidence exists at all; a NULL
|
|
79
|
+
# api_calls then means a measured zero for that day, not missing data.
|
|
80
|
+
"api_calls_known": (f"CASE WHEN {source('daily_calls_json')} IS NOT NULL "
|
|
81
|
+
f"AND json_valid({source('daily_calls_json')}) THEN 1 ELSE 0 END"),
|
|
82
|
+
}
|
|
83
|
+
cohort_defaults = {
|
|
84
|
+
"message_count": "0", "duration_minutes": "0", "skills_json": "'{}'",
|
|
85
|
+
"subagents_json": "'{}'", "tool_calls_json": "'{}'", "stale_waste_tokens": "0",
|
|
86
|
+
"quality_score": "NULL", "quality_grade": "NULL", "avg_call_gap_seconds": "NULL",
|
|
87
|
+
"max_call_gap_seconds": "NULL", "p95_call_gap_seconds": "NULL",
|
|
88
|
+
}
|
|
89
|
+
for name, default in cohort_defaults.items():
|
|
90
|
+
overrides[name] = f"CASE WHEN d.key={source('date')} THEN {source(name, default)} ELSE {default} END"
|
|
91
|
+
for name in ("message_count", "duration_minutes", "skills_json", "subagents_json", "tool_calls_json"):
|
|
92
|
+
key = name.removesuffix("_json")
|
|
93
|
+
overrides[name] = f"COALESCE(json_extract({source('daily_metrics_json')}, '$.\"' || d.key || '\".{key}'), {overrides[name]})"
|
|
94
|
+
# Optional ingestion/provenance columns are deliberately not dependencies of
|
|
95
|
+
# this view. Their migrations can fail or be retried independently.
|
|
96
|
+
for name in ("id", "jsonl_path", "project", "is_sidechain", "session_uuid", "slug", "topic", "collected_at", "version"):
|
|
97
|
+
overrides[name] = source(name, "s.rowid" if name == "id" else "NULL")
|
|
98
|
+
# Metadata-only activity days (user/tool activity with no billed usage that
|
|
99
|
+
# day) still belong to the projection: they carry message/tool/skill counts
|
|
100
|
+
# and hold the cohort fields on the session's last activity day. Token and
|
|
101
|
+
# model columns stay zero/empty rather than inventing billed volume.
|
|
102
|
+
metric_overrides = dict(overrides)
|
|
103
|
+
metric_overrides.update({
|
|
104
|
+
"input_tokens": "0", "output_tokens": "0", "cache_hit_rate": "0",
|
|
105
|
+
"cache_create_1h_tokens": "0", "cache_create_5m_tokens": "0",
|
|
106
|
+
"model_usage_json": "'{}'", "all_model_usage_json": "'{}'",
|
|
107
|
+
"model_usage_breakdown_json": "'{}'", "daily_usage_json": "'{}'",
|
|
108
|
+
})
|
|
109
|
+
usage_projection = ", ".join(f'{expr} AS "{name}"' for name, expr in overrides.items())
|
|
110
|
+
metric_projection = ", ".join(f'{expr} AS "{name}"' for name, expr in metric_overrides.items())
|
|
111
|
+
usage = f"COALESCE({source('daily_usage_json')},{source('parent_daily_usage_json')})"
|
|
112
|
+
metrics = source("daily_metrics_json")
|
|
113
|
+
day_ok = ("length(d.key)=10 AND d.key GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]' "
|
|
114
|
+
"AND date(d.key)=d.key AND d.type='object'")
|
|
115
|
+
conn.execute(f"""CREATE TEMP VIEW session_activity AS
|
|
116
|
+
SELECT {usage_projection}
|
|
117
|
+
FROM main.session_log s, json_each(CASE WHEN json_valid({usage})
|
|
118
|
+
THEN {usage} ELSE '{{}}' END) d
|
|
119
|
+
WHERE {day_ok}
|
|
120
|
+
UNION ALL
|
|
121
|
+
SELECT {metric_projection}
|
|
122
|
+
FROM main.session_log s, json_each(CASE WHEN json_valid({metrics})
|
|
123
|
+
THEN {metrics} ELSE '{{}}' END) d
|
|
124
|
+
WHERE {day_ok}
|
|
125
|
+
AND CASE WHEN json_valid({usage})
|
|
126
|
+
THEN json_extract({usage}, '$.\"' || d.key || '\"') END IS NULL""")
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def repair_activity_dates(conn):
|
|
130
|
+
"""Repair even missing-transcript rows from retained daily evidence, once."""
|
|
131
|
+
if conn.execute("SELECT 1 FROM schema_migrations WHERE name='activity_dating_v1'").fetchone():
|
|
132
|
+
return False
|
|
133
|
+
conn.execute("BEGIN IMMEDIATE")
|
|
134
|
+
if conn.execute("SELECT 1 FROM schema_migrations WHERE name='activity_dating_v1'").fetchone():
|
|
135
|
+
conn.commit()
|
|
136
|
+
return False
|
|
137
|
+
columns = {r[1] for r in conn.execute("PRAGMA table_info(session_log)")}
|
|
138
|
+
metrics_col = "daily_metrics_json" if "daily_metrics_json" in columns else "NULL"
|
|
139
|
+
parent_col = "parent_daily_usage_json" if "parent_daily_usage_json" in columns else "NULL"
|
|
140
|
+
calls_col = "daily_calls_json" if "daily_calls_json" in columns else "NULL"
|
|
141
|
+
api_col = "api_calls" if "api_calls" in columns else "NULL"
|
|
142
|
+
updates = []
|
|
143
|
+
call_updates = []
|
|
144
|
+
for sid, raw, parent_raw, metrics_raw, api_calls, calls_raw in conn.execute(
|
|
145
|
+
f"SELECT id,daily_usage_json,{parent_col},{metrics_col},{api_col},{calls_col} FROM session_log"):
|
|
146
|
+
maps = []
|
|
147
|
+
fully_dated = True
|
|
148
|
+
for source in (raw, parent_raw, metrics_raw):
|
|
149
|
+
try:
|
|
150
|
+
usage = json.loads(source or "{}")
|
|
151
|
+
except (ValueError, TypeError):
|
|
152
|
+
usage = None
|
|
153
|
+
if not isinstance(usage, dict) or len(activity_days(usage)) != len(usage):
|
|
154
|
+
fully_dated = False
|
|
155
|
+
maps.append(usage)
|
|
156
|
+
days = activity_bounds(*maps)
|
|
157
|
+
updates.append((days[0] if days else None, days[-1] if days else None,
|
|
158
|
+
days[-1] if days else "", sid))
|
|
159
|
+
# A session with exactly one proven activity day can carry its whole call
|
|
160
|
+
# count on that day (the same allocation the adapter path uses). Sessions
|
|
161
|
+
# with any invalid bucket or several activity days keep NULL: per-day call
|
|
162
|
+
# evidence that was never recorded stays unknown, never zero or split.
|
|
163
|
+
if (calls_raw is None and len(days) == 1
|
|
164
|
+
and isinstance(api_calls, (int, float)) and fully_dated):
|
|
165
|
+
call_updates.append((json.dumps({days[0]: int(api_calls)}), sid))
|
|
166
|
+
conn.executemany("UPDATE session_log SET first_activity_day=?,last_activity_day=?,date=? WHERE id=?", updates)
|
|
167
|
+
if call_updates:
|
|
168
|
+
conn.executemany("UPDATE session_log SET daily_calls_json=? WHERE id=?", call_updates)
|
|
169
|
+
return True
|
|
@@ -24,6 +24,7 @@ Configuration:
|
|
|
24
24
|
|
|
25
25
|
from __future__ import annotations
|
|
26
26
|
|
|
27
|
+
import hashlib
|
|
27
28
|
import json
|
|
28
29
|
import re
|
|
29
30
|
import sqlite3
|
|
@@ -38,6 +39,11 @@ SNAPSHOT_DIR = resolve_snapshot_dir()
|
|
|
38
39
|
SESSION_STORE_DIR = SNAPSHOT_DIR / "session-store"
|
|
39
40
|
|
|
40
41
|
MAX_DB_SIZE_BYTES = 50 * 1024 * 1024 # 50MB cap
|
|
42
|
+
# tool_outputs.output_text is a search index copy, not the recovery source (the
|
|
43
|
+
# archive sidecar keeps the full redacted body). Bound it so a few multi-MB
|
|
44
|
+
# archives cannot fill the 50MB session DB and pause every later write.
|
|
45
|
+
MAX_TOOL_OUTPUT_INDEX_BYTES = 256 * 1024
|
|
46
|
+
_INDEX_TRUNCATED_MARKER = "\n[... index truncated ...]\n"
|
|
41
47
|
CLEANUP_AGE_HOURS = 48
|
|
42
48
|
|
|
43
49
|
# v2: added tool_outputs lineage columns + the FTS5 archive index, and
|
|
@@ -76,7 +82,9 @@ CREATE TABLE IF NOT EXISTS tool_outputs (
|
|
|
76
82
|
source_file_path TEXT,
|
|
77
83
|
language TEXT,
|
|
78
84
|
archived_from TEXT,
|
|
79
|
-
output_text TEXT
|
|
85
|
+
output_text TEXT,
|
|
86
|
+
truncated INTEGER,
|
|
87
|
+
index_truncated INTEGER
|
|
80
88
|
);
|
|
81
89
|
|
|
82
90
|
CREATE TABLE IF NOT EXISTS command_outputs (
|
|
@@ -162,6 +170,27 @@ def _sanitize_session_id(sid: str) -> str:
|
|
|
162
170
|
return sid
|
|
163
171
|
|
|
164
172
|
|
|
173
|
+
def _bound_tool_output_index(text: Optional[str]):
|
|
174
|
+
"""Bound ``output_text`` to a head+tail search index.
|
|
175
|
+
|
|
176
|
+
Returns ``(index_text, index_truncated)``. The full redacted body still lives
|
|
177
|
+
in the archive sidecar; this column only feeds FTS/LIKE search, so keeping a
|
|
178
|
+
bounded head and tail preserves findability without letting a few multi-MB
|
|
179
|
+
outputs fill the per-session database cap.
|
|
180
|
+
"""
|
|
181
|
+
if text is None:
|
|
182
|
+
return None, 0
|
|
183
|
+
raw = text.encode("utf-8", "replace")
|
|
184
|
+
if len(raw) <= MAX_TOOL_OUTPUT_INDEX_BYTES:
|
|
185
|
+
return text, 0
|
|
186
|
+
marker = _INDEX_TRUNCATED_MARKER.encode("utf-8")
|
|
187
|
+
head_budget = MAX_TOOL_OUTPUT_INDEX_BYTES // 2
|
|
188
|
+
tail_budget = MAX_TOOL_OUTPUT_INDEX_BYTES - head_budget - len(marker)
|
|
189
|
+
head = raw[:head_budget].decode("utf-8", "ignore")
|
|
190
|
+
tail = raw[len(raw) - tail_budget:].decode("utf-8", "ignore") if tail_budget > 0 else ""
|
|
191
|
+
return head + _INDEX_TRUNCATED_MARKER + tail, 1
|
|
192
|
+
|
|
193
|
+
|
|
165
194
|
class SessionStore:
|
|
166
195
|
"""Per-session SQLite store for tool output caching."""
|
|
167
196
|
|
|
@@ -276,10 +305,17 @@ class SessionStore:
|
|
|
276
305
|
cols = {r[1] for r in conn.execute("PRAGMA table_info(tool_outputs)").fetchall()}
|
|
277
306
|
except sqlite3.DatabaseError:
|
|
278
307
|
return
|
|
279
|
-
for col in (
|
|
308
|
+
for col, decl in (
|
|
309
|
+
("source_file_path", "TEXT"),
|
|
310
|
+
("language", "TEXT"),
|
|
311
|
+
("archived_from", "TEXT"),
|
|
312
|
+
("output_text", "TEXT"),
|
|
313
|
+
("truncated", "INTEGER"),
|
|
314
|
+
("index_truncated", "INTEGER"),
|
|
315
|
+
):
|
|
280
316
|
if col not in cols:
|
|
281
317
|
try:
|
|
282
|
-
conn.execute(f"ALTER TABLE tool_outputs ADD COLUMN {col}
|
|
318
|
+
conn.execute(f"ALTER TABLE tool_outputs ADD COLUMN {col} {decl}")
|
|
283
319
|
except sqlite3.OperationalError:
|
|
284
320
|
pass
|
|
285
321
|
|
|
@@ -648,23 +684,27 @@ class SessionStore:
|
|
|
648
684
|
language: Optional[str] = None,
|
|
649
685
|
archived_from: Optional[str] = None,
|
|
650
686
|
output_text: Optional[str] = None,
|
|
687
|
+
truncated: Optional[int] = None,
|
|
651
688
|
) -> None:
|
|
652
689
|
if self._is_over_size_cap():
|
|
653
690
|
return
|
|
691
|
+
index_text, index_truncated = _bound_tool_output_index(output_text)
|
|
654
692
|
conn = self._connect()
|
|
655
693
|
conn.execute(
|
|
656
694
|
"""INSERT OR IGNORE INTO tool_outputs
|
|
657
695
|
(tool_use_id, tool_name, tool_type, command_or_path,
|
|
658
696
|
output_hash, output_chars, output_tokens_est,
|
|
659
697
|
compressed_preview, timestamp,
|
|
660
|
-
source_file_path, language, archived_from, output_text
|
|
661
|
-
|
|
698
|
+
source_file_path, language, archived_from, output_text,
|
|
699
|
+
truncated, index_truncated)
|
|
700
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
662
701
|
""",
|
|
663
702
|
(
|
|
664
703
|
tool_use_id, tool_name, tool_type, command_or_path,
|
|
665
704
|
output_hash, output_chars, output_tokens_est,
|
|
666
705
|
compressed_preview, time.time(),
|
|
667
|
-
source_file_path, language, archived_from,
|
|
706
|
+
source_file_path, language, archived_from, index_text,
|
|
707
|
+
truncated, index_truncated,
|
|
668
708
|
),
|
|
669
709
|
)
|
|
670
710
|
# fix-1: the external-content FTS mirror is maintained by the AFTER
|
|
@@ -676,9 +716,10 @@ class SessionStore:
|
|
|
676
716
|
# ----- tool_outputs search (U6: FTS5 with LIKE fallback) -----
|
|
677
717
|
|
|
678
718
|
def search_tool_outputs(self, query: str, limit: int = 20) -> list[dict[str, Any]]:
|
|
679
|
-
"""Full-text search over archived tool outputs Returns rows
|
|
680
|
-
|
|
681
|
-
|
|
719
|
+
"""Full-text search over archived tool outputs Returns rows carrying
|
|
720
|
+
(tool_use_id, tool_name, command_or_path, source_file_path, language,
|
|
721
|
+
archived_from, output_hash, output_chars, timestamp, truncated,
|
|
722
|
+
index_truncated, snippet) ranked by relevance. Uses FTS5 ``bm25()`` when available; falls back to a
|
|
682
723
|
bounded ``LIKE '%term%'`` query over the lineage + output_text
|
|
683
724
|
columns when FTS5 is not compiled into SQLite. Never raises: an
|
|
684
725
|
empty/invalid query or a missing index returns an empty list.
|
|
@@ -692,6 +733,8 @@ class SessionStore:
|
|
|
692
733
|
rows = conn.execute(
|
|
693
734
|
"""SELECT t.tool_use_id, t.tool_name, t.command_or_path,
|
|
694
735
|
t.source_file_path, t.language, t.archived_from,
|
|
736
|
+
t.output_hash, t.output_chars, t.timestamp, t.truncated,
|
|
737
|
+
t.index_truncated,
|
|
695
738
|
snippet(tool_outputs_fts, 6, '>>', '<<', '...', 16) AS snippet
|
|
696
739
|
FROM tool_outputs_fts f
|
|
697
740
|
JOIN tool_outputs t ON t.rowid = f.rowid
|
|
@@ -718,6 +761,8 @@ class SessionStore:
|
|
|
718
761
|
rows = conn.execute(
|
|
719
762
|
r"""SELECT tool_use_id, tool_name, command_or_path,
|
|
720
763
|
source_file_path, language, archived_from,
|
|
764
|
+
output_hash, output_chars, timestamp, truncated,
|
|
765
|
+
index_truncated,
|
|
721
766
|
substr(COALESCE(output_text, compressed_preview, ''), 1, 200) AS snippet
|
|
722
767
|
FROM tool_outputs
|
|
723
768
|
WHERE tool_name LIKE ? ESCAPE '\' OR command_or_path LIKE ? ESCAPE '\'
|
|
@@ -835,6 +880,15 @@ class SessionStore:
|
|
|
835
880
|
)
|
|
836
881
|
conn.commit()
|
|
837
882
|
|
|
883
|
+
def record_file_edit(self, file_path: str) -> None:
|
|
884
|
+
"""Keep edit evidence without persisting credential-shaped path text."""
|
|
885
|
+
fingerprint = hashlib.sha256(file_path.encode("utf-8")).hexdigest()
|
|
886
|
+
self.set_meta("checkpoint_edit:" + fingerprint, "1")
|
|
887
|
+
|
|
888
|
+
def was_file_edited(self, file_path: str) -> bool:
|
|
889
|
+
fingerprint = hashlib.sha256(file_path.encode("utf-8")).hexdigest()
|
|
890
|
+
return self.get_meta("checkpoint_edit:" + fingerprint) == "1"
|
|
891
|
+
|
|
838
892
|
# ----- context_intel_events -----
|
|
839
893
|
|
|
840
894
|
def insert_intel_event(
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// Token Optimizer - Claude Code Status Line (two-row layout)
|
|
3
3
|
//
|
|
4
4
|
// Row 1: model | effort | project | context bar used% | ContextQ:grade(score)
|
|
5
|
-
// Row 2: Eff:grade(score) | warnings | Compacts:N(
|
|
5
|
+
// Row 2: Eff:grade(score) | warnings | Compacts:N(observing) | duration | Agents
|
|
6
6
|
//
|
|
7
7
|
// Install: python3 measure.py setup-quality-bar
|
|
8
8
|
// The quality score is updated by a UserPromptSubmit hook every ~2 minutes.
|
|
@@ -555,15 +555,13 @@ process.stdin.on('end', () => {
|
|
|
555
555
|
}
|
|
556
556
|
}
|
|
557
557
|
|
|
558
|
-
//
|
|
558
|
+
// Recovery thresholds remain shadow-only until calibrated.
|
|
559
559
|
if (q) {
|
|
560
560
|
const c = q.compactions;
|
|
561
561
|
if (c != null) {
|
|
562
562
|
if (c > 0) {
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
const color = c <= 2 ? '\x1b[33m' : '\x1b[31m';
|
|
566
|
-
row2Parts.push(`${color}Compacts:${c}(${loss} lost)${RESET}`);
|
|
563
|
+
// Recovery evidence is shadow-only, even for older cached flags.
|
|
564
|
+
row2Parts.push(`${DIM}Compacts:${c}(observing)${RESET}`);
|
|
567
565
|
} else {
|
|
568
566
|
row2Parts.push(`\x1b[32mCompacts:0${RESET}`);
|
|
569
567
|
}
|