tokensafe 4.6.3 → 4.7.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.
Files changed (47) hide show
  1. package/.codex-plugin/plugin.json +2 -2
  2. package/LICENSE +202 -21
  3. package/README.md +44 -7
  4. package/hooks/claude_code_hook.py +24 -2
  5. package/hooks/kimi_hook.py +20 -0
  6. package/hooks/pre_invocation.py +7 -12
  7. package/hooks/session_start.py +8 -0
  8. package/kimi.plugin.json +2 -2
  9. package/package.json +2 -2
  10. package/plugin.json +2 -1
  11. package/server.json +3 -3
  12. package/src/acp/__init__.py +15 -0
  13. package/src/acp/server.py +328 -0
  14. package/src/adapter_core.py +22 -3
  15. package/src/agent/__init__.py +11 -0
  16. package/src/agent/context.py +99 -0
  17. package/src/agent/loop.py +385 -0
  18. package/src/agent/pricing.py +77 -0
  19. package/src/agent/providers.py +486 -0
  20. package/src/agent/tools.py +98 -0
  21. package/src/auto_inject.py +517 -0
  22. package/src/bench/__init__.py +1 -0
  23. package/src/bench/driver.py +219 -0
  24. package/src/bench/go_target.py +360 -0
  25. package/src/bench/react_target.py +234 -0
  26. package/src/bench/runner.py +247 -0
  27. package/src/cli.py +244 -5
  28. package/src/command_sanitizer.py +54 -0
  29. package/src/guard.py +63 -10
  30. package/src/history_compactor.py +200 -2
  31. package/src/mcp_server.py +65 -13
  32. package/src/paths.py +99 -2
  33. package/src/retrofit.py +91 -4
  34. package/src/savings.py +81 -0
  35. package/src/scaffold.py +190 -8
  36. package/src/session_brief.py +154 -0
  37. package/src/session_context.py +124 -0
  38. package/src/telemetry_sync.py +93 -25
  39. package/src/version_checker.py +1 -1
  40. package/hooks/__pycache__/claude_code_hook.cpython-312.pyc +0 -0
  41. package/hooks/__pycache__/cursor_hook.cpython-312.pyc +0 -0
  42. package/hooks/__pycache__/kimi_hook.cpython-312.pyc +0 -0
  43. package/hooks/__pycache__/pre_invocation.cpython-312.pyc +0 -0
  44. package/hooks/__pycache__/pre_tool_use.cpython-312.pyc +0 -0
  45. package/hooks/__pycache__/session_start.cpython-312.pyc +0 -0
  46. package/hooks/__pycache__/stop_hook.cpython-312.pyc +0 -0
  47. package/hooks/__pycache__/zcode_hook.cpython-312.pyc +0 -0
@@ -10,10 +10,97 @@ from typing import Dict, Any, Optional, List, Tuple
10
10
  from src.tokenizer import count_tokens
11
11
 
12
12
 
