tokensafe 4.15.0 → 4.16.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.
@@ -3,6 +3,7 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import json
6
+ import os
6
7
  import tempfile
7
8
  import time
8
9
  from pathlib import Path
@@ -81,6 +82,8 @@ def _matrix_report(
81
82
  "arms": arms,
82
83
  "runs": runs,
83
84
  "model": model,
85
+ "reasoning_effort": (os.environ.get("TOKENSAFE_BENCH_REASONING_EFFORT") or "").strip() or None,
86
+ "max_tokens": (os.environ.get("TOKENSAFE_BENCH_MAX_TOKENS") or "").strip() or None,
84
87
  "budget_usd": budget_usd,
85
88
  "spent_usd": round(spent, 6),
86
89
  "aborted": aborted,
@@ -228,6 +231,8 @@ def run_react_matrix(
228
231
  "arms": arms,
229
232
  "runs": runs,
230
233
  "model": model,
234
+ "reasoning_effort": (os.environ.get("TOKENSAFE_BENCH_REASONING_EFFORT") or "").strip() or None,
235
+ "max_tokens": (os.environ.get("TOKENSAFE_BENCH_MAX_TOKENS") or "").strip() or None,
231
236
  "budget_usd": budget_usd,
232
237
  "spent_usd": round(spent, 6),
233
238
  "aborted": aborted,
@@ -279,13 +284,22 @@ def summarize(report: Dict[str, Any]) -> List[Dict[str, Any]]:
279
284
  key = result["arm"]
280
285
  row = rows.setdefault(
281
286
  key,
282
- {"arm": key, "runs": 0, "solved": 0, "input": 0, "output": 0, "usd": 0.0, "steps": 0, "seconds": 0.0},
287
+ {"arm": key, "runs": 0, "solved": 0, "input": 0, "output": 0, "usd": 0.0, "steps": 0, "seconds": 0.0,
288
+ "calls": 0, "reasoning": 0, "output_solved": 0, "reasoning_solved": 0,
289
+ "reasoning_reported": False},
283
290
  )
284
291
  row["runs"] += 1
285
292
  row["solved"] += 1 if result.get("solved") else 0
286
293
  usage = result.get("usage") or {}
287
294
  row["input"] += int(usage.get("input_tokens") or 0)
288
295
  row["output"] += int(usage.get("output_tokens") or 0)
296
+ row["calls"] += int(usage.get("calls") or 0)
297
+ if "reasoning_tokens" in usage:
298
+ row["reasoning_reported"] = True
299
+ row["reasoning"] += int(usage.get("reasoning_tokens") or 0)
300
+ if result.get("solved"):
301
+ row["output_solved"] += int(usage.get("output_tokens") or 0)
302
+ row["reasoning_solved"] += int(usage.get("reasoning_tokens") or 0)
289
303
  row["usd"] += float(usage.get("usd") or 0.0)
290
304
  row["steps"] += len(result.get("steps") or [])
291
305
  row["seconds"] += float(result.get("wall_clock_s") or 0.0)
@@ -294,6 +308,25 @@ def summarize(report: Dict[str, Any]) -> List[Dict[str, Any]]:
294
308
  row["mean_seconds"] = round(row["seconds"] / row["runs"], 1) if row["runs"] else 0.0
295
309
  row["mean_input"] = round(row["input"] / row["runs"]) if row["runs"] else 0
296
310
  row["mean_output"] = round(row["output"] / row["runs"]) if row["runs"] else 0
311
+ row["output_per_call"] = round(row["output"] / row["calls"], 1) if row["calls"] else 0.0
312
+ row["output_per_solved"] = (
313
+ round(row["output_solved"] / row["solved"], 1) if row["solved"] else 0.0
314
+ )
315
+ if row["reasoning_reported"]:
316
+ row["reasoning_per_solved"] = (
317
+ round(row["reasoning_solved"] / row["solved"], 1) if row["solved"] else 0.0
318
+ )
319
+ row["reasoning_per_call"] = (
320
+ round(row["reasoning"] / row["calls"], 1) if row["calls"] else 0.0
321
+ )
322
+ row["reasoning_share_pct"] = (
323
+ round(row["reasoning"] / row["output"] * 100.0, 1) if row["output"] else 0.0
324
+ )
325
+ else:
326
+ # Older artifacts did not record reasoning_tokens: unknown is not zero.
327
+ row["reasoning_per_solved"] = None
328
+ row["reasoning_per_call"] = None
329
+ row["reasoning_share_pct"] = None
297
330
  return sorted(rows.values(), key=lambda r: r["arm"])
298
331
 
299
332
 
@@ -311,10 +344,24 @@ def render_markdown(report: Dict[str, Any]) -> str:
311
344
  + (f", plus {files} generated service files so discovery competes with a realistic tree" if files else "")
312
345
  + "."
313
346
  )
347
+ arms = report.get("arms") or []
348
+ arm_bits = ["`baseline` uses file/command tools only"]
349
+ if "tokensafe" in arms:
350
+ arm_bits.append(
351
+ "`tokensafe` adds the shipped MCP tools (`smart_read_file` with `endpoint=`, "
352
+ "`scoped_search`, `apply_edits` with inline verify)"
353
+ )
354
+ if "oumv" in arms:
355
+ arm_bits.append(
356
+ "`oumv` adds observe L3 (endpoint → handler source + version) and `applyEdit` "
357
+ "`mode=patch` (hunks) served by the shipped OUMV adapter"
358
+ )
359
+ methodology_line = "; ".join(arm_bits) + "."
314
360
  lines = [
315
361
  f"# OUMV benchmark — {target} sandbox (measured)",
316
362
  "",
317
- f"> Model: `{report['model']}` · runs: {report['runs']} · budget: ${report['budget_usd']} · "
363
+ f"> Model: `{report['model']}` · reasoning: `{report.get('reasoning_effort') or 'default'}` · "
364
+ f"runs: {report['runs']} · budget: ${report['budget_usd']} · "
318
365
  f"spent: ${report['spent_usd']} · {report['generated_at']}",
319
366
  "",
320
367
  "## Methodology",
@@ -322,19 +369,22 @@ def render_markdown(report: Dict[str, Any]) -> str:
322
369
  sandbox_line,
323
370
  f"- Correctness is {oracle}, re-run after every agent step.",
324
371
  "- Token and cost numbers come from the provider `usage` payload; prices are a pinned snapshot printed in the JSON artifact.",
325
- "- `baseline` uses file/command tools only; `tokensafe` adds the shipped MCP tools (`smart_read_file` with "
326
- "`endpoint=`, `scoped_search`, `apply_edits` with inline verify); `oumv` adds observe L3 (endpoint → handler "
327
- "source + version) and `applyEdit` `mode=patch` (hunks) served by the shipped OUMV adapter.",
372
+ f"- {methodology_line}",
328
373
  "",
329
374
  "## Results",
330
375
  "",
331
- "| Arm | Runs | Solved | Mean steps | Mean wall clock | Mean input tokens | Mean output tokens | Cost |",
332
- "| :--- | ---: | ---: | ---: | ---: | ---: | ---: | ---: |",
376
+ "| Arm | Runs | Solved | Mean steps | Mean wall clock | Mean input tokens | Mean output tokens | Output / call | Output / solved | Reasoning / call | Cost |",
377
+ "| :--- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |",
333
378
  ]
334
379
  for row in summarize(report):
380
+ reasoning_cell = (
381
+ f"{row['reasoning_per_call']:,}" if row["reasoning_per_call"] is not None else "—"
382
+ )
335
383
  lines.append(
336
384
  f"| `{row['arm']}` | {row['runs']} | {row['solved']}/{row['runs']} | {row['mean_steps']} | "
337
- f"{row['mean_seconds']}s | {row['mean_input']:,} | {row['mean_output']:,} | ${row['usd']:.4f} |"
385
+ f"{row['mean_seconds']}s | {row['mean_input']:,} | {row['mean_output']:,} | "
386
+ f"{row['output_per_call']:,} | {row['output_per_solved']:,} | "
387
+ f"{reasoning_cell} | ${row['usd']:.4f} |"
338
388
  )
339
389
  if report.get("aborted"):
340
390
  lines += ["", f"> Stopped early: {report['aborted']}"]
@@ -41,10 +41,16 @@ _WEBPACK_FILE_SIZES_RE = re.compile(r"File\s+sizes\s+after\s+gzip:", re.IGNORECA
41
41
  _CARGO_FINISHED_RE = re.compile(r"Finished\s+(release|dev|bench)\s+\[(.*?)\]\s+target\(s\)\s+in\s+([\d.]+[a-zA-Z]*)", re.IGNORECASE)
42
42
  _CARGO_COMPILING_LINE_RE = re.compile(r"^\s*Compiling\s+(\S+)\s+v(\S+)", re.MULTILINE)
43
43
 
44
+ # Go: failures print `# import/path` followed by `file.go:12:3: message`; a verbose
45
+ # success prints one module path per compiled package and nothing else.
46
+ _GO_PKG_HEADER_RE = re.compile(r"^#\s+[\w.\-]+(?:/[\w.\-]+)+\s*$", re.MULTILINE)
47
+ _GO_PACKAGE_LINE_RE = re.compile(r"^[\w.\-]+(?:/[\w.\-]+)+\s*$")
48
+ _GO_ERROR_RE = re.compile(r"\.go:\d+:\d+:")
49
+
44
50
  _FAILURE_SIGNALS_RE = re.compile(
45
- r"\b(error\s+TS\d+|SyntaxError|Failed\s+to\s+compile|error\s+during\s+build|"
51
+ r"(?:\b(error\s+TS\d+|SyntaxError|Failed\s+to\s+compile|error\s+during\s+build|"
46
52
  r"Rollup\s+failed\s+to\s+resolve|Could\s+not\s+resolve|error\[E\d+\]|"
47
- r"could\s+not\s+compile|UnhandledSchemeError|ModuleNotFoundException)\b",
53
+ r"could\s+not\s+compile|UnhandledSchemeError|ModuleNotFoundException)\b|\.go:\d+:\d+:)",
48
54
  re.IGNORECASE
49
55
  )
50
56
 
@@ -90,6 +96,8 @@ class BuildOutputParser:
90
96
  return "next"
91
97
  if "cargo" in cmd_lower and "build" in cmd_lower:
92
98
  return "cargo"
99
+ if re.search(r"(?:^|[;&|]\s*)go\s+(?:build|vet)\b", cmd_lower):
100
+ return "go"
93
101
 
94
102
  # Check content signatures
95
103
  if _VITE_START_RE.search(raw) or _VITE_BUILT_RE.search(raw) or ("modules transformed" in raw and "dist/" in raw):
@@ -100,6 +108,8 @@ class BuildOutputParser:
100
108
  return "webpack"
101
109
  if _CARGO_FINISHED_RE.search(raw) or ("Compiling " in raw and "Finished " in raw):
102
110
  return "cargo"
111
+ if _GO_ERROR_RE.search(raw) and _GO_PKG_HEADER_RE.search(raw):
112
+ return "go"
103
113
  if "[bun] Built in" in raw:
104
114
  return "bun"
105
115
 
@@ -138,6 +148,8 @@ class BuildOutputParser:
138
148
  return cls._compact_webpack_success(cleaned, raw)
139
149
  elif runner == "cargo":
140
150
  return cls._compact_cargo_success(cleaned, raw)
151
+ elif runner == "go":
152
+ return cls._compact_go_success(cleaned, raw)
141
153
  else:
142
154
  return cls._compact_generic_success(cleaned, raw)
143
155
 
@@ -301,6 +313,27 @@ class BuildOutputParser:
301
313
 
302
314
  return "\n".join(out_lines), True
303
315
 
316
+ @classmethod
317
+ def _compact_go_success(cls, cleaned: str, raw_original: str) -> Tuple[str, bool]:
318
+ """Compacts a successful `go build`/`go vet` run.
319
+
320
+ Plain `go build` is silent on success, so the only compressible case is a
321
+ verbose run that lists one module path per compiled package.
322
+ """
323
+ packages = [ln.strip() for ln in cleaned.splitlines() if _GO_PACKAGE_LINE_RE.match(ln.strip())]
324
+ if packages:
325
+ out_lines = [f"✓ go build succeeded ({len(packages)} packages compiled)"]
326
+ for pkg in packages[:3]:
327
+ out_lines.append(f" • {pkg}")
328
+ if len(packages) > 3:
329
+ out_lines.append(f" ... (+{len(packages) - 3} more packages folded)")
330
+ else:
331
+ out_lines = ["✓ go build succeeded (no output)"]
332
+ if len(cleaned.splitlines()) > 8:
333
+ _, marker = stash_block(raw_original, source="go_build")
334
+ out_lines.append(marker)
335
+ return "\n".join(out_lines), True
336
+
304
337
  @classmethod
305
338
  def _compact_generic_success(cls, cleaned: str, raw_original: str) -> Tuple[str, bool]:
306
339
  """Generic fallback for build commands with long asset/progress outputs."""
@@ -444,6 +444,51 @@ def collect_live_burn_snapshot(
444
444
  return None
445
445
 
446
446
 
447
+ def _output_budget_for(agent: str) -> int:
448
+ """Resolves the output budget: global env, then per-agent env, then the
449
+ calibration file written by `tokensafe usage --calibrate --write`."""
450
+ raw = os.environ.get("TOKENSAFE_OUTPUT_BUDGET")
451
+ if raw is not None and raw.strip():
452
+ try:
453
+ return max(1, int(raw))
454
+ except ValueError:
455
+ pass
456
+ if agent:
457
+ key = "TOKENSAFE_OUTPUT_BUDGET_" + re.sub(r"[^A-Za-z0-9]+", "_", agent).upper()
458
+ raw = os.environ.get(key)
459
+ if raw is not None and raw.strip():
460
+ try:
461
+ return max(1, int(raw))
462
+ except ValueError:
463
+ pass
464
+ try:
465
+ from src.paths import resolve_data_dir
466
+
467
+ path = os.path.join(resolve_data_dir(), "output_budget.json")
468
+ with open(path, "r", encoding="utf-8") as f:
469
+ data = json.load(f)
470
+ entry = (data.get("agents") or {}).get(agent)
471
+ if isinstance(entry, dict):
472
+ value = entry.get("budget")
473
+ elif entry is not None:
474
+ value = entry
475
+ else:
476
+ value = data.get("default")
477
+ if value is not None and int(value) > 0:
478
+ return int(value)
479
+ except Exception:
480
+ pass
481
+ return 2000
482
+
483
+
484
+ def _context_handoff_threshold() -> int:
485
+ """Context size at which a fresh session is cheaper than the next compaction."""
486
+ try:
487
+ return max(1, int(os.environ.get("TOKENSAFE_CONTEXT_HANDOFF", "") or 300000))
488
+ except (TypeError, ValueError):
489
+ return 300000
490
+
491
+
447
492
  def evaluate_burn_warnings(
448
493
  snapshot: Optional[Dict[str, Any]],
449
494
  now: Optional[datetime.datetime] = None,
@@ -468,7 +513,19 @@ def evaluate_burn_warnings(
468
513
  rl_hits = snapshot.get("rate_limit_hits") or {}
469
514
  max_gap = float(snapshot.get("max_gap_seconds") or 0.0)
470
515
 
471
- if in_tok >= 120000:
516
+ handoff_at = _context_handoff_threshold()
517
+ if in_tok >= handoff_at:
518
+ # One warning, not two: past the handoff line the compaction cost is the
519
+ # message that matters (sess_ba3e8135 compacted at 874k and re-billed
520
+ # 848k tokens in a single request).
521
+ warnings.append({
522
+ "code": "context_handoff",
523
+ "message": (
524
+ f"Session context is {in_tok:,} tokens; the host's next compaction rewrites the "
525
+ f"prompt and re-bills it once. Write a short state file and start a fresh session."
526
+ ),
527
+ })
528
+ elif in_tok >= 120000:
472
529
  warnings.append({
473
530
  "code": "context_bloat",
474
531
  "message": (
@@ -524,6 +581,17 @@ def evaluate_burn_warnings(
524
581
  ),
525
582
  })
526
583
 
584
+ out_tok = int(snapshot.get("last_output_tokens") or 0)
585
+ out_budget = _output_budget_for(str(snapshot.get("agent") or ""))
586
+ if out_tok >= max(1, out_budget):
587
+ warnings.append({
588
+ "code": "output_heavy",
589
+ "message": (
590
+ f"Last turn generated {out_tok:,} output tokens (budget {out_budget:,}) — "
591
+ f"keep this turn terse and don't restate tool results."
592
+ ),
593
+ })
594
+
527
595
  if parallel >= 2:
528
596
  warnings.append({
529
597
  "code": "parallel_sessions",
@@ -115,7 +115,7 @@ class PromptCacheNormalizer:
115
115
  re.compile(r"Conversation ID:\s*[a-f0-9-]{8,36}", re.IGNORECASE),
116
116
  re.compile(r"invocationNum[\"']?\s*[:=]\s*\d+", re.IGNORECASE),
117
117
  re.compile(r"Generated locally at \d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}", re.IGNORECASE),
118
- re.compile(r"⚡ \*\*TokenSafe Turn Savings\*\*:.*?(?=\n|$)", re.IGNORECASE),
118
+ re.compile(r"⚡ \*\*TokenSafe(?: Turn Savings)?\*\*:.*?(?=\n|$)", re.IGNORECASE),
119
119
  re.compile(r"\(TokenSafe: compacted ~?\d[\d,]* prompt tokens.*?\)", re.IGNORECASE),
120
120
  re.compile(r"\[TokenSafe(?: Subagent Firewall)?: Pointer Hit .*?\]", re.IGNORECASE),
121
121
  re.compile(r"Community Edition limit reached.*?(?=\n|$)", re.IGNORECASE),
package/src/cli.py CHANGED
@@ -109,6 +109,7 @@ def _print_help():
109
109
  print(" init [--template ...] Initialize TokenSafe stack in current directory")
110
110
  print(" stats / markdown / html Savings analytics (terminal / .md report / dashboard)")
111
111
  print(" savings [--json] Canonical totals + last event (cite these numbers, never guess)")
112
+ print(" usage [--json] [--session ID] Per-session context report: peak, host compactions, cache-miss events")
112
113
  print(" bench-oumv [--target go|react] [--tasks all] [--arms baseline,oumv] [--runs N] [--budget USD] Measured agent benchmark")
113
114
  print(" dict lint|coverage|show|apply String catalogs: suspect keys only, byte-preserving write-back")
114
115
  print(" status One-screen health check: hooks, weekly savings, tier, sync")
@@ -364,12 +365,99 @@ def main(argv: Optional[List[str]] = None):
364
365
  print(f" Data dir: {report['data_dir']}")
365
366
  print(f" Events / sessions: {report['total_events']} / {report['sessions']}")
366
367
  print(f" Saved (live): {report['saved_tokens_live']:,} tokens")
367
- print(f" Saved (pruned+sync): {report['pruned_synced_saved_tokens']:,} tokens")
368
- print(f" Cumulative: {report['cumulative_saved_tokens']:,} tokens (≈${report['usd_saved_approx']:.2f})")
368
+ print(f" Synced to cloud: {report['pruned_synced_saved_tokens']:,} tokens (subset of live)")
369
+ print(f" Cumulative: {report['cumulative_saved_tokens']:,} tokens")
369
370
  if last:
370
371
  print(f" Last event: {last.get('event_type')} — {last.get('saved_tokens'):,} tokens at {last.get('timestamp')}")
371
372
  print()
372
373
 
374
+ elif command in ("usage", "output"):
375
+ # MetricsTracker is imported at module level on purpose: a function-local
376
+ # import would shadow it for the whole main() and break earlier branches
377
+ # (see the check-update note above).
378
+ tracker = MetricsTracker()
379
+ if "--backfill" in args:
380
+ from src.usage_ledger import backfill_from_transcripts
381
+ bf = backfill_from_transcripts(tracker=tracker)
382
+ if "--json" not in args:
383
+ print(f"\n Backfill: {bf['updated']} session(s) updated, {bf['skipped']} skipped · by agent {bf['by_agent']}")
384
+ if "--calibrate" in args:
385
+ from src.usage_ledger import compute_output_budgets, write_output_budgets
386
+ cal = compute_output_budgets(tracker=tracker)
387
+ written = write_output_budgets(cal) if "--write" in args else ""
388
+ if "--json" in args:
389
+ import json as _json
390
+ print(_json.dumps({**cal, "written": written or None}, indent=2, ensure_ascii=False))
391
+ else:
392
+ print("\n\033[1m\033[36m⚡ OUTPUT BUDGET CALIBRATION (p90 output/call) ⚡\033[0m\n")
393
+ for agent, stats in (cal.get("agents") or {}).items():
394
+ print(f" {agent:<14} sessions={stats['sessions']:<4} p50={stats['p50']:<8} p90={stats['p90']:<8} budget={stats['budget']}")
395
+ print(f"\n Default: {cal['default']}" + (f" · written: {written}" if written else "") + "\n")
396
+ return
397
+ session_filter = ""
398
+ for i, a in enumerate(args):
399
+ if a.startswith("--session="):
400
+ session_filter = a.split("=", 1)[1]
401
+ elif a == "--session" and i + 1 < len(args):
402
+ session_filter = str(args[i + 1])
403
+ if session_filter:
404
+ row = tracker.get_usage_session(session_filter)
405
+ if "--json" in args:
406
+ import json as _json
407
+ print(_json.dumps({"source": "transcript-ledger", "session": row}, indent=2, ensure_ascii=False))
408
+ elif not row:
409
+ print(f"\n\033[33m○ No usage recorded for session {session_filter}.\033[0m\n")
410
+ sys.exit(0)
411
+ else:
412
+ out = int(row.get("output_tokens") or 0)
413
+ turns = int(row.get("llm_turns") or 0)
414
+ tools = int(row.get("tool_calls") or 0)
415
+ reason = int(row.get("reasoning_chars") or 0)
416
+ vis = int(row.get("visible_chars") or 0)
417
+ share = round(reason / (reason + vis) * 100, 1) if (reason + vis) else None
418
+ print("\n\033[1m\033[36m⚡ TOKENSAFE OUTPUT USAGE (measured) ⚡\033[0m\n")
419
+ print(f" Session: {row['session_id']} ({row.get('source')})")
420
+ print(f" Model: {row.get('model') or 'unknown'}")
421
+ print(f" Output tokens: {out:,}")
422
+ print(f" Model calls / tools: {turns:,} / {tools:,}")
423
+ peak = int(row.get("peak_context_tokens") or 0)
424
+ last_ctx = int(row.get("last_context_tokens") or 0)
425
+ comps = int(row.get("compactions") or 0)
426
+ miss = int(row.get("miss_tokens") or 0)
427
+ miss_events = int(row.get("miss_events") or 0)
428
+ cache_read = int(row.get("cache_read_tokens") or 0)
429
+ total_in = int(row.get("input_tokens") or 0)
430
+ cache_pct = round(cache_read / total_in * 100, 1) if total_in else None
431
+ cache_label = f"{cache_pct}%" if cache_pct is not None else "unknown"
432
+ print(f" Context: last {last_ctx:,} · peak {peak:,} · compactions {comps}")
433
+ print(f" Cache: read {cache_read:,} ({cache_label}) · miss {miss:,} · miss events {miss_events}")
434
+ print(f" Output / call: {round(out / turns, 1) if turns else 'unknown'}")
435
+ print(f" Output / tool call: {round(out / tools, 1) if tools else 'unknown'}")
436
+ print(f" Reasoning share: {f'{share}%' if share is not None else 'unknown'}\n")
437
+ else:
438
+ u = tracker.get_usage_summary()
439
+ if "--json" in args:
440
+ import json as _json
441
+ print(_json.dumps({"source": "transcript-ledger", **u}, indent=2, ensure_ascii=False))
442
+ else:
443
+ print("\n\033[1m\033[36m⚡ TOKENSAFE OUTPUT USAGE (measured) ⚡\033[0m\n")
444
+ print(f" Sessions: {u['sessions']} ({u['measured_sessions']} measured / {u['steps_only_sessions']} steps-only)")
445
+ if u["measured_sessions"]:
446
+ print(f" Output tokens: {u['output_tokens']:,}")
447
+ print(f" Model calls: {u['llm_turns']:,}")
448
+ print(f" Output / call: {u['output_per_call']}")
449
+ print(f" Tool calls: {u['tool_calls']:,}")
450
+ print(f" Output / tool call: {u['output_per_tool_call']}")
451
+ print(f" Reasoning share: {u['reasoning_share_pct']}%")
452
+ top = u.get("top") or []
453
+ if top:
454
+ print("\n Top sessions:")
455
+ for r in top[:5]:
456
+ print(f" • {r['session_id'][:18]:<18} {int(r.get('output_tokens') or 0):>12,} output")
457
+ else:
458
+ print(" No measured output yet — the Stop-hook ledger fills on the next session turn.")
459
+ print()
460
+
373
461
  elif command in ("stats", "dashboard"):
374
462
  tracker = MetricsTracker()
375
463
  dashboard = Dashboard(tracker)
@@ -885,6 +973,16 @@ def main(argv: Optional[List[str]] = None):
885
973
 
886
974
  elif command == "oumv":
887
975
  sub = args[1] if len(args) > 1 else "status"
976
+ # A session may hold several repos: `oumv status --workspace_dir <repo>`
977
+ # must answer for that repo, not for the process cwd. The routing brief
978
+ # and the apply_edits nudge both point at this form.
979
+ workspace_dir = ""
980
+ for i, arg in enumerate(args):
981
+ if arg in ("--workspace_dir", "--workspace-dir") and i + 1 < len(args):
982
+ workspace_dir = str(args[i + 1])
983
+ elif arg.startswith(("--workspace_dir=", "--workspace-dir=")):
984
+ workspace_dir = arg.split("=", 1)[1]
985
+ workspace = os.path.abspath(os.path.expanduser(workspace_dir)) if workspace_dir else os.getcwd()
888
986
  if sub in ("doctor", "audit"):
889
987
  from src.retrofit import run_doctor
890
988
  if "--prune" in args[2:]:
@@ -907,7 +1005,7 @@ def main(argv: Optional[List[str]] = None):
907
1005
  f"ledger archives: {prune_archives()}"
908
1006
  )
909
1007
  return
910
- doc = run_doctor(os.getcwd())
1008
+ doc = run_doctor(workspace)
911
1009
  print(f"\n\033[1m\033[36m⚡ TOKENSAFE OUMV DOCTOR ⚡\033[0m\n")
912
1010
  print(f" Config (.tokensafe/oumv.json): {'✔ Present' if doc['config_present'] else '○ Not found (run tokensafe integrate)'}")
913
1011
  print(f" Runtime Beacon (.tokensafe/...): {'✔ Active' if doc['runtime_beacon_present'] else '○ Offline (DevServer not running)'}")
@@ -927,7 +1025,7 @@ def main(argv: Optional[List[str]] = None):
927
1025
  print()
928
1026
  else:
929
1027
  from src.oumv_gateway import OUMVGateway
930
- status = OUMVGateway.status()
1028
+ status = OUMVGateway.status(workspace_dir=workspace)
931
1029
  print(f"\n\033[1m\033[36m⚡ TOKENSAFE OUMV RUNTIME STATUS ⚡\033[0m\n")
932
1030
  print(f" Frontend Runtime: {status['frontend'].get('status', 'OK')} ({status['frontend'].get('name', 'N/A')})")
933
1031
  print(f" Backend Runtime: {status['backend'].get('status', 'OK')} ({status['backend'].get('name', 'N/A')})")
@@ -1361,6 +1459,13 @@ def main(argv: Optional[List[str]] = None):
1361
1459
  run_mcp_server()
1362
1460
 
1363
1461
  elif command in ("acp",):
1462
+ if any(arg in ("--print-command", "--print_command") for arg in args[1:]):
1463
+ import shutil as _shutil
1464
+ import sys as _sys
1465
+ node = _shutil.which("node") or "node"
1466
+ shim = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "bin", "tokensafe-acp.js")
1467
+ print(f'{node} "{shim}"')
1468
+ _sys.exit(0)
1364
1469
  from src.acp.server import run_acp_server
1365
1470
  run_acp_server()
1366
1471
 
@@ -425,11 +425,18 @@ class CommandSanitizer:
425
425
  if "--tail" not in stage and not any(a == "-n" or a.startswith(("-n", "--tail=")) for a in cmd_args):
426
426
  return f"{stage} --tail 100", 2000, "Capped docker logs to last 100 lines", None
427
427
 
428
- # docker build / docker compose build: the failing step sits at the end
429
- # of the log — keep only the tail instead of a full build dump
428
+ # docker build / docker compose build: fold the stage log without losing the
429
+ # exit code. A `| tail -50` pipeline reports tail's status, so a failed build
430
+ # read as success; `tokensafe wrap` keeps the command's own exit code and now
431
+ # folds STEP/#n stage lines into a summary.
430
432
  if cmd_tok == "docker" and (cmd_args[:1] == ["build"] or cmd_args[:2] == ["compose", "build"]):
431
- if not cls._has_redirect(stage) and "|" not in stage:
432
- return f"{stage} 2>&1 | tail -50", 2500, "Tailed docker build output to the last 50 lines (failing step is last)", None
433
+ if not cls._has_redirect(stage) and "|" not in stage and cls._is_tokensafe_available():
434
+ return (
435
+ f"tokensafe wrap {shlex.quote(stage)}",
436
+ 2500,
437
+ "Wrapped docker build with tokensafe wrap to fold stage logs and keep the exit code",
438
+ None,
439
+ )
433
440
 
434
441
  # kubectl logs
435
442
  if cmd_tok == "kubectl" and cmd_args[:1] == ["logs"]:
@@ -1098,12 +1105,21 @@ class CommandSanitizer:
1098
1105
  if len(stripped) >= len(raw) * 0.85:
1099
1106
  return None
1100
1107
  return stripped, len(raw), len(stripped)
1101
- # Check build output parser first (vite, next, webpack, cargo build)
1108
+ # Check build output parser first (vite, next, webpack, cargo, go build)
1102
1109
  from src.build_parsers import BuildOutputParser
1103
1110
  compacted_build, was_build = BuildOutputParser.compact(raw, resolved_exit)
1104
1111
  if was_build and len(compacted_build) < len(raw) * 0.8:
1105
1112
  return compacted_build, len(raw), len(compacted_build)
1106
1113
 
1114
+ # Docker build logs: the reducer already folds STEP/#n stage lines and keeps
1115
+ # errors, but only `tokensafe wrap` and the result ledger used it — this path
1116
+ # rewrote docker output to `| tail -50` and lost the stage structure. Success
1117
+ # only: a failed build keeps every diagnostic line for the failure branch.
1118
+ from src.format_parsers.docker_k8s import ContainerAndK8sReducer
1119
+ reduced_docker, was_docker = ContainerAndK8sReducer.reduce_docker_build(raw)
1120
+ if was_docker and len(reduced_docker) < len(raw) * 0.8:
1121
+ return reduced_docker, len(raw), len(reduced_docker)
1122
+
1107
1123
  compacted = cls.compact_test_output(raw, resolved_exit)
1108
1124
  if compacted is raw or len(compacted) >= len(raw) * 0.6:
1109
1125
  return None
package/src/dashboard.py CHANGED
@@ -146,6 +146,19 @@ class Dashboard:
146
146
  out.append(f" • {BOLD}{'Cold MCP tools pruned (proxy)':<34}{RESET} : {GREEN}{tp['saved']:,} floor tokens{RESET} ({tp['count']} events)")
147
147
  out.append("")
148
148
 
149
+ # Measured output (Stop-hook transcript ledger): provider-reported only.
150
+ try:
151
+ usage = self.tracker.get_usage_summary()
152
+ except Exception:
153
+ usage = None
154
+ if usage and usage.get("measured_sessions"):
155
+ out.append(f"{BOLD}── Measured Output (transcript ledger) ─────────────────────────────{RESET}")
156
+ out.append(f" • {BOLD}{'Output tokens':<34}{RESET} : {GREEN}{usage['output_tokens']:,}{RESET} over {usage['llm_turns']:,} model calls")
157
+ out.append(f" • {BOLD}{'Output / model call':<34}{RESET} : {usage['output_per_call']}")
158
+ out.append(f" • {BOLD}{'Output / tool call':<34}{RESET} : {usage['output_per_tool_call']}")
159
+ out.append(f" • {BOLD}{'Reasoning share':<34}{RESET} : {usage['reasoning_share_pct']}% of generated chars")
160
+ out.append("")
161
+
149
162
  # Cache stability (proxy): does history mutation erode KV-cache hits?
150
163
  try:
151
164
  cache_obs = self.tracker.get_cache_obs()
@@ -233,6 +246,19 @@ class Dashboard:
233
246
  md.append(f"| **Net Efficiency Gain** | `{render_bar(pct)}` |")
234
247
  md.append(f"| **Estimated Value Saved** | **≈${usd:.4f} USD** (derived approximation) |\n")
235
248
 
249
+ try:
250
+ usage = self.tracker.get_usage_summary()
251
+ except Exception:
252
+ usage = None
253
+ if usage and usage.get("measured_sessions"):
254
+ md.append("\n### Measured Output (transcript ledger)\n")
255
+ md.append("| Metric | Value |")
256
+ md.append("| :--- | :--- |")
257
+ md.append(f"| **Output tokens** | **{usage['output_tokens']:,}** |")
258
+ md.append(f"| **Output / model call** | {usage['output_per_call']} |")
259
+ md.append(f"| **Output / tool call** | {usage['output_per_tool_call']} |")
260
+ md.append(f"| **Reasoning share** | {usage['reasoning_share_pct']}% |")
261
+
236
262
  md.append("### Source Breakdown\n")
237
263
  md.append("| Pipeline Stage | Events | Tokens Saved |")
238
264
  md.append("| :--- | :--- | :--- |")