sessioncost 1.2.7__tar.gz → 1.2.8__tar.gz

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 (112) hide show
  1. {sessioncost-1.2.7/sessioncost.egg-info → sessioncost-1.2.8}/PKG-INFO +1 -1
  2. {sessioncost-1.2.7 → sessioncost-1.2.8}/pyproject.toml +1 -1
  3. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/__init__.py +1 -1
  4. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/analyse.py +6 -5
  5. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/cli.py +6 -1
  6. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/fixer.py +25 -9
  7. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/fixer_plan.py +53 -17
  8. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/fixes/__init__.py +15 -1
  9. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/fixes/big_results.py +10 -1
  10. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/fixes/common.py +24 -0
  11. sessioncost-1.2.8/sessioncost/fixes/helper_model.py +131 -0
  12. sessioncost-1.2.8/sessioncost/fixes/hook_output.py +85 -0
  13. sessioncost-1.2.8/sessioncost/fixes/ignore_folders.py +80 -0
  14. sessioncost-1.2.8/sessioncost/fixes/large_files.py +69 -0
  15. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/fixes/long_chat.py +37 -12
  16. sessioncost-1.2.8/sessioncost/fixes/model_choice.py +109 -0
  17. sessioncost-1.2.8/sessioncost/fixes/notes_file.py +62 -0
  18. sessioncost-1.2.8/sessioncost/fixes/skill_cost.py +227 -0
  19. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/fixes/startup_bloat.py +53 -9
  20. sessioncost-1.2.8/sessioncost/fixes/unused_skills.py +123 -0
  21. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/fixes/unused_tools.py +66 -5
  22. sessioncost-1.2.8/sessioncost/fixes/verbose_tests.py +63 -0
  23. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/guard.py +18 -8
  24. sessioncost-1.2.8/sessioncost/guard_break.py +175 -0
  25. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/guard_checks.py +12 -201
  26. sessioncost-1.2.8/sessioncost/guard_reads.py +234 -0
  27. sessioncost-1.2.8/sessioncost/helper_agent.py +151 -0
  28. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/model.py +4 -0
  29. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/practices.py +50 -0
  30. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/readers/claude.py +17 -2
  31. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/readers/claude_text.py +23 -1
  32. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/report_board.html +30 -19
  33. sessioncost-1.2.8/sessioncost/risk_network.py +49 -0
  34. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/risk_patterns.py +68 -9
  35. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/risks.py +112 -13
  36. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/sarif.py +4 -2
  37. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/serve.py +126 -119
  38. sessioncost-1.2.8/sessioncost/workspace.py +138 -0
  39. {sessioncost-1.2.7 → sessioncost-1.2.8/sessioncost.egg-info}/PKG-INFO +1 -1
  40. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost.egg-info/SOURCES.txt +13 -0
  41. sessioncost-1.2.7/sessioncost/fixes/model_choice.py +0 -82
  42. {sessioncost-1.2.7 → sessioncost-1.2.8}/LICENSE +0 -0
  43. {sessioncost-1.2.7 → sessioncost-1.2.8}/MANIFEST.in +0 -0
  44. {sessioncost-1.2.7 → sessioncost-1.2.8}/README.md +0 -0
  45. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/__main__.py +0 -0
  46. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/analyse_calls.py +0 -0
  47. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/analyse_lists.py +0 -0
  48. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/cli_setup.py +0 -0
  49. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/current_chat.py +0 -0
  50. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/editor.py +0 -0
  51. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/fixer_store.py +0 -0
  52. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/fixes/cache_break.py +0 -0
  53. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/fixes/confirm_turns.py +0 -0
  54. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/fixes/error_loop.py +0 -0
  55. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/fixes/helper_polling.py +0 -0
  56. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/fixes/helper_rereads.py +0 -0
  57. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/fixes/images.py +0 -0
  58. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/fixes/long_output.py +0 -0
  59. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/fixes/overlap.py +0 -0
  60. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/fixes/repeated_reads.py +0 -0
  61. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/fixes/repeated_writes.py +0 -0
  62. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/fixes/reruns.py +0 -0
  63. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/fixes/stale_context.py +0 -0
  64. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/fixes/unused_builtins.py +0 -0
  65. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/fresh_chat.py +0 -0
  66. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/guard_agents.py +0 -0
  67. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/guard_auto.py +0 -0
  68. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/guard_decide.py +0 -0
  69. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/guard_fresh.py +0 -0
  70. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/guard_inventory.py +0 -0
  71. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/guard_owasp.py +0 -0
  72. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/guard_post.py +0 -0
  73. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/guard_quiet.py +0 -0
  74. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/guard_report.py +0 -0
  75. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/guard_scan.py +0 -0
  76. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/guard_setup.py +0 -0
  77. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/guard_store.py +0 -0
  78. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/guard_waste.py +0 -0
  79. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/help_menu.py +0 -0
  80. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/hook.py +0 -0
  81. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/locate.py +0 -0
  82. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/names.py +0 -0
  83. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/opener.py +0 -0
  84. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/prices.json +0 -0
  85. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/prices.py +0 -0
  86. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/prices_cmd.py +0 -0
  87. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/readers/__init__.py +0 -0
  88. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/readers/_pb.py +0 -0
  89. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/readers/_util.py +0 -0
  90. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/readers/antigravity.py +0 -0
  91. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/readers/codex.py +0 -0
  92. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/readers/copilot.py +0 -0
  93. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/readers/cursor.py +0 -0
  94. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/readers/cursor_steps.py +0 -0
  95. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/readers/cursor_usage.py +0 -0
  96. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/readers/vscode_chat.py +0 -0
  97. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/report.py +0 -0
  98. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/risk_bypass.py +0 -0
  99. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/risk_shell.py +0 -0
  100. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/rules.py +0 -0
  101. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/skill/SKILL.md +0 -0
  102. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/skill/liveguard.md +0 -0
  103. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/status.py +0 -0
  104. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/textflags.py +0 -0
  105. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/uninstall.py +0 -0
  106. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/unsafe_code.py +0 -0
  107. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/update.py +0 -0
  108. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost/zfile.py +0 -0
  109. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost.egg-info/dependency_links.txt +0 -0
  110. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost.egg-info/entry_points.txt +0 -0
  111. {sessioncost-1.2.7 → sessioncost-1.2.8}/sessioncost.egg-info/top_level.txt +0 -0
  112. {sessioncost-1.2.7 → sessioncost-1.2.8}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sessioncost
