@alexgreensh/token-optimizer 0.0.0-stage → 5.13.51

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/.claude-plugin/marketplace.json +76 -0
  2. package/.claude-plugin/plugin.json +21 -0
  3. package/LICENSE +130 -0
  4. package/LICENSE-SMALL-BUSINESS.md +62 -0
  5. package/PRIVACY.md +200 -0
  6. package/README.md +13 -2
  7. package/hooks/codex-hooks.json +4 -0
  8. package/hooks/hooks.json +182 -0
  9. package/hooks/module_runner.py +448 -0
  10. package/hooks/posttooluse_runner.py +1110 -0
  11. package/hooks/python-launcher.sh +816 -0
  12. package/hooks/run.py +788 -0
  13. package/hooks/sessionstart_runner.py +629 -0
  14. package/hooks/stop_runner.py +408 -0
  15. package/hooks/userpromptsubmit_runner.py +722 -0
  16. package/hooks/windows-launcher.py +163 -0
  17. package/install-cloud.sh +23 -0
  18. package/package.json +29 -4
  19. package/skills/fleet-auditor/SKILL.md +149 -0
  20. package/skills/fleet-auditor/references/fleet-systems.md +167 -0
  21. package/skills/fleet-auditor/references/report-template.md +50 -0
  22. package/skills/fleet-auditor/references/waste-patterns.md +126 -0
  23. package/skills/fleet-auditor/scripts/fleet.py +3633 -0
  24. package/skills/fleet-auditor/scripts/shared.py +277 -0
  25. package/skills/resume-checkpoint/SKILL.md +52 -0
  26. package/skills/resume-checkpoint/scripts/pull_checkpoint.py +188 -0
  27. package/skills/token-coach/SKILL.md +141 -0
  28. package/skills/token-coach/assets/coach-dashboard-tab.html +45 -0
  29. package/skills/token-coach/examples/coaching-session-agentic.md +62 -0
  30. package/skills/token-coach/examples/coaching-session-heavy-setup.md +46 -0
  31. package/skills/token-coach/examples/coaching-session-new-project.md +38 -0
  32. package/skills/token-coach/references/agentic-systems.md +147 -0
  33. package/skills/token-coach/references/coach-patterns.md +120 -0
  34. package/skills/token-coach/references/coaching-scripts.md +146 -0
  35. package/skills/token-coach/references/deterministic-stages.md +102 -0
  36. package/skills/token-coach/references/keepwarm-consent.md +48 -0
  37. package/skills/token-coach/references/quick-reference.md +155 -0
  38. package/skills/token-dashboard/SKILL.md +93 -0
  39. package/skills/token-optimizer/SKILL.md +150 -0
  40. package/skills/token-optimizer/assets/dashboard.html +7251 -0
  41. package/skills/token-optimizer/examples/claude-md-optimized.md +40 -0
  42. package/skills/token-optimizer/examples/hooks-starter.json +179 -0
  43. package/skills/token-optimizer/examples/permissions-deny-template.json +24 -0
  44. package/skills/token-optimizer/pricing/prices.json +695 -0
  45. package/skills/token-optimizer/references/agent-prompts.md +687 -0
  46. package/skills/token-optimizer/references/cli-reference.md +92 -0
  47. package/skills/token-optimizer/references/codex-workflow.md +188 -0
  48. package/skills/token-optimizer/references/cursor-workflow.md +74 -0
  49. package/skills/token-optimizer/references/error-recovery.md +37 -0
  50. package/skills/token-optimizer/references/implementation-playbook.md +416 -0
  51. package/skills/token-optimizer/references/keepwarm-consent.md +48 -0
  52. package/skills/token-optimizer/references/opencode-workflow.md +72 -0
  53. package/skills/token-optimizer/references/optimization-checklist.md +714 -0
  54. package/skills/token-optimizer/references/phase0-setup.md +142 -0
  55. package/skills/token-optimizer/references/presentation-workflow.md +72 -0
  56. package/skills/token-optimizer/references/session-continuity.md +19 -0
  57. package/skills/token-optimizer/references/token-flow-architecture.md +629 -0
  58. package/skills/token-optimizer/scripts/activity_tracker.py +143 -0
  59. package/skills/token-optimizer/scripts/antigravity_doctor.py +548 -0
  60. package/skills/token-optimizer/scripts/antigravity_hook_bridge.py +511 -0
  61. package/skills/token-optimizer/scripts/antigravity_install.py +379 -0
  62. package/skills/token-optimizer/scripts/antigravity_proto.py +413 -0
  63. package/skills/token-optimizer/scripts/antigravity_session.py +346 -0
  64. package/skills/token-optimizer/scripts/antigravity_state.py +486 -0
  65. package/skills/token-optimizer/scripts/archive_result.py +1725 -0
  66. package/skills/token-optimizer/scripts/bash_compress.py +2490 -0
  67. package/skills/token-optimizer/scripts/bash_compress_hook.py +766 -0
  68. package/skills/token-optimizer/scripts/bash_hook.py +61 -0
  69. package/skills/token-optimizer/scripts/bash_whitelist.py +243 -0
  70. package/skills/token-optimizer/scripts/benchmark.py +1765 -0
  71. package/skills/token-optimizer/scripts/build_output_compress.py +776 -0
  72. package/skills/token-optimizer/scripts/cloud_kit.py +1011 -0
  73. package/skills/token-optimizer/scripts/codex_command_compress.py +434 -0
  74. package/skills/token-optimizer/scripts/codex_compact_prompt.py +273 -0
  75. package/skills/token-optimizer/scripts/codex_doctor.py +454 -0
  76. package/skills/token-optimizer/scripts/codex_hook_bridge.py +311 -0
  77. package/skills/token-optimizer/scripts/codex_install.py +810 -0
  78. package/skills/token-optimizer/scripts/codex_io.py +119 -0
  79. package/skills/token-optimizer/scripts/codex_log_index.py +219 -0
  80. package/skills/token-optimizer/scripts/codex_models.py +34 -0
  81. package/skills/token-optimizer/scripts/codex_session.py +1186 -0
  82. package/skills/token-optimizer/scripts/codex_state.py +707 -0
  83. package/skills/token-optimizer/scripts/codex_statusline.py +303 -0
  84. package/skills/token-optimizer/scripts/command_filters.py +386 -0
  85. package/skills/token-optimizer/scripts/compression_backfill.py +600 -0
  86. package/skills/token-optimizer/scripts/compression_log.py +230 -0
  87. package/skills/token-optimizer/scripts/context_intel.py +331 -0
  88. package/skills/token-optimizer/scripts/context_pressure.py +115 -0
  89. package/skills/token-optimizer/scripts/copilot_doctor.py +406 -0
  90. package/skills/token-optimizer/scripts/copilot_hook_bridge.py +709 -0
  91. package/skills/token-optimizer/scripts/copilot_install.py +288 -0
  92. package/skills/token-optimizer/scripts/copilot_session.py +496 -0
  93. package/skills/token-optimizer/scripts/copilot_state.py +569 -0
  94. package/skills/token-optimizer/scripts/copilot_vscode.py +832 -0
  95. package/skills/token-optimizer/scripts/cowork_doctor.py +270 -0
  96. package/skills/token-optimizer/scripts/cowork_install.py +380 -0
  97. package/skills/token-optimizer/scripts/credential_patterns.py +1514 -0
  98. package/skills/token-optimizer/scripts/cursor_doctor.py +602 -0
  99. package/skills/token-optimizer/scripts/cursor_hook_bridge.py +843 -0
  100. package/skills/token-optimizer/scripts/cursor_install.py +426 -0
  101. package/skills/token-optimizer/scripts/cursor_session.py +303 -0
  102. package/skills/token-optimizer/scripts/cursor_state.py +348 -0
  103. package/skills/token-optimizer/scripts/delta_diff.py +110 -0
  104. package/skills/token-optimizer/scripts/detectors/__init__.py +2 -0
  105. package/skills/token-optimizer/scripts/detectors/bad_decomposition.py +78 -0
  106. package/skills/token-optimizer/scripts/detectors/cache_instability.py +504 -0
  107. package/skills/token-optimizer/scripts/detectors/looping.py +88 -0
  108. package/skills/token-optimizer/scripts/detectors/output_waste.py +143 -0
  109. package/skills/token-optimizer/scripts/detectors/overpowered.py +116 -0
  110. package/skills/token-optimizer/scripts/detectors/pdf_ingestion.py +52 -0
  111. package/skills/token-optimizer/scripts/detectors/registry.py +65 -0
  112. package/skills/token-optimizer/scripts/detectors/respond_to_bash.py +76 -0
  113. package/skills/token-optimizer/scripts/detectors/retry_churn.py +83 -0
  114. package/skills/token-optimizer/scripts/detectors/tool_cascade.py +62 -0
  115. package/skills/token-optimizer/scripts/detectors/wasteful_thinking.py +75 -0
  116. package/skills/token-optimizer/scripts/detectors/weak_model.py +55 -0
  117. package/skills/token-optimizer/scripts/detectors/websearch_routing.py +72 -0
  118. package/skills/token-optimizer/scripts/deterministic_candidates.py +1458 -0
  119. package/skills/token-optimizer/scripts/devin_compress.py +790 -0
  120. package/skills/token-optimizer/scripts/devin_doctor.py +403 -0
  121. package/skills/token-optimizer/scripts/devin_hooks.py +453 -0
  122. package/skills/token-optimizer/scripts/devin_install.py +1086 -0
  123. package/skills/token-optimizer/scripts/devin_source.py +119 -0
  124. package/skills/token-optimizer/scripts/devin_state.py +330 -0
  125. package/skills/token-optimizer/scripts/devin_verify.py +67 -0
  126. package/skills/token-optimizer/scripts/grok_doctor.py +560 -0
  127. package/skills/token-optimizer/scripts/grok_hook_bridge.py +699 -0
  128. package/skills/token-optimizer/scripts/grok_install.py +400 -0
  129. package/skills/token-optimizer/scripts/grok_session.py +317 -0
  130. package/skills/token-optimizer/scripts/grok_state.py +299 -0
  131. package/skills/token-optimizer/scripts/hermes_doctor.py +479 -0
  132. package/skills/token-optimizer/scripts/hermes_hook_bridge.py +285 -0
  133. package/skills/token-optimizer/scripts/hermes_install.py +668 -0
  134. package/skills/token-optimizer/scripts/hermes_session.py +691 -0
  135. package/skills/token-optimizer/scripts/hermes_state.py +448 -0
  136. package/skills/token-optimizer/scripts/hook_io.py +120 -0
  137. package/skills/token-optimizer/scripts/hook_runtime.py +716 -0
  138. package/skills/token-optimizer/scripts/injection.py +156 -0
  139. package/skills/token-optimizer/scripts/install_reconcile.py +952 -0
  140. package/skills/token-optimizer/scripts/measure.py +59531 -0
  141. package/skills/token-optimizer/scripts/outline.py +53 -0
  142. package/skills/token-optimizer/scripts/pipeline_analyzer.py +723 -0
  143. package/skills/token-optimizer/scripts/plugin_env.py +562 -0
  144. package/skills/token-optimizer/scripts/py_trust.py +80 -0
  145. package/skills/token-optimizer/scripts/quality_cache_gate.py +320 -0
  146. package/skills/token-optimizer/scripts/read_cache.py +2489 -0
  147. package/skills/token-optimizer/scripts/recovery_output.py +110 -0
  148. package/skills/token-optimizer/scripts/refetch_fingerprint.py +236 -0
  149. package/skills/token-optimizer/scripts/refetch_guard.py +244 -0
  150. package/skills/token-optimizer/scripts/routing_advisor.py +389 -0
  151. package/skills/token-optimizer/scripts/runtime_env.py +1923 -0
  152. package/skills/token-optimizer/scripts/session_store.py +979 -0
  153. package/skills/token-optimizer/scripts/spawn_utils.py +122 -0
  154. package/skills/token-optimizer/scripts/statusline.js +660 -0
  155. package/skills/token-optimizer/scripts/structure_map.py +2880 -0
  156. package/skills/token-optimizer/scripts/structure_map_ts.py +676 -0
  157. package/skills/token-optimizer/scripts/structure_replay.py +1556 -0
  158. package/skills/token-optimizer/scripts/thrash_guard.py +604 -0
  159. package/skills/token-optimizer/scripts/token_estimate.py +80 -0
  160. package/skills/token-optimizer/scripts/tool_search_diagnostic.py +61 -0
  161. package/skills/token-optimizer/scripts/utf8_io.py +219 -0
