tokensafe 4.0.1 → 4.1.0

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.
@@ -172,7 +172,7 @@ def _handle(payload: dict) -> dict:
172
172
 
173
173
  hist_badge = (
174
174
  f"⚡ **History Compactor:** Stabilized {orig_hist_tokens:,} tokens of previous turns — "
175
- f"saved **{stats['saved_tokens']:,} tokens**."
175
+ f"saved **{stats['saved_tokens']:,} tokens** (orientation digest active)."
176
176
  )
177
177
 
178
178
  inject_steps.append({
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "mcpName": "dev.tokensafe/tokensafe",
4
- "version": "4.0.1",
4
+ "version": "4.1.0",
5
5
  "description": "Make AI coding agents 3x faster without burning team quotas. Exact code context. Fewer tokens. Safer changes.",
6
6
  "main": "bin/tokensafe.js",
7
7
  "bin": {
package/plugin.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "displayName": "TokenSafe",
4
- "version": "4.0.1",
4
+ "version": "4.1.0",
5
5
  "description": "Reduce your AI bills by up to 99% locally. Your agents read only needed code, keep prompt caches intact across turns, and keep secrets out of git.",
6
6
  "logo": "assets/logo.svg",
7
7
  "author": {
package/rules/AGENTS.md CHANGED
@@ -38,7 +38,7 @@ Execute the specified action directly based on these extracted parameters.
38
38
  8. **Directory Navigation**: Never run verbose `ls -la` or `ls -l`; use `tokensafe:list_dir(path=".", depth=2)` to inspect directory trees without permissions, timestamps, or lockfiles (-90% tokens). Supports relative subfolders (`path="src"`).
39
39
  9. **Style & Design Tokens**: When inspecting CSS/SCSS/LESS/Tailwind, `tokensafe:smart_read_file` automatically preserves all design tokens (`:root`, `@theme`, CSS variables) in full while folding component selectors.
40
40
  10. **Command Output Wrapping & Test Execution**: Run noisy commands and test suites via `tokensafe wrap '<command>'` or `tokensafe tests [cmd]`. Passing tests return a 1-line summary (`✓ PASS: ...`), and failures return focused failure blocks with full tracebacks preserved in stash.
41
- 11. **Context Budget & Smart Compaction**: Before large multi-step tasks, call `tokensafe:context_budget(model=...)` to check window usage (tools/history/prompts breakdown, 50/80/95% thresholds). When it reports `warning` or `critical`, call `tokensafe:compact_conversation(transcript_path=...)` to fold past turns into a State Ledger instead of letting code quality degrade.
41
+ 11. **Context Budget & Smart Compaction**: Before large multi-step tasks, call `tokensafe:context_budget(model=...)` to check window usage and Context Quality Score (Grade S-F). When it reports `warning`, `critical`, or Grade C/F, call `tokensafe:compact_conversation(transcript_path=...)` to fold past turns into a Consolidated State Ledger with a 3-line Post-Compaction Orientation Digest (Active Goal, Last State, Next Focus) before continuing.
42
42
  12. **Vision Image Optimization (`optimize_image`)**: When handling screenshots or visual diagrams, call `tokensafe:optimize_image` or run `tokensafe optimize-image <file>` to downscale images exceeding 1024px (-50-75% vision tokens) while preserving original disk files.
43
43
  13. **Superseded Output Pruning (`prune_superseded`)**: In long multi-turn sessions, prune obsolete intermediate file reads via `tokensafe:prune_superseded(transcript_path)` to free up context without losing history.
44
44
  14. **Anti-Stuck Revert Memory (`get_mistakes`)**: Consult `tokensafe:get_mistakes` to retrieve persistent records of prior dead-ends, loop guard trips, and git reverts to avoid attempting previously failed solutions.
package/server.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "name": "dev.tokensafe/tokensafe",
4
4
  "title": "TokenSafe",
5
5
  "description": "Reduce your AI bills by up to 99% locally: focused code, warm prompt caches & zero secret leaks.",
6
- "version": "4.0.1",
6
+ "version": "4.1.0",
7
7
  "websiteUrl": "https://tokensafe.dev",
8
8
  "repository": {
9
9
  "url": "https://github.com/tokensafe-dev/tokensafe",
@@ -30,7 +30,7 @@
30
30
  "registryType": "npm",
31
31
  "registryBaseUrl": "https://registry.npmjs.org",
32
32
  "identifier": "tokensafe",
33
- "version": "4.0.1",
33
+ "version": "4.1.0",
34
34
  "runtimeHint": "npx",
35
35
  "transport": {
36
36
  "type": "stdio"
@@ -46,7 +46,7 @@
46
46
  "registryType": "pypi",
47
47
  "registryBaseUrl": "https://pypi.org",
48
48
  "identifier": "tokensafe",
49
- "version": "4.0.1",
49
+ "version": "4.1.0",
50
50
  "runtimeHint": "uvx",
51
51
  "transport": {
52
52
  "type": "stdio"
@@ -48,9 +48,9 @@ folds multi-turn conversation history, slices verbose tool outputs, and guards a
48
48
  7. **SECRET LEAK PREVENTION (ZERO HARDCODED FALLBACKS)**:
49
49
  - Never provide real private keys, API secrets, or credentials as fallback values in `os.environ.get()` or `process.env`. Real credentials must exist strictly in environment variables.
50
50
 
51
- 8. **CONTEXT BUDGET BEFORE HEAVY WORK (`context_budget` → `compact_conversation`)**:
52
- - Before large multi-step tasks, call `tokensafe:context_budget(model=...)` to check the window budget (tools/history/prompts breakdown, 50/80/95% thresholds).
53
- - When it reports `warning` or `critical`, call `tokensafe:compact_conversation(transcript_path=...)` to fold past turns into a State Ledger before continuing — do not let context exhaustion degrade code quality mid-task.
51
+ 8. **CONTEXT BUDGET & HEALTH SCORE (`context_budget` → `compact_conversation`)**:
52
+ - Before large multi-step tasks, call `tokensafe:context_budget(model=...)` to check the window budget and Context Quality Score (Grade S/A/B/C/F, tools/history/prompts breakdown, 50/80/95% thresholds).
53
+ - When it reports `warning`, `critical`, or Grade C/F, call `tokensafe:compact_conversation(transcript_path=...)` to fold past turns into a Consolidated State Ledger with a 3-line Post-Compaction Orientation Digest (Active Goal, Last State, Next Focus) before continuing — resuming flow immediately without post-compaction disorientation.
54
54
 
55
55
  9. **REPEAT READ DEDUPLICATION & CACHE POINTERS**:
56
56
  - Never repeatedly re-read the same file or symbol within an active session.
@@ -94,10 +94,10 @@ Quick pointers:
94
94
 
95
95
  For long-running autonomous sessions, TokenSafe actively manages context bloat:
96
96
 
97
- 1. **Multi-Turn History Compaction**:
98
- - At conversation turn >= 3, automatically compiles past turns into a lean **Consolidated State Ledger**.
99
- - Preserves active file paths, modified symbols, and pending tasks while discarding transient tool output noise.
100
- - **Manual trigger**: call `tokensafe:compact_conversation` with the session's `transcript_path` any time you need to shed context between subtasks — it returns the ledger JSON plus exact original/folded token counts.
97
+ 1. **Multi-Turn History Compaction & Post-Compaction Orientation Digest**:
98
+ - At conversation turn >= 3, automatically compiles past turns into a lean **Consolidated State Ledger** paired with a deterministic 3-line **Post-Compaction Orientation Digest** (`1. Active Goal: ...`, `2. Last State: ...`, `3. Next Focus: ...`).
99
+ - Preserves active file paths, modified symbols, and pending tasks while discarding transient tool output noise and preventing post-compaction amnesia.
100
+ - **Manual trigger**: call `tokensafe:compact_conversation` with the session's `transcript_path` any time you need to shed context between subtasks — it returns the ledger JSON, orientation digest, and exact token counts.
101
101
  2. **Subagent Deduplication Firewall**:
102
102
  - Caches file reads across subagents and sessions using SHA-256 content hashes. Interactive MCP clients receive self-healing pointer hits on unchanged repeat reads inside the same session; fresh subagents or post-compaction callers recover automatically with `force_full=true`.
103
103
  3. **Loop Guard**:
@@ -15,8 +15,8 @@ All tools are exposed via Model Context Protocol (stdio JSON-RPC 2.0).
15
15
  | `tokensafe:sanitize_command` | Per-stage command rewrites: lockfile diffs, unbounded `git log`/`git show`/`git blame`/`rg`, docker/kubectl log caps, quiet npm/pip installs, bounded `cat`/`curl` output. Compound commands (`a && b ; c`) are optimized per stage without breaking operators. Pass the optional `cwd` argument for test-runner commands: the guard reads `<cwd>/package.json` to identify the runner behind opaque `yarn/npm test` scripts and forces jest/vitest into run-once mode (`CI=true`, `--watch=false`, `--forceExit`) so agents never hang waiting on watch mode. | Saves **10k-50k tokens** per run |
16
16
  | `tokensafe:slice_diff` | Slices unified git diffs, eliminating lockfiles and minimizing hunk context lines. | **-50% to -80%** diff size |
17
17
  | `tokensafe:compress_prompt` | Compresses verbose user instructions into lean TOCP S-expressions via DeepSeek/Regex. | **-40% to -65%** prompt tokens |
18
- | `tokensafe:compact_conversation` | On-demand context compaction: folds a long JSONL session transcript into a lean Consolidated State Ledger (`transcript_path`, optional `invocation_num`). Call when the context window feels heavy or before a new subtask. | **-80% to -95%** history tokens |
19
- | `tokensafe:context_budget` | Context Budget HUD: estimated window usage (`model`/`window_tokens`/`session_id`) with tools/history/prompts breakdown and 50/80/95% thresholds. Call before deciding to compact. | Floor estimate, always labeled estimated |
18
+ | `tokensafe:compact_conversation` | On-demand context compaction: folds a long JSONL session transcript into a lean Consolidated State Ledger with a 3-line Post-Compaction Orientation Digest (`transcript_path`, optional `invocation_num`). Preserves flow instantly without post-compaction amnesia. | **-80% to -95%** history tokens |
19
+ | `tokensafe:context_budget` | Context Budget HUD & Context Quality Score (Grade S/A/B/C/F): estimated window usage and unified health grade (tools/history/prompts breakdown, static tool/skill tax, headroom %). Call before deciding to compact. | Floor estimate, always labeled estimated |
20
20
  | `tokensafe:guard_inspect` | Pre-flight security & hygiene audit: denies literal secrets/destructive commands in shell lines (secrets, TLS, SQLi, raw grep); advisory for never-terminating streams (`tail -f`, `watch`, `docker attach`) and TLS bypasses. | **Zero-Risk** pre-flight gate |
21
21
  | `tokensafe:optimize_image` | Downscales oversized screenshots/diagrams (>1024px) before LLM vision ingestion while preserving original disk files and aspect ratios. | **-50% to -75%** vision tokens |
22
22
  | `tokensafe:prune_superseded` | Prunes obsolete intermediate tool read outputs in long transcripts that were superseded by subsequent edits or re-reads. | **-30% to -40%** context mass |
@@ -40,8 +40,8 @@ TOKENSAFE_DIRECTIVES = (
40
40
  "• Compact Test Execution: Run unit tests with concise flags or via 'tokensafe tests [cmd]' so passing suites emit a 1-line summary.\n"
41
41
  "• To locate dependencies & God Nodes: call 'tokensafe:get_architecture_graph(project_path)'.\n"
42
42
  "• To inspect all exported types/interfaces: call 'tokensafe:get_api_surface(project_path)'.\n"
43
- "• Before large multi-step tasks: call 'tokensafe:context_budget(model=...)' to check the context window budget.\n"
44
- "• When context_budget reports warning/critical: call 'tokensafe:compact_conversation(transcript_path=...)' to fold history before continuing.\n"
43
+ "• Before large multi-step tasks: call 'tokensafe:context_budget(model=...)' to check context headroom and Quality Score (Grade S-F).\n"
44
+ "• When context_budget reports warning/critical or Grade C/F: call 'tokensafe:compact_conversation(transcript_path=...)' to fold history before continuing.\n"
45
45
  "• Prefer 'edit_file' over 'write_file' for existing files."
46
46
  )
47
47
 
package/src/cli.py CHANGED
@@ -99,6 +99,8 @@ def _print_help():
99
99
  print("Commands:")
100
100
  print(" stats / markdown / html Savings analytics (terminal / .md report / dashboard)")
101
101
  print(" status One-screen health check: hooks, weekly savings, tier, sync")
102
+ print(" budget [--transcript=...] Context Window Budget HUD & Context Quality Score (Grade S-F)")
103
+ print(" compact <transcript.jsonl> Fold conversation transcript into Consolidated State Ledger")
102
104
  print(" benchmark Zero-context-loss benchmark suite (simulated SWE-bench harness)")
103
105
  print(" bench --real [--repo=key|--here] Measured benchmark on real repos (zero-loss gates)")
104
106
  print(" graph / map / skeleton Architecture graph / API surface / AST skeleton of a file")
@@ -172,6 +174,15 @@ def main(argv: Optional[List[str]] = None):
172
174
  print(f" Hooks: \033[32m✔ active\033[0m in {len(active_agents)} agent(s): {', '.join(active_agents)}")
173
175
  else:
174
176
  print(" Hooks: \033[33m○ not detected\033[0m — run \033[1mtokensafe install\033[0m to configure your agents")
177
+ # Context Quality Health Indicator (S/A/B/C/F)
178
+ try:
179
+ from src.quality_score import ContextQualityScore
180
+ q_score = ContextQualityScore.evaluate(tracker)
181
+ color = "\033[32m" if q_score["grade"] in ("S", "A") else ("\033[33m" if q_score["grade"] == "B" else "\033[31m")
182
+ tax_str = f"~{q_score['static_tax_tokens']:,} tok/turn" if q_score['static_tax_tokens'] else "0 tok/turn"
183
+ print(f" Context: {color}\033[1mGrade {q_score['grade']} ({q_score['label']})\033[0m — {q_score['headroom_pct']:.0f}% headroom (static tax: {tax_str})")
184
+ except Exception:
185
+ pass
175
186
  # The value moment: recent measured savings
176
187
  weekly = tracker.get_weekly_saved()
177
188
  print(f" This Week: \033[32m\033[1m{weekly['saved_tokens']:,} tokens saved\033[0m across {weekly['events']:,} events (≈${weekly['usd_saved']:.2f})")
@@ -208,6 +219,49 @@ def main(argv: Optional[List[str]] = None):
208
219
  pass
209
220
  print()
210
221
 
222
+ elif command in ("budget", "quality", "score"):
223
+ from src.governor import ContextBudget
224
+ from src.quality_score import ContextQualityScore
225
+ from src.environment_auditor import EnvironmentAuditor
226
+ tracker = MetricsTracker()
227
+ model = args[1] if len(args) > 1 and not args[1].startswith("-") else ""
228
+ transcript = ""
229
+ for a in args[1:]:
230
+ if a.startswith("--transcript="):
231
+ transcript = a.split("=", 1)[1]
232
+ elif a.endswith(".jsonl"):
233
+ transcript = a
234
+ budget = ContextBudget.estimate(tracker, session_id="mcp_session", model=model, transcript_path=transcript)
235
+ audit = EnvironmentAuditor.audit()
236
+ q_score = ContextQualityScore.calculate(budget=budget, audit=audit)
237
+
238
+ color = "\033[32m" if q_score["grade"] in ("S", "A") else ("\033[33m" if q_score["grade"] == "B" else "\033[31m")
239
+ print("\n\033[1m\033[36m⚡ TOKENSAFE CONTEXT QUALITY & BUDGET HUD ⚡\033[0m\n")
240
+ print(f" Health Grade: {color}\033[1mGrade {q_score['grade']} ({q_score['label']})\033[0m — {q_score['score']}/100 pts")
241
+ print(f" Window Headroom: {color}{q_score['headroom_pct']:.1f}% free\033[0m ({budget['used_estimated']:,} / {budget['window_tokens']:,} tokens estimated)")
242
+ print(f" Static Tax: ~{q_score['static_tax_tokens']:,} tokens on every API turn")
243
+ print(f" Breakdown: tools: {budget['breakdown']['tools']:,} | history: {budget['breakdown']['history']:,} | prompts: {budget['breakdown']['prompts']:,}")
244
+ if q_score["deductions"]:
245
+ print(f" Deductions: {', '.join(q_score['deductions'])}")
246
+ print(f" Recommendation: {budget['recommendation']}\n")
247
+
248
+ elif command in ("compact", "fold"):
249
+ if len(args) < 2:
250
+ print("Usage: tokensafe compact <path_to_transcript.jsonl>")
251
+ sys.exit(1)
252
+ transcript_path = args[1].strip()
253
+ from src.history_compactor import HistoryCompactor
254
+ ledger, orig_t, fold_t, stats = HistoryCompactor.fold_transcript(transcript_path, invocation_num=3)
255
+ if not ledger:
256
+ print("\n\033[33m○ Transcript not compactable (requires >= 4 steps and >= 1,000 history tokens).\033[0m\n")
257
+ sys.exit(0)
258
+ print("\n\033[1m\033[36m⚡ TOKENSAFE COMPACT CONVERSATION ⚡\033[0m\n")
259
+ print(f" Original history: {orig_t:,} tokens")
260
+ print(f" Compacted ledger: {fold_t:,} tokens")
261
+ print(f" Tokens saved: \033[32m\033[1m+{orig_t - fold_t:,} tokens\033[0m\n")
262
+ print(ledger)
263
+ print()
264
+
211
265
  elif command in ("stats", "dashboard"):
212
266
  tracker = MetricsTracker()
213
267
  dashboard = Dashboard(tracker)
@@ -264,7 +318,7 @@ def main(argv: Optional[List[str]] = None):
264
318
  print(f"📊 JSON: {out['json']}")
265
319
  print(f"📊 MD: {out['md']}\n")
266
320
  sys.exit(0 if all(
267
- (s.get("status") == "ok")
321
+ (s.get("status") in ("ok", "skipped"))
268
322
  for r in data["results"] for s in (r.get("symbol_read"), r.get("test_output"), r.get("multiturn"))
269
323
  if s
270
324
  ) else 1)
@@ -808,7 +862,7 @@ def main(argv: Optional[List[str]] = None):
808
862
  pass
809
863
 
810
864
  # 2. Remove local license files
811
- for p in (LICENSE_FILE, GLOBAL_LICENSE_FILE):
865
+ for p in LicenseManager._candidate_license_files():
812
866
  try:
813
867
  if os.path.exists(p):
814
868
  os.remove(p)
@@ -513,11 +513,27 @@ class EnvironmentAuditor:
513
513
  def format_cli_report(cls, workspace_root: Optional[str] = None) -> str:
514
514
  """Formats visual CLI report for tokensafe doctor."""
515
515
  report = cls.audit(workspace_root)
516
+ score_line = ""
517
+ try:
518
+ from src.quality_score import ContextQualityScore
519
+ from src.governor import ContextBudget
520
+ from src.metrics import MetricsTracker
521
+ budget = ContextBudget.estimate(MetricsTracker(), session_id="mcp_session")
522
+ q_score = ContextQualityScore.calculate(budget=budget, audit=report)
523
+ color = "\033[32m" if q_score["grade"] in ("S", "A") else ("\033[33m" if q_score["grade"] == "B" else "\033[31m")
524
+ score_line = f" \033[1mContext Quality Score:\033[0m {color}\033[1mGrade {q_score['grade']} ({q_score['label']})\033[0m — {q_score['headroom_pct']:.0f}% headroom, {q_score['score']}/100 pts\n"
525
+ except Exception:
526
+ score_line = ""
527
+
516
528
  lines = [
517
529
  "\n\033[1m\033[36m⚡ TOKENSAFE ENVIRONMENT AUDIT (CONTEXT TAX DOCTOR) ⚡\033[0m\n",
530
+ ]
531
+ if score_line:
532
+ lines.append(score_line)
533
+ lines.extend([
518
534
  f" \033[1mTotal Base Context Tax:\033[0m ~{report['total_static_tokens_per_turn']:,} tokens on EVERY API turn\n",
519
535
  " \033[1mActive MCP Servers:\033[0m"
520
- ]
536
+ ])
521
537
 
522
538
  for name, s in sorted(report["servers"].items()):
523
539
  if s["active"]:
package/src/governor.py CHANGED
@@ -399,7 +399,7 @@ class ContextBudget:
399
399
  caveat = ("Floor estimate: only TokenSafe-instrumented flows are counted "
400
400
  "(agent reasoning/output is invisible to local hooks).")
401
401
 
402
- return {
402
+ res = {
403
403
  "window_tokens": window,
404
404
  "used_estimated": used,
405
405
  "used_pct": pct,
@@ -410,3 +410,9 @@ class ContextBudget:
410
410
  "caveat": caveat,
411
411
  "measurement": "estimated",
412
412
  }
413
+ try:
414
+ from src.quality_score import ContextQualityScore
415
+ res["quality_score"] = ContextQualityScore.calculate(budget=res)
416
+ except Exception:
417
+ pass
418
+ return res
@@ -96,8 +96,128 @@ def _extract_step_tool_calls(step: dict) -> List[Tuple[str, dict]]:
96
96
  calls.append((str(block.get("name", "")), inp if isinstance(inp, dict) else {}))
97
97
  return calls
98
98
 
99
+ def _clean_goal_text(text: str) -> str:
100
+ """Extracts a clean, single-sentence goal from raw user text or prompt."""
101
+ if not text:
102
+ return ""
103
+ # Strip XML-style wrapper tags commonly injected into agent transcripts
104
+ cleaned = re.sub(r"</?(?:USER_REQUEST|CONTEXT_SUMMARY|ADDITIONAL_METADATA|SYSTEM_MESSAGE)[^>]*>", " ", text)
105
+ # Remove markdown headers or bolding
106
+ cleaned = re.sub(r"^[#\s*\->]+", "", cleaned.strip())
107
+ # Take first meaningful non-empty line
108
+ lines = [ln.strip() for ln in cleaned.splitlines() if ln.strip() and not ln.strip().startswith(("//", "/*", "<!--"))]
109
+ if not lines:
110
+ return ""
111
+ first_line = lines[0]
112
+ # Remove leading numbering like "1. ", "1) "
113
+ first_line = re.sub(r"^\d+[\.\)]\s*", "", first_line).strip()
114
+ if len(first_line) > 120:
115
+ first_line = first_line[:117] + "..."
116
+ return first_line
117
+
99
118
  class HistoryCompactor:
100
- """Folds past conversation tool steps into a compact state ledger."""
119
+ """Folds past conversation tool steps into a compact state ledger with an orientation digest."""
120
+
121
+ @classmethod
122
+ def build_orientation_digest(
123
+ cls,
124
+ steps: List[dict],
125
+ read_files: set,
126
+ edited_files: set,
127
+ executed_commands: List[str]
128
+ ) -> Tuple[str, Dict[str, str]]:
129
+ """
130
+ Builds a concise 3-line Post-Compaction Orientation Digest:
131
+ 1. Active Goal: extracted from latest user prompt
132
+ 2. Last State: the most recent action/operation performed
133
+ 3. Next Focus: clear immediate resumption directive
134
+ """
135
+ # 1. Active Goal
136
+ active_goal = ""
137
+ for step in reversed(steps):
138
+ source = str(step.get("source") or "")
139
+ stype = str(step.get("type") or "")
140
+ role = str(step.get("role") or "")
141
+ if not role and isinstance(step.get("message"), dict):
142
+ role = str(step["message"].get("role") or "")
143
+
144
+ if source == "USER_EXPLICIT" or stype == "USER_INPUT" or role == "user":
145
+ raw_txt = _extract_step_text(step)
146
+ cleaned = _clean_goal_text(raw_txt)
147
+ if cleaned:
148
+ active_goal = cleaned
149
+ break
150
+
151
+ if not active_goal:
152
+ # Fallback to key turns if any
153
+ for step in steps:
154
+ raw_txt = _extract_step_text(step)
155
+ cleaned = _clean_goal_text(raw_txt)
156
+ if cleaned and len(cleaned) > 15:
157
+ active_goal = cleaned
158
+ break
159
+
160
+ if not active_goal:
161
+ active_goal = "Resume multi-step task execution"
162
+
163
+ # 2. Last State
164
+ last_state = ""
165
+ last_tool = None
166
+ # Find the last tool call executed across all steps
167
+ for step in reversed(steps):
168
+ tcs = _extract_step_tool_calls(step)
169
+ if tcs:
170
+ last_tool = tcs[-1]
171
+ break
172
+
173
+ if last_tool:
174
+ tname, targs = last_tool
175
+ p = _arg_value(targs, _PATH_KEYS)
176
+ base_p = os.path.basename(p) if p else ""
177
+ if tname in _EDIT_TOOLS:
178
+ last_state = f"Modified {base_p or 'target files'}; changes applied"
179
+ elif tname in _COMMAND_TOOLS:
180
+ cmd = _arg_value(targs, _COMMAND_KEYS)
181
+ short_cmd = cmd.split()[0] if cmd.split() else cmd
182
+ last_state = f"Executed {short_cmd}; output processed"
183
+ elif tname in _READ_TOOLS:
184
+ last_state = f"Inspected {base_p or 'target code'}; context gathered"
185
+ else:
186
+ last_state = f"Invoked tool {tname}"
187
+
188
+ if not last_state:
189
+ if edited_files:
190
+ last_state = f"Modified {', '.join(sorted(edited_files)[:3])}"
191
+ elif executed_commands:
192
+ last_state = f"Executed {', '.join(executed_commands[-2:])}"
193
+ elif read_files:
194
+ last_state = f"Inspected {', '.join(sorted(read_files)[:3])}"
195
+ else:
196
+ last_state = "Processed past conversation turns"
197
+
198
+ # 3. Next Focus
199
+ if edited_files:
200
+ next_focus = "Verify modifications with tests and check edge cases."
201
+ elif executed_commands and any("test" in c for c in executed_commands):
202
+ next_focus = "Proceed with remaining tasks or finalize changes."
203
+ elif read_files:
204
+ next_focus = "Apply surgical edits based on inspected symbols."
205
+ else:
206
+ next_focus = "Continue direct execution toward active goal without repeating past reads."
207
+
208
+ digest_dict = {
209
+ "active_goal": active_goal,
210
+ "last_state": last_state,
211
+ "next_focus": next_focus,
212
+ }
213
+
214
+ digest_lines = [
215
+ "[Post-Compaction Orientation Digest]:",
216
+ f"1. Active Goal: {active_goal}",
217
+ f"2. Last State: {last_state}",
218
+ f"3. Next Focus: {next_focus}",
219
+ ]
220
+ return "\n".join(digest_lines), digest_dict
101
221
 
102
222
  @classmethod
103
223
  def measure_transcript(cls, transcript_path: str) -> int:
@@ -188,7 +308,11 @@ class HistoryCompactor:
188
308
  if orig_tokens < 1000:
189
309
  return None, 0, 0, {}
190
310
 
191
- # Build Consolidated State Ledger
311
+ # Build Consolidated State Ledger & Post-Compaction Orientation Digest
312
+ digest_text, digest_dict = cls.build_orientation_digest(
313
+ steps, read_files, edited_files, executed_commands
314
+ )
315
+
192
316
  ledger_lines = ["[TOCP State Ledger]:"]
193
317
  if read_files:
194
318
  ledger_lines.append(f"• Inspected: {', '.join(sorted(read_files))}")
@@ -202,6 +326,10 @@ class HistoryCompactor:
202
326
  for snippet in key_turns[:3]:
203
327
  ledger_lines.append(f"• Context: {snippet}")
204
328
 
329
+ if digest_text:
330
+ ledger_lines.append("")
331
+ ledger_lines.append(digest_text)
332
+
205
333
  consolidated_text = "\n".join(ledger_lines)
206
334
  folded_tokens = count_tokens(consolidated_text)
207
335
 
@@ -212,7 +340,8 @@ class HistoryCompactor:
212
340
  "executed_commands_count": len(executed_commands),
213
341
  "saved_tokens": saved_tokens,
214
342
  "orig_tokens": orig_tokens,
215
- "folded_tokens": folded_tokens
343
+ "folded_tokens": folded_tokens,
344
+ "orientation_digest": digest_dict,
216
345
  }
217
346
 
218
347
  return consolidated_text, orig_tokens, folded_tokens, stats
package/src/installer.py CHANGED
@@ -55,7 +55,7 @@ UNIFIED_TOKENSAFE_RULE = (
55
55
  "7. **No Unconstrained Shell Grep/Find & No Verbose ls -la**: Strictly avoid running raw recursive grep/find across projects. Never run verbose `ls -la` or `ls -l`; use `tokensafe:list_dir(path='.', depth=2)` to inspect directory trees in clean markdown without permissions, timestamps, or lockfiles (-90% tokens). Supports relative subfolders (`path='src'`).\n"
56
56
  "8. **Command Sanitization & Compact Tests**: Use `sanitize_command` on high-output terminal commands (`git diff/log/show/blame`, `rg`, `find`, `grep`, `docker`/`kubectl logs`, `npm`/`pip install`, `cat` of lockfiles, `curl`) — compound commands (`a && b ; c`) are rewritten per stage. Run unit tests with concise flags or via the `tokensafe tests [cmd]` CLI (compact passing summary `PASS: ...`, full traceback only on failure) instead of raw verbose test crawls; never leave `vitest`/`jest` in watch mode — pass the optional `cwd` to `sanitize_command` for test commands so the package.json peek can identify the runner behind opaque `yarn/npm test` scripts.\n"
57
57
  "9. **Styles & Design Token Preservation**: When inspecting CSS, SCSS, LESS, or Tailwind, `smart_read_file` automatically preserves all design tokens (`:root`, `@theme`, CSS variables) in full while folding component selectors to protect project design integrity.\n"
58
- "10. **Context Budget & Smart Compaction**: Before large multi-step tasks, call `tokensafe:context_budget(model=...)` to inspect window usage; when it reports `warning` or `critical`, call `tokensafe:compact_conversation(transcript_path=...)` before continuing.\n"
58
+ "10. **Context Budget & Smart Compaction**: Before large multi-step tasks, call `tokensafe:context_budget(model=...)` to inspect window usage and Context Quality Score (Grade S-F); when it reports `warning` or `critical` (or Grade C/F), call `tokensafe:compact_conversation(transcript_path=...)` to fold history into a State Ledger with a 3-line Post-Compaction Orientation Digest before continuing.\n"
59
59
  "11. **Secret Leak Prevention Directive (Zero Hardcoded Fallbacks)**:\n"
60
60
  "Never hardcode real private keys, API secrets, access tokens, or webhook secrets as default fallback arguments in `os.environ.get()`, `os.getenv()`, or `process.env`. If an environment variable is absent, raise an explicit configuration error or use an empty string / test mock. Whenever a secret fallback attempt is blocked, state:\n"
61
61
  "`🛡️ **TokenSafe Security Guard**: Prevented secret / private key leak into git (<target_file>: <details>)`\n"
@@ -73,8 +73,8 @@ POINTER_RULE = (
73
73
  "(~/.zcode/AGENTS.md, ~/.claude/CLAUDE.md, ~/.codex/AGENTS.md) and applies to this project. "
74
74
  "Core rules: never raw grep/find or `ls -la` — use `tokensafe:scoped_search`, "
75
75
  "`tokensafe:smart_read_file(path, symbol)`, `tokensafe:smart_bundle` and `tokensafe:list_dir`; "
76
- "sanitize high-output commands via `tokensafe:sanitize_command`; check `tokensafe:context_budget` "
77
- "before large tasks and compact via `tokensafe:compact_conversation`; never hardcode secret "
76
+ "sanitize high-output commands via `tokensafe:sanitize_command`; check `tokensafe:context_budget` (Grade S-F) "
77
+ "before large tasks and compact via `tokensafe:compact_conversation` (orientation digest active); never hardcode secret "
78
78
  "fallbacks; append the `⚡ TokenSafe Turn Savings` footer on tool-using turns.\n"
79
79
  )
80
80
 
@@ -599,12 +599,12 @@ WantedBy=default.target
599
599
  if os.environ.get("TOKENSAFE_NONINTERACTIVE", "").strip() in ("1", "true", "yes") or "unittest" in sys.modules:
600
600
  return
601
601
 
602
- if context == "update" and is_anonymous:
603
- print(f"\n {YELLOW}→ Anonymous Community license detected (migrating to verified personal account).{RESET}")
604
- print(f" Connect your free account at {CYAN}https://tokensafe.dev{RESET} to unlock your web dashboard.")
605
- else:
606
- print(f"\n {CYAN}→ Connect your free TokenSafe account (500,000 tokens/mo) to unlock your web dashboard:{RESET}")
602
+ if context == "update":
603
+ if is_anonymous or not email:
604
+ print(f" {CYAN}ℹ{RESET} Connect your account anytime with {BOLD}tokensafe login{RESET} to view your cloud dashboard.\n")
605
+ return
607
606
 
607
+ print(f"\n {CYAN}→ Connect your free TokenSafe account (500,000 tokens/mo) to unlock your web dashboard:{RESET}")
608
608
  print(f" Open browser to authorize? [{GREEN}Y{RESET}/n] ", end="", flush=True)
609
609
  answer = input().strip().lower()
610
610
  if answer in ("", "y", "yes"):
package/src/mcp_server.py CHANGED
@@ -42,7 +42,7 @@ from src.paths import get_active_workspace, is_plugin_or_system_dir
42
42
 
43
43
  SERVER_INFO = {
44
44
  "name": "tokensafe-mcp",
45
- "version": "4.0.1"
45
+ "version": "4.1.0"
46
46
  }
47
47
 
48
48
  # MCP client attribution: the initialize handshake carries clientInfo, which
@@ -154,7 +154,7 @@ TOOLS = [
154
154
  },
155
155
  {
156
156
  "name": "context_budget",
157
- "description": "Context Budget HUD: estimates how much of the model's context window this session has consumed (tools/history/prompts breakdown, 50/80/95% thresholds). Call before large multi-step tasks. When the threshold is warning or critical, immediately call tokensafe:compact_conversation on the session transcript.",
157
+ "description": "Context Budget HUD & Context Quality Score (Grade S/A/B/C/F): estimates context window usage, headroom %, static tool/skill tax, and outputs a unified health grade. Call before large multi-step tasks. When warning/critical or Grade C/F, call tokensafe:compact_conversation.",
158
158
  "inputSchema": {
159
159
  "type": "object",
160
160
  "properties": {
@@ -167,7 +167,7 @@ TOOLS = [
167
167
  },
168
168
  {
169
169
  "name": "compact_conversation",
170
- "description": "On-demand context compaction: folds a long agent conversation transcript into a compact Consolidated State Ledger. Use when tokensafe:context_budget reports warning/critical, when the context window feels heavy, or before starting a new subtask inside the same session. The transcript path comes from your host session (hook payload transcript_path / session start context).",
170
+ "description": "On-demand context compaction: folds a long agent conversation transcript into a Consolidated State Ledger with a 3-line Post-Compaction Orientation Digest (Active Goal, Last State, Next Focus) so the agent immediately resumes without losing flow. Use when context_budget reports warning/critical or Grade C/F.",
171
171
  "inputSchema": {
172
172
  "type": "object",
173
173
  "properties": {
@@ -1207,6 +1207,13 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
1207
1207
  tracker, session_id=session_id, model=model, window_tokens=window_tokens,
1208
1208
  transcript_path=transcript_path
1209
1209
  )
1210
+ try:
1211
+ from src.quality_score import ContextQualityScore
1212
+ from src.environment_auditor import EnvironmentAuditor
1213
+ audit = EnvironmentAuditor.audit()
1214
+ budget["quality_score"] = ContextQualityScore.calculate(budget=budget, audit=audit)
1215
+ except Exception:
1216
+ pass
1210
1217
  return {"content": [{"type": "text", "text": json.dumps(budget, indent=2, ensure_ascii=False)}]}
1211
1218
 
1212
1219
  elif name == "compact_conversation":
@@ -1254,13 +1261,15 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
1254
1261
  details={"mode": "manual_compact_conversation", "turns": invocation_num,
1255
1262
  "transcript_path": transcript_path, "total_accum_orig": orig_t, **stats}
1256
1263
  )
1264
+ digest_dict = stats.get("orientation_digest") or {}
1257
1265
  return {"content": [{"type": "text", "text": json.dumps({
1258
1266
  "compactable": True,
1259
1267
  "ledger": ledger,
1268
+ "orientation_digest": digest_dict,
1260
1269
  "original_tokens": orig_t,
1261
1270
  "folded_tokens": folded_t,
1262
1271
  "saved_tokens": saved,
1263
- "note": "Inject this ledger as a system message and start fresh context from it; savings are labeled estimated (digest injected, history not removed).",
1272
+ "note": "Inject this ledger and 3-line orientation digest as a system message to resume flow instantly.",
1264
1273
  "stats": stats
1265
1274
  }, indent=2, ensure_ascii=False)}]}
1266
1275
 
@@ -0,0 +1,170 @@
1
+ """
2
+ Context Quality Score Engine for TokenSafe.
3
+ Synthesizes dynamic context window headroom with static environment overhead
4
+ (MCP tools, installed skills, rule file limits, ghost tokens, and competitor conflicts)
5
+ into a unified Letter Grade (S / A / B / C / F) and visual health indicator.
6
+ """
7
+
8
+ import os
9
+ from typing import Dict, Any, Optional, List
10
+
11
+ class ContextQualityScore:
12
+ """
13
+ Evaluates and grades context health (S / A / B / C / F).
14
+
15
+ Grading Rubric:
16
+ - Dynamic Headroom (60 pts max):
17
+ headroom = max(0, 100 - used_pct)
18
+ score = (headroom / 100) * 60
19
+ - Static Footprint (25 pts max):
20
+ < 2,000 static tokens/turn -> 25 pts (ideal / lean)
21
+ 2,000 - 5,000 tokens/turn -> 20 pts (standard)
22
+ 5,000 - 10,000 tokens/turn -> 12 pts (moderate)
23
+ 10,000 - 20,000 tokens/turn -> 5 pts (heavy)
24
+ > 20,000 tokens/turn -> 0 pts (bloated)
25
+ - Hygiene & Deductions (15 pts base):
26
+ -5 per bloated MCP server (tool_count >= 40)
27
+ -6 if ghost tokens detected (> 2,000 tokens wasted in configs/rules)
28
+ -5 if rule files exceed limit (> 24KB file or > 20,000 token budget)
29
+ -4 if competitor / stale conflicts detected
30
+ clamped to [0, 15]
31
+
32
+ Grades:
33
+ - S (90 - 100): Optimal (Pristine context, maximal headroom > 90%)
34
+ - A (80 - 89): Healthy (Ample headroom > 75%, lean static overhead)
35
+ - B (65 - 79): Moderate (Moderate load, surgical reads advised)
36
+ - C (45 - 64): Constrained (High consumption or heavy static tax, compaction advised)
37
+ - F (0 - 44): Critical (Window nearly exhausted or critical bloat, compaction required)
38
+ """
39
+
40
+ @classmethod
41
+ def calculate(
42
+ cls,
43
+ budget: Dict[str, Any],
44
+ audit: Optional[Dict[str, Any]] = None,
45
+ conflicts: Optional[List[Dict[str, Any]]] = None
46
+ ) -> Dict[str, Any]:
47
+ """Calculates letter grade and detailed health metrics from budget and audit data."""
48
+ # 1. Dynamic Headroom (0 to 70 pts)
49
+ used_pct = float(budget.get("used_pct", 0.0) or 0.0)
50
+ used_estimated = int(budget.get("used_estimated", 0) or 0)
51
+ window_tokens = int(budget.get("window_tokens", 200_000) or 200_000)
52
+ headroom_pct = max(0.0, round(100.0 - used_pct, 1))
53
+
54
+ headroom_score = (headroom_pct / 100.0) * 70.0
55
+
56
+ # 2. Static Context Tax (0 to 20 pts)
57
+ audit = audit or {}
58
+ static_tokens = int(audit.get("total_static_tokens_per_turn", 0) or 0)
59
+ if static_tokens < 2000:
60
+ static_score = 20.0
61
+ elif static_tokens < 5000:
62
+ static_score = 16.0
63
+ elif static_tokens < 10000:
64
+ static_score = 12.0
65
+ elif static_tokens < 20000:
66
+ static_score = 6.0
67
+ else:
68
+ static_score = 0.0
69
+
70
+ # 3. Hygiene & Deductions (0 to 10 pts)
71
+ hygiene_base = 10.0
72
+ deductions = []
73
+
74
+ bloated_servers = audit.get("bloated_servers") or []
75
+ if bloated_servers:
76
+ penalty = len(bloated_servers) * 4.0
77
+ hygiene_base -= penalty
78
+ deductions.append(f"{len(bloated_servers)} bloated MCP server(s) (-{int(penalty)} pts)")
79
+
80
+ ghost = audit.get("ghost_tokens") or {}
81
+ if ghost.get("has_ghost_tokens"):
82
+ hygiene_base -= 4.0
83
+ deductions.append("Ghost tokens in configs/rules (-4 pts)")
84
+
85
+ rules = audit.get("rules") or {}
86
+ if rules.get("budget_exceeded") or rules.get("violations"):
87
+ hygiene_base -= 3.0
88
+ deductions.append("Rule file budget or size limit exceeded (-3 pts)")
89
+
90
+ if conflicts:
91
+ hygiene_base -= 3.0
92
+ deductions.append("Conflicting / orphan tool hooks detected (-3 pts)")
93
+
94
+ hygiene_score = max(0.0, min(10.0, hygiene_base))
95
+
96
+ total_score = max(0, min(100, int(round(headroom_score + static_score + hygiene_score))))
97
+
98
+ # Determine Letter Grade & Label
99
+ if total_score >= 88:
100
+ grade = "S"
101
+ label = "Optimal"
102
+ desc = "Pristine context, maximal headroom (>90%)"
103
+ elif total_score >= 75:
104
+ grade = "A"
105
+ label = "Healthy"
106
+ desc = "Healthy context, ample headroom"
107
+ elif total_score >= 60:
108
+ grade = "B"
109
+ label = "Moderate"
110
+ desc = "Moderate load, surgical reads advised"
111
+ elif total_score >= 40:
112
+ grade = "C"
113
+ label = "Constrained"
114
+ desc = "Constrained context, compaction recommended"
115
+ else:
116
+ grade = "F"
117
+ label = "Critical"
118
+ desc = "Critical exhaustion or severe bloat, immediate compaction required"
119
+
120
+ tax_str = f"~{static_tokens:,} tok/turn" if static_tokens else "0 tok/turn"
121
+ summary = f"Grade: {grade} ({label}, {headroom_pct:.0f}% headroom · static tax: {tax_str})"
122
+
123
+ return {
124
+ "grade": grade,
125
+ "score": total_score,
126
+ "label": label,
127
+ "descriptor": desc,
128
+ "headroom_pct": headroom_pct,
129
+ "used_pct": used_pct,
130
+ "used_estimated": used_estimated,
131
+ "window_tokens": window_tokens,
132
+ "static_tax_tokens": static_tokens,
133
+ "has_mcp_bloat": bool(bloated_servers),
134
+ "has_ghost_tokens": bool(ghost.get("has_ghost_tokens")),
135
+ "deductions": deductions,
136
+ "summary": summary,
137
+ }
138
+
139
+ @classmethod
140
+ def evaluate(
141
+ cls,
142
+ tracker: Optional[Any] = None,
143
+ session_id: str = "mcp_session",
144
+ model: str = "",
145
+ window_tokens: Optional[int] = None,
146
+ workspace_root: Optional[str] = None
147
+ ) -> Dict[str, Any]:
148
+ """Convenience evaluator that fetches current budget, environment audit, and conflicts."""
149
+ from src.governor import ContextBudget
150
+ from src.environment_auditor import EnvironmentAuditor
151
+ from src.competitors import CompetitorAuditor
152
+
153
+ if tracker is None:
154
+ from src.metrics import MetricsTracker
155
+ tracker = MetricsTracker()
156
+
157
+ budget = ContextBudget.estimate(
158
+ tracker, session_id=session_id, model=model, window_tokens=window_tokens
159
+ )
160
+ try:
161
+ audit = EnvironmentAuditor.audit(workspace_root)
162
+ except Exception:
163
+ audit = {}
164
+
165
+ try:
166
+ conflicts = CompetitorAuditor.audit()
167
+ except Exception:
168
+ conflicts = []
169
+
170
+ return cls.calculate(budget=budget, audit=audit, conflicts=conflicts)
@@ -241,7 +241,7 @@ class TelemetrySync:
241
241
  current_last_id = last_id
242
242
  headers = {
243
243
  "Content-Type": "application/json",
244
- "User-Agent": "TokenSafe-Sync/4.0.1"
244
+ "User-Agent": "TokenSafe-Sync/4.1.0"
245
245
  }
246
246
  if active_key:
247
247
  headers["Authorization"] = f"Bearer {active_key}"
@@ -17,7 +17,7 @@ import urllib.request
17
17
  import urllib.error
18
18
  from typing import Dict, Any, Optional, Tuple
19
19
 
20
- CURRENT_VERSION = "4.0.1"
20
+ CURRENT_VERSION = "4.1.0"
21
21
  CACHE_TTL = 86400 # 24 hours
22
22
  # When the cloud is unreachable we must NOT cache the synthesized "up to date"
23
23
  # answer for a full day — otherwise an update released right after an outage