3
- Version: 1.2.7
3
+ Version: 1.2.8
4
4
  Summary: See how many tokens each turn of your coding-agent chat sends, why, and what to cut. Cost goes down with it.
5
5
  Author: kish21
6
6
  License-Expression: MIT
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "sessioncost"
7
- version = "1.2.7"
7
+ version = "1.2.8"
8
8
  description = "See how many tokens each turn of your coding-agent chat sends, why, and what to cut. Cost goes down with it."
9
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -1,2 +1,2 @@
1
1
  """SessionCost: see where every token of your agent session went, turn by turn, and what to fix."""
2
- __version__ = "1.2.7"
2
+ __version__ = "1.2.8"
@@ -13,6 +13,7 @@ from datetime import datetime
13
13
 
14
14
  from . import fixes as fixmod, rules
15
15
  from .fixes.overlap import combine, shared
16
+ from .helper_agent import RULES_FILE
16
17
  from . import __version__, prices as pricemod
17
18
  from .model import Call, Session
18
19
  from .readers._util import clean_cmd
@@ -226,10 +227,7 @@ def analyse(s: Session, prices: dict, subscription: bool = False, engines: list
226
227
  "date": s.started.astimezone().strftime("%d %b %Y") if s.started else "",
227
228
  # the file each agent reads at the start of every chat (Cursor: AGENTS.md in the project root; a plain
228
229
  # file in .cursor/rules is ignored, those need Cursor's .mdc format)
229
- "rules_file": {"claude-code": "CLAUDE.md", "codex": "AGENTS.md", "cursor": ".cursor/rules/sessioncost.mdc",
230
- "antigravity": "GEMINI.md", "copilot": ".github/copilot-instructions.md",
231
- "copilot-vscode": ".github/copilot-instructions.md"}.get(
232
- s.agent, "the agent's instruction file"),
230
+ "rules_file": RULES_FILE.get(s.agent, "the agent's instruction file"),
233
231
  # which recommended rules are already in the instruction files (read here, never sent)
234
232
  "rules_check": rules.check(s.agent, s.cwd),
235
233
  },
@@ -285,10 +283,13 @@ def analyse(s: Session, prices: dict, subscription: bool = False, engines: list
285
283
  out["fixes"] = [{"id": f.id, "title": f.title, "why": f.why, "saving_usd": f.saving_usd,
286
284
  "saving_tokens": f.saving_tokens, "where": f.where, "turns": f.turns, "items": f.items,
287
285
  "source": f.source, "per_turn": {str(k): v for k, v in f.per_turn.items()},
288
- "calls": [call_ix[k] for k in f.calls if k in call_ix], "how": f.how, "paste": f.paste,
286
+ "calls": [call_ix[k] for k in f.calls if k in call_ix], "how": f.how, "paste": f.paste, "ask": f.ask,
289
287
  "targets": list(f.targets), "per_target": dict(f.per_target),
290
288
  "overlaps": both["overlaps"].get(f.id, []), "shared": pairs.get(f.id, {})}
291
289
  for f in s.fixes]
290
+ # every fix found, also those the top cut left out: earlier chats' unused servers and skills (fixer.record_seen)
291
+ out["fixes_found"] = {f.id: {"targets": list(f.targets), "per_target": dict(f.per_target)}
292
+ for f in s.fixes_found or s.fixes}
292
293
  for f in s.fixes:
293
294
  for tr in turn_rows:
294
295
  if tr["n"] in f.turns:
@@ -195,6 +195,11 @@ def build(path, args) -> tuple[dict, Path | None]:
195
195
  fixer.record_seen(a, project)
196
196
  a["fix_verify"] = fixer.verify_lines(project)
197
197
  a["fix_done"] = {v["id"]: v["at"] for v in fixer.verify(project) if v.get("id") and v.get("at")}
198
+ from .fixes.unused_tools import settle # after record_seen: the memory keeps this chat's full unused list
199
+ settle(a, fixer.earlier_chats(a, project) if project else None)
200
+ from .fixes.skill_cost import add_history
201
+ add_history(a, fixer.earlier_chats(a, project) if project else None)
202
+ if project:
198
203
  fixer.for_report(a, project)
199
204
  out = None
200
205
  if not args.json and not (getattr(args, "live", False) and not guard.reports_on()):
@@ -336,7 +341,7 @@ def cmd_fix(argv: list[str]) -> int:
336
341
  fixer.mark_shown(plan) # the live tip does not list these again in that chat
337
342
  if not any(i.can_apply or i.kind == "handover" for i in plan.items) or args.preview:
338
343
  return 0
339
- if not args.yes:
344
+ if not args.yes and any(i.can_apply for i in plan.items): # a handover alone changes no file: no yes needed
340
345
  try:
341
346
  yes = input("\nApply these? [y/N] ").strip().lower() in ("y", "yes")
342
347
  except (KeyboardInterrupt, EOFError):
@@ -22,7 +22,7 @@ from datetime import datetime, timezone
22
22
  from pathlib import Path
23
23
 
24
24
  from . import practices
25
- from .fixer_plan import Plan, plan
25
+ from .fixer_plan import UNUSED_IDS, Plan, handover_unignored, plan
26
26
  from .fixer_store import (ASKED_FIX, BIG_TIP_TOKENS, CHAT_KEEP_S, HANDOVER_END, HANDOVER_NAME, HEAD, KEEP_SEEN, MIN_TIP_TOKENS,
27
27
  NOTE_MAX_AGE_S, OFFER_QUIET_S, RULE_OF, SAY_FIX, SAY_HANDOVER, SETTINGS, _load, _norm, _now, _save, _sha, _size, _tok, _ts, _usd,
28
28
  asks_handover, auto_on, backups_dir, base, chat_file, find_handover, fixes_file, handover_file, known,
@@ -46,7 +46,7 @@ def apply(p: Plan) -> tuple[int, str]:
46
46
  now = Path(path).read_bytes() if Path(path).exists() else None
47
47
  if now != p.originals.get(path):
48
48
  return 1, f"{path} changed while SessionCost was working; nothing was applied. Run `sessioncost fix` again."
49
- if p.finals: # the fixes, and the handover's .gitignore line
49
+ if p.finals: # the fixes (the handover writes nothing here)
50
50
  bid = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S-%f")
51
51
  folder = backups_dir(p.project) / bid
52
52
  folder.mkdir(parents=True, exist_ok=True)
@@ -67,13 +67,10 @@ def apply(p: Plan) -> tuple[int, str]:
67
67
  entries.append(e)
68
68
  mf = backups_dir(p.project) / "manifest.json"
69
69
  _save(mf, _load(mf, []) + [{"id": bid, "at": _now(), "chat": p.chat,
70
- "items": [i.id for i in todo] or ["long-chat"], "entries": entries}])
70
+ "items": [i.id for i in todo], "entries": entries}])
71
71
  for path in paths: # the backup is on disk before any file changes