@@ -0,0 +1,707 @@
1
+ #!/usr/bin/env python3
2
+ """Read-only reader for Codex's runtime SQLite state.
3
+
4
+ Codex (v0.130+) moved runtime state out of in-process structures into
5
+ versioned SQLite databases under ``CODEX_HOME``:
6
+
7
+ - ``state_<N>.sqlite`` -> ``threads`` (per-thread token totals, model),
8
+ ``thread_spawn_edges`` (subagent parent->child graph), ``stage1_outputs``
9
+ (densified memory summaries: ``raw_memory`` + ``rollout_summary``).
10
+ - ``goals_<N>.sqlite`` -> ``thread_goals`` (objective, token_budget,
11
+ tokens_used, status).
12
+
13
+ This module reads those databases to power Codex subagent-cost, memory-overhead,
14
+ and goal-budget measurement. It is **strictly read-only** and is designed to
15
+ never disrupt the live Codex process that owns these databases:
16
+
17
+ - Opens with ``file:...?mode=ro`` and a short busy-timeout (KTD3).
18
+ - Keeps each connection open for the minimum possible window: introspect the
19
+ schema and run a single bounded query, then close before doing any Python-side
20
+ aggregation. A connection lingering across a Codex WAL checkpoint would defer
21
+ the checkpoint and grow the ``-wal`` file, degrading Codex write latency.
22
+ - Discovers databases by glob and tolerates schema-version drift, missing
23
+ tables, renamed columns, missing files, and a freshly-migrated empty database
24
+ (KTD2/KTD4): every public function degrades to an empty/zero result instead
25
+ of raising.
26
+
27
+ The 117MB ``logs_<N>.sqlite`` is internal telemetry (not context tokens) and is
28
+ intentionally out of scope.
29
+ """
30
+
31
+ from __future__ import annotations
32
+
33
+ import math
34
+ import os
35
+ import re
36
+ import sqlite3
37
+ import time
38
+ from contextlib import contextmanager
39
+ from pathlib import Path
40
+ from typing import Any, Iterator
41
+
42
+ from runtime_env import codex_home, detect_runtime
43
+
44
+ CHARS_PER_TOKEN = 4
45
+ _BUSY_TIMEOUT_SECONDS = 0.25
46
+ # Subagents whose spawn edge is still "open" this long after their thread last
47
+ # updated are treated as leaked (spawned, never closed).
48
+ LEAK_STALE_MINUTES = 30
49
+ # Bound raw row reads so a pathological future state DB can't dominate work.
50
+ _MAX_ROWS = 5000
51
+ # How many detail rows to surface in the structured output.
52
+ _DETAIL_LIMIT = 20
53
+ # Whitelist of tables this module ever inspects. PRAGMA table_info cannot use
54
+ # parameter binding, so the table name is interpolated — gating on this set
55
+ # guarantees no externally-derived value can ever reach that f-string.
56
+ _ALLOWED_TABLES = frozenset({"threads", "thread_spawn_edges", "stage1_outputs", "thread_goals"})
57
+
58
+ # Opt-in parent-goal rollup marker. When an independent worker Codex goal
59
+ # session is orchestrated by an outer coordinator, the worker's objective
60
+ # carries ``Parent goal <outer-thread-id>``. Matching is case-insensitive and
61
+ # anchored on the angle-bracketed id so a stray "parent goal" phrase in prose
62
+ # cannot pull an unrelated session into the current goal's report.
63
+ _PARENT_GOAL_RE = re.compile(r"Parent goal\s*<([A-Za-z0-9_-]+)>", re.IGNORECASE)
64
+ # Status label used in ``aggregation_edges`` for a worker goal grouped under a
65
+ # coordinator via the explicit marker (no spawn edge exists between them).
66
+ _PARENT_GOAL_EDGE_STATUS = "parent_goal"
67
+
68
+
69
+ def _is_codex() -> bool:
70
+ return detect_runtime() == "codex"
71
+
72
+
73
+ def _find_versioned_db(prefix: str, primary_table: str) -> Path | None:
74
+ """Return the best ``{prefix}_<N>.sqlite`` under CODEX_HOME.
75
+
76
+ Selection rule (KTD2, migration-in-flight safe): prefer the highest numeric
77
+ suffix whose ``primary_table`` has at least one row; if the highest-suffix
78
+ database is empty (Codex created the new schema but has not migrated data
79
+ yet), fall back to the next-highest with data. If none have data, return the
80
+ highest suffix (an empty but valid result). ``None`` when no file matches.
81
+ """
82
+ home = codex_home()
83
+ candidates: list[tuple[int, Path]] = []
84
+ for path in home.glob(f"{prefix}_*.sqlite"):
85
+ suffix = path.stem[len(prefix) + 1:]
86
+ if suffix.isdigit():
87
+ candidates.append((int(suffix), path))
88
+ if not candidates:
89
+ return None
90
+ candidates.sort(key=lambda item: item[0], reverse=True)
91
+ for _, path in candidates:
92
+ if _table_has_rows(path, primary_table):
93
+ return path
94
+ # No populated database found; return the highest suffix so callers still
95
+ # get a valid (empty) read rather than None.
96
+ return candidates[0][1]
97
+
98
+
99
+ @contextmanager
100
+ def _ro_connect(path: Path) -> Iterator[sqlite3.Connection]:
101
+ """Open ``path`` read-only with a short busy-timeout; always close.
102
+
103
+ Never writes, never checkpoints, never attaches. The caller must keep the
104
+ open window minimal: introspect + one query + fetch, then exit.
105
+ """
106
+ # Build the file: URI via Path.as_uri() rather than string interpolation:
107
+ # with uri=True, characters like ?, #, % and spaces in the path are URI
108
+ # syntax, so a path containing '?' would start the query string early and
109
+ # could drop or override mode=ro (opening the wrong DB, or read-write).
110
+ # as_uri() percent-encodes those, keeping the whole path in the path
111
+ # component. (Discovered DB paths are absolute, which as_uri() requires.)
112
+ # M-3: as_uri() raises ValueError on relative paths. Resolve first so a
113
+ # relative CODEX_HOME doesn't propagate an uncaught ValueError past
114
+ # callers that only catch (sqlite3.Error, OSError).
115
+ db_uri = Path(path).resolve().as_uri()
116
+ conn = sqlite3.connect(f"{db_uri}?mode=ro", uri=True, timeout=_BUSY_TIMEOUT_SECONDS)
117
+ try:
118
+ # Defense-in-depth: `mode=ro` blocks writes to this DB but not ATTACH;
119
+ # `query_only` also blocks ATTACH and any write through the connection,
120
+ # so a future code change can't accidentally write via a "read-only" conn.
121
+ conn.execute("PRAGMA query_only = ON")
122
+ conn.row_factory = sqlite3.Row
123
+ yield conn
124
+ finally:
125
+ conn.close()
126
+
127
+
128
+ def _table_has_rows(path: Path, table: str) -> bool:
129
+ try:
130
+ with _ro_connect(path) as conn:
131
+ if not _table_columns(conn, table):
132
+ return False
133
+ row = conn.execute(f"SELECT 1 FROM {table} LIMIT 1").fetchone()
134
+ return row is not None
135
+ except (sqlite3.Error, OSError):
136
+ return False
137
+
138
+
139
+ def _table_columns(conn: sqlite3.Connection, table: str) -> set[str]:
140
+ """Return the column names of ``table``, or empty set if it does not exist.
141
+
142
+ Guards every read against a missing table or renamed column on a future
143
+ schema (KTD4). ``PRAGMA table_info`` returns no rows for an unknown table,
144
+ so this doubles as an existence check without a separate sqlite_master pass.
145
+ """
146
+ if table not in _ALLOWED_TABLES:
147
+ return set()
148
+ try:
149
+ rows = conn.execute(f"PRAGMA table_info({table})").fetchall()
150
+ except sqlite3.Error:
151
+ return set()
152
+ return {str(row[1]) for row in rows}
153
+
154
+
155
+ def _now_ms() -> int:
156
+ return int(time.time() * 1000)
157
+
158
+
159
+ def _normalize_ms(updated_at_ms: Any, updated_at: Any) -> int | None:
160
+ """Resolve a thread's last-update time in epoch milliseconds.
161
+
162
+ ``threads`` carries both the original ``updated_at`` (seconds) and a later
163
+ nullable ``updated_at_ms``. Prefer the millisecond column; fall back to the
164
+ seconds column; ``None`` when neither is usable.
165
+
166
+ Guards against unit drift: any epoch time after 2001 is > 1e12 ms, so a
167
+ positive value below that in the "ms" column is almost certainly seconds
168
+ (a migration mistake) and is rescaled — otherwise every active subagent
169
+ would be misread as decades stale and falsely flagged as leaked.
170
+ """
171
+ _MS_2001 = 1_000_000_000_000 # ms epoch for ~2001; below this = seconds
172
+ # M-2: float('inf') passes the > 0 check but int(float('inf')) raises
173
+ # OverflowError, which is not caught by any caller's try/except. Guard
174
+ # with math.isfinite() so inf and nan return None instead of crashing.
175
+ if isinstance(updated_at_ms, (int, float)) and updated_at_ms > 0:
176
+ if not math.isfinite(updated_at_ms):
177
+ return None
178
+ return int(updated_at_ms) if updated_at_ms >= _MS_2001 else int(updated_at_ms * 1000)
179
+ if isinstance(updated_at, (int, float)) and updated_at > 0:
180
+ if not math.isfinite(updated_at):
181
+ return None
182
+ return int(updated_at) if updated_at >= _MS_2001 else int(updated_at * 1000)
183
+ return None
184
+
185
+
186
+ def _parse_parent_goal_marker(objective: Any) -> str | None:
187
+ """Return the coordinator thread id encoded in a ``Parent goal <id>`` marker.
188
+
189
+ ``None`` when the objective lacks the explicit opt-in marker. This is the
190
+ ONLY mechanism by which an independent worker goal session is grouped under
191
+ a coordinator thread — absent the marker, no cross-goal aggregation happens
192
+ (requirement 4).
193
+ """
194
+ if not objective:
195
+ return None
196
+ match = _PARENT_GOAL_RE.search(str(objective))
197
+ return match.group(1) if match else None
198
+
199
+
200
+ def _fetch_spawn_edges(db: Path) -> list[dict[str, str]]:
201
+ """Read every ``thread_spawn_edges`` row as plain dicts, fail-open.
202
+
203
+ Returns a list of ``{"parent_id", "child_id", "status"}`` dicts. The
204
+ connection is closed before returning so the caller can aggregate in
205
+ Python without holding the DB open (KTD3). Empty list on any sqlite/OS
206
+ error or missing columns — a caller that then walks an empty edge set
207
+ simply sees a single-node subtree (the root only).
208
+ """
209
+ try:
210
+ with _ro_connect(db) as conn:
211
+ cols = _table_columns(conn, "thread_spawn_edges")
212
+ if not {"parent_thread_id", "child_thread_id", "status"} <= cols:
213
+ return []
214
+ rows = conn.execute(
215
+ f"""
216
+ SELECT parent_thread_id AS parent_id,
217
+ child_thread_id AS child_id,
218
+ status AS status
219
+ FROM thread_spawn_edges
220
+ LIMIT {_MAX_ROWS}
221
+ """
222
+ ).fetchall()
223
+ return [
224
+ {
225
+ "parent_id": str(row["parent_id"] or ""),
226
+ "child_id": str(row["child_id"] or ""),
227
+ "status": str(row["status"] or ""),
228
+ }
229
+ for row in rows
230
+ ]
231
+ except (sqlite3.Error, OSError):
232
+ return []
233
+
234
+
235
+ def _resolve_subtree(
236
+ edge_rows: list[dict[str, str]], root_thread_id: str
237
+ ) -> tuple[set[str], list[dict[str, str]]]:
238
+ """Walk the transitive descendant set of ``root_thread_id`` cycle-safe.
239
+
240
+ Pure-Python BFS over the fetched edge rows. The visited set plus the
241
+ ``_MAX_ROWS`` cap make a malformed (self-referential / cyclic) edge graph
242
+ terminate: a child already in the subtree is never re-enqueued, and the
243
+ subtree never grows past the row bound (non-negotiable:
244
+ cycle-safe descendant walk).
245
+
246
+ Returns ``(subtree_ids, aggregation_edges)`` where ``aggregation_edges`` is
247
+ every edge whose parent sits inside the subtree — i.e. the exact edges
248
+ whose tokens are attributed to this goal. The root itself is in the subtree
249
+ so its direct spawn edges are included; an edge whose parent is the root's
250
+ OWN parent (outside the subtree) is excluded, which is what stops a current
251
+ goal from inheriting historical/unrelated spawn edges.
252
+ """
253
+ subtree: set[str] = {root_thread_id}
254
+ children_by_parent: dict[str, list[str]] = {}
255
+ for edge in edge_rows:
256
+ parent = edge["parent_id"]
257
+ child = edge["child_id"]
258
+ if parent and child:
259
+ children_by_parent.setdefault(parent, []).append(child)
260
+
261
+ frontier = [root_thread_id]
262
+ while frontier and len(subtree) < _MAX_ROWS:
263
+ node = frontier.pop()
264
+ for child in children_by_parent.get(node, []):
265
+ if child in subtree:
266
+ continue
267
+ subtree.add(child)
268
+ frontier.append(child)
269
+
270
+ aggregation_edges = [
271
+ {
272
+ "parent_thread_id": edge["parent_id"],
273
+ "child_thread_id": edge["child_id"],
274
+ "status": edge["status"],
275
+ }
276
+ for edge in edge_rows
277
+ if edge["parent_id"] in subtree and edge["child_id"]
278
+ ]
279
+ return subtree, aggregation_edges
280
+
281
+
282
+ _THREAD_ID_ENV = "CODEX_THREAD_ID"
283
+ _THREAD_ID_RE = re.compile(r"[A-Za-z0-9_-]{6,128}")
284
+
285
+
286
+ def invoking_thread_id() -> str | None:
287
+ """Return the invoking Codex thread id from ``CODEX_THREAD_ID``, or None.
288
+
289
+ Codex exports the id of the thread that launched the process. That is the
290
+ only identity of the caller we have, and the value is validated exactly
291
+ as exported: an unset, empty or whitespace-only value is treated as
292
+ absent, while a non-empty value carrying stray whitespace or any other
293
+ character outside the id alphabet is malformed. Malformed values are
294
+ never sanitized or trimmed into some other id.
295
+ """
296
+ raw = os.environ.get(_THREAD_ID_ENV, "")
297
+ return raw if _THREAD_ID_RE.fullmatch(raw) else None
298
+
299
+
300
+ def thread_identity_status() -> str:
301
+ """``"ok"``, ``"absent"`` (unset, empty or whitespace-only) or ``"invalid"``.
302
+
303
+ The unmodified ``CODEX_THREAD_ID`` value is matched exactly; padding such
304
+ as a leading or trailing space, tab or newline makes the value invalid,
305
+ not absent.
306
+ """
307
+ raw = os.environ.get(_THREAD_ID_ENV, "")
308
+ if not raw.strip():
309
+ return "absent"
310
+ return "ok" if _THREAD_ID_RE.fullmatch(raw) else "invalid"
311
+
312
+
313
+ def current_thread_id() -> str | None:
314
+ """Resolve the invoking Codex thread id.
315
+
316
+ Binds to the caller's own identity (``CODEX_THREAD_ID``) and returns it
317
+ as-is, whether or not the state DB has a row for it yet. It never infers
318
+ "current" from the newest ``threads`` row: with several threads open
319
+ concurrently that row belongs to whichever thread wrote last, which can be
320
+ a different thread from the caller (issue #108).
321
+
322
+ Returns ``None`` off-Codex, or on Codex when the caller's identity is not
323
+ available. ``None`` means *unresolved*; callers must surface that instead
324
+ of substituting a guess.
325
+ """
326
+ if not _is_codex():
327
+ return None
328
+ return invoking_thread_id()
329
+
330
+
331
+ def _empty_subagents() -> dict[str, Any]:
332
+ return {
333
+ "available": False,
334
+ "total_subagents": 0,
335
+ "open_subagents": 0,
336
+ "closed_subagents": 0,
337
+ "leaked_subagents": 0,
338
+ "total_child_tokens": 0,
339
+ "by_parent": [],
340
+ "leaked": [],
341
+ }
342
+
343
+
344
+ def subagent_costs(root_thread_id: str | None = None) -> dict[str, Any]:
345
+ """Per-subagent token cost and leak detection from the state database.
346
+
347
+ Reads ``thread_spawn_edges`` joined to ``threads`` to attribute each child
348
+ (subagent) thread's cumulative ``tokens_used`` to its parent, and flags
349
+ children whose edge is still ``open`` long after their thread last updated.
350
+
351
+ When ``root_thread_id`` is given, only the current goal subtree is
352
+ aggregated: the root plus its transitive descendants via
353
+ ``thread_spawn_edges``. Historical/closed spawn edges from unrelated prior
354
+ work are excluded, so a current goal no longer reports old subagents and
355
+ token totals reflect only the selected goal (requirements 1, 2).
356
+ When ``root_thread_id`` is ``None`` the legacy whole-DB aggregation runs
357
+ unchanged so existing callers keep working (backward-compatible signature).
358
+
359
+ The resolved thread id and every aggregation edge used are surfaced for
360
+ audit (requirement 5).
361
+ """
362
+ if not _is_codex():
363
+ return _empty_subagents()
364
+ db = _find_versioned_db("state", "threads")
365
+ if db is None:
366
+ return _empty_subagents()
367
+
368
+ try:
369
+ with _ro_connect(db) as conn:
370
+ edge_cols = _table_columns(conn, "thread_spawn_edges")
371
+ thread_cols = _table_columns(conn, "threads")
372
+ if not {"parent_thread_id", "child_thread_id", "status"} <= edge_cols:
373
+ return _empty_subagents()
374
+ if not {"id", "tokens_used"} <= thread_cols:
375
+ return _empty_subagents()
376
+ has_ms = "updated_at_ms" in thread_cols
377
+ has_secs = "updated_at" in thread_cols
378
+ updated_ms = "t.updated_at_ms" if has_ms else "NULL"
379
+ updated_secs = "t.updated_at" if has_secs else "NULL"
380
+ rows = conn.execute(
381
+ f"""
382
+ SELECT e.parent_thread_id AS parent_id,
383
+ e.child_thread_id AS child_id,
384
+ e.status AS status,
385
+ COALESCE(t.tokens_used, 0) AS child_tokens,
386
+ {updated_ms} AS updated_at_ms,
387
+ {updated_secs} AS updated_at
388
+ FROM thread_spawn_edges e
389
+ LEFT JOIN threads t ON t.id = e.child_thread_id
390
+ LIMIT {_MAX_ROWS}
391
+ """
392
+ ).fetchall()
393
+ except (sqlite3.Error, OSError):
394
+ return _empty_subagents()
395
+
396
+ # Aggregation runs after the connection is closed (KTD3).
397
+ aggregation_edges: list[dict[str, str]] = []
398
+ if root_thread_id:
399
+ edge_rows = [
400
+ {
401
+ "parent_id": str(row["parent_id"] or ""),
402
+ "child_id": str(row["child_id"] or ""),
403
+ "status": str(row["status"] or ""),
404
+ }
405
+ for row in rows
406
+ ]
407
+ subtree, aggregation_edges = _resolve_subtree(edge_rows, root_thread_id)
408
+ rows = [row for row in rows if str(row["parent_id"] or "") in subtree]
409
+
410
+ now_ms = _now_ms()
411
+ stale_cutoff_ms = LEAK_STALE_MINUTES * 60 * 1000
412
+ open_count = closed_count = leaked_count = total_child_tokens = 0
413
+ by_parent: dict[str, dict[str, int]] = {}
414
+ leaked: list[dict[str, Any]] = []
415
+
416
+ for row in rows:
417
+ status = str(row["status"] or "").lower()
418
+ child_tokens = int(row["child_tokens"] or 0)
419
+ total_child_tokens += child_tokens
420
+ parent = str(row["parent_id"] or "unknown")
421
+ bucket = by_parent.setdefault(parent, {"child_count": 0, "child_tokens": 0, "open_count": 0})
422
+ bucket["child_count"] += 1
423
+ bucket["child_tokens"] += child_tokens
424
+ if status == "open":
425
+ open_count += 1
426
+ bucket["open_count"] += 1
427
+ last_ms = _normalize_ms(row["updated_at_ms"], row["updated_at"])
428
+ age_ms = (now_ms - last_ms) if last_ms is not None else None
429
+ if age_ms is None or age_ms > stale_cutoff_ms:
430
+ leaked_count += 1
431
+ leaked.append({
432
+ "child_thread_id": str(row["child_id"] or ""),
433
+ "parent_thread_id": parent,
434
+ "tokens_used": child_tokens,
435
+ "age_minutes": round(age_ms / 60000, 1) if age_ms is not None else None,
436
+ })
437
+ elif status == "closed":
438
+ closed_count += 1
439
+
440
+ by_parent_list = sorted(
441
+ ({"parent_thread_id": pid, **vals} for pid, vals in by_parent.items()),
442
+ key=lambda item: item["child_tokens"],
443
+ reverse=True,
444
+ )[:_DETAIL_LIMIT]
445
+ leaked.sort(key=lambda item: item["tokens_used"], reverse=True)
446
+
447
+ return {
448
+ "available": True,
449
+ "total_subagents": len(rows),
450
+ "open_subagents": open_count,
451
+ "closed_subagents": closed_count,
452
+ "leaked_subagents": leaked_count,
453
+ "total_child_tokens": total_child_tokens,
454
+ "by_parent": by_parent_list,
455
+ "leaked": leaked[:_DETAIL_LIMIT],
456
+ "selected_thread_id": root_thread_id,
457
+ "aggregation_edges": aggregation_edges,
458
+ }
459
+
460
+
461
+ def _empty_memory() -> dict[str, Any]:
462
+ return {
463
+ "available": False,
464
+ "thread_count": 0,
465
+ "truncated": False,
466
+ "total_raw_memory_chars": 0,
467
+ "total_rollout_summary_chars": 0,
468
+ "total_memory_tokens": 0,
469
+ "max_thread_memory_tokens": 0,
470
+ "by_thread": [],
471
+ }
472
+
473
+
474
+ def memory_overhead(root_thread_id: str | None = None) -> dict[str, Any]:
475
+ """Per-thread memory overhead from ``stage1_outputs``.
476
+
477
+ ``root_thread_id=None`` is the machine-wide audit view (every thread's
478
+ memory rows). With a thread id, only that thread's rows are measured; the
479
+ id is bound as a SQL parameter, never interpolated.
480
+
481
+ Codex's densified memory (``raw_memory`` + ``rollout_summary``) is injected
482
+ into context. This measures its size in tokens per thread. Returns zeros
483
+ cleanly when the table is empty (the common case until a user accumulates
484
+ memory).
485
+ """
486
+ if not _is_codex():
487
+ return _empty_memory()
488
+ if root_thread_id is not None and not root_thread_id:
489
+ # An empty id is a scoping failure, never a request for the whole DB.
490
+ return _empty_memory()
491
+ db = _find_versioned_db("state", "stage1_outputs")
492
+ if db is None:
493
+ return _empty_memory()
494
+
495
+ try:
496
+ with _ro_connect(db) as conn:
497
+ cols = _table_columns(conn, "stage1_outputs")
498
+ if "thread_id" not in cols:
499
+ return _empty_memory()
500
+ raw_expr = "length(raw_memory)" if "raw_memory" in cols else "0"
501
+ summary_expr = "length(rollout_summary)" if "rollout_summary" in cols else "0"
502
+ where = "WHERE thread_id = ?" if root_thread_id is not None else ""
503
+ params = (root_thread_id,) if root_thread_id is not None else ()
504
+ rows = conn.execute(
505
+ f"""
506
+ SELECT thread_id AS thread_id,
507
+ COALESCE({raw_expr}, 0) AS raw_chars,
508
+ COALESCE({summary_expr}, 0) AS summary_chars
509
+ FROM stage1_outputs
510
+ {where}
511
+ LIMIT {_MAX_ROWS + 1}
512
+ """,
513
+ params,
514
+ ).fetchall()
515
+ except (sqlite3.Error, OSError):
516
+ return _empty_memory()
517
+
518
+ # Fetched one past the cap so a binding cap is detectable, never silent.
519
+ truncated = len(rows) > _MAX_ROWS
520
+ rows = rows[:_MAX_ROWS]
521
+ # Only threads that actually carry memory text count; null/empty rows do not.
522
+ rows = [r for r in rows if int(r["raw_chars"] or 0) + int(r["summary_chars"] or 0) > 0]
523
+ if not rows:
524
+ return {**_empty_memory(), "available": True, "truncated": truncated}
525
+
526
+ total_raw = total_summary = max_tokens = 0
527
+ by_thread: list[dict[str, Any]] = []
528
+ for row in rows:
529
+ raw_chars = int(row["raw_chars"] or 0)
530
+ summary_chars = int(row["summary_chars"] or 0)
531
+ total_raw += raw_chars
532
+ total_summary += summary_chars
533
+ thread_tokens = (raw_chars + summary_chars) // CHARS_PER_TOKEN
534
+ max_tokens = max(max_tokens, thread_tokens)
535
+ by_thread.append({"thread_id": str(row["thread_id"] or ""), "memory_tokens": thread_tokens})
536
+
537
+ by_thread.sort(key=lambda item: item["memory_tokens"], reverse=True)
538
+ return {
539
+ "available": True,
540
+ "thread_count": len(rows),
541
+ "truncated": truncated,
542
+ "total_raw_memory_chars": total_raw,
543
+ "total_rollout_summary_chars": total_summary,
544
+ "total_memory_tokens": (total_raw + total_summary) // CHARS_PER_TOKEN,
545
+ "max_thread_memory_tokens": max_tokens,
546
+ "by_thread": by_thread[:_DETAIL_LIMIT],
547
+ }
548
+
549
+
550
+ def _empty_goals() -> dict[str, Any]:
551
+ return {
552
+ "available": False,
553
+ "total_goals": 0,
554
+ "active_goals": 0,
555
+ "budget_limited": 0,
556
+ "usage_limited": 0,
557
+ "over_budget": 0,
558
+ "goals": [],
559
+ }
560
+
561
+
562
+ def goal_budgets(root_thread_id: str | None = None) -> dict[str, Any]:
563
+ """Goal budget utilization from ``thread_goals``.
564
+
565
+ Surfaces per-goal token budget vs. usage and flags goals Codex marked
566
+ ``budget_limited`` / ``usage_limited``, plus goals that exceeded their
567
+ explicit ``token_budget``. Empty-safe.
568
+
569
+ When ``root_thread_id`` is given, only goals belonging to the current goal
570
+ subtree are reported: a goal whose ``thread_id`` sits inside the root's
571
+ transitive descendant set (via ``thread_spawn_edges`` in the state DB), plus
572
+ the opt-in parent-goal rollup — an independent worker goal whose objective
573
+ carries an explicit ``Parent goal <root_thread_id>`` marker is grouped
574
+ under the coordinator WITHOUT pulling unrelated historical sessions in
575
+ (requirements 1, 2, 4). When ``root_thread_id`` is ``None`` the
576
+ legacy whole-DB aggregation runs unchanged (backward-compatible signature).
577
+
578
+ The resolved thread id and every aggregation edge used (spawn edges for the
579
+ subtree + parent-goal rollup edges) are surfaced for audit (requirement 5).
580
+ """
581
+ if not _is_codex():
582
+ return _empty_goals()
583
+ db = _find_versioned_db("goals", "thread_goals")
584
+ if db is None:
585
+ return _empty_goals()
586
+
587
+ try:
588
+ with _ro_connect(db) as conn:
589
+ cols = _table_columns(conn, "thread_goals")
590
+ if "status" not in cols:
591
+ return _empty_goals()
592
+ objective = "objective" if "objective" in cols else "''"
593
+ budget = "token_budget" if "token_budget" in cols else "NULL"
594
+ used = "tokens_used" if "tokens_used" in cols else "0"
595
+ time_used = "time_used_seconds" if "time_used_seconds" in cols else "0"
596
+ thread_id = "thread_id" if "thread_id" in cols else "''"
597
+ rows = conn.execute(
598
+ f"""
599
+ SELECT {thread_id} AS thread_id,
600
+ {objective} AS objective,
601
+ status AS status,
602
+ {budget} AS token_budget,
603
+ COALESCE({used}, 0) AS tokens_used,
604
+ COALESCE({time_used}, 0) AS time_used_seconds
605
+ FROM thread_goals
606
+ LIMIT {_MAX_ROWS}
607
+ """
608
+ ).fetchall()
609
+ except (sqlite3.Error, OSError):
610
+ return _empty_goals()
611
+
612
+ if not rows:
613
+ return {**_empty_goals(), "available": True}
614
+
615
+ # Scope to the current goal subtree when a root is given. The subtree is
616
+ # resolved from the STATE db's spawn edges (a separate database), read in a
617
+ # short-lived read-only connection. Fail-open: an unreadable state DB
618
+ # collapses the subtree to just the root, so only the root's own goal and
619
+ # marker-rollup workers survive — never historical unrelated goals.
620
+ aggregation_edges: list[dict[str, str]] = []
621
+ subtree: set[str] | None = None
622
+ if root_thread_id:
623
+ subtree = {root_thread_id}
624
+ state_db = _find_versioned_db("state", "threads")
625
+ if state_db is not None:
626
+ edge_rows = _fetch_spawn_edges(state_db)
627
+ subtree, spawn_agg_edges = _resolve_subtree(edge_rows, root_thread_id)
628
+ aggregation_edges.extend(spawn_agg_edges)
629
+
630
+ active = budget_limited = usage_limited = over_budget = 0
631
+ goals: list[dict[str, Any]] = []
632
+ for row in rows:
633
+ thread = str(row["thread_id"] or "")
634
+ objective_text = str(row["objective"] or "").strip()
635
+ in_subtree = subtree is None or thread in subtree
636
+ # Opt-in parent-goal rollup: an independent worker goal session whose
637
+ # objective carries ``Parent goal <root_thread_id>`` groups under the
638
+ # coordinator. Absent the marker, no cross-goal aggregation happens.
639
+ rollup_parent = _parse_parent_goal_marker(objective_text) if subtree is not None else None
640
+ if rollup_parent is not None and rollup_parent == root_thread_id:
641
+ in_subtree = True
642
+ aggregation_edges.append({
643
+ "parent_thread_id": root_thread_id,
644
+ "child_thread_id": thread,
645
+ "status": _PARENT_GOAL_EDGE_STATUS,
646
+ })
647
+ if not in_subtree:
648
+ continue
649
+ status = str(row["status"] or "").lower()
650
+ token_budget = row["token_budget"]
651
+ tokens_used = int(row["tokens_used"] or 0)
652
+ utilization: float | None = None
653
+ if isinstance(token_budget, (int, float)) and token_budget > 0:
654
+ utilization = round(tokens_used / token_budget, 3)
655
+ if tokens_used > token_budget:
656
+ over_budget += 1
657
+ if status == "active":
658
+ active += 1
659
+ elif status == "budget_limited":
660
+ budget_limited += 1
661
+ elif status == "usage_limited":
662
+ usage_limited += 1
663
+ goals.append({
664
+ "thread_id": thread,
665
+ "objective": objective_text[:117] + "..." if len(objective_text) > 120 else objective_text,
666
+ "status": status,
667
+ "token_budget": int(token_budget) if isinstance(token_budget, (int, float)) else None,
668
+ "tokens_used": tokens_used,
669
+ "utilization": utilization,
670
+ "time_used_seconds": int(row["time_used_seconds"] or 0),
671
+ })
672
+
673
+ goals.sort(key=lambda item: item["utilization"] if item["utilization"] is not None else -1, reverse=True)
674
+ return {
675
+ "available": True,
676
+ "total_goals": len(goals),
677
+ "active_goals": active,
678
+ "budget_limited": budget_limited,
679
+ "usage_limited": usage_limited,
680
+ "over_budget": over_budget,
681
+ "goals": goals[:_DETAIL_LIMIT],
682
+ "selected_thread_id": root_thread_id,
683
+ "aggregation_edges": aggregation_edges,
684
+ }
685
+
686
+
687
+ def state_db_status() -> dict[str, Any]:
688
+ """Lightweight presence/readability report for the doctor."""
689
+ state_db = _find_versioned_db("state", "threads")
690
+ goals_db = _find_versioned_db("goals", "thread_goals")
691
+ return {
692
+ "state_db": str(state_db) if state_db else None,
693
+ "goals_db": str(goals_db) if goals_db else None,
694
+ "state_readable": bool(state_db and _table_has_rows(state_db, "threads")) if state_db else False,
695
+ "goals_present": goals_db is not None,
696
+ }
697
+
698
+
699
+ if __name__ == "__main__":
700
+ import json
701
+
702
+ print(json.dumps({
703
+ "subagent_costs": subagent_costs(),
704
+ "memory_overhead": memory_overhead(),
705
+ "goal_budgets": goal_budgets(),
706
+ "state_db_status": state_db_status(),
707
+ }, indent=2))