13
+ def _block_text(content: Any) -> str:
14
+ """Plain text of a message content (plain string or typed block list)."""
15
+ if isinstance(content, str):
16
+ return content
17
+ if not isinstance(content, list):
18
+ return ""
19
+ parts: List[str] = []
20
+ for block in content:
21
+ if not isinstance(block, dict):
22
+ continue
23
+ btype = str(block.get("type") or "")
24
+ if btype in ("text", "thinking", "reasoning"):
25
+ text = block.get("text") or block.get("thinking")
26
+ if isinstance(text, str) and text:
27
+ parts.append(text)
28
+ elif btype == "tool_result":
29
+ nested = _block_text(block.get("content"))
30
+ if nested:
31
+ parts.append(nested)
32
+ return " ".join(parts)
33
+
34
+
35
+ def _model_io_parts(step: dict) -> Tuple[str, List[Tuple[str, dict]], str]:
36
+ """Normalize a ZCode `model_io` record into (text, tool_calls, user_prompt).
37
+
38
+ One record is one provider call: `request.messages` carries either only the
39
+ new messages (`messagesKind: "delta"`) or a window ending with the newest
40
+ message, while `response` holds that call's assistant output. Only the newest
41
+ message is new state, so folding stays linear instead of re-counting the
42
+ cumulative conversation once per record. `user_prompt` is non-empty when the
43
+ record sits on a turn boundary (the digest's active goal).
44
+ """
45
+ request = step.get("request") if isinstance(step.get("request"), dict) else {}
46
+ response = step.get("response") if isinstance(step.get("response"), dict) else {}
47
+
48
+ messages = request.get("messages") if isinstance(request.get("messages"), list) else []
49
+ newest: dict = messages[-1] if messages and isinstance(messages[-1], dict) else {}
50
+ newest_role = str(newest.get("role") or "")
51
+ newest_text = _block_text(newest.get("content"))
52
+
53
+ user_prompt = ""
54
+ if newest_role == "user":
55
+ candidate = newest_text.strip()
56
+ if candidate and not _is_injected_prompt(candidate):
57
+ user_prompt = candidate
58
+ if not user_prompt and request.get("messagesKind") in ("full", "delta"):
59
+ # Complete (or purely new) windows: the newest user message is this
60
+ # turn's prompt even when trailing tool results follow it.
61
+ for item in reversed(messages):
62
+ if not isinstance(item, dict) or item.get("role") != "user":
63
+ continue
64
+ candidate = _block_text(item.get("content")).strip()
65
+ if candidate and not _is_injected_prompt(candidate):
66
+ user_prompt = candidate
67
+ break
68
+
69
+ assistant_text = response.get("text")
70
+ if not isinstance(assistant_text, str):
71
+ assistant_text = ""
72
+ reasoning_text = response.get("reasoningText")
73
+ if not isinstance(reasoning_text, str):
74
+ reasoning_text = ""
75
+
76
+ parts: List[str] = []
77
+ if newest_role == "user" and newest_text.strip():
78
+ parts.append(newest_text) # the prompt itself leads the step
79
+ elif user_prompt:
80
+ parts.append(user_prompt) # prompt recovered from deeper in the window
81
+ if assistant_text.strip():
82
+ parts.append(assistant_text)
83
+ if reasoning_text.strip():
84
+ parts.append(reasoning_text)
85
+ if newest_role != "user" and newest_text.strip():
86
+ parts.append(newest_text)
87
+
88
+ calls: List[Tuple[str, dict]] = []
89
+ for call in response.get("toolCalls") or []:
90
+ if not isinstance(call, dict):
91
+ continue
92
+ args = call.get("input")
93
+ calls.append((str(call.get("name") or ""), args if isinstance(args, dict) else {}))
94
+
95
+ return "\n".join(part for part in parts if part), calls, user_prompt
96
+
97
+
13
98
  def _extract_step_text(step: dict) -> str:
14
99
  """Step text in any supported transcript format (Antigravity string/list, Claude Code text/thinking/tool_result)."""
15
100
  if not isinstance(step, dict):
16
101
  return ""
102
+ if step.get("type") == "model_io":
103
+ return _model_io_parts(step)[0]
17
104
  content = step.get("content")
18
105
  if isinstance(content, str) and content:
19
106
  return content
@@ -23,6 +110,61 @@ def _extract_step_text(step: dict) -> str:
23
110
  for b in content
24
111
  if isinstance(b, dict)
25
112
  ).strip()
