@alexgreensh/token-optimizer 5.13.62 → 5.13.64
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 +25 -4
- package/package.json +1 -1
- package/skills/fleet-auditor/SKILL.md +1 -1
- package/skills/fleet-auditor/scripts/fleet.py +4 -1
- package/skills/fleet-auditor/scripts/shared.py +31 -14
- 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 +571 -106
- 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/adapter_hook_command.py +94 -0
- package/skills/token-optimizer/scripts/antigravity_doctor.py +12 -0
- package/skills/token-optimizer/scripts/antigravity_hook_bridge.py +4 -0
- package/skills/token-optimizer/scripts/antigravity_install.py +9 -18
- package/skills/token-optimizer/scripts/antigravity_session.py +31 -6
- 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_install.py +5 -3
- package/skills/token-optimizer/scripts/codex_session.py +149 -1
- package/skills/token-optimizer/scripts/cursor_doctor.py +12 -27
- package/skills/token-optimizer/scripts/cursor_install.py +11 -19
- package/skills/token-optimizer/scripts/devin_source.py +3 -3
- package/skills/token-optimizer/scripts/grok_doctor.py +12 -24
- package/skills/token-optimizer/scripts/grok_install.py +9 -16
- package/skills/token-optimizer/scripts/measure.py +7300 -1642
- package/skills/token-optimizer/scripts/read_cache.py +52 -27
- package/skills/token-optimizer/scripts/recovery_output.py +67 -18
- package/skills/token-optimizer/scripts/refetch_guard.py +9 -3
- package/skills/token-optimizer/scripts/session_activity.py +169 -0
- package/skills/token-optimizer/scripts/session_store.py +127 -9
- package/skills/token-optimizer/scripts/statusline.js +4 -6
|
@@ -36,11 +36,14 @@ from plugin_env import is_v5_flag_enabled, resolve_snapshot_dir
|
|
|
36
36
|
from runtime_env import project_config_value, run_origin, runtime_home
|
|
37
37
|
|
|
38
38
|
try:
|
|
39
|
-
from session_store import SessionStore, cleanup_old_stores
|
|
39
|
+
from session_store import SessionStore, cleanup_old_stores, mark_context_reset
|
|
40
40
|
except ImportError:
|
|
41
41
|
SessionStore = None # type: ignore[assignment,misc]
|
|
42
42
|
cleanup_old_stores = None # type: ignore[assignment]
|
|
43
43
|
|
|
44
|
+
def mark_context_reset(*_a, **_k): # type: ignore[misc]
|
|
45
|
+
return None
|
|
46
|
+
|
|
44
47
|
try:
|
|
45
48
|
from credential_patterns import redact_credentials as _redact_creds
|
|
46
49
|
from credential_patterns import pop_redaction_warning as _pop_redaction_warning
|
|
@@ -330,9 +333,13 @@ DEFAULT_MODE = "soft_block"
|
|
|
330
333
|
MIN_STRUCTURE_CONFIDENCE = 0.75
|
|
331
334
|
MAX_CONSECUTIVE_DENIALS = 3
|
|
332
335
|
REASON_ONLY_TOKENS_EST = 10
|
|
333
|
-
# U-G3: conservative avoided-search
|
|
334
|
-
# straight to a file (~2 exploratory reads of ~2500 tokens it
|
|
335
|
-
# 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.
|
|
336
343
|
_HINT_FOLLOW_AVOIDED_TOKENS = 5000
|
|
337
344
|
STRICT_CONTEXT_CAPS = {
|
|
338
345
|
"signatures": 350,
|
|
@@ -1123,7 +1130,7 @@ def _first_read_compress(
|
|
|
1123
1130
|
source_file_path=_safe_path,
|
|
1124
1131
|
language=language,
|
|
1125
1132
|
archived_from="first_read_skeleton",
|
|
1126
|
-
output_text=_safe_skel
|
|
1133
|
+
output_text=_safe_skel,
|
|
1127
1134
|
)
|
|
1128
1135
|
except Exception:
|
|
1129
1136
|
pass
|
|
@@ -1464,9 +1471,11 @@ def handle_read(hook_input: dict[str, Any], mode: str, quiet: bool) -> None:
|
|
|
1464
1471
|
return
|
|
1465
1472
|
|
|
1466
1473
|
# U-G3: if a proactive prior-session hint surfaced this exact file to this
|
|
1467
|
-
# session, the agent reading it is observed evidence the hint
|
|
1468
|
-
# exploratory search
|
|
1469
|
-
#
|
|
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.
|
|
1470
1479
|
try:
|
|
1471
1480
|
if store.claim_hint_follow(file_path):
|
|
1472
1481
|
_log_savings_event(
|
|
@@ -1482,10 +1491,16 @@ def handle_read(hook_input: dict[str, Any], mode: str, quiet: bool) -> None:
|
|
|
1482
1491
|
# model's context: forget them so this Read is judged a first read.
|
|
1483
1492
|
try:
|
|
1484
1493
|
if _scan_for_compaction(store, hook_input.get("transcript_path")):
|
|
1485
|
-
|
|
1494
|
+
if hook_input.get("agent_id"):
|
|
1495
|
+
# A subagent keeps its own context; only its read ledger follows
|
|
1496
|
+
# the transcript's compaction marker.
|
|
1497
|
+
store.clear_file_entries()
|
|
1498
|
+
else:
|
|
1499
|
+
store.reset_context_state()
|
|
1500
|
+
mark_context_reset(session_id)
|
|
1486
1501
|
if not quiet:
|
|
1487
1502
|
print(
|
|
1488
|
-
f"[Read Cache] Compaction detected;
|
|
1503
|
+
f"[Read Cache] Compaction detected; reset context state for {session_id}",
|
|
1489
1504
|
file=sys.stderr,
|
|
1490
1505
|
)
|
|
1491
1506
|
except Exception:
|
|
@@ -2052,21 +2067,22 @@ def handle_read(hook_input: dict[str, Any], mode: str, quiet: bool) -> None:
|
|
|
2052
2067
|
|
|
2053
2068
|
|
|
2054
2069
|
def handle_clear_compacted(hook_input: dict[str, Any], quiet: bool) -> None:
|
|
2055
|
-
"""
|
|
2056
|
-
|
|
2057
|
-
Wired to SessionStart (
|
|
2058
|
-
flag, which reads ``session_id`` from the stdin hook
|
|
2059
|
-
the
|
|
2060
|
-
|
|
2061
|
-
|
|
2062
|
-
|
|
2063
|
-
|
|
2064
|
-
|
|
2065
|
-
(``
|
|
2066
|
-
|
|
2067
|
-
|
|
2068
|
-
|
|
2069
|
-
|
|
2070
|
+
"""Reset ONE session's "already in context" state after a /clear or compaction.
|
|
2071
|
+
|
|
2072
|
+
Wired to SessionStart (sources ``compact`` and ``clear``) via the
|
|
2073
|
+
``--clear-compacted`` flag, which reads ``session_id`` from the stdin hook
|
|
2074
|
+
input. Both events empty the model's context while the session id, and so the
|
|
2075
|
+
session store, lives on. Left alone, an unchanged file whose ``file_reads``
|
|
2076
|
+
row survives is judged redundant on the next Read and served as an outline or
|
|
2077
|
+
a block even though the model no longer holds it, and the same goes for
|
|
2078
|
+
delta baselines, cross-turn command outputs and repeat-command streaks.
|
|
2079
|
+
|
|
2080
|
+
Calls ``store.reset_context_state()`` (and stamps the re-fetch guard's reset
|
|
2081
|
+
marker) for the named session ONLY: other sessions and subagent stores are not
|
|
2082
|
+
touched. It never takes ``handle_clear``'s session-scoped branch, which also
|
|
2083
|
+
unlinks the decisions telemetry log (``_decisions_log_path``) and the legacy
|
|
2084
|
+
cache json; that would delete per-session decision/shadow telemetry on every
|
|
2085
|
+
reset.
|
|
2070
2086
|
|
|
2071
2087
|
Contention-safe: SessionStore connects fail-fast
|
|
2072
2088
|
(``busy_timeout=50ms``), so under a sibling SessionStart compact-restore or
|
|
@@ -2115,7 +2131,7 @@ def handle_clear_compacted(hook_input: dict[str, Any], quiet: bool) -> None:
|
|
|
2115
2131
|
# honored by _connect() for BOTH the schema init and the DELETE, so the
|
|
2116
2132
|
# clear waits out a sibling write lock within the hook budget instead
|
|
2117
2133
|
# of dying at the 50ms fail-fast default during _init_schema.
|
|
2118
|
-
store.
|
|
2134
|
+
store.reset_context_state()
|
|
2119
2135
|
except sqlite3.OperationalError as exc:
|
|
2120
2136
|
# LOUD failure: never a silent exit-0 no-op that resurrects the bug.
|
|
2121
2137
|
print(
|
|
@@ -2126,9 +2142,11 @@ def handle_clear_compacted(hook_input: dict[str, Any], quiet: bool) -> None:
|
|
|
2126
2142
|
return
|
|
2127
2143
|
finally:
|
|
2128
2144
|
store.close()
|
|
2145
|
+
if not hook_input.get("agent_id"):
|
|
2146
|
+
mark_context_reset(session_id)
|
|
2129
2147
|
if not quiet:
|
|
2130
2148
|
print(
|
|
2131
|
-
f"[Read Cache]
|
|
2149
|
+
f"[Read Cache] Reset session context state for {session_id}",
|
|
2132
2150
|
file=sys.stderr,
|
|
2133
2151
|
)
|
|
2134
2152
|
|
|
@@ -2193,6 +2211,13 @@ def handle_invalidate(hook_input: dict[str, Any], quiet: bool) -> None:
|
|
|
2193
2211
|
if store is None:
|
|
2194
2212
|
return
|
|
2195
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
|
+
|
|
2196
2221
|
# U5: resolve the first-read shadow quality proxy (edit-after-shadow-read).
|
|
2197
2222
|
_resolve_first_read_shadow_on_edit(
|
|
2198
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):
|
|
@@ -40,6 +40,7 @@ try:
|
|
|
40
40
|
)
|
|
41
41
|
from recovery_output import is_recovery_tool
|
|
42
42
|
from session_store import _sanitize_session_id as sanitize_sid
|
|
43
|
+
from session_store import context_reset_at
|
|
43
44
|
except Exception:
|
|
44
45
|
# If our own modules can't load, never block a tool call.
|
|
45
46
|
print(_NEUTRAL)
|
|
@@ -116,17 +117,21 @@ def _entry_is_renderable(archive_dir: Path, tool_use_id: str) -> bool:
|
|
|
116
117
|
return False
|
|
117
118
|
|
|
118
119
|
|
|
119
|
-
def _within_window(timestamp, now: float) -> bool:
|
|
120
|
+
def _within_window(timestamp, now: float, reset_at: float = 0.0) -> bool:
|
|
120
121
|
"""True when an archive entry's ISO timestamp is inside the guard window.
|
|
121
122
|
|
|
122
123
|
An unparseable or missing timestamp counts as OUTSIDE the window: the guard
|
|
123
|
-
only ever denies on proof, so doubt means allow.
|
|
124
|
+
only ever denies on proof, so doubt means allow. A result archived before the
|
|
125
|
+
session's last /clear or compaction is outside the window too: the model no
|
|
126
|
+
longer holds it, so re-running the call is not a loop. Never raises.
|
|
124
127
|
"""
|
|
125
128
|
try:
|
|
126
129
|
from datetime import datetime
|
|
127
130
|
ts = datetime.fromisoformat(str(timestamp)).timestamp()
|
|
128
131
|
except Exception:
|
|
129
132
|
return False
|
|
133
|
+
if ts <= reset_at:
|
|
134
|
+
return False
|
|
130
135
|
return 0 <= now - ts <= _guard_window_seconds()
|
|
131
136
|
|
|
132
137
|
|
|
@@ -159,11 +164,12 @@ def _lookup_archived(session_id: str, tool_name: str, fingerprint: str):
|
|
|
159
164
|
if not manifest.is_file() or manifest.is_symlink():
|
|
160
165
|
return None, 0
|
|
161
166
|
now = time.time()
|
|
167
|
+
reset_at = context_reset_at(session_id)
|
|
162
168
|
for entry in reversed(_read_manifest_tail(manifest)): # newest first
|
|
163
169
|
if entry.get("tool_name") == tool_name and entry.get(ARGS_HASH_KEY) == fingerprint:
|
|
164
170
|
# Newest match is too old: every older one is too, and an old
|
|
165
171
|
# identical call is a deliberate re-check of live data, not a loop.
|
|
166
|
-
if not _within_window(entry.get("timestamp"), now):
|
|
172
|
+
if not _within_window(entry.get("timestamp"), now, reset_at):
|
|
167
173
|
return None, 0
|
|
168
174
|
tool_use_id = entry.get("tool_use_id")
|
|
169
175
|
if tool_use_id and _entry_is_renderable(archive_dir, tool_use_id):
|
|
@@ -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
|