72
72
  Path(path).parent.mkdir(parents=True, exist_ok=True)
73
73
  Path(path).write_bytes(data[path])
74
- if not todo and p.finals:
75
- out.append(f"Added {handover_file(p.project).name} to .gitignore, so the handover is not committed "
76
- "(`sessioncost fix --undo` takes it out).")
77
74
  if todo:
78
75
  mem = _load(fixes_file(p.project), {})
79
76
  mem["project"] = str(p.project)
@@ -107,6 +104,10 @@ def apply(p: Plan) -> tuple[int, str]:
107
104
  f"file if there is none; {ON_TOP}): the goal, what is done, files "
108
105
  "changed, tests run, what is next. Show it in your reply, then tell the user to start a new chat "
109
106
  "and say \"continue from handover\" there." + fresh_chat.handover_words(p.agent, p.project.as_posix()))
107
+ if handover_unignored(p.project): # the agent's own edit: SessionCost writes no file here (owner, 2026-11-23)
108
+ out.append(f"So the handover is not committed: with your own file-edit tool, add the line {h.name} to "
109
+ f"{(p.project / '.gitignore').as_posix()} (keep everything already in it; a new file if there "
110
+ "is none).")
110
111
  out.append("In the same handover, add a short section \"Other token waste in this chat\": what cost tokens in "
111
112
  "this chat that SessionCost does not know yet. It knows: " + "; ".join(known()) + ". Leave out "
112
113
  "anything on that list, except what you already recorded in this chat with `fix learn`: list that "
@@ -177,17 +178,31 @@ def record_seen(a: dict, project) -> None:
177
178
  mem = _load(p, {})
178
179
  meta = a.get("meta") or {}
179
180
  seen = mem.setdefault("seen", {})
181
+ # all fixes found, not only the top ones shown: a card left out still names what the chat did not use
182
+ found = a.get("fixes_found")
183
+ if found is None:
184
+ found = {f["id"]: f for f in a.get("fixes") or []}
180
185
  seen[str(meta.get("session_id") or "")] = {
181
186
  "started": meta.get("started"), "calls": int((a.get("totals") or {}).get("calls") or 0),
182
187
  "waste": {f["id"]: int(f.get("saving_tokens") or 0) for f in a.get("fixes") or []},
183
188
  "waste_usd": {f["id"]: float(f.get("saving_usd") or 0.0) for f in a.get("fixes") or []},
184
- "unused_targets": {f["id"]: list(f.get("targets") or []) for f in a.get("fixes") or []
185
- if f.get("id") in ("unused-tools", "unused-builtin")}}
189
+ "unused_targets": {i: list(f.get("targets") or []) for i, f in found.items() if i in UNUSED_IDS},
190
+ # a Claude Code chat recorded since unused skills are checked: no "unused-skills" entry means it used them all
191
+ "skills_known": meta.get("agent") == "claude-code",
192
+ # tokens of each skill the skill-cost card found (the card's per-skill line over the recent chats)
193
+ "skill_tokens": dict((found.get("skill-cost") or {}).get("per_target") or {})}
186
194
  if len(seen) > KEEP_SEEN:
187
195
  mem["seen"] = dict(sorted(seen.items(), key=lambda x: -_ts(x[1].get("started")))[:KEEP_SEEN])
188
196
  _save(p, mem)
189
197
 
190
198
 
199
+ def earlier_chats(a: dict, project) -> list[dict]:
200
+ """The project's remembered chats, newest first, without this one (for the report's unused-tools card)."""
201
+ me = str((a.get("meta") or {}).get("session_id") or "")
202
+ seen = _load(fixes_file(project_path(project)), {}).get("seen") or {}
203
+ return [s for c, s in sorted(seen.items(), key=lambda x: -_ts(x[1].get("started"))) if c != me]
204
+
205
+
191
206
  def verify(project) -> list[dict]:
192
207
  mem = _load(fixes_file(project_path(project)), {})
193
208
  out = []