113
+ # ZCode event log: {"type": "...", "payload": {...}}
114
+ payload = step.get("payload")
115
+ if isinstance(payload, dict):
116
+ pcontent = payload.get("content")
117
+ if isinstance(pcontent, str) and pcontent:
118
+ return pcontent
119
+ if isinstance(pcontent, list):
120
+ parts = [
121
+ str(b.get("text") or b.get("thinking") or "")
122
+ for b in pcontent
123
+ if isinstance(b, dict)
124
+ ]
125
+ joined = " ".join(parts).strip()
126
+ if joined:
127
+ return joined
128
+ pinput = payload.get("input")
129
+ if isinstance(pinput, str) and pinput:
130
+ return pinput
131
+ if step.get("type") == "turn_started" and isinstance(pinput, dict):
132
+ text = pinput.get("text") or pinput.get("prompt")
133
+ if isinstance(text, str) and text:
134
+ return text
135
+
136
+ # ZCode model-io log: {request:{body:{messages}}, response:{body:{choices}}}
137
+ response = step.get("response")
138
+ if isinstance(response, dict):
139
+ try:
140
+ msg = response["body"]["choices"][0]["message"]
141
+ except Exception:
142
+ msg = None
143
+ if isinstance(msg, dict):
144
+ content = msg.get("content")
145
+ if isinstance(content, str) and content:
146
+ return content
147
+ if isinstance(content, list):
148
+ joined = " ".join(
149
+ str(b.get("text") or "")
150
+ for b in content
151
+ if isinstance(b, dict)
152
+ ).strip()
153
+ if joined:
154
+ return joined
155
+ request = step.get("request")
156
+ if isinstance(request, dict):
157
+ try:
158
+ messages = request["body"]["messages"]
159
+ except Exception:
160
+ messages = None
161
+ if isinstance(messages, list):
162
+ for item in reversed(messages):
163
+ if isinstance(item, dict) and item.get("role") == "user":
164
+ content = item.get("content")
165
+ if isinstance(content, str) and content:
166
+ return content
167
+
26
168
  message = step.get("message")
27
169
  if not isinstance(message, dict):
28
170
  return ""
@@ -80,12 +222,40 @@ def _extract_step_tool_calls(step: dict) -> List[Tuple[str, dict]]:
80
222
  calls: List[Tuple[str, dict]] = []
81
223
  if not isinstance(step, dict):
82
224
  return calls
225
+ if step.get("type") == "model_io":
226
+ return _model_io_parts(step)[1]
83
227
  tc_list = step.get("tool_calls")
84
228
  if isinstance(tc_list, list):
85
229
  for tc in tc_list:
86
230
  if isinstance(tc, dict):
87
231
  args = tc.get("args")
88
232
  calls.append((str(tc.get("name", "")), args if isinstance(args, dict) else {}))
233
+ response = step.get("response")
234
+ if isinstance(response, dict):
235
+ try:
236
+ message = response["body"]["choices"][0]["message"]
237
+ except Exception:
238
+ message = None
239
+ if isinstance(message, dict):
240
+ for tc in message.get("tool_calls") or []:
241
+ fn = (tc or {}).get("function") or {}
242
+ name = str(fn.get("name") or "")
243
+ raw_args = fn.get("arguments")
244
+ args = {}
245
+ if isinstance(raw_args, str):
246
+ try:
247
+ args = json.loads(raw_args)
248
+ except Exception:
249
+ args = {}
250
+ elif isinstance(raw_args, dict):
251
+ args = raw_args
252
+ calls.append((name, args if isinstance(args, dict) else {}))
253
+
254
+ payload = step.get("payload")
255
+ if isinstance(payload, dict) and step.get("type") == "tool_call_scheduled":
256
+ args = payload.get("input")
257
+ calls.append((str(payload.get("toolName", "")), args if isinstance(args, dict) else {}))
258
+
89
259
  message = step.get("message")
90
260
  if isinstance(message, dict):
91
261
  mc = message.get("content")
@@ -96,6 +266,21 @@ def _extract_step_tool_calls(step: dict) -> List[Tuple[str, dict]]:
96
266
  calls.append((str(block.get("name", "")), inp if isinstance(inp, dict) else {}))
97
267
  return calls
98
268
 
