@alexgreensh/token-optimizer 5.13.68 → 5.13.70

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 (182) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/PRIVACY.md +4 -0
  4. package/hooks/hooks.json +11 -1
  5. package/hooks/module_runner.py +4 -1
  6. package/hooks/posttooluse_runner.py +44 -48
  7. package/hooks/sessionstart_runner.py +24 -5
  8. package/hooks/stop_runner.py +6 -6
  9. package/package.json +1 -1
  10. package/skills/fleet-auditor/references/fleet-systems.md +38 -0
  11. package/skills/fleet-auditor/scripts/fleet.py +63 -92
  12. package/skills/fleet-auditor/scripts/fleet_base.py +106 -0
  13. package/skills/fleet-auditor/scripts/fleet_cursor_adapter.py +376 -0
  14. package/skills/token-coach/SKILL.md +21 -23
  15. package/skills/token-dashboard/SKILL.md +5 -4
  16. package/skills/token-optimizer/SKILL.md +1 -1
  17. package/skills/token-optimizer/assets/dashboard.html +492 -551
  18. package/skills/token-optimizer/assets/savings_story.js +661 -0
  19. package/skills/token-optimizer/pricing/prices.json +1 -0
  20. package/skills/token-optimizer/references/cli-reference.md +1 -1
  21. package/skills/token-optimizer/references/cursor-workflow.md +1 -1
  22. package/skills/token-optimizer/references/implementation-playbook.md +3 -0
  23. package/skills/token-optimizer/references/phase0-setup.md +1 -1
  24. package/skills/token-optimizer/references/presentation-workflow.md +1 -1
  25. package/skills/token-optimizer/scripts/_measure/__init__.py +3 -1
  26. package/skills/token-optimizer/scripts/_measure/archive_health.py +14 -0
  27. package/skills/token-optimizer/scripts/_measure/archive_void_codex.py +163 -0
  28. package/skills/token-optimizer/scripts/_measure/archive_void_evidence.py +165 -0
  29. package/skills/token-optimizer/scripts/_measure/audit.py +27 -135
  30. package/skills/token-optimizer/scripts/_measure/baseline_provenance.py +339 -0
  31. package/skills/token-optimizer/scripts/_measure/cache_policy.py +261 -581
  32. package/skills/token-optimizer/scripts/_measure/checkpoint_direction.py +97 -0
  33. package/skills/token-optimizer/scripts/_measure/checkpoint_retention.py +20 -0
  34. package/skills/token-optimizer/scripts/_measure/cli.py +98 -8
  35. package/skills/token-optimizer/scripts/_measure/codex_quality.py +246 -0
  36. package/skills/token-optimizer/scripts/_measure/compaction_survival.py +158 -0
  37. package/skills/token-optimizer/scripts/_measure/compression_fixture_void.py +147 -0
  38. package/skills/token-optimizer/scripts/_measure/compression_scan_checkpoint.py +72 -0
  39. package/skills/token-optimizer/scripts/_measure/context_reset_marker.py +64 -0
  40. package/skills/token-optimizer/scripts/_measure/continuity.py +64 -118
  41. package/skills/token-optimizer/scripts/_measure/cost_per_message_trend.py +40 -0
  42. package/skills/token-optimizer/scripts/_measure/counted_cap.py +28 -0
  43. package/skills/token-optimizer/scripts/_measure/counted_orphans.py +190 -0
  44. package/skills/token-optimizer/scripts/_measure/counted_position.py +20 -0
  45. package/skills/token-optimizer/scripts/_measure/counted_pricing_v5.py +267 -0
  46. package/skills/token-optimizer/scripts/_measure/counted_subagents.py +371 -0
  47. package/skills/token-optimizer/scripts/_measure/coverage_report.py +285 -0
  48. package/skills/token-optimizer/scripts/_measure/daemon.py +61 -94
  49. package/skills/token-optimizer/scripts/_measure/dashboard.py +149 -187
  50. package/skills/token-optimizer/scripts/_measure/dashboard_heal_claim.py +36 -0
  51. package/skills/token-optimizer/scripts/_measure/dashboard_history.py +79 -0
  52. package/skills/token-optimizer/scripts/_measure/evidence_parallel.py +95 -0
  53. package/skills/token-optimizer/scripts/_measure/feature_health.py +256 -0
  54. package/skills/token-optimizer/scripts/_measure/file_refetch.py +250 -0
  55. package/skills/token-optimizer/scripts/_measure/first_call_context.py +216 -0
  56. package/skills/token-optimizer/scripts/_measure/first_read_outcomes.py +261 -0
  57. package/skills/token-optimizer/scripts/_measure/first_read_revive.py +137 -0
  58. package/skills/token-optimizer/scripts/_measure/fixture_context.py +65 -0
  59. package/skills/token-optimizer/scripts/_measure/headline.py +100 -0
  60. package/skills/token-optimizer/scripts/_measure/holdout_fallback.py +96 -0
  61. package/skills/token-optimizer/scripts/_measure/holdout_report.py +125 -0
  62. package/skills/token-optimizer/scripts/_measure/keepwarm_economics.py +201 -0
  63. package/skills/token-optimizer/scripts/_measure/keepwarm_fork.py +140 -0
  64. package/skills/token-optimizer/scripts/_measure/keepwarm_guard.py +35 -0
  65. package/skills/token-optimizer/scripts/_measure/keepwarm_guard_server.py +85 -0
  66. package/skills/token-optimizer/scripts/_measure/keepwarm_linux.py +121 -0
  67. package/skills/token-optimizer/scripts/_measure/keepwarm_prefix.py +143 -0
  68. package/skills/token-optimizer/scripts/_measure/keepwarm_response_filter.py +84 -0
  69. package/skills/token-optimizer/scripts/_measure/keepwarm_safety.py +256 -0
  70. package/skills/token-optimizer/scripts/_measure/lean_resume_receivers.py +260 -0
  71. package/skills/token-optimizer/scripts/_measure/lean_resume_threshold.py +76 -0
  72. package/skills/token-optimizer/scripts/_measure/lease_candidate_cleanup.py +82 -0
  73. package/skills/token-optimizer/scripts/_measure/lifecycle.py +59 -168
  74. package/skills/token-optimizer/scripts/_measure/mcp_archive_tripwire.py +120 -0
  75. package/skills/token-optimizer/scripts/_measure/mod_action_booking.py +178 -0
  76. package/skills/token-optimizer/scripts/_measure/mod_compaction_booking.py +276 -0
  77. package/skills/token-optimizer/scripts/_measure/mod_fresh_booking.py +105 -0
  78. package/skills/token-optimizer/scripts/_measure/output_reread.py +629 -0
  79. package/skills/token-optimizer/scripts/_measure/own_price_card.py +268 -0
  80. package/skills/token-optimizer/scripts/_measure/periphery_exposure.py +85 -0
  81. package/skills/token-optimizer/scripts/_measure/pricing.py +152 -87
  82. package/skills/token-optimizer/scripts/_measure/quality_archive.py +159 -215
  83. package/skills/token-optimizer/scripts/_measure/quality_checkpoint.py +173 -0
  84. package/skills/token-optimizer/scripts/_measure/quality_continuity.py +43 -0
  85. package/skills/token-optimizer/scripts/_measure/rework_metrics.py +194 -0
  86. package/skills/token-optimizer/scripts/_measure/routing_period.py +48 -0
  87. package/skills/token-optimizer/scripts/_measure/savings.py +451 -933
  88. package/skills/token-optimizer/scripts/_measure/savings_story.py +187 -0
  89. package/skills/token-optimizer/scripts/_measure/session_best.py +24 -0
  90. package/skills/token-optimizer/scripts/_measure/session_effect.py +557 -0
  91. package/skills/token-optimizer/scripts/_measure/session_flush_lock.py +75 -0
  92. package/skills/token-optimizer/scripts/_measure/session_store_spool.py +220 -0
  93. package/skills/token-optimizer/scripts/_measure/sessions.py +154 -216
  94. package/skills/token-optimizer/scripts/_measure/setup_attachment_counter.py +196 -0
  95. package/skills/token-optimizer/scripts/_measure/setup_budget_monitor.py +180 -0
  96. package/skills/token-optimizer/scripts/_measure/setup_connector_ledger.py +126 -0
  97. package/skills/token-optimizer/scripts/_measure/setup_step.py +220 -0
  98. package/skills/token-optimizer/scripts/_measure/status_bar_lock.py +117 -0
  99. package/skills/token-optimizer/scripts/_measure/structural_archives.py +79 -0
  100. package/skills/token-optimizer/scripts/_measure/structural_dedupe.py +91 -0
  101. package/skills/token-optimizer/scripts/_measure/structural_ledger.py +418 -0
  102. package/skills/token-optimizer/scripts/_measure/structural_listing.py +163 -0
  103. package/skills/token-optimizer/scripts/_measure/structural_report.py +339 -0
  104. package/skills/token-optimizer/scripts/_measure/structural_seed.py +164 -0
  105. package/skills/token-optimizer/scripts/_measure/structural_value.py +248 -0
  106. package/skills/token-optimizer/scripts/_measure/structure_funnel.py +97 -0
  107. package/skills/token-optimizer/scripts/_measure/timestamp_cache.py +11 -0
  108. package/skills/token-optimizer/scripts/_measure/token_type_split.py +29 -0
  109. package/skills/token-optimizer/scripts/_measure/transcript_backfill.py +419 -0
  110. package/skills/token-optimizer/scripts/_measure/transcript_product.py +228 -0
  111. package/skills/token-optimizer/scripts/_measure/transcript_stream.py +279 -0
  112. package/skills/token-optimizer/scripts/_measure/trends.py +44 -185
  113. package/skills/token-optimizer/scripts/_measure/ttl_period.py +6 -0
  114. package/skills/token-optimizer/scripts/_measure/upgrade_drain_control.py +287 -0
  115. package/skills/token-optimizer/scripts/_measure/weekly_activity.py +69 -0
  116. package/skills/token-optimizer/scripts/activity_tracker.py +4 -33
  117. package/skills/token-optimizer/scripts/antigravity_install.py +6 -0
  118. package/skills/token-optimizer/scripts/archive_result.py +15 -19
  119. package/skills/token-optimizer/scripts/archive_verify.py +165 -0
  120. package/skills/token-optimizer/scripts/bash_compress.py +22 -83
  121. package/skills/token-optimizer/scripts/bash_compress_hook.py +137 -1
  122. package/skills/token-optimizer/scripts/bash_search_results.py +43 -0
  123. package/skills/token-optimizer/scripts/checkpoint_state.py +2 -2
  124. package/skills/token-optimizer/scripts/cloud_kit.py +3 -6
  125. package/skills/token-optimizer/scripts/codemap.py +274 -0
  126. package/skills/token-optimizer/scripts/codemap_hint.py +153 -0
  127. package/skills/token-optimizer/scripts/codemap_index.py +656 -0
  128. package/skills/token-optimizer/scripts/codemap_ledger.py +309 -0
  129. package/skills/token-optimizer/scripts/codemap_reread.py +161 -0
  130. package/skills/token-optimizer/scripts/codex_doctor.py +9 -1
  131. package/skills/token-optimizer/scripts/codex_log_index.py +34 -15
  132. package/skills/token-optimizer/scripts/codex_session.py +16 -216
  133. package/skills/token-optimizer/scripts/compression_backfill.py +4 -35
  134. package/skills/token-optimizer/scripts/context_intel.py +5 -3
  135. package/skills/token-optimizer/scripts/copilot_install.py +6 -0
  136. package/skills/token-optimizer/scripts/coverage_funnel.py +261 -0
  137. package/skills/token-optimizer/scripts/credential_patterns.py +4 -19
  138. package/skills/token-optimizer/scripts/credential_url_patterns.py +42 -0
  139. package/skills/token-optimizer/scripts/cursor_audit.py +723 -0
  140. package/skills/token-optimizer/scripts/cursor_bridge_checkpoint.py +213 -0
  141. package/skills/token-optimizer/scripts/cursor_bridge_payload.py +170 -0
  142. package/skills/token-optimizer/scripts/cursor_bridge_rewrite.py +106 -0
  143. package/skills/token-optimizer/scripts/cursor_bridge_rollup.py +115 -0
  144. package/skills/token-optimizer/scripts/cursor_coach.py +485 -0
  145. package/skills/token-optimizer/scripts/cursor_doctor.py +89 -9
  146. package/skills/token-optimizer/scripts/cursor_hook_bridge.py +393 -276
  147. package/skills/token-optimizer/scripts/cursor_install.py +118 -19
  148. package/skills/token-optimizer/scripts/cursor_quality.py +457 -0
  149. package/skills/token-optimizer/scripts/cursor_read_cache.py +597 -0
  150. package/skills/token-optimizer/scripts/cursor_session.py +26 -5
  151. package/skills/token-optimizer/scripts/cursor_state.py +8 -0
  152. package/skills/token-optimizer/scripts/cursor_statusline.py +372 -0
  153. package/skills/token-optimizer/scripts/cursor_thrash.py +78 -0
  154. package/skills/token-optimizer/scripts/cursor_transcript.py +223 -0
  155. package/skills/token-optimizer/scripts/dashboard_assets.py +21 -0
  156. package/skills/token-optimizer/scripts/deterministic_candidates.py +2 -10
  157. package/skills/token-optimizer/scripts/devin_source.py +19 -4
  158. package/skills/token-optimizer/scripts/devin_verify.py +13 -6
  159. package/skills/token-optimizer/scripts/grok_install.py +6 -0
  160. package/skills/token-optimizer/scripts/heal_report.py +7 -6
  161. package/skills/token-optimizer/scripts/hermes_doctor.py +12 -1
  162. package/skills/token-optimizer/scripts/hermes_install.py +10 -1
  163. package/skills/token-optimizer/scripts/hermes_session.py +14 -136
  164. package/skills/token-optimizer/scripts/hint_paths.py +21 -0
  165. package/skills/token-optimizer/scripts/holdout.py +136 -0
  166. package/skills/token-optimizer/scripts/hook_runtime.py +1 -0
  167. package/skills/token-optimizer/scripts/hook_skip_log.py +89 -0
  168. package/skills/token-optimizer/scripts/large_transcripts.py +31 -0
  169. package/skills/token-optimizer/scripts/lean_resume_carry.py +518 -0
  170. package/skills/token-optimizer/scripts/measure.py +36 -78
  171. package/skills/token-optimizer/scripts/post_run_classify.py +349 -0
  172. package/skills/token-optimizer/scripts/preserved_reinject.py +54 -0
  173. package/skills/token-optimizer/scripts/read_cache.py +99 -100
  174. package/skills/token-optimizer/scripts/reset_epoch.py +3 -3
  175. package/skills/token-optimizer/scripts/session_store.py +49 -99
  176. package/skills/token-optimizer/scripts/session_store_guard.py +75 -0
  177. package/skills/token-optimizer/scripts/settings_backup.py +379 -0
  178. package/skills/token-optimizer/scripts/shipped_hook_templates.py +1 -0
  179. package/skills/token-optimizer/scripts/statusline.js +1 -1
  180. package/skills/token-optimizer/scripts/structural.py +25 -0
  181. package/skills/token-optimizer/scripts/structure_map.py +4 -26
  182. package/skills/token-optimizer/scripts/thrash_guard.py +10 -5