@@ -394,7 +409,8 @@ def tip(chat: str, cwd: str, prompt: str = "", start: bool = False, turn: str |
394
409
  if long: # a long chat: the handover is written at once, no yes needed (owner, 2026-11-17)
395
410
  say.append(f"This chat is long, so write a handover now, without waiting for the user's yes: "
396
411
  "after your work for the user's message and before that last line, run "
397
- f"`{run_cmd()} fix -y {of}--only long-chat --project {where}` and do what it prints. "
412
+ f"`{run_cmd()} fix {of}--only long-chat --project {where}` (it changes no file, only "
413
+ "prints the steps) and do what it prints. "
398
414
  "If running it is blocked or refused, write the handover yourself at the top of "
399
415
  f"{handover_file(cwd).as_posix()} ({ON_TOP}): the goal, what is done, files "
400
416
  "changed, tests run, what is next. Write it with your own file-edit tool, not a script "
@@ -7,6 +7,7 @@ from dataclasses import dataclass, field
7
7
  from pathlib import Path
8
8
 
9
9
  from . import fixes as fixmod
10
+ from .fixes.unused_skills import HIDE as SKILL_HIDE, off_steps as skill_steps, plain as plain_skill
10
11
  from . import practices, rules
11
12
  from .fixer_store import (BUILTIN_SETTING, HANDOVER_NAME, HEAD, LONG_CHAT, RULE_OF, SETTINGS, _first, _load, _size, _tok, _ts, _usd,
12
13
  budget_usd, fixes_file, learned, learned_here, long_chat, project_path)
@@ -131,6 +132,12 @@ def _read(path: Path) -> tuple[str | None, bytes | None, str]:
131
132
  return None, raw, f"{path.name} is not UTF-8 text, so it was not changed"
132
133
 
133
134
 
135
+ UNUSED_IDS = ("unused-tools", "unused-builtin", "unused-skills") # kept only if recent chats did not use them either
136
+ # report only, never in `fix`: the user's own agent proposes these changes and waits for a yes (skills, helper files)
137
+ REPORT_ONLY = ("long-chat", "model-choice", "helper-model", "skill-cost", "hook-output", "ignore-folders",
138
+ "large-files", "verbose-tests", "notes-file")
139
+
140
+
134
141
  def _settings(text: str | None, updates: dict) -> tuple[str | None, str]:
135
142
  """(new text, problem). A settings file that does not parse is never overwritten."""
136
143
  data: dict = {}
@@ -143,7 +150,12 @@ def _settings(text: str | None, updates: dict) -> tuple[str | None, str]:
143
150
  return None, "is not a JSON object, so SessionCost did not change it"
144
151
  new, changed = dict(data), False
145
152
  for k, v in updates.items():
146
- if isinstance(v, list):
153
+ if isinstance(v, dict): # e.g. skillOverrides: a value the user set stays as they set it
154
+ have = new.get(k) if isinstance(new.get(k), dict) else {}
155
+ add = {x: y for x, y in v.items() if x not in have}
156
+ if add:
157
+ new[k], changed = {**have, **add}, True
158
+ elif isinstance(v, list):
147
159
  have = new.get(k) if isinstance(new.get(k), list) else []
148
160
  add = [x for x in v if x not in have]
149
161
  if add:
@@ -195,6 +207,12 @@ def for_report(a: dict, project) -> None:
195
207
  if idle:
196
208
  f["sc_can"] = idle
197
209
  f["how"] = fixmod.turn_off_steps("claude-code", rest) if rest else ""
210
+ elif f.get("id") == "unused-skills":
211
+ mine = [t for t in f.get("targets") or [] if plain_skill(t, project)]
212
+ if mine:
213
+ f["sc_can"] = mine
214
+ rest = [t for t in f.get("targets") or [] if not plain_skill(t, project)]
215
+ f["how"] = skill_steps(rest, project) if rest else ""
198
216
 
199
217
 
200
218
  def plan(a: dict, project, only: set[str] | None = None, home: Path | None = None) -> Plan:
@@ -249,11 +267,12 @@ def plan(a: dict, project, only: set[str] | None = None, home: Path | None = Non
249
267
 
250
268
  for f in a.get("fixes") or []:
251
269
  fid = str(f.get("id") or "")
252
- if fid in ("long-chat", "model-choice") or (only is not None and fid not in only):
270
+ if fid in REPORT_ONLY or (only is not None and fid not in only):
253
271
  continue
254
272
  targets = list(f.get("targets") or [])
255
- if fid in ("unused-tools", "unused-builtin") and targets and recent_seen:
256
- targets = [t for t in targets if all(t in (s.get("unused_targets") or {}).get(fid, []) for s in recent_seen)]
273
+ recent = [s for s in recent_seen if fid != "unused-skills" or s.get("skills_known")]
274
+ if fid in UNUSED_IDS and targets and recent:
275
+ targets = [t for t in targets if all(t in (s.get("unused_targets") or {}).get(fid, []) for s in recent)]
257
276
  if not targets:
258
277
  continue
259
278
  it = Item(id=fid, title=str(f.get("title") or fid), why=_first(f.get("why", "")),
@@ -273,6 +292,18 @@ def plan(a: dict, project, only: set[str] | None = None, home: Path | None = Non
273
292
  it.tokens = (sum(int(per.get(t) or 0) for t in idle) if per else
274
293
  round(it.tokens * len(idle) / max(1, len(idle) + len(rest))))
275
294
  it.usd = it.usd * it.tokens / whole if whole else 0.0 # the same share of the money
295
+ elif fid == "unused-skills" and agent == "claude-code":
296
+ idle = [t for t in targets if plain_skill(t, project, home)]
297
+ rest = [t for t in targets if not plain_skill(t, project, home)]
298
+ if idle:
299
+ updates = {"skillOverrides": {t: SKILL_HIDE for t in idle}}
300
+ per, whole, every = f.get("per_target") or {}, it.tokens, f.get("targets") or []
301
+ count = idle or targets # plugin / claude.ai skills the setting cannot hide: not counted
302
+ if len(count) < len(every): # a recent chat used some, or some cannot be hidden: count only these
303
+ it.tokens = (sum(int(per.get(t) or 0) for t in count) if per else
304
+ round(whole * len(count) / max(1, len(every))))
305
+ it.usd = it.usd * it.tokens / whole if whole else 0.0
306
+ it.title = f"Hide {', '.join(count)} (not used in this project's recent chats)"
276
307
  if rule:
277
308
  it.kind, it.steps = "rule", "" # the rule is the change itself: nothing for the user to do by hand
278
309
  if in_file.get(rule):
@@ -301,8 +332,12 @@ def plan(a: dict, project, only: set[str] | None = None, home: Path | None = Non
301
332
  else:
302
333
  it.change = Change(path, before, after)
303
334
  texts[path] = after
304
- it.steps = (f"Not in this project's .mcp.json, so SessionCost cannot switch these off: {', '.join(rest)}.\n"
305
- + fixmod.turn_off_steps(agent, rest)) if rest else ""
335
+ if fid == "unused-skills":
336
+ it.steps = (f"SessionCost leaves these to you: {', '.join(rest)}.\n"
337
+ + skill_steps(rest, project, home)) if rest else ""
338
+ else:
339
+ it.steps = (f"Not in this project's .mcp.json, so SessionCost cannot switch these off: "
340
+ f"{', '.join(rest)}.\n" + fixmod.turn_off_steps(agent, rest)) if rest else ""
306
341
  elif not it.steps:
307
342
  continue
308
343
  if (it.kind in ("rule", "setting")) and not it.change and not it.problem:
@@ -345,14 +380,6 @@ def plan(a: dict, project, only: set[str] | None = None, home: Path | None = Non
345
380
  ho = Item(id="long-chat", title="Start a fresh chat with a handover", kind="handover",
346
381
  why=why, tokens=int(lc.get("saving_tokens") or 0) if lc else 0,
347
382
  usd=float(lc.get("saving_usd") or 0.0) if lc else 0.0, line=line)
348
- gi = project / ".gitignore"
349
- if (project / ".git").exists(): # the handover file in the project stays out of git
350
- before, prob = current(gi)
351
- listed = any(x.strip().lstrip("/") == HANDOVER_NAME for x in (before or "").splitlines())
352
- if not prob and not listed:
353
- sep = "" if not before or before.endswith(("\n", "\r\n")) else "\n"
354
- ho.change = Change(gi, before, f"{before or ''}{sep}{HANDOVER_NAME}\n")
355
- texts[gi] = ho.change.after
356
383
  p.items.append(ho)
357
384
  p.items.sort(key=lambda i: -i.tokens)
358
385
  for path, text in texts.items():
@@ -363,6 +390,16 @@ def plan(a: dict, project, only: set[str] | None = None, home: Path | None = Non
363
390
  return p
364
391
 
365
392
 
393
+ def handover_unignored(project) -> bool:
394
+ """A git project whose .gitignore does not list the handover file yet. SessionCost does not write that line
395
+ itself: auto mode refused a program that edits .gitignore (owner, 2026-11-23); the agent adds it."""
396
+ project = Path(project)
397
+ if not (project / ".git").exists():
398
+ return False
399
+ before, _raw, prob = _read(project / ".gitignore")
400
+ return not prob and not any(x.strip().lstrip("/") == HANDOVER_NAME for x in (before or "").splitlines())
401
+
402
+
366
403
  def render(p: Plan, verify: list[str] | None = None, newest: bool = True) -> str:
367
404
  """newest: the chat is the project's newest (`fix` with no chat id); a named chat may be an older one."""
368
405
  out = []
@@ -394,9 +431,8 @@ def render(p: Plan, verify: list[str] | None = None, newest: bool = True) -> str
394
431
  elif it.kind == "handover":
395
432
  out.append(f" The fix: your agent writes a handover in {HANDOVER_NAME} in this project (goal, what is "
396
433
  "done, files changed, tests run, what is next) and you start a fresh chat."
397
- + (" So it is not committed, it goes into .gitignore:" if it.change else ""))
398
- if it.change:
399
- out += [" " + x for x in it.change.diff(p.project).rstrip("\n").splitlines()]
434
+ + (f" So it is not committed, your agent will add {HANDOVER_NAME} to .gitignore."
435
+ if handover_unignored(p.project) else ""))
400
436
  elif it.change:
401
437
  out.append(" The change:")
402
438
  for c in [it.change, *it.also]: # the agent's own file first, then every other agent's file here
@@ -25,16 +25,24 @@ from .confirm_turns import confirm_turns, skill_in_use # noqa: F401
25
25
  from .error_loop import error_loop
26
26
  from .helper_polling import helper_polling
27
27
  from .helper_rereads import helper_rereads
28
+ from .hook_output import hook_output
29
+ from .ignore_folders import ignore_folders
28
30
  from .images import images
31
+ from .large_files import large_files
32
+ from .notes_file import notes_file
33
+ from .verbose_tests import verbose_tests
29
34
  from .long_chat import LONG_BREAK_S, LONG_CHAT, SUMMARY, long_chat, new_chat_steps, task_starts # noqa: F401
30
35
  from .long_output import long_output
36
+ from .helper_model import helper_model
31
37
  from .model_choice import model_choice
32
38
  from .repeated_reads import repeated_reads
33
39
  from .repeated_writes import repeated_writes
34
40
  from .reruns import is_test, test_reruns, untested_edits # noqa: F401 (not test_*.py: pytest would collect it)
41
+ from .skill_cost import skill_cost
35
42
  from .stale_context import stale_context
36
43
  from .startup_bloat import startup_bloat
37
44
  from .unused_builtins import unused_builtins
45
+ from .unused_skills import unused_skills
38
46
  from .unused_tools import server_name, server_of, turn_off_steps, unused_tools # noqa: F401
39
47
 
40
48
  MAX_FIXES = 6
@@ -52,6 +60,7 @@ class BasicFixes:
52
60
 
53
61
  def find(self, session: Session, pricer) -> list[Fix]:
54
62
  return [f for f in (unused_tools(session, pricer), unused_builtins(session, pricer),
63
+ unused_skills(session, pricer),
55
64
  repeated_reads(session, pricer), repeated_writes(session, pricer),
56
65
  error_loop(session, pricer), helper_polling(session, pricer),
57
66
  test_reruns(session, pricer),
@@ -60,7 +69,11 @@ class BasicFixes:
60
69
  cache_break(session, pricer), stale_context(session, pricer),
61
70
  big_results(session, pricer), startup_bloat(session, pricer),
62
71
  images(session, pricer), long_output(session, pricer),
63
- helper_rereads(session, pricer), model_choice(session, pricer)) if f]
72
+ helper_rereads(session, pricer), model_choice(session, pricer),
73
+ helper_model(session, pricer), skill_cost(session, pricer),
74
+ hook_output(session, pricer), ignore_folders(session, pricer),
75
+ large_files(session, pricer), verbose_tests(session, pricer),
76
+ notes_file(session, pricer)) if f]
64
77
 
65
78
 
66
79
  def load_engines() -> list:
@@ -84,6 +97,7 @@ def find(session: Session, pricer, engines: list | None = None) -> list[Fix]:
84
97
  out.append(f)
85
98
  out = [f for f in out if f.saving_usd > 0]
86
99
  out.sort(key=lambda f: (-f.saving_tokens, -f.saving_usd)) # tokens cut first; money follows
100
+ session.fixes_found = list(out) # before the cut: what each chat left unused is remembered (fixer.record_seen)
87
101
  top = out[:MAX_FIXES]
88
102
  by_usd = {id(f) for f in sorted(out, key=lambda f: -f.saving_usd)[:MAX_FIXES]}
89
103
  for f in out[MAX_FIXES:]:
@@ -76,6 +76,15 @@ def big_results(s: Session, pr) -> Fix | None:
76
76
 
77
77
  if not items:
78
78
  return None
79
+ ask = ""
80
+ if "cmd" in kinds_hit: # long command output: the digester helper sends back only the lines that matter
81
+ from .. import workspace
82
+ from ..helper_agent import make_stick, prompt
83
+ ws = workspace.of(s)
84
+ have = ws.helper_file("digester")
85
+ n_cmd = sum(1 for x in items if x.endswith("tool output)"))
86
+ ask = (make_stick(s.agent, ws.show(have), n_cmd, ws, "digester") if have
87
+ else prompt(s.agent, "digester", ws))
79
88
  total_tok, per_turn = led.tokens, led.per_turn()
80
89
  turns = sorted(hit_turns)
81
90
  n = len(items)
@@ -94,5 +103,5 @@ def big_results(s: Session, pr) -> Fix | None:
94
103
  saving_usd=led.usd, saving_tokens=total_tok, claims=led.claims,
95
104
  where=turns_where(turns), turns=turns, items=items[:6], per_turn=per_turn, calls=hit_calls,
96
105
  how="Keep command output short: use head/tail or a quiet flag, or write long output to a file and read only the lines you need.",
97
- paste=True,
106
+ paste=True, ask=ask,
98
107
  )
@@ -15,6 +15,30 @@ def tok(chars: int) -> int:
15
15
  return max(0, int(chars) // 4)
16
16
 
17
17
 
18
+ def changed_after_start(s: Session, paths) -> list[str]:
19
+ """The files among `paths` last saved after the chat began: the report's numbers are from before that change."""
20
+ from pathlib import Path
21
+ if not s.started:
22
+ return []
23
+ began = s.started.timestamp()
24
+ out = []
25
+ for p in paths:
26
+ try:
27
+ if p and Path(p).is_file() and Path(p).stat().st_mtime > began and str(p) not in out:
28
+ out.append(str(p))
29
+ except OSError:
30
+ continue
31
+ return out
32
+
33
+
34
+ def before_change_note(names: list[str]) -> str:
35
+ """One sentence for a card whose files changed after the chat began."""
36
+ if not names:
37
+ return ""
38
+ return (f" You changed {' and '.join(names)} after this chat began, so these numbers are from before that "
39
+ "change: a new chat shows the effect.")
40
+
41
+
18
42
  def helper_name(s: Session, agent: str) -> str:
19
43
  """A helper as the report names it: its task ("Vision Co-Founder Reviewer"), else its id."""
20
44
  h = next((h for h in s.helpers if h.calls and h.calls[0].agent == agent), None)
@@ -0,0 +1,131 @@
1
+ """Check helper-model (owner yes 2026-11-24): helpers that only read, searched, ran checks or reviewed, on the
2
+ most expensive model. Names where that model is set: the helper's own agent file and its `model:` line, or (a
3
+ built-in helper with no file, such as Claude Code's general-purpose, which takes the chat's model) the file format
4
+ that gives it a cheaper one. Every agent with helpers in its log (Claude Code, Codex, Cursor, Copilot, Antigravity);
5
+ the saving is the price of the helper's own calls on the cheaper model, nothing guessed."""
6
+ from __future__ import annotations
7
+
8
+ import re
9
+ from pathlib import Path
10
+
11
+ from .. import prices as pricemod
12
+ from ..model import Call, Fix, Helper, Session
13
+ from .common import turns_where
14
+ from .model_choice import _cheaper_peer
15
+
16
+ MIN_SAVING_USD = 0.20
17
+ READ_WORK = {"read", "search", "command", "web", "skill", "plan", "other"} # no edit / write: review and read work
18
+ from ..workspace import AGENT_DIRS, HOME_DIRS # one list of where helper files live
19
+
20
+ _REVIEW = re.compile(r"\b(review|audit|security|check the (change|diff|pr))", re.I)
21
+ _MODEL = re.compile(r"^\s*model\s*[:=]\s*[\"']?([^\"'\s#]+)", re.I)
22
+
23
+
24
+ def read_only(h: Helper) -> bool:
25
+ kinds = {a.kind for c in h.calls for a in c.actions}
26
+ return bool(kinds) and kinds <= READ_WORK
27
+
28
+
29
+ def agent_file(agent: str, kind: str, project: str, home: Path | None = None) -> tuple[str, int, str] | None:
30
+ """(path, line of `model:` or 0, model named or "") of a named helper's own file, or None (built-in, no file)."""
31
+ if not kind or kind in ("helper", "general-purpose"):
32
+ return None
33
+ home = home or Path.home()
34
+ places = [Path(project) / d / f"{kind}{ext}" for d, ext in AGENT_DIRS.get(agent, [])] if project else []
35
+ if agent in HOME_DIRS:
36
+ places.append(home / HOME_DIRS[agent] / f"{kind}{AGENT_DIRS[agent][0][1]}")
37
+ for p in places:
38
+ try:
39
+ lines = p.read_text(encoding="utf-8", errors="replace").splitlines()
40
+ except OSError:
41
+ continue
42
+ for i, line in enumerate(lines[:40], 1):
43
+ if m := _MODEL.match(line):
44
+ return str(p), i, m.group(1)
45
+ return str(p), 0, ""
46
+ return None
47
+
48
+
49
+ def peer_saving(calls: list[Call], pr) -> tuple[float, str]:
50
+ """What these calls would have cost on the cheaper model of the same family, and that model."""
51
+ diff, peer_name = 0.0, ""
52
+ for c in calls:
53
+ peer = _cheaper_peer(c.model)
54
+ if not peer:
55
+ continue
56
+ rates, _, _ = pricemod.rates(peer, pr.prices)
57
+ rates = pricemod.for_prompt(rates, c.usage.context)
58
+ diff += max(0.0, pr.total(c) - sum(pricemod.cost(c.usage, rates).values()))
59
+ peer_name = peer_name or peer
60
+ return diff, peer_name
61
+
62
+
63
+ def where_set(s: Session, kind: str, peer: str, home: Path | None = None) -> str:
64
+ """One sentence: where this helper's model is set and what to change."""
65
+ found = agent_file(s.agent, kind, s.cwd, home)
66
+ if found and found[1]:
67
+ return f"`{found[0]}` line {found[1]} sets `model: {found[2]}`: change it to a cheaper one ({peer} or similar)."
68
+ if found:
69
+ return f"`{found[0]}` has no `model:` line, so the helper takes this chat's model: add a cheaper one."
70
+ if s.agent == "claude-code":
71
+ return (f"“{kind or 'helper'}” is a built-in helper with no file of its own: it takes this chat's model. "
72
+ "Have the step that starts it name a cheaper model, or start a helper of your own with a cheaper "
73
+ "model in its file (`.claude/agents/<name>.md`, `model: sonnet`).")
74
+ from ..helper_agent import FILE
75
+ return ("It has no file of its own here, so it takes this chat's model: give it one with a cheaper model "
76
+ f"({FILE.get(s.agent, 'your agent’s helper file')}).")
77
+
78
+
79
+ def helper_model(s: Session, pr, home: Path | None = None) -> Fix | None:
80
+ groups: dict[str, list[Helper]] = {}
81
+ for h in s.helpers:
82
+ if h.calls and read_only(h) and any(_cheaper_peer(c.model) for c in h.calls):
83
+ groups.setdefault(h.agent_type or "helper", []).append(h)
84
+ hits = []
85
+ for kind, hs in groups.items():
86
+ calls = [c for h in hs for c in h.calls]
87
+ diff, peer = peer_saving(calls, pr)
88
+ if diff > 0:
89
+ hits.append((diff, kind, hs, calls, peer))
90
+ total = sum(x[0] for x in hits)
91
+ if not hits or total < MIN_SAVING_USD:
92
+ return None
93
+ hits.sort(key=lambda x: -x[0])
94
+ items, asks, turns, calls_all = [], [], set(), []
95
+ for diff, kind, hs, calls, peer in hits:
96
+ model = calls[0].model
97
+ tokens = sum(c.usage.context + c.usage.output for c in calls)
98
+ what = "; ".join(sorted({h.description for h in hs if h.description}))[:120]
99
+ place = where_set(s, kind, peer, home)
100
+ items.append(f"{len(hs)} “{kind}” helper{'s' if len(hs) > 1 else ''} on {model} ({tokens:,} tokens, "
101
+ f"saved ${diff:.2f} on {peer}): {what}. {place}")
102
+ asks.append(f"“{kind}” ({what}): {place}")
103
+ turns |= {h.turn for h in hs}
104
+ calls_all += [(c.agent, c.n) for c in calls]
105
+ n = sum(len(x[2]) for x in hits)
106
+ # a built-in helper doing reviews: a reviewer helper of the user's own, on a cheaper model, findings only
107
+ from .. import workspace
108
+ from ..helper_agent import make_stick, prompt
109
+ ws = workspace.of(s, home)
110
+ built_in = [h for x in hits if not agent_file(s.agent, x[1], s.cwd, home) for h in x[2]]
111
+ reviews = [h for h in built_in if _REVIEW.search(h.description or "")]
112
+ extra = ""
113
+ if reviews:
114
+ have = ws.helper_file("reviewer")
115
+ extra = " " + (make_stick(s.agent, ws.show(have), len(reviews), ws, "reviewer") if have
116
+ else prompt(s.agent, "reviewer", ws))
117
+ items.append(f"{len(reviews)} review{'s' if len(reviews) > 1 else ''} ran on a built-in helper: a reviewer "
118
+ "helper of your own sets a cheaper model once and sends back only the findings.")
119
+ return Fix(
120
+ id="helper-model",
121
+ title=f"Run read and review helpers on a cheaper model ({n} ran on {hits[0][3][0].model})",
122
+ why=(f"{n} helper{'s' if n > 1 else ''} in this chat only read, searched, ran checks or reviewed, on the most "
123
+ "expensive model. That work rarely needs it; a cheaper model of the same family costs a fraction."),
124
+ saving_usd=total, saving_tokens=0, where=turns_where(turns), turns=sorted(turns), items=items[:6],
125
+ per_turn={t: 0 for t in turns}, calls=calls_all,
126
+ how=("Change the model where the helper is set up (below). A new chat picks it up. Trade-off: for a "
127
+ "security or design review, keep the top model if its findings matter more than the cost."),
128
+ ask=("Some helpers in this project run on the most expensive model for read-only or review work. Make them "
129
+ "use a cheaper model: " + " ".join(asks) + extra + " Propose the exact change for each and wait for my yes "
130
+ "before editing any file."),
131
+ )
@@ -0,0 +1,85 @@
1
+ """Check hook-output (owner, 2026-11-24): a hook printed long text into the chat. Everything a hook prints for the
2
+ agent stays in the chat and goes out again with every later message. Claude Code only: its log is the one that marks
3
+ hook output. The settings lines that define the hooks are quoted (workspace.py), SessionCost's own hooks left out."""
4
+ from __future__ import annotations
5
+
6
+ import json
7
+ import re
8
+
9
+ from ..model import Fix, Session
10
+ from .common import Ledger, tok, turns_where
11
+
12
+ MIN_EACH = 300 # tokens one hook output must reach to count
13
+ ONE_LINE = 40 # what a one-line hook output costs instead
14
+ MIN_TOTAL = 2_000 # carried tokens the tip needs to be worth showing
15
+ OURS = ("sessioncost", "continue from the handover of an earlier chat") # SessionCost's own hooks
16
+ SHOWN_ONLY = "to you only: " # the reader's mark for a hook message shown to the user, not sent to the agent
17
+ # hook events whose output the agent sees on a normal run (Claude Code hooks docs, read 2026-11-24); a PreToolUse
18
+ # guard speaks only when it blocks, and the status line is not a hook
19
+ TALKS = ("SessionStart", "UserPromptSubmit", "PostToolUse", "PostToolBatch", "SubagentStart")
20
+ # a value after Bearer / token= / password: in a hook's command line; known key shapes are caught by _SECRET_VALUE
21
+ _NAMED_SECRET = re.compile(r"(\bBearer\s+|\b(?:[\w-]*(?:token|key|secret|password|passwd|pwd))\s*[=:]\s*['\"]?)"
22
+ r"[^\s'\"]+", re.I)
23
+
24
+
25
+ def _no_keys(text: str) -> str:
26
+ """A hook's command or words as the tip quotes them: keys and tokens hidden (the tip's text is pasted into chat)."""
27
+ from ..risk_patterns import _SECRET_VALUE
28
+ return _NAMED_SECRET.sub(r"\1[secret hidden]", _SECRET_VALUE.sub("[secret hidden]", text or ""))
29
+
30
+
31
+ def hook_output(s: Session, pr, home=None) -> Fix | None:
32
+ calls = s.calls
33
+ if s.agent != "claude-code" or len(calls) < 2:
34
+ return None
35
+ order = {id(c): i for i, c in enumerate(calls)}
36
+ led, items, turns, hit = Ledger(), [], set(), []
37
+ for t in s.turns:
38
+ if not t.calls:
39
+ continue
40
+ first = order.get(id(t.calls[0]))
41
+ for k, e in enumerate(t.events):
42
+ if e.kind != "injected" or "hook output" not in e.label or any(o in e.text.lower() for o in OURS) \
43
+ or e.text.startswith((SHOWN_ONLY, "<ide_")): # the editor's own notes are not your hooks
44
+ continue
45
+ n = tok(e.chars)
46
+ if n < MIN_EACH or first is None:
47
+ continue
48
+ start = first
49
+ if e.ts: # output after a tool step: carried from the next call on
50
+ start = next((order[id(c)] for c in t.calls if c.ts_first and c.ts_first >= e.ts), first)
51
+ led.carry(("hook", t.n, k), n - ONE_LINE, calls[start:], pr)
52
+ turns.add(t.n)
53
+ hit.append(("main", calls[start].n))
54
+ items.append(f"turn {t.n}: ~{n:,} tokens of hook output" + (f" (“{_no_keys(e.text)[:60]}”)" if e.text else ""))
55
+ if led.tokens < MIN_TOTAL:
56
+ return None
57
+ from .. import workspace
58
+ ws = workspace.of(s, home)
59
+ defined = []
60
+ for p, data in ws.settings(): # only events whose output reaches the agent on a normal run
61
+ hooks = data.get("hooks") if isinstance(data, dict) else None
62
+ for event, groups in (hooks if isinstance(hooks, dict) else {}).items():
63
+ if event not in TALKS:
64
+ continue
65
+ for g in groups if isinstance(groups, list) else []:
66
+ hs = g.get("hooks") if isinstance(g, dict) else None
67
+ for h in hs if isinstance(hs, list) else []: # a hand-edited file can hold any JSON shape
68
+ cmd = str(h.get("command") or "") if isinstance(h, dict) else ""
69
+ if cmd and not any(o in cmd.lower() for o in OURS):
70
+ as_json = json.dumps(cmd)[1:41] # as written in the file (quotes escaped)
71
+ ln = next((x for x in ws.find(re.escape(as_json), [p], 0)), None)
72
+ defined.append(f"{event}: {ln.at() if ln else ws.show(p)} (“{_no_keys(cmd)[:70]}”)")
73
+ where = "; ".join(defined[:4]) if defined else "your hooks (Claude Code settings, `hooks`)"
74
+ return Fix(
75
+ id="hook-output",
76
+ title=f"Make your hooks print one line ({len(items)} long hook output{'s' if len(items) > 1 else ''})",
77
+ why=(f"Your hooks added long text to the chat {len(items)} time{'s' if len(items) > 1 else ''}. What a hook "
78
+ "prints for the agent stays in the chat and is sent again with every later message."),
79
+ saving_usd=led.usd, saving_tokens=led.tokens, claims=led.claims, where=turns_where(sorted(turns)),
80
+ turns=sorted(turns), items=items[:6], per_turn=led.per_turn(), calls=hit,
81
+ how=(f"Best practice: a hook prints at most one short line for the agent and writes any detail to a log "
82
+ f"file. Your hooks are set at: {where}."),
83
+ ask=(f"My hooks print long text into the chat. They are set at: {where}. For each one, propose a change so it "
84
+ "prints one short line for you and writes the rest to a log file. Wait for my yes before editing."),
85
+ )