@alexgreensh/token-optimizer 5.13.63 → 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 +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
|
@@ -0,0 +1,385 @@
|
|
|
1
|
+
"""Versioned task-state extraction for session checkpoints.
|
|
2
|
+
|
|
3
|
+
gap-checkpoint (arxiv-2611.05306 findings §3.1 + §4): a checkpoint must carry a
|
|
4
|
+
versioned, source-backed picture of WHERE the task stands — objective, open
|
|
5
|
+
requirements with status, verified facts vs assumptions, checks with outcomes,
|
|
6
|
+
dead ends, the immediate next action and the done condition — not just the
|
|
7
|
+
last user/assistant lines cut to 300 chars.
|
|
8
|
+
|
|
9
|
+
Determinism contract: every field is derived from observable transcript
|
|
10
|
+
events (user messages, tool calls, tool results, todo snapshots). Nothing is
|
|
11
|
+
inferred semantically; fields with no observable basis are named in
|
|
12
|
+
``unknown_fields`` instead of being guessed. All text arriving here is
|
|
13
|
+
already credential-redacted by the caller; this module never sees raw
|
|
14
|
+
transcript secrets.
|
|
15
|
+
|
|
16
|
+
The module is stdlib-only and shared by every adapter (Claude JSONL,
|
|
17
|
+
Codex rollout, Hermes translated transcripts) so all hosts emit the same
|
|
18
|
+
sidecar shape.
|
|
19
|
+
"""
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import re
|
|
23
|
+
from typing import Any, Iterable
|
|
24
|
+
|
|
25
|
+
TASK_STATE_VERSION = 2
|
|
26
|
+
|
|
27
|
+
# Bounds: the sidecar is JSON and the .md renderer applies its own budget, but
|
|
28
|
+
# the extractor itself must stay small enough to serialize cheaply on every
|
|
29
|
+
# Stop/SessionEnd hook fire.
|
|
30
|
+
_MAX_CONSTRAINTS = 12
|
|
31
|
+
_MAX_REQUIREMENTS = 20
|
|
32
|
+
_MAX_FACTS = 8
|
|
33
|
+
_MAX_CHECKS = 15
|
|
34
|
+
_MAX_DEAD_ENDS = 8
|
|
35
|
+
_MAX_ASSUMPTIONS = 8
|
|
36
|
+
_MAX_CHANGED_FILES = 20
|
|
37
|
+
_TEXT = 400 # per-item text cap
|
|
38
|
+
OBJECTIVE_MAX_CHARS = 1500
|
|
39
|
+
|
|
40
|
+
# Constraint cues in USER text. Deliberately conservative: a false positive
|
|
41
|
+
# costs one extra preserved line, a false negative can drop the only stated
|
|
42
|
+
# constraint, so the pattern list errs toward recall.
|
|
43
|
+
_CONSTRAINT_RE = re.compile(
|
|
44
|
+
r"\b(?:must(?:n['’]t|\s+not)?|never|always|do(?:es)?\s+not|don['’]t|"
|
|
45
|
+
r"should(?:\s+not|n['’]t)?|cannot|can['’]t|won['’]t|shall|required|"
|
|
46
|
+
r"requirement|constraint|forbidden|avoid|only|no\s+more\s+than|"
|
|
47
|
+
r"at\s+most|exactly|without|must\s+keep|do\s+not\s+dare)\b",
|
|
48
|
+
re.IGNORECASE,
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
# Hedge cues in ASSISTANT text. Assumptions are the complement of verified
|
|
52
|
+
# facts: the model saying "probably"/"I assume" is an observable transcript
|
|
53
|
+
# signal, so it is extracted (never inferred) and kept distinct from facts.
|
|
54
|
+
_ASSUMPTION_RE = re.compile(
|
|
55
|
+
r"\b(?:i\s+assume|assuming|presumably|probably|i\s+think|i\s+believe|"
|
|
56
|
+
r"might|may\s+be|not\s+sure|unclear|appears\s+to|seems\s+to|guess)\b",
|
|
57
|
+
re.IGNORECASE,
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
# A check only counts as a "verified fact" when the tool looks like a
|
|
61
|
+
# verification step (test/build/lint run), not any successful command.
|
|
62
|
+
_VERIFY_RE = re.compile(
|
|
63
|
+
r"(?:^|[;&|])\s*(?:env\s+)?(?:[A-Za-z_]\w*=\S+\s+)*"
|
|
64
|
+
r"(?:[^\s;|&]*[/\\])?(?:"
|
|
65
|
+
r"python(?:\d+(?:\.\d+)*)?\s+-m\s+(?:pytest|unittest)|"
|
|
66
|
+
r"pytest|py\.test|ctest|rspec|jest|vitest|mypy|eslint|ruff\s+check|"
|
|
67
|
+
r"(?:npm|pnpm|yarn|bun)\s+(?:test|build|lint|check|run\s+(?:test|build|lint|check))|"
|
|
68
|
+
r"(?:npx|pnpm\s+exec|bunx)\s+(?:jest|vitest|eslint|tsc)|"
|
|
69
|
+
r"cargo\s+(?:test|check|build|clippy)|go\s+(?:test|build|vet)|"
|
|
70
|
+
r"make\s+(?:test|check|build|lint|all)|mvn\s+(?:test|verify|package)|"
|
|
71
|
+
r"gradle\s+(?:test|check|build)|tsc)(?=\s|$)",
|
|
72
|
+
re.IGNORECASE,
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
_FAIL_RE = re.compile(
|
|
76
|
+
r"traceback \(most recent call last\)|\bcommand not found\b|"
|
|
77
|
+
r"\bcannot find\b|\b[1-9]\d*\s+failed\b|\bFAILED\b|\berror:\s|"
|
|
78
|
+
r"\bexit(?:ed)?\s+(?:with\s+)?(?:code\s+)?[1-9]",
|
|
79
|
+
re.IGNORECASE,
|
|
80
|
+
)
|
|
81
|
+
_PASS_RE = re.compile(
|
|
82
|
+
r"\b\d+\s+passed\b|\b0\s+failed\b|\btest result:\s*ok\b|"
|
|
83
|
+
r"^\s*(?:all (?:checks|tests) passed|BUILD SUCCESS(?:FUL)?|Build succeeded)\b|"
|
|
84
|
+
r"^\s*PASS(?:\s|$)|^ok\s+\S+|^OK\s*$|^Found 0 errors\b",
|
|
85
|
+
re.IGNORECASE | re.MULTILINE,
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
_DONE_STATUSES = {"completed", "done", "complete"}
|
|
89
|
+
_IN_PROGRESS_STATUSES = {"in_progress", "in-progress", "in progress"}
|
|
90
|
+
_OPEN_STATUSES = _IN_PROGRESS_STATUSES | {"pending", "todo", "open"}
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _clip(text: Any, limit: int = _TEXT) -> str:
|
|
94
|
+
"""Whitespace-collapse and cap a transcript string."""
|
|
95
|
+
return " ".join(str(text or "").split())[:limit]
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _src(kind: str, ident: Any = None) -> dict[str, Any]:
|
|
99
|
+
return {"kind": kind, "id": str(ident) if ident is not None else None}
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _norm(text: Any) -> str:
|
|
103
|
+
return " ".join(str(text or "").lower().split())
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _sentences(text: str) -> list[str]:
|
|
107
|
+
return [s.strip() for s in re.split(r"(?<=[.!?])\s+|\n+", text) if s.strip()]
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def result_excerpt(text: str) -> str:
|
|
111
|
+
"""Bound already-redacted output while retaining runner summary tails."""
|
|
112
|
+
if len(text) <= 2000:
|
|
113
|
+
return text
|
|
114
|
+
return text[:500] + "\n…\n" + text[-1500:]
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _check_outcome(is_error: Any, exit_code: Any, text: str) -> tuple[str, bool]:
|
|
118
|
+
"""(outcome, explicit_success) for one tool call/result pair.
|
|
119
|
+
|
|
120
|
+
``explicit_success`` requires a pass marker in the summary tail. Exit 0
|
|
121
|
+
completes a check but alone cannot make its target a verified fact.
|
|
122
|
+
"""
|
|
123
|
+
if is_error or (exit_code is not None and exit_code != 0):
|
|
124
|
+
return "failed", False
|
|
125
|
+
t = (text or "")[-1500:]
|
|
126
|
+
fail_hits = len(_FAIL_RE.findall(t))
|
|
127
|
+
pass_hits = len(_PASS_RE.findall(t))
|
|
128
|
+
if fail_hits and fail_hits >= pass_hits:
|
|
129
|
+
return "failed", False
|
|
130
|
+
if pass_hits or exit_code == 0:
|
|
131
|
+
return "completed", bool(pass_hits)
|
|
132
|
+
return "unknown", False
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _looks_like_verification(tool: str, target: str) -> bool:
|
|
136
|
+
return bool(_VERIFY_RE.search(target))
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def build_task_state(
|
|
140
|
+
*,
|
|
141
|
+
user_texts: Iterable[tuple[str, str | None]] = (),
|
|
142
|
+
assistant_texts: Iterable[tuple[str, str | None]] = (),
|
|
143
|
+
tool_calls: Iterable[dict[str, Any]] = (),
|
|
144
|
+
tool_results: Iterable[dict[str, Any]] = (),
|
|
145
|
+
todos: Iterable[tuple[str, str]] = (),
|
|
146
|
+
changed_files: Iterable[tuple[str, str]] = (),
|
|
147
|
+
archive_pointers: Iterable[str] = (),
|
|
148
|
+
objective: dict[str, Any] | None = None,
|
|
149
|
+
) -> dict[str, Any]:
|
|
150
|
+
"""Assemble the versioned task_state dict (sidecar schema v2).
|
|
151
|
+
|
|
152
|
+
All inputs are already-redacted, normalized observations:
|
|
153
|
+
|
|
154
|
+
- ``user_texts`` / ``assistant_texts``: ``(text, source_id)`` pairs in
|
|
155
|
+
transcript order.
|
|
156
|
+
- ``tool_calls``: ``{"id", "name", "target"}`` in transcript order.
|
|
157
|
+
- ``tool_results``: ``{"tool_use_id", "is_error", "exit_code", "text"}``.
|
|
158
|
+
- ``todos``: ``(content, status)`` latest snapshot.
|
|
159
|
+
- ``changed_files``: ``(path, op)`` file-mutating tool observations.
|
|
160
|
+
- ``objective``: ``{"text", "source"}`` from the caller's head-scan of the
|
|
161
|
+
FIRST user message; ``None`` when the transcript has none.
|
|
162
|
+
"""
|
|
163
|
+
user_texts = [(str(t).strip(), sid) for t, sid in user_texts if t and str(t).strip()]
|
|
164
|
+
assistant_texts = [(_clip(t, 500), sid) for t, sid in assistant_texts if _clip(t, 500)]
|
|
165
|
+
tool_calls = [c for c in tool_calls if isinstance(c, dict) and c.get("id")]
|
|
166
|
+
tool_results = [r for r in tool_results if isinstance(r, dict)]
|
|
167
|
+
todos = [( _clip(c, 160), str(s or "").strip().lower()) for c, s in todos if _clip(c, 160)]
|
|
168
|
+
|
|
169
|
+
# --- objective: the FIRST user message (head-scan), never the last "continue".
|
|
170
|
+
if objective and objective.get("text"):
|
|
171
|
+
objective_obj = {
|
|
172
|
+
"text": _clip(objective["text"], OBJECTIVE_MAX_CHARS),
|
|
173
|
+
"source": objective.get("source") or _src("user_message"),
|
|
174
|
+
}
|
|
175
|
+
elif user_texts:
|
|
176
|
+
# Fallback: first user text observed in the extraction window. For
|
|
177
|
+
# sessions within the tail window this IS the first message.
|
|
178
|
+
objective_obj = {"text": _clip(user_texts[0][0], OBJECTIVE_MAX_CHARS),
|
|
179
|
+
"source": _src("user_message", user_texts[0][1])}
|
|
180
|
+
else:
|
|
181
|
+
objective_obj = None
|
|
182
|
+
|
|
183
|
+
# --- user constraints: pattern-extracted candidates from user messages.
|
|
184
|
+
constraints: list[dict[str, Any]] = []
|
|
185
|
+
seen_constraints: set[str] = set()
|
|
186
|
+
constraint_inputs = [
|
|
187
|
+
(text, _src("user_message", sid)) for text, sid in user_texts]
|
|
188
|
+
if objective and objective.get("text"):
|
|
189
|
+
constraint_inputs.insert(0, (str(objective["text"]), objective_obj["source"]))
|
|
190
|
+
for text, source in constraint_inputs:
|
|
191
|
+
for sent in _sentences(text):
|
|
192
|
+
sent = " ".join(sent.split())
|
|
193
|
+
cue = _CONSTRAINT_RE.search(sent)
|
|
194
|
+
if not cue:
|
|
195
|
+
continue
|
|
196
|
+
# A cue beyond the sentence cap must not disappear behind its
|
|
197
|
+
# background prefix. Preserve nearby context and mark the excerpt.
|
|
198
|
+
start = max(0, cue.start() - 60) if cue.end() > 300 else 0
|
|
199
|
+
clip = _clip(("… " if start else "") + sent[start:], 300)
|
|
200
|
+
key = _norm(clip)
|
|
201
|
+
if key in seen_constraints:
|
|
202
|
+
continue
|
|
203
|
+
seen_constraints.add(key)
|
|
204
|
+
constraints.append({"text": clip, "source": source})
|
|
205
|
+
if len(constraints) >= _MAX_CONSTRAINTS:
|
|
206
|
+
break
|
|
207
|
+
if len(constraints) >= _MAX_CONSTRAINTS:
|
|
208
|
+
break
|
|
209
|
+
|
|
210
|
+
# --- requirements: latest todo snapshot, with explicit status.
|
|
211
|
+
requirements = [
|
|
212
|
+
{"text": text, "status": status or "unknown",
|
|
213
|
+
"source": _src("todo_snapshot")}
|
|
214
|
+
for text, status in todos[:_MAX_REQUIREMENTS]
|
|
215
|
+
]
|
|
216
|
+
|
|
217
|
+
# --- checks: pair each tool call with its result, in transcript order.
|
|
218
|
+
results_by_id: dict[str, dict[str, Any]] = {}
|
|
219
|
+
for r in tool_results:
|
|
220
|
+
rid = str(r.get("tool_use_id") or "")
|
|
221
|
+
if not rid:
|
|
222
|
+
continue
|
|
223
|
+
previous = results_by_id.get(rid)
|
|
224
|
+
if previous is None:
|
|
225
|
+
results_by_id[rid] = dict(r)
|
|
226
|
+
elif r.get("exit_code") is not None:
|
|
227
|
+
results_by_id[rid] = dict(r, text=r.get("text") or previous.get("text") or "")
|
|
228
|
+
elif previous.get("exit_code") is None:
|
|
229
|
+
results_by_id[rid] = dict(r, is_error=bool(r.get("is_error") or previous.get("is_error")),
|
|
230
|
+
text=r.get("text") or previous.get("text") or "")
|
|
231
|
+
elif not previous.get("text"):
|
|
232
|
+
previous["text"] = r.get("text") or ""
|
|
233
|
+
|
|
234
|
+
checks: list[dict[str, Any]] = []
|
|
235
|
+
succeeded_targets: set[str] = set()
|
|
236
|
+
for call in tool_calls[-40:]:
|
|
237
|
+
cid = str(call.get("id"))
|
|
238
|
+
res = results_by_id.get(cid, {})
|
|
239
|
+
outcome, explicit = _check_outcome(
|
|
240
|
+
res.get("is_error"), res.get("exit_code"), str(res.get("text") or ""))
|
|
241
|
+
target = _clip(call.get("target"), 200)
|
|
242
|
+
checks.append({
|
|
243
|
+
"tool": _clip(call.get("name"), 60),
|
|
244
|
+
"target": target,
|
|
245
|
+
"outcome": outcome,
|
|
246
|
+
"explicit_success": explicit,
|
|
247
|
+
"source_id": cid,
|
|
248
|
+
"source": _src("tool_result", cid),
|
|
249
|
+
})
|
|
250
|
+
if outcome == "completed":
|
|
251
|
+
succeeded_targets.add(_norm(f"{call.get('name')} {target}"))
|
|
252
|
+
succeeded_targets.add(_norm(target))
|
|
253
|
+
checks = checks[-_MAX_CHECKS:]
|
|
254
|
+
|
|
255
|
+
# --- verified facts: only explicit successes on verification-looking tools.
|
|
256
|
+
verified_facts: list[dict[str, Any]] = []
|
|
257
|
+
seen_facts: set[str] = set()
|
|
258
|
+
for chk in checks:
|
|
259
|
+
if chk["outcome"] != "completed" or not chk["explicit_success"]:
|
|
260
|
+
continue
|
|
261
|
+
if not _looks_like_verification(chk["tool"], chk["target"]):
|
|
262
|
+
continue
|
|
263
|
+
label = chk["target"] or chk["tool"]
|
|
264
|
+
text = _clip(f"{chk['tool']}: {label} — passed", 300)
|
|
265
|
+
key = _norm(text)
|
|
266
|
+
if key in seen_facts:
|
|
267
|
+
continue
|
|
268
|
+
seen_facts.add(key)
|
|
269
|
+
verified_facts.append({"text": text, "source": chk["source"]})
|
|
270
|
+
if len(verified_facts) >= _MAX_FACTS:
|
|
271
|
+
break
|
|
272
|
+
|
|
273
|
+
# --- dead ends: failed checks never later superseded by a success on the
|
|
274
|
+
# same target. Read frequency is irrelevant here — a hot dead end is
|
|
275
|
+
# still a dead end.
|
|
276
|
+
dead_ends: list[dict[str, Any]] = []
|
|
277
|
+
seen_dead: set[str] = set()
|
|
278
|
+
for chk in checks:
|
|
279
|
+
if chk["outcome"] != "failed":
|
|
280
|
+
continue
|
|
281
|
+
tnorm = _norm(f"{chk['tool']} {chk['target']}")
|
|
282
|
+
tnorm_target = _norm(chk["target"])
|
|
283
|
+
if tnorm in succeeded_targets or (tnorm_target and tnorm_target in succeeded_targets):
|
|
284
|
+
continue # the approach eventually worked — not a dead end
|
|
285
|
+
text = _clip(f"failed: {chk['tool']} {chk['target']}", 300)
|
|
286
|
+
key = _norm(text)
|
|
287
|
+
if key in seen_dead:
|
|
288
|
+
continue
|
|
289
|
+
seen_dead.add(key)
|
|
290
|
+
dead_ends.append({
|
|
291
|
+
"text": text,
|
|
292
|
+
"tool": chk["tool"],
|
|
293
|
+
"target": chk["target"],
|
|
294
|
+
"source": chk["source"],
|
|
295
|
+
})
|
|
296
|
+
if len(dead_ends) >= _MAX_DEAD_ENDS:
|
|
297
|
+
break
|
|
298
|
+
|
|
299
|
+
# --- assumptions: hedged statements observable in assistant text.
|
|
300
|
+
assumptions: list[dict[str, Any]] = []
|
|
301
|
+
seen_assume: set[str] = set()
|
|
302
|
+
for text, sid in assistant_texts:
|
|
303
|
+
for sent in _sentences(text):
|
|
304
|
+
if not _ASSUMPTION_RE.search(sent):
|
|
305
|
+
continue
|
|
306
|
+
clip = _clip(sent, 300)
|
|
307
|
+
key = _norm(clip)
|
|
308
|
+
if key in seen_assume:
|
|
309
|
+
continue
|
|
310
|
+
seen_assume.add(key)
|
|
311
|
+
assumptions.append({"text": clip, "source": _src("assistant_message", sid)})
|
|
312
|
+
if len(assumptions) >= _MAX_ASSUMPTIONS:
|
|
313
|
+
break
|
|
314
|
+
if len(assumptions) >= _MAX_ASSUMPTIONS:
|
|
315
|
+
break
|
|
316
|
+
|
|
317
|
+
# --- changed files: deterministic mutation observations only.
|
|
318
|
+
changed = [
|
|
319
|
+
{"path": _clip(p, 400), "op": _clip(op, 40) or "modified",
|
|
320
|
+
"source": _src("tool_use")}
|
|
321
|
+
for p, op in list(changed_files)[:_MAX_CHANGED_FILES]
|
|
322
|
+
if _clip(p, 400)
|
|
323
|
+
]
|
|
324
|
+
|
|
325
|
+
# --- next action: first open requirement (in_progress beats pending),
|
|
326
|
+
# else the last assistant statement (marked as such — a claim, not state).
|
|
327
|
+
next_action = None
|
|
328
|
+
for wanted in (_IN_PROGRESS_STATUSES, _OPEN_STATUSES - _IN_PROGRESS_STATUSES):
|
|
329
|
+
for req in requirements:
|
|
330
|
+
if str(req.get("status") or "").lower() in wanted:
|
|
331
|
+
next_action = {
|
|
332
|
+
"text": _clip(req["text"], 300),
|
|
333
|
+
"basis": "requirements",
|
|
334
|
+
"source": req["source"],
|
|
335
|
+
}
|
|
336
|
+
break
|
|
337
|
+
if next_action:
|
|
338
|
+
break
|
|
339
|
+
if next_action is None and assistant_texts:
|
|
340
|
+
last_text, last_sid = assistant_texts[-1]
|
|
341
|
+
next_action = {
|
|
342
|
+
"text": _clip(last_text, 300),
|
|
343
|
+
"basis": "assistant_statement",
|
|
344
|
+
"source": _src("assistant_message", last_sid),
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
# --- done condition: only when EVERY tracked requirement reports done.
|
|
348
|
+
done_condition = None
|
|
349
|
+
if todos and all(s in _DONE_STATUSES for _, s in todos):
|
|
350
|
+
done_condition = {
|
|
351
|
+
"text": f"all {len(todos)} tracked requirements marked completed",
|
|
352
|
+
"basis": "todo_snapshot",
|
|
353
|
+
"source": _src("todo_snapshot"),
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
# --- unknowns: named, never guessed.
|
|
357
|
+
unknown_fields: list[str] = []
|
|
358
|
+
if not objective_obj:
|
|
359
|
+
unknown_fields.append("objective")
|
|
360
|
+
if not constraint_inputs:
|
|
361
|
+
unknown_fields.append("user_constraints")
|
|
362
|
+
if not todos:
|
|
363
|
+
unknown_fields.append("requirements")
|
|
364
|
+
if not next_action:
|
|
365
|
+
unknown_fields.append("next_action")
|
|
366
|
+
if not done_condition:
|
|
367
|
+
unknown_fields.append("done_condition")
|
|
368
|
+
if not assumptions:
|
|
369
|
+
unknown_fields.append("assumptions")
|
|
370
|
+
|
|
371
|
+
return {
|
|
372
|
+
"version": TASK_STATE_VERSION,
|
|
373
|
+
"objective": objective_obj,
|
|
374
|
+
"user_constraints": constraints,
|
|
375
|
+
"requirements": requirements,
|
|
376
|
+
"verified_facts": verified_facts,
|
|
377
|
+
"assumptions": assumptions,
|
|
378
|
+
"changed_files": changed,
|
|
379
|
+
"checks": checks,
|
|
380
|
+
"dead_ends": dead_ends,
|
|
381
|
+
"next_action": next_action,
|
|
382
|
+
"done_condition": done_condition,
|
|
383
|
+
"archive_pointers": [_clip(p, 300) for p in archive_pointers if _clip(p, 300)][:20],
|
|
384
|
+
"unknown_fields": unknown_fields,
|
|
385
|
+
}
|
|
@@ -20,6 +20,8 @@ from typing import Any
|
|
|
20
20
|
|
|
21
21
|
from runtime_env import codex_home
|
|
22
22
|
|
|
23
|
+
import checkpoint_state
|
|
24
|
+
|
|
23
25
|
CHARS_PER_TOKEN = 4
|
|
24
26
|
MAX_PARSE_FILE_BYTES = 96 * 1024 * 1024
|
|
25
27
|
LARGE_FILE_TAIL_BYTES = 8 * 1024 * 1024
|
|
@@ -457,6 +459,8 @@ def _parse_session_records(records, incomplete=False, sampled=False):
|
|
|
457
459
|
previous_usage: dict[str, int] | None = None
|
|
458
460
|
current_model = _UNKNOWN_MODEL
|
|
459
461
|
per_model_usage: dict[str, dict[str, int]] = {}
|
|
462
|
+
daily_usage: dict[str, dict[str, dict[str, int]]] = {}
|
|
463
|
+
daily_calls: dict[str, int] = {}
|
|
460
464
|
rate_limits_latest: dict[str, Any] | None = None
|
|
461
465
|
effort_counts: dict[str, int] = {}
|
|
462
466
|
tool_durations_ms: list[float] = []
|
|
@@ -532,6 +536,14 @@ def _parse_session_records(records, incomplete=False, sampled=False):
|
|
|
532
536
|
bucket["fresh_input"] += max(0, turn_usage["input_tokens"] - turn_usage["cached_input_tokens"])
|
|
533
537
|
bucket["cache_read"] += max(0, turn_usage["cached_input_tokens"])
|
|
534
538
|
bucket["output"] += max(0, turn_usage["output_tokens"])
|
|
539
|
+
day = ts.astimezone().date().isoformat() if ts else "undated"
|
|
540
|
+
day_bucket = daily_usage.setdefault(day, {}).setdefault(model_key, {
|
|
541
|
+
"fresh_input": 0, "cache_read": 0, "cache_create": 0, "output": 0})
|
|
542
|
+
day_bucket["fresh_input"] += max(0, turn_usage["input_tokens"] - turn_usage["cached_input_tokens"])
|
|
543
|
+
day_bucket["cache_read"] += max(0, turn_usage["cached_input_tokens"])
|
|
544
|
+
day_bucket["output"] += max(0, turn_usage["output_tokens"])
|
|
545
|
+
if turn_usage['input_tokens'] or turn_usage['output_tokens']:
|
|
546
|
+
daily_calls[day] = daily_calls.get(day, 0) + 1
|
|
535
547
|
if turn_usage['input_tokens'] or turn_usage['output_tokens']:
|
|
536
548
|
bucket.setdefault('requests', []).append({
|
|
537
549
|
'fresh_input': max(0, turn_usage['input_tokens'] - turn_usage['cached_input_tokens']),
|
|
@@ -652,6 +664,8 @@ def _parse_session_records(records, incomplete=False, sampled=False):
|
|
|
652
664
|
"p95_call_gap_seconds": None,
|
|
653
665
|
"model_usage": model_usage,
|
|
654
666
|
"model_usage_breakdown": model_usage_breakdown,
|
|
667
|
+
"daily_usage": daily_usage,
|
|
668
|
+
"daily_calls": daily_calls,
|
|
655
669
|
"skills_used": skills_used,
|
|
656
670
|
"subagents_used": subagents_used,
|
|
657
671
|
"tool_calls": tool_calls,
|
|
@@ -735,17 +749,25 @@ def parse_jsonl_for_quality(filepath: str | Path) -> dict[str, Any] | None:
|
|
|
735
749
|
agent_dispatches: list[tuple[int, int, int]] = []
|
|
736
750
|
decisions: list[tuple[int, str]] = []
|
|
737
751
|
compaction_ratios: list[dict[str, Any]] = []
|
|
752
|
+
compaction_events: list[dict[str, Any]] = []
|
|
738
753
|
last_usage: dict[str, int] | None = None
|
|
739
754
|
current_model = _UNKNOWN_MODEL
|
|
740
755
|
topics: dict[str, str | None] = {}
|
|
741
756
|
idx = 0
|
|
742
757
|
prev_was_compacted = False
|
|
743
758
|
last_turn_context: int | None = None
|
|
759
|
+
safe_pause = False
|
|
744
760
|
|
|
745
761
|
for record in _iter_json_records(filepath):
|
|
746
762
|
payload = _payload(record)
|
|
747
763
|
payload_type = payload.get("type")
|
|
748
764
|
ts = str(record.get("timestamp") or "")
|
|
765
|
+
if payload_type in {"task_complete", "turn_complete"}:
|
|
766
|
+
safe_pause = True
|
|
767
|
+
elif payload_type in {"task_started", "turn_started", "function_call", "custom_tool_call",
|
|
768
|
+
"function_call_output", "custom_tool_call_output", "exec_command_end",
|
|
769
|
+
"patch_apply_end", "agent_message"}:
|
|
770
|
+
safe_pause = False
|
|
749
771
|
|
|
750
772
|
model = _extract_model(payload)
|
|
751
773
|
if model:
|
|
@@ -759,8 +781,31 @@ def parse_jsonl_for_quality(filepath: str | Path) -> dict[str, Any] | None:
|
|
|
759
781
|
# keeps the count==len(ratios) invariant even for back-to-back compactions.
|
|
760
782
|
is_compacted_record = record.get("type") == "compacted"
|
|
761
783
|
if is_compacted_record or payload_type == "context_compacted":
|
|
784
|
+
safe_pause = False
|
|
762
785
|
if is_compacted_record:
|
|
763
786
|
compactions += 1
|
|
787
|
+
# Minimal recovery event for the quality panel: Codex has no
|
|
788
|
+
# matched pre/post tool-call windows, so window_data=False
|
|
789
|
+
# keeps every boundary honestly "unmeasurable" rather than
|
|
790
|
+
# implying healthy recovery.
|
|
791
|
+
compaction_events.append({
|
|
792
|
+
"boundary_id": f"codex-{compactions}",
|
|
793
|
+
"ordinal": compactions,
|
|
794
|
+
"line": idx,
|
|
795
|
+
"ts": ts,
|
|
796
|
+
"trigger": "auto",
|
|
797
|
+
"pre_tokens": last_turn_context,
|
|
798
|
+
"post_tokens": None,
|
|
799
|
+
"host_version": None,
|
|
800
|
+
"model": current_model if current_model != _UNKNOWN_MODEL else None,
|
|
801
|
+
"pre_seg_calls": 0,
|
|
802
|
+
"post_seg_calls": 0,
|
|
803
|
+
"matched_calls": 0,
|
|
804
|
+
"eligible": False,
|
|
805
|
+
"window_data": False,
|
|
806
|
+
"restore_transcript": False,
|
|
807
|
+
"capture_notice": False,
|
|
808
|
+
})
|
|
764
809
|
rh = payload.get("replacement_history")
|
|
765
810
|
# Codex total_token_usage is cumulative (monotonic), so it does
|
|
766
811
|
# not drop at compaction. The meaningful "before" is the context
|
|
@@ -778,6 +823,24 @@ def parse_jsonl_for_quality(filepath: str | Path) -> dict[str, Any] | None:
|
|
|
778
823
|
})
|
|
779
824
|
elif not prev_was_compacted:
|
|
780
825
|
compactions += 1
|
|
826
|
+
compaction_events.append({
|
|
827
|
+
"boundary_id": f"codex-{compactions}",
|
|
828
|
+
"ordinal": compactions,
|
|
829
|
+
"line": idx,
|
|
830
|
+
"ts": ts,
|
|
831
|
+
"trigger": "auto",
|
|
832
|
+
"pre_tokens": last_turn_context,
|
|
833
|
+
"post_tokens": None,
|
|
834
|
+
"host_version": None,
|
|
835
|
+
"model": current_model if current_model != _UNKNOWN_MODEL else None,
|
|
836
|
+
"pre_seg_calls": 0,
|
|
837
|
+
"post_seg_calls": 0,
|
|
838
|
+
"matched_calls": 0,
|
|
839
|
+
"eligible": False,
|
|
840
|
+
"window_data": False,
|
|
841
|
+
"restore_transcript": False,
|
|
842
|
+
"capture_notice": False,
|
|
843
|
+
})
|
|
781
844
|
prev_was_compacted = is_compacted_record
|
|
782
845
|
reads = []
|
|
783
846
|
writes = []
|
|
@@ -807,6 +870,7 @@ def parse_jsonl_for_quality(filepath: str | Path) -> dict[str, Any] | None:
|
|
|
807
870
|
elif payload_type in {"user_message", "message", "agent_message"}:
|
|
808
871
|
text = _extract_text(payload)
|
|
809
872
|
role = "assistant" if payload_type == "agent_message" else str(payload.get("role") or "user")
|
|
873
|
+
safe_pause = role == "user" and bool(_task_user_text(text))
|
|
810
874
|
if role == "user" and not topics.get(payload_type):
|
|
811
875
|
task = _task_user_text(text)
|
|
812
876
|
if task:
|
|
@@ -856,10 +920,12 @@ def parse_jsonl_for_quality(filepath: str | Path) -> dict[str, Any] | None:
|
|
|
856
920
|
"tool_results": tool_results,
|
|
857
921
|
"system_reminders": system_reminders,
|
|
858
922
|
"messages": messages,
|
|
923
|
+
"safe_pause": safe_pause,
|
|
859
924
|
"compactions": compactions,
|
|
860
925
|
"agent_dispatches": agent_dispatches,
|
|
861
926
|
"decisions": decisions,
|
|
862
927
|
"compaction_ratios": compaction_ratios,
|
|
928
|
+
"compaction_events": compaction_events,
|
|
863
929
|
"total_entries": idx,
|
|
864
930
|
"estimated": True,
|
|
865
931
|
"context_tokens": last_turn_context or None,
|
|
@@ -964,6 +1030,12 @@ def extract_session_state(filepath: str | Path, tail_lines: int = 500, max_files
|
|
|
964
1030
|
last_assistant_msg = ""
|
|
965
1031
|
seen_files: set[str] = set()
|
|
966
1032
|
recent_errors: list[str] = []
|
|
1033
|
+
# Versioned task-state observations (checkpoint_state.build_task_state) —
|
|
1034
|
+
# same normalized shape the Claude extractor feeds it.
|
|
1035
|
+
user_texts: list[tuple[str, Any]] = []
|
|
1036
|
+
assistant_texts: list[tuple[str, Any]] = []
|
|
1037
|
+
tool_calls: list[dict[str, Any]] = []
|
|
1038
|
+
tool_results: list[dict[str, Any]] = []
|
|
967
1039
|
|
|
968
1040
|
records: deque[dict[str, Any]] = deque(maxlen=tail_lines)
|
|
969
1041
|
for record in _iter_json_records(filepath):
|
|
@@ -988,10 +1060,16 @@ def extract_session_state(filepath: str | Path, tail_lines: int = 500, max_files
|
|
|
988
1060
|
if role == "user":
|
|
989
1061
|
if _task_user_text(text):
|
|
990
1062
|
last_user_msg = text
|
|
1063
|
+
user_texts.append((text, payload.get("id") or payload.get("message_id")))
|
|
1064
|
+
if len(user_texts) > 80:
|
|
1065
|
+
user_texts.pop(0)
|
|
991
1066
|
else:
|
|
992
1067
|
continue # injected context: not a task, not a question
|
|
993
1068
|
elif role == "assistant":
|
|
994
1069
|
last_assistant_msg = text
|
|
1070
|
+
assistant_texts.append((text, payload.get("id") or payload.get("message_id")))
|
|
1071
|
+
if len(assistant_texts) > 60:
|
|
1072
|
+
assistant_texts.pop(0)
|
|
995
1073
|
_append_decisions(text, decisions)
|
|
996
1074
|
if recent_errors and _looks_like_fix(text):
|
|
997
1075
|
error_context.append((recent_errors[-1][:200], text[:200]))
|
|
@@ -1002,6 +1080,21 @@ def extract_session_state(filepath: str | Path, tail_lines: int = 500, max_files
|
|
|
1002
1080
|
elif payload_type in {"function_call", "custom_tool_call"}:
|
|
1003
1081
|
name = str(payload.get("name") or "")
|
|
1004
1082
|
args = _parse_arguments(payload)
|
|
1083
|
+
call_id = payload.get("call_id") or payload.get("id")
|
|
1084
|
+
_target = ""
|
|
1085
|
+
if name == "exec_command":
|
|
1086
|
+
_cmd = args.get("cmd") or args.get("command") or ""
|
|
1087
|
+
_target = (" ".join(str(c) for c in _cmd)
|
|
1088
|
+
if isinstance(_cmd, list) else str(_cmd))
|
|
1089
|
+
elif name == "apply_patch":
|
|
1090
|
+
_paths = PATCH_FILE_RE.findall(str(args.get("patch") or ""))
|
|
1091
|
+
_target = ", ".join(p.strip() for p in _paths[:3])
|
|
1092
|
+
if call_id:
|
|
1093
|
+
tool_calls.append({
|
|
1094
|
+
"id": str(call_id), "name": name,
|
|
1095
|
+
"target": _ingest_redact(_target)[:200]})
|
|
1096
|
+
if len(tool_calls) > 200:
|
|
1097
|
+
tool_calls.pop(0)
|
|
1005
1098
|
if name == "exec_command":
|
|
1006
1099
|
cmd = str(args.get("cmd") or args.get("command") or "")
|
|
1007
1100
|
if READ_CMD_RE.search(cmd):
|
|
@@ -1035,15 +1128,69 @@ def extract_session_state(filepath: str | Path, tail_lines: int = 500, max_files
|
|
|
1035
1128
|
|
|
1036
1129
|
elif payload_type in {"function_call_output", "custom_tool_call_output"}:
|
|
1037
1130
|
text = _ingest_redact(str(payload.get("output") or ""))
|
|
1131
|
+
_out_id = payload.get("call_id") or payload.get("id")
|
|
1132
|
+
if _out_id:
|
|
1133
|
+
tool_results.append({
|
|
1134
|
+
"tool_use_id": str(_out_id), "is_error": False,
|
|
1135
|
+
"text": checkpoint_state.result_excerpt(text)})
|
|
1136
|
+
if len(tool_results) > 200:
|
|
1137
|
+
tool_results.pop(0)
|
|
1038
1138
|
if _looks_like_error_text(text):
|
|
1039
1139
|
recent_errors.append(text[:300].strip())
|
|
1040
1140
|
elif payload_type in {"exec_command_end", "patch_apply_end"}:
|
|
1041
1141
|
text = _ingest_redact(_event_output_text(payload))
|
|
1042
1142
|
exit_code = payload.get("exit_code")
|
|
1043
1143
|
status = str(payload.get("status") or "").lower()
|
|
1144
|
+
_end_id = payload.get("call_id") or payload.get("id")
|
|
1145
|
+
if _end_id:
|
|
1146
|
+
tool_results.append({
|
|
1147
|
+
"tool_use_id": str(_end_id),
|
|
1148
|
+
"is_error": bool(exit_code not in (None, 0) or "error" in status),
|
|
1149
|
+
"exit_code": exit_code,
|
|
1150
|
+
"text": checkpoint_state.result_excerpt(text)})
|
|
1151
|
+
if len(tool_results) > 200:
|
|
1152
|
+
tool_results.pop(0)
|
|
1044
1153
|
if exit_code not in (None, 0) or "error" in status or _looks_like_error_text(text):
|
|
1045
1154
|
recent_errors.append(text[:300].strip())
|
|
1046
1155
|
|
|
1156
|
+
# Objective head-scan: the FIRST real user message. The tail deque loses
|
|
1157
|
+
# it on long sessions; _iter_json_records is lazy so this early-exits.
|
|
1158
|
+
objective = None
|
|
1159
|
+
try:
|
|
1160
|
+
for i, record in enumerate(_iter_json_records(filepath)):
|
|
1161
|
+
if i >= 400:
|
|
1162
|
+
break
|
|
1163
|
+
payload = _payload(record)
|
|
1164
|
+
ptype = payload.get("type")
|
|
1165
|
+
if ptype not in {"user_message", "message"}:
|
|
1166
|
+
continue
|
|
1167
|
+
role = payload.get("role")
|
|
1168
|
+
if ptype == "user_message":
|
|
1169
|
+
role = "user"
|
|
1170
|
+
if role != "user":
|
|
1171
|
+
continue
|
|
1172
|
+
text = _extract_text(payload).strip()
|
|
1173
|
+
if not _task_user_text(text):
|
|
1174
|
+
continue
|
|
1175
|
+
objective = {
|
|
1176
|
+
"text": _ingest_redact(text),
|
|
1177
|
+
"source": {"kind": "user_message",
|
|
1178
|
+
"id": str(payload.get("id") or payload.get("message_id") or "") or None},
|
|
1179
|
+
}
|
|
1180
|
+
break
|
|
1181
|
+
except Exception:
|
|
1182
|
+
objective = None
|
|
1183
|
+
|
|
1184
|
+
task_state = checkpoint_state.build_task_state(
|
|
1185
|
+
user_texts=user_texts,
|
|
1186
|
+
assistant_texts=assistant_texts,
|
|
1187
|
+
tool_calls=tool_calls,
|
|
1188
|
+
tool_results=tool_results,
|
|
1189
|
+
todos=todos,
|
|
1190
|
+
changed_files=[(p, a) for p, a, _r in active_files],
|
|
1191
|
+
objective=objective,
|
|
1192
|
+
)
|
|
1193
|
+
|
|
1047
1194
|
return {
|
|
1048
1195
|
"active_files": active_files[-max_files:],
|
|
1049
1196
|
"recent_reads": recent_reads[-max_files:],
|
|
@@ -1054,9 +1201,10 @@ def extract_session_state(filepath: str | Path, tail_lines: int = 500, max_files
|
|
|
1054
1201
|
"todos": todos,
|
|
1055
1202
|
"active_plan": active_plan,
|
|
1056
1203
|
"current_step": {
|
|
1057
|
-
"last_user": last_user_msg[:
|
|
1204
|
+
"last_user": last_user_msg[:4000],
|
|
1058
1205
|
"last_assistant": last_assistant_msg[:500],
|
|
1059
1206
|
},
|
|
1207
|
+
"task_state": task_state,
|
|
1060
1208
|
}
|
|
1061
1209
|
|
|
1062
1210
|
|
|
@@ -33,8 +33,8 @@ REPO_MODULES = frozenset((
|
|
|
33
33
|
'hermes_state', 'hermes_tool_hooks', 'hook_io', 'hook_runtime', 'injection', 'install_reconcile', 'measure',
|
|
34
34
|
'outline', 'pipeline_analyzer', 'plugin_env', 'py_trust', 'quality_cache_gate',
|
|
35
35
|
'read_cache', 'recovery_output', 'refetch_fingerprint', 'refetch_guard', 'routing_advisor',
|
|
36
|
-
'runtime_env', 'session_store', 'spawn_utils', 'structure_map', 'structure_map_ts',
|
|
37
|
-
'structure_replay', 'thrash_guard', 'token_estimate', 'tool_search_diagnostic', 'utf8_io',
|
|
36
|
+
'runtime_env', 'session_activity', 'session_store', 'spawn_utils', 'structure_map', 'structure_map_ts',
|
|
37
|
+
'structure_replay', 'thrash_guard', 'token_estimate', 'tool_search_diagnostic', 'utf8_io', 'archive_window', 'checkpoint_state',
|
|
38
38
|
))
|
|
39
39
|
|
|
40
40
|
class SourceOnly(importlib.abc.MetaPathFinder, importlib.abc.Loader):
|