@@ -0,0 +1,274 @@
1
+ #!/usr/bin/env python3
2
+ """Code map lookup: answer structural code questions without reading whole files.
3
+
4
+ codemap.py find <symbol> where a function/class/method/variable is defined
5
+ codemap.py show <symbol> the source of that one definition (line-numbered)
6
+ codemap.py callers <symbol> call sites, grouped by file and enclosing function
7
+ codemap.py outline <file> definitions in a file with line ranges
8
+ codemap.py deps <file> what a file imports and which files import it
9
+ codemap.py refresh | stats (maintenance)
10
+
11
+ Options: --root DIR (default: the project containing the cwd), --in TEXT (only
12
+ paths containing TEXT), --max-lines N (show).
13
+
14
+ Python and JS/TS only. Every answer is hard-capped (~800 tokens) and the index
15
+ is synced (mtime+size) before each query, so answers match the files on disk.
16
+ On any index problem it prints one line telling the agent to use Grep/Read and
17
+ exits 0: lookups fail open, never in the agent's way.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import argparse
23
+ import hashlib
24
+ import os
25
+ import sys
26
+ from pathlib import Path
27
+ from typing import List, Optional, Sequence, Tuple
28
+
29
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
30
+
31
+ MAX_OUT_CHARS = 3200
32
+ MAX_SHOW_LINES = 120
33
+ FALLBACK = "codemap: {why}. Use Grep/Read instead."
34
+
35
+
36
+ def _estimate_tokens(text: str) -> int:
37
+ try:
38
+ from token_estimate import estimate_tokens
39
+ return int(estimate_tokens(text))
40
+ except Exception:
41
+ return max(1, len(text) // 4)
42
+
43
+
44
+ class _Out:
45
+ """Line buffer with a hard character cap."""
46
+
47
+ def __init__(self, cap: int = MAX_OUT_CHARS):
48
+ self.cap = cap
49
+ self.lines: List[str] = []
50
+ self.size = 0
51
+ self.dropped = 0
52
+
53
+ def add(self, line: str) -> bool:
54
+ if self.size + len(line) + 1 > self.cap:
55
+ self.dropped += 1
56
+ return False
57
+ self.lines.append(line)
58
+ self.size += len(line) + 1
59
+ return True
60
+
61
+ def text(self, more_hint: str = "") -> str:
62
+ out = list(self.lines)
63
+ if self.dropped:
64
+ out.append(f"... +{self.dropped} more lines cut at the answer cap{more_hint}")
65
+ return "\n".join(out)
66
+
67
+
68
+ def _filter(rows: Sequence[Tuple], within: str, path_idx: int) -> List[Tuple]:
69
+ if not within:
70
+ return list(rows)
71
+ return [r for r in rows if within in r[path_idx]]
72
+
73
+
74
+ def _span(line: int, end: int) -> str:
75
+ return f"{line}" if not end or end <= line else f"{line}-{end}"
76
+
77
+
78
+ def cmd_find(idx, symbol: str, within: str, out: _Out) -> List[str]:
79
+ rows = _filter(idx.find_defs(symbol), within, 3)
80
+ if not rows:
81
+ out.add(f"no definition of '{symbol}' in the index ({idx.counts()['files']} files)."
82
+ " It may be external, dynamic, or in an unsupported language.")
83
+ return []
84
+ exact = any(r[0] == symbol.rsplit(".", 1)[-1] for r in rows)
85
+ out.add(f"{len(rows)} definition(s) of '{symbol}'" + ("" if exact else " (partial-name matches)") + ":")
86
+ for name, qual, kind, path, line, end, sig in rows:
87
+ out.add(f"{path}:{_span(line, end)} {kind} {qual} {sig}")
88
+ paths = list(dict.fromkeys(r[3] for r in rows))
89
+ return paths[:1] if exact and len(rows) <= 6 else []
90
+
91
+
92
+ def cmd_show(idx, symbol: str, within: str, max_lines: int, out: _Out) -> List[str]:
93
+ rows = _filter(idx.find_defs(symbol), within, 3)
94
+ rows = [r for r in rows if r[0] == symbol.rsplit(".", 1)[-1] or r[1] == symbol] or rows
95
+ if not rows:
96
+ out.add(f"no definition of '{symbol}' in the index.")
97
+ return []
98
+ rows.sort(key=lambda r: (r[2] == "variable", r[1] != symbol))
99
+ name, qual, kind, path, line, end, sig = rows[0]
100
+ abs_path = idx.root / path
101
+ try:
102
+ src = abs_path.read_text(encoding="utf-8", errors="replace").splitlines()
103
+ except OSError:
104
+ out.add(f"{path} is no longer readable.")
105
+ return []
106
+ end = max(line, end or line)
107
+ last = min(end, line + max_lines - 1, len(src))
108
+ out.add(f"{path}:{_span(line, end)} {kind} {qual} (lines {line}-{last} of {len(src)}; Edit-ready numbering)")
109
+ for n in range(line, last + 1):
110
+ if not out.add(f"{n:>6}\t{src[n - 1]}"):
111
+ break
112
+ if last < end:
113
+ out.add(f"... body continues to line {end}: Read {path} with offset={last + 1} for the rest")
114
+ if len(rows) > 1:
115
+ others = ", ".join(f"{r[3]}:{r[4]}" for r in rows[1:4])
116
+ out.add(f"also defined at: {others}" + (" ..." if len(rows) > 4 else ""))
117
+ return [path]
118
+
119
+
120
+ def cmd_callers(idx, symbol: str, within: str, out: _Out) -> List[str]:
121
+ rows = _filter(idx.callers(symbol), within, 0)
122
+ if not rows:
123
+ out.add(f"no call sites of '{symbol}' found (name-based; dynamic calls are invisible).")
124
+ return []
125
+ by_file: dict = {}
126
+ for path, line, caller, n in rows:
127
+ by_file.setdefault(path, []).append((line, caller, n))
128
+ total = sum(r[3] for r in rows)
129
+ out.add(f"{total} call(s) of '{symbol.rsplit('.', 1)[-1]}' in {len(by_file)} file(s)"
130
+ " (matched by name; same-named symbols are included):")
131
+ ranked = sorted(by_file.items(), key=lambda kv: -sum(x[2] for x in kv[1]))
132
+ for path, sites in ranked:
133
+ parts = [f"{caller}@{line}" + (f" x{n}" if n > 1 else "") for line, caller, n in sites[:8]]
134
+ extra = f" +{len(sites) - 8}" if len(sites) > 8 else ""
135
+ out.add(f"{path}: " + ", ".join(parts) + extra)
136
+ return [p for p, _ in ranked[:2]]
137
+
138
+
139
+ def _resolve_file(idx, file_arg: str) -> Optional[str]:
140
+ rel = idx.rel(file_arg)
141
+ if rel and idx.file_row(rel):
142
+ return rel
143
+ tail = file_arg.replace("\\", "/").lstrip("./")
144
+ row = idx.conn.execute(
145
+ "SELECT path FROM files WHERE path=? OR path LIKE ? ORDER BY length(path) LIMIT 1",
146
+ (tail, "%/" + tail)).fetchone()
147
+ return row[0] if row else None
148
+
149
+
150
+ def cmd_outline(idx, file_arg: str, out: _Out) -> List[str]:
151
+ rel = _resolve_file(idx, file_arg)
152
+ if rel is None:
153
+ out.add(f"{file_arg} is not in the index (Python/JS/TS only).")
154
+ return []
155
+ row = idx.file_row(rel)
156
+ defs = idx.outline(rel)
157
+ out.add(f"{rel}: {row[5]} lines, ~{row[4]:,} tokens to Read in full, {len(defs)} definitions"
158
+ + ("" if row[6] else " (parse failed; outline incomplete)"))
159
+ for name, qual, kind, line, end, sig in defs:
160
+ if kind == "variable":
161
+ continue
162
+ indent = " " * qual.count(".")
163
+ out.add(f"{indent}{_span(line, end)} {sig}")
164
+ return [rel]
165
+
166
+
167
+ def cmd_deps(idx, file_arg: str, out: _Out) -> List[str]:
168
+ rel = _resolve_file(idx, file_arg)
169
+ if rel is None:
170
+ out.add(f"{file_arg} is not in the index (Python/JS/TS only).")
171
+ return []
172
+ imports = idx.imports_of(rel)
173
+ internal = [t for _, t in imports if t]
174
+ external = [m for m, t in imports if not t]
175
+ out.add(f"{rel} imports {len(internal)} project file(s): " + (", ".join(internal) or "none"))
176
+ if external:
177
+ out.add("external/unresolved: " + ", ".join(external[:30]) + (" ..." if len(external) > 30 else ""))
178
+ importers = idx.importers_of(rel)
179
+ out.add(f"imported by {len(importers)} file(s): " + (", ".join(importers) or "none"))
180
+ return [rel]
181
+
182
+
183
+ def _root_hash(root: Path) -> str:
184
+ return hashlib.sha256(str(root).encode("utf-8", "replace")).hexdigest()[:16]
185
+
186
+
187
+ def run(argv: Sequence[str]) -> Tuple[int, str]:
188
+ parser = argparse.ArgumentParser(prog="codemap.py", add_help=True)
189
+ parser.add_argument("command", choices=["find", "show", "callers", "outline", "deps", "refresh", "stats"])
190
+ parser.add_argument("arg", nargs="?", default="")
191
+ parser.add_argument("--root", default="")
192
+ parser.add_argument("--in", dest="within", default="")
193
+ parser.add_argument("--max-lines", type=int, default=MAX_SHOW_LINES)
194
+ parser.add_argument("--budget", type=float, default=None)
195
+ parser.add_argument("--quiet", action="store_true")
196
+ parser.add_argument("--background", action="store_true", help=argparse.SUPPRESS)
197
+ args = parser.parse_args(list(argv))
198
+ if args.background:
199
+ try:
200
+ os.nice(10)
201
+ except (AttributeError, OSError):
202
+ pass
203
+
204
+ import codemap_index as ci
205
+ if not ci.codemap_enabled():
206
+ return 0, "codemap is turned off (TOKEN_OPTIMIZER_CODEMAP=0). Use Grep/Read."
207
+ if args.command in ("find", "show", "callers", "outline", "deps") and not args.arg.strip():
208
+ return 2, f"usage: codemap.py {args.command} <{'file' if args.command in ('outline', 'deps') else 'symbol'}>"
209
+
210
+ start = args.root or os.getcwd()
211
+ idx = ci.open_synced(start, budget_s=args.budget)
212
+ try:
213
+ if args.command == "refresh":
214
+ if args.background:
215
+ try:
216
+ idx.db_path.with_suffix(".building").unlink()
217
+ except OSError:
218
+ pass
219
+ c = idx.counts()
220
+ return 0, "" if args.quiet else f"codemap index: {c['files']} files, complete={idx.complete}"
221
+ if args.command == "stats":
222
+ c = idx.counts()
223
+ return 0, (f"root {idx.root}\nfiles {c['files']} defs {c['defs']} imports {c['imports']} "
224
+ f"call-edges {c['refs']} complete={idx.complete} db={idx.db_path.stat().st_size // 1024}KB")
225
+ out = _Out()
226
+ max_lines = max(5, min(int(args.max_lines or MAX_SHOW_LINES), 400))
227
+ symbol = args.arg.strip()
228
+ if args.command == "find":
229
+ covered = cmd_find(idx, symbol, args.within, out)
230
+ elif args.command == "show":
231
+ covered = cmd_show(idx, symbol, args.within, max_lines, out)
232
+ elif args.command == "callers":
233
+ covered = cmd_callers(idx, symbol, args.within, out)
234
+ elif args.command == "outline":
235
+ covered = cmd_outline(idx, symbol, out)
236
+ else:
237
+ covered = cmd_deps(idx, symbol, out)
238
+ if not idx.complete:
239
+ out.lines.append(f"(index still building: {idx.counts()['files']} files so far; rerun or Grep for anything missing)")
240
+ text = out.text(" (narrow with --in <path> or Class.method)")
241
+ _log(idx, args.command, text, covered)
242
+ return 0, text
243
+ finally:
244
+ idx.close()
245
+
246
+
247
+ def _log(idx, command: str, text: str, covered: List[str]) -> None:
248
+ try:
249
+ import codemap_ledger as led
250
+ cov = [(str(idx.root / rel), idx.file_tokens(rel)) for rel in covered]
251
+ led.log_lookup(command, _estimate_tokens(text), cov, root_hash=_root_hash(idx.root))
252
+ led.resolve_pending()
253
+ except Exception:
254
+ pass
255
+
256
+
257
+ def main(argv: Optional[Sequence[str]] = None) -> int:
258
+ argv = list(sys.argv[1:] if argv is None else argv)
259
+ try:
260
+ code, text = run(argv)
261
+ except SystemExit as exc: # argparse usage errors
262
+ return int(exc.code or 0)
263
+ except Exception as exc:
264
+ why = type(exc).__name__
265
+ msg = str(exc).splitlines()[0][:120] if str(exc) else ""
266
+ print(FALLBACK.format(why=f"index unavailable ({why}{': ' + msg if msg else ''})"))
267
+ return 0
268
+ if text:
269
+ print(text)
270
+ return code
271
+
272
+
273
+ if __name__ == "__main__":
274
+ sys.exit(main())
@@ -0,0 +1,153 @@
1
+ #!/usr/bin/env python3
2
+ """Discovery hint for the code map (SessionStart and SubagentStart).
3
+
4
+ Tells the agent, in about 80 tokens, to ask the code map before grepping or
5
+ reading whole files for structural questions, and warms the index in a
6
+ detached background process so the first lookup is fast. Silent (no output,
7
+ no spawn) when the feature is off, when the cwd is the home directory or the
8
+ filesystem root, or when the project has no Python/JS/TS files.
9
+
10
+ Run as a hook: ``codemap_hint.py`` reads the hook payload on stdin and prints
11
+ SubagentStart JSON (additionalContext). SessionStart uses ``session_text()``
12
+ from hooks/sessionstart_runner.py, which wraps plain text itself.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ import os
19
+ import shlex
20
+ import sys
21
+ import time
22
+ from pathlib import Path
23
+ from typing import Optional
24
+
25
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
26
+
27
+ PROBE_MAX_ENTRIES = 400
28
+ PROBE_MAX_S = 0.25
29
+ LOCK_FRESH_S = 300.0
30
+ # Subagents that never explore code: no hint for them.
31
+ SKIP_AGENT_TYPES = frozenset({"statusline-setup", "claude-code-guide", "web-fetch"})
32
+
33
+
34
+ def _has_code(root: Path) -> bool:
35
+ import codemap_index as ci
36
+ seen = 0
37
+ deadline = time.monotonic() + PROBE_MAX_S
38
+ for dirpath, dirnames, filenames in os.walk(root):
39
+ dirnames[:] = [d for d in dirnames if d not in ci.SKIP_DIRS and not d.startswith(".")]
40
+ seen += 1 + len(dirnames)
41
+ for fn in filenames:
42
+ seen += 1
43
+ if Path(fn).suffix.lower() in ci.SUPPORTED_SUFFIXES:
44
+ return True
45
+ if seen > PROBE_MAX_ENTRIES or time.monotonic() > deadline:
46
+ return False
47
+ return False
48
+
49
+
50
+ def _project_root(cwd: str) -> Optional[Path]:
51
+ import codemap_index as ci
52
+ if not cwd:
53
+ return None # hosts always send cwd; never guess (and never index) an unknown dir
54
+ try:
55
+ p = Path(cwd).expanduser().resolve()
56
+ except OSError:
57
+ return None
58
+ if p == Path.home().resolve() or p.parent == p or not p.is_dir():
59
+ return None
60
+ root = ci.find_project_root(p)
61
+ return root if _has_code(root) else None
62
+
63
+
64
+ def warm_index(root: Path) -> bool:
65
+ """Start a detached, niced index build unless one is fresh or running."""
66
+ import codemap_index as ci
67
+ db = ci.index_path(root)
68
+ lock = db.with_suffix(".building")
69
+ try:
70
+ if db.exists():
71
+ import sqlite3
72
+ conn = sqlite3.connect(str(db), timeout=1.0)
73
+ try:
74
+ row = conn.execute("SELECT v FROM meta WHERE k='complete'").fetchone()
75
+ finally:
76
+ conn.close()
77
+ if row and row[0] == "1":
78
+ return False # each lookup syncs incrementally; nothing to warm
79
+ if lock.exists() and time.time() - lock.stat().st_mtime < LOCK_FRESH_S:
80
+ return False
81
+ lock.parent.mkdir(parents=True, exist_ok=True)
82
+ lock.write_text(str(os.getpid()), encoding="utf-8")
83
+ from spawn_utils import spawn_detached
84
+ script = str(Path(__file__).resolve().parent / "codemap.py")
85
+ import subprocess
86
+ # DEVNULL streams: an inherited hook stdout pipe would hold the host's
87
+ # SessionStart/SubagentStart read open until the build finishes.
88
+ proc = spawn_detached([sys.executable, script, "refresh", "--root", str(root),
89
+ "--budget", "120", "--quiet", "--background"],
90
+ stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
91
+ return proc is not None
92
+ except Exception:
93
+ return False
94
+
95
+
96
+ def hint_text(root: Path) -> str:
97
+ script = shlex.quote(str(Path(__file__).resolve().parent / "codemap.py"))
98
+ py = shlex.quote(sys.executable or "python3")
99
+ return (
100
+ "[Token Optimizer] Code map available for this project (Python/JS/TS). For \"where is X "
101
+ "defined\", \"what calls Y\" or \"what does this file import\", run it BEFORE Grep, grep/rg in "
102
+ f"Bash, or reading whole files: `{py} {script} find|show|callers <symbol>` or `outline|deps <file>`. "
103
+ "`show` prints one definition with Edit-ready line numbers; answers are small and match the files on disk."
104
+ )
105
+
106
+
107
+ def session_text(hook_input: dict) -> str:
108
+ """Plain hint text for SessionStart ('' when off or not a code project)."""
109
+ try:
110
+ import codemap_index as ci
111
+ if not ci.codemap_enabled():
112
+ return ""
113
+ root = _project_root(str(hook_input.get("cwd") or ""))
114
+ if root is None:
115
+ return ""
116
+ warm_index(root)
117
+ return hint_text(root)
118
+ except Exception:
119
+ return ""
120
+
121
+
122
+ def subagent_payload(hook_input: dict) -> Optional[dict]:
123
+ agent_type = str(hook_input.get("agent_type") or "")
124
+ if agent_type in SKIP_AGENT_TYPES:
125
+ return None
126
+ text = session_text(hook_input)
127
+ if not text:
128
+ return None
129
+ return {"hookSpecificOutput": {"hookEventName": "SubagentStart", "additionalContext": text}}
130
+
131
+
132
+ def main() -> int:
133
+ try:
134
+ from hook_io import read_stdin_hook_input
135
+ hook_input = read_stdin_hook_input() or {}
136
+ except Exception:
137
+ try:
138
+ hook_input = json.loads(sys.stdin.read() or "{}")
139
+ except Exception:
140
+ hook_input = {}
141
+ if not isinstance(hook_input, dict):
142
+ return 0
143
+ payload = subagent_payload(hook_input)
144
+ if payload:
145
+ print(json.dumps(payload))
146
+ return 0
147
+
148
+
149
+ if __name__ == "__main__":
150
+ try:
151
+ sys.exit(main())
152
+ except Exception:
153
+ sys.exit(0)