269
+ _INJECTED_PROMPT_MARKERS = (
270
+ "<system-reminder",
271
+ "critical: respond with text",
272
+ "respond with text only",
273
+ "[tokensafe",
274
+ "[oumv",
275
+ )
276
+
277
+
278
+ def _is_injected_prompt(text: str) -> bool:
279
+ """True for harness-injected reminders that arrive as user-role messages."""
280
+ lowered = text.lower()
281
+ return any(marker in lowered for marker in _INJECTED_PROMPT_MARKERS)
282
+
283
+
99
284
  def _clean_goal_text(text: str) -> str:
100
285
  """Extracts a clean, single-sentence goal from raw user text or prompt."""
101
286
  if not text:
@@ -143,6 +328,8 @@ class HistoryCompactor:
143
328
 
144
329
  if source == "USER_EXPLICIT" or stype == "USER_INPUT" or role == "user":
145
330
  raw_txt = _extract_step_text(step)
331
+ if _is_injected_prompt(raw_txt):
332
+ continue
146
333
  cleaned = _clean_goal_text(raw_txt)
147
334
  if cleaned:
148
335
  active_goal = cleaned
@@ -152,6 +339,8 @@ class HistoryCompactor:
152
339
  # Fallback to key turns if any
153
340
  for step in steps:
154
341
  raw_txt = _extract_step_text(step)
342
+ if _is_injected_prompt(raw_txt):
343
+ continue
155
344
  cleaned = _clean_goal_text(raw_txt)
156
345
  if cleaned and len(cleaned) > 15:
157
346
  active_goal = cleaned
@@ -261,9 +450,18 @@ class HistoryCompactor:
261
450
  line = line.strip()
262
451
  if line:
263
452
  try:
264
- steps.append(json.loads(line))
453
+ parsed = json.loads(line)
265
454
  except Exception:
266
- pass
455
+ continue
456
+ # A model-io record whose newest message is the user's
457
+ # prompt is the turn boundary the digest looks for.
458
+ if (
459
+ isinstance(parsed, dict)
460
+ and parsed.get("type") == "model_io"
461
+ and _model_io_parts(parsed)[2]
462
+ ):
463
+ parsed["role"] = "user"
464
+ steps.append(parsed)
267
465
  except Exception:
268
466
  return None, 0, 0, {}
269
467
 
package/src/mcp_server.py CHANGED
@@ -39,10 +39,11 @@ from src.guard import TokenSafeGuard
39
39
  from src.scoped_search import ScopedSearch
40
40
  from src.license_manager import LicenseManager
41
41
  from src.paths import get_active_workspace, is_plugin_or_system_dir
42
+ from src.session_context import current_root, current_session_id
42
43
 
43
44
  SERVER_INFO = {
44
45
  "name": "tokensafe-mcp",
45
- "version": "4.6.3"
46
+ "version": "4.7.0"
46
47
  }
47
48
 
48
49
  # MCP client attribution: the initialize handshake carries clientInfo, which
@@ -65,9 +66,25 @@ def _set_mcp_client(name: str):
65
66
 
66
67
 
67
68
  def _mcp_session_id() -> str:
69
+ """Metrics key for the current call.
70
+
71
+ An explicit session scope (ACP agent server, in-process loop, tests) wins:
72
+ one process can own several sessions, and mixing their metrics or pointer
73
+ caches together is what the legacy global client name did."""
74
+ scoped = current_session_id()
75
+ if scoped:
76
+ return scoped
68
77
  return f"mcp:{_MCP_CLIENT_NAME}" if _MCP_CLIENT_NAME else "mcp_session"
69
78
 
70
79
 
80
+ def _workspace_root() -> Optional[str]:
81
+ """Project root for relative-path resolution.
82
+
83
+ Session scope first, then the machine-wide marker written by lifecycle
84
+ hooks. Never returns scratch space (``get_active_workspace`` filters it)."""
85
+ return current_root() or get_active_workspace()
86
+
87
+
71
88
  def _client_supports_pointers() -> bool:
72
89
  """Out-of-the-box capability detection (zero env vars): returns True once the
73
90
  MCP client has fetched tools/list (seeing force_full) or identified as an
@@ -981,7 +998,7 @@ def _resolve_project_root(args: dict) -> Tuple[Optional[str], Optional[str]]:
981
998
  Safely resolves the target project root without falling back to system root dirs or plugin dirs.
982
999
  """
983
1000
  target = args.get("project_path") or args.get("root_dir") or args.get("path") or args.get("directory")
984
- active_ws = get_active_workspace()
1001
+ active_ws = _workspace_root()
985
1002
 
986
1003
  if target:
987
1004
  if not os.path.isabs(target):
@@ -1265,7 +1282,7 @@ def handle_tool_call(name: str, args: dict) -> dict:
1265
1282
  or ("monthly limit (" in text_out and "optimizations paused" in text_out)
1266
1283
  )
1267
1284
  if text_out and path and not is_ranged and not is_quota_truncated:
1268
- active_ws = get_active_workspace()
1285
+ active_ws = _workspace_root()
1269
1286
  if not os.path.isabs(path) and active_ws and os.path.exists(os.path.join(active_ws, path)):
1270
1287
  abs_path = os.path.abspath(os.path.join(active_ws, path))
1271
1288
  else:
@@ -1356,6 +1373,21 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
1356
1373
  elif args.get("package_name") and not (args.get("path") or args.get("file_path") or args.get("file")):
1357
1374
  name = "slice_external_type"
1358
1375
  elif name == "scoped_search":
1376
+ # Schema contract: `path` is "Directory path (default project root)",
1377
+ # while `queries[].path` is a sub-scope. When the caller passes an
1378
+ # absolute directory and no explicit root, promote it to the root.
1379
+ # Without this, batch_search validated the path against the machine-wide
1380
+ # active-workspace marker (which may belong to another repo or a stale
1381
+ # temp dir) and rejected a path that is demonstrably inside the project.
1382
+ _raw_path = args.get("path")
1383
+ if (
1384
+ _raw_path
1385
+ and not (args.get("cwd") or args.get("project_path"))
1386
+ and os.path.isabs(str(_raw_path))
1387
+ and os.path.isdir(str(_raw_path))
1388
+ ):
1389
+ args = dict(args, project_path=str(_raw_path))
1390
+ args.pop("path", None)
1359
1391
  mode = str(args.get("mode") or "").strip().lower()
1360
1392
  if args.get("queries"):
1361
1393
  name = "batch_search"
@@ -1444,7 +1476,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
1444
1476
  if start_line is not None:
1445
1477
  start_line = max(1, start_line)
1446
1478
 
1447
- active_ws = get_active_workspace()
1479
+ active_ws = _workspace_root()
1448
1480
  if path and not os.path.isabs(path):
1449
1481
  if active_ws and os.path.exists(os.path.join(active_ws, path)):
1450
1482
  path = os.path.abspath(os.path.join(active_ws, path))
@@ -1770,7 +1802,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
1770
1802
  inc_deps, _eff_dep_mode = _resolve_dep_mode(args)
1771
1803
  max_tokens = _safe_int(os.environ.get("TOKENSAFE_BUNDLE_MAX_TOKENS"), 6000, lo=1000, hi=50000)
1772
1804
 
1773
- active_ws = get_active_workspace()
1805
+ active_ws = _workspace_root()
1774
1806
  by_file: Dict[str, List[str]] = {}
1775
1807
  for t in targets:
1776
1808
  if not isinstance(t, dict) or not str(t.get("path") or "").strip():
@@ -2283,7 +2315,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
2283
2315
  return _fallback_error("list_dir", "missing required 'path' argument")
2284
2316
 
2285
2317
  # Resolve path relative to active workspace, cwd, or absolute
2286
- active_ws = get_active_workspace()
2318
+ active_ws = _workspace_root()
2287
2319
  if not os.path.isabs(path):
2288
2320
  if active_ws and os.path.isdir(os.path.join(active_ws, path)):
2289
2321
  abs_path = os.path.abspath(os.path.join(active_ws, path))
@@ -2323,7 +2355,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
2323
2355
 
2324
2356
  raw_scope = str(args.get("scope") or "all").strip()
2325
2357
  raw_path = args.get("project_path") or args.get("path") or args.get("root_dir") or args.get("directory")
2326
- active_ws = get_active_workspace()
2358
+ active_ws = _workspace_root()
2327
2359
 
2328
2360
  # 1. Resolve base directory safely without scanning plugin or system roots
2329
2361
  if raw_path:
@@ -2459,7 +2491,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
2459
2491
  pkg = str(args.get("package_name") or args.get("package") or "").strip()
2460
2492
  lock_p = str(args.get("lockfile_path") or args.get("path") or "").strip() or None
2461
2493
  if lock_p and not os.path.isabs(lock_p):
2462
- active_ws = get_active_workspace()
2494
+ active_ws = _workspace_root()
2463
2495
  if active_ws and os.path.exists(os.path.join(active_ws, lock_p)):
2464
2496
  lock_p = os.path.abspath(os.path.join(active_ws, lock_p))
2465
2497
  if not pkg:
@@ -2467,7 +2499,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
2467
2499
  try:
2468
2500
  from src.format_parsers.lockfiles import LockfileReducer
2469
2501
  if not lock_p:
2470
- active_ws = get_active_workspace()
2502
+ active_ws = _workspace_root()
2471
2503
  if active_ws and hasattr(LockfileReducer, "find_lockfile"):
2472
2504
  orig_cwd = os.getcwd()
2473
2505
  try:
@@ -2672,7 +2704,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
2672
2704
  verify = args.get("verify")
2673
2705
  verify_timeout = int(args.get("verify_timeout_sec") or 30)
2674
2706
  raw_cwd = args.get("cwd")
2675
- active_ws = get_active_workspace()
2707
+ active_ws = _workspace_root()
2676
2708
  if raw_cwd:
2677
2709
  if not os.path.isabs(str(raw_cwd)) and active_ws and os.path.isdir(os.path.join(active_ws, str(raw_cwd))):
2678
2710
  cwd = os.path.abspath(os.path.join(active_ws, str(raw_cwd)))
@@ -2792,7 +2824,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
2792
2824
  return _fallback_error("batch_search", "missing required 'queries' list")
2793
2825
 
2794
2826
  raw_cwd = args.get("cwd") or args.get("project_path") or args.get("path")
2795
- active_ws = get_active_workspace()
2827
+ active_ws = _workspace_root()
2796
2828
  if raw_cwd:
2797
2829
  if not os.path.isabs(raw_cwd) and active_ws and os.path.isdir(os.path.join(active_ws, raw_cwd)):
2798
2830
  cwd = os.path.abspath(os.path.join(active_ws, raw_cwd))
@@ -2815,12 +2847,23 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
2815
2847
  sub_p = q_copy.get("path")
2816
2848
  if sub_p:
2817
2849
  sub_abs = os.path.realpath(os.path.normpath(os.path.join(cwd, str(sub_p))))
2850
+ if is_plugin_or_system_dir(sub_abs):
2851
+ return _fallback_error(
2852
+ "batch_search",
2853
+ f"refusing subquery path in a system/plugin dir '{sub_abs}' "
2854
+ f"(project root '{real_cwd}')",
2855
+ )
2818
2856
  try:
2819
2857
  inside = os.path.commonpath([real_cwd, sub_abs]) == real_cwd
2820
2858
  except ValueError:
2821
2859
  inside = False
2822
- if not inside or is_plugin_or_system_dir(sub_abs):
2823
- return _fallback_error("batch_search", f"refusing subquery path outside project root '{sub_p}'")
2860
+ if not inside:
2861
+ return _fallback_error(
2862
+ "batch_search",
2863
+ f"subquery path '{sub_p}' resolves to '{sub_abs}', outside project root "
2864
+ f"'{real_cwd}'. Pass the repo root as project_path and a repo-relative "
2865
+ f"path, or omit path entirely.",
2866
+ )
2824
2867
  if is_quota_exceeded:
2825
2868
  q_copy["max_results"] = min(_safe_int(q_copy.get("max_results"), 3, lo=1, hi=100), 3)
2826
2869
  safe_queries.append(q_copy)
@@ -3173,6 +3216,15 @@ def run_mcp_server():
3173
3216
  "capabilities": {"tools": {}},
3174
3217
  "serverInfo": SERVER_INFO
3175
3218
  }
3219
+ # Routing brief (MCP `instructions`): which stacks this workspace
3220
+ # works through OUMV and which through the TokenSafe tools.
3221
+ try:
3222
+ from src.session_brief import build_workspace_brief
3223
+ brief = build_workspace_brief(os.getcwd(), include_live=False)
3224
+ if brief:
3225
+ response["result"]["instructions"] = brief
3226
+ except Exception:
3227
+ pass
3176
3228
  elif method == "tools/list":
3177
3229
  _TOOLS_LISTED = True
3178
3230
  profile = os.environ.get("TOKENSAFE_MCP_PROFILE", "").strip().lower()
package/src/paths.py CHANGED
@@ -127,12 +127,47 @@ def is_plugin_or_system_dir(path: str) -> bool:
127
127
  return False
128
128
 
129
129
 
130
+ _TRANSIENT_ROOTS = ("/tmp", "/var/tmp", "/private/tmp", "/var/folders", "/private/var/folders")
131
+
132
+
133
+ def is_transient_dir(path: str) -> bool:
134
+ """True for OS scratch space (tempfile/TMPDIR, /tmp, /var/folders).
135
+
136
+ A temp directory is a legitimate workspace for a test process, but it must
137
+ never become the machine-wide active-project marker: every other agent
138
+ session would then validate real repo paths against a directory that is
139
+ about to disappear, and reject them as "outside project root".
140
+ """
141
+ if not path:
142
+ return True
143
+ real = os.path.realpath(os.path.abspath(path))
144
+ roots = [os.path.realpath(p) for p in _TRANSIENT_ROOTS]
145
+ try:
146
+ import tempfile
147
+ roots.append(os.path.realpath(tempfile.gettempdir()))
148
+ except Exception:
149
+ pass
150
+ for root in roots:
151
+ if not root or root == os.sep:
152
+ continue
153
+ if real == root:
154
+ return True
155
+ try:
156
+ if os.path.commonpath([real, root]) == root:
157
+ return True
158
+ except ValueError:
159
+ continue
160
+ return False
161
+
162
+
130
163
  def save_active_workspace(path: str) -> None:
131
164
  """Records the active user workspace directory observed by lifecycle hooks."""
132
165
  if not path or not os.path.isabs(path) or not os.path.isdir(path):
133
166
  return
134
167
  if is_plugin_or_system_dir(path):
135
168
  return
169
+ if is_transient_dir(path):
170
+ return
136
171
  try:
137
172
  import threading
138
173
  data_dir = resolve_data_dir()
@@ -147,7 +182,11 @@ def save_active_workspace(path: str) -> None:
147
182
 
148
183
 
149
184
  def get_active_workspace() -> Optional[str]:
150
- """Retrieves the last known active user workspace directory."""
185
+ """Retrieves the last known active user workspace directory.
186
+
187
+ A marker pointing at scratch space (already-poisoned installs, test
188
+ leftovers) is ignored rather than returned: it is never a usable project
189
+ root for a search or a read."""
151
190
  try:
152
191
  data_dir = resolve_data_dir()
153
192
  marker = os.path.join(data_dir, ".active_workspace")
@@ -155,7 +194,7 @@ def get_active_workspace() -> Optional[str]:
155
194
  with open(marker, "r", encoding="utf-8") as f:
156
195
  path = f.read().strip()
157
196
  if path and os.path.isabs(path) and os.path.isdir(path):
158
- if not is_plugin_or_system_dir(path):
197
+ if not is_plugin_or_system_dir(path) and not is_transient_dir(path):
159
198
  return path
160
199
  except Exception:
161
200
  pass
@@ -205,6 +244,64 @@ def ensure_tokensafe_gitignore(project_root: Optional[str]) -> bool:
205
244
  return updated
206
245
 
207
246
 
247
+ def ensure_local_git_exclude(project_root: Optional[str]) -> bool:
248
+ """Ignores ``.tokensafe/`` WITHOUT editing any tracked file.
249
+
250
+ ``ensure_tokensafe_gitignore`` appends to the project's ``.gitignore``, which
251
+ is a tracked file — a visible diff in the user's repository. For the
252
+ zero-trace injection flow we instead write to ``$GIT_DIR/info/exclude``
253
+ (local-only, never committed) and drop a self-ignoring
254
+ ``.tokensafe/.gitignore`` so the directory stays invisible even if a future
255
+ ``git add -f`` picks it up.
256
+ """
257
+ if not project_root or not os.path.isdir(project_root):
258
+ return False
259
+
260
+ updated = False
261
+ proj_tokensafe = os.path.join(project_root, ".tokensafe")
262
+ if os.path.isdir(proj_tokensafe):
263
+ inner_ignore = os.path.join(proj_tokensafe, ".gitignore")
264
+ if not os.path.isfile(inner_ignore):
265
+ try:
266
+ with open(inner_ignore, "w", encoding="utf-8") as f:
267
+ f.write("# TokenSafe local runtime artifacts & caches\n*\n!.gitignore\n")
268
+ updated = True
269
+ except Exception:
270
+ pass
271
+
272
+ git_dir = os.path.join(project_root, ".git")
273
+ if os.path.isfile(git_dir):
274
+ # Worktrees/submodules: .git is a file pointing at the real git dir.
275
+ try:
276
+ with open(git_dir, "r", encoding="utf-8") as f:
277
+ pointer = f.read().strip()
278
+ if pointer.startswith("gitdir:"):
279
+ git_dir = os.path.abspath(os.path.join(project_root, pointer.split(":", 1)[1].strip()))
280
+ except Exception:
281
+ pass
282
+ elif not os.path.isdir(git_dir):
283
+ return updated
284
+
285
+ exclude_path = os.path.join(git_dir, "info", "exclude")
286
+ try:
287
+ content = ""
288
+ if os.path.isfile(exclude_path):
289
+ with open(exclude_path, "r", encoding="utf-8", errors="replace") as f:
290
+ content = f.read()
291
+ entries = {ln.strip() for ln in content.splitlines()}
292
+ if not ({".tokensafe/", ".tokensafe"} & entries):
293
+ os.makedirs(os.path.dirname(exclude_path), exist_ok=True)
294
+ with open(exclude_path, "a", encoding="utf-8") as f:
295
+ if content and not content.endswith("\n"):
296
+ f.write("\n")
297
+ f.write("# TokenSafe local runtime artifacts (local-only, never committed)\n.tokensafe/\n")
298
+ updated = True
299
+ except Exception:
300
+ pass
301
+
302
+ return updated
303
+
304
+
208
305
  _PROJECT_MARKER_FILES = (
209
306
  "package.json", "pyproject.toml", "setup.py", "setup.cfg", "requirements.txt",
210
307
  "go.mod", "Cargo.toml", "pom.xml", "build.gradle", "build.gradle.kts",