@ictechgy/context-guard 0.4.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 (71) hide show
  1. package/CHANGELOG.md +49 -0
  2. package/LICENSE +201 -0
  3. package/NOTICE +4 -0
  4. package/README.ko.md +353 -0
  5. package/README.md +353 -0
  6. package/context-guard-kit/README.md +76 -0
  7. package/context-guard-kit/benchmark_runner.py +1898 -0
  8. package/context-guard-kit/claude_transcript_cost_audit.py +1591 -0
  9. package/context-guard-kit/context_compress.py +543 -0
  10. package/context-guard-kit/context_escrow.py +919 -0
  11. package/context-guard-kit/context_guard_cli.py +149 -0
  12. package/context-guard-kit/context_guard_diet.py +1036 -0
  13. package/context-guard-kit/context_pack.py +929 -0
  14. package/context-guard-kit/failed_attempt_nudge.py +567 -0
  15. package/context-guard-kit/guard_large_read.py +690 -0
  16. package/context-guard-kit/hook_secret_patterns.py +43 -0
  17. package/context-guard-kit/read_symbol.py +483 -0
  18. package/context-guard-kit/rewrite_bash_for_token_budget.py +501 -0
  19. package/context-guard-kit/sanitize_output.py +725 -0
  20. package/context-guard-kit/settings.example.json +67 -0
  21. package/context-guard-kit/setup_wizard.py +1724 -0
  22. package/context-guard-kit/statusline.sh +362 -0
  23. package/context-guard-kit/statusline_merged.sh +157 -0
  24. package/context-guard-kit/tool_schema_pruner.py +837 -0
  25. package/context-guard-kit/trim_command_output.py +1098 -0
  26. package/docs/distribution.md +55 -0
  27. package/package.json +70 -0
  28. package/packaging/homebrew/context-guard.rb.template +34 -0
  29. package/plugins/context-guard/.claude-plugin/plugin.json +41 -0
  30. package/plugins/context-guard/LICENSE +201 -0
  31. package/plugins/context-guard/NOTICE +4 -0
  32. package/plugins/context-guard/README.ko.md +135 -0
  33. package/plugins/context-guard/README.md +135 -0
  34. package/plugins/context-guard/bin/claude-read-symbol +6 -0
  35. package/plugins/context-guard/bin/claude-sanitize-output +6 -0
  36. package/plugins/context-guard/bin/claude-token-artifact +6 -0
  37. package/plugins/context-guard/bin/claude-token-audit +6 -0
  38. package/plugins/context-guard/bin/claude-token-bench +6 -0
  39. package/plugins/context-guard/bin/claude-token-diet +6 -0
  40. package/plugins/context-guard/bin/claude-token-failed-nudge +6 -0
  41. package/plugins/context-guard/bin/claude-token-guard-read +6 -0
  42. package/plugins/context-guard/bin/claude-token-rewrite-bash +6 -0
  43. package/plugins/context-guard/bin/claude-token-setup +6 -0
  44. package/plugins/context-guard/bin/claude-token-statusline +6 -0
  45. package/plugins/context-guard/bin/claude-token-statusline-merged +6 -0
  46. package/plugins/context-guard/bin/claude-trim-output +6 -0
  47. package/plugins/context-guard/bin/context-guard +149 -0
  48. package/plugins/context-guard/bin/context-guard-artifact +919 -0
  49. package/plugins/context-guard/bin/context-guard-audit +1591 -0
  50. package/plugins/context-guard/bin/context-guard-bench +1898 -0
  51. package/plugins/context-guard/bin/context-guard-compress +543 -0
  52. package/plugins/context-guard/bin/context-guard-diet +1036 -0
  53. package/plugins/context-guard/bin/context-guard-failed-nudge +567 -0
  54. package/plugins/context-guard/bin/context-guard-guard-read +690 -0
  55. package/plugins/context-guard/bin/context-guard-pack +929 -0
  56. package/plugins/context-guard/bin/context-guard-read-symbol +483 -0
  57. package/plugins/context-guard/bin/context-guard-rewrite-bash +501 -0
  58. package/plugins/context-guard/bin/context-guard-sanitize-output +725 -0
  59. package/plugins/context-guard/bin/context-guard-setup +1724 -0
  60. package/plugins/context-guard/bin/context-guard-statusline +362 -0
  61. package/plugins/context-guard/bin/context-guard-statusline-merged +157 -0
  62. package/plugins/context-guard/bin/context-guard-tool-prune +837 -0
  63. package/plugins/context-guard/bin/context-guard-trim-output +1098 -0
  64. package/plugins/context-guard/brief/README.md +65 -0
  65. package/plugins/context-guard/brief/brief-mode.lite.md +29 -0
  66. package/plugins/context-guard/brief/brief-mode.standard.md +31 -0
  67. package/plugins/context-guard/brief/brief-mode.ultra.md +32 -0
  68. package/plugins/context-guard/lib/hook_secret_patterns.py +43 -0
  69. package/plugins/context-guard/skills/audit/SKILL.md +39 -0
  70. package/plugins/context-guard/skills/optimize/SKILL.md +48 -0
  71. package/plugins/context-guard/skills/setup/SKILL.md +40 -0
@@ -0,0 +1,1724 @@
1
+ #!/usr/bin/env python3
2
+ """Interactive project setup for the ContextGuard plugin.
3
+
4
+ The wizard applies only project-local, opt-in settings. It can run interactively
5
+ in a terminal, or non-interactively with --yes/--plan for Claude Code skills and
6
+ CI tests.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import copy
12
+ import datetime as _dt
13
+ import json
14
+ import os
15
+ import re
16
+ import shlex
17
+ import shutil
18
+ import stat
19
+ import subprocess
20
+ import sys
21
+ import uuid
22
+ from dataclasses import dataclass
23
+ from pathlib import Path
24
+ from typing import Any
25
+
26
+ try:
27
+ import fcntl
28
+ except ImportError: # pragma: no cover - setup already requires POSIX no-follow file ops.
29
+ fcntl = None
30
+
31
+ SETTINGS_REL = Path(".claude/settings.json")
32
+
33
+ RECOMMENDED_DENIES = [
34
+ "Read(./node_modules/**)",
35
+ "Read(./dist/**)",
36
+ "Read(./build/**)",
37
+ "Read(./coverage/**)",
38
+ "Read(./logs/**)",
39
+ "Read(./tmp/**)",
40
+ "Read(./target/**)",
41
+ "Read(./.next/**)",
42
+ "Read(./.venv/**)",
43
+ "Read(./vendor/**)",
44
+ "Read(./.context-guard/**)",
45
+ "Read(./.claude-token-optimizer/**)",
46
+ "Read(./.env)",
47
+ "Read(./.env.*)",
48
+ "Read(./.npmrc)",
49
+ "Read(./.pypirc)",
50
+ "Read(./.netrc)",
51
+ "Read(~/.ssh/**)",
52
+ "Read(~/.aws/**)",
53
+ "Read(~/.gnupg/**)",
54
+ "Read(~/.kube/**)",
55
+ "Read(~/.docker/**)",
56
+ ]
57
+ HELPER_STATUSLINE = "context-guard-statusline-merged"
58
+ HELPER_REWRITE_BASH = "context-guard-rewrite-bash"
59
+ HELPER_GUARD_READ = "context-guard-guard-read"
60
+ HELPER_FAILED_NUDGE = "context-guard-failed-nudge"
61
+ HELPER_DIET = "context-guard-diet"
62
+ HELPER_EQUIVALENT_BASENAMES = {
63
+ "context-guard-rewrite-bash": {
64
+ "context-guard-rewrite-bash",
65
+ "claude-token-rewrite-bash",
66
+ "rewrite_bash_for_token_budget.py",
67
+ },
68
+ "context-guard-guard-read": {
69
+ "context-guard-guard-read",
70
+ "claude-token-guard-read",
71
+ "guard_large_read.py",
72
+ },
73
+ "context-guard-failed-nudge": {
74
+ "context-guard-failed-nudge",
75
+ "claude-token-failed-nudge",
76
+ "failed_attempt_nudge.py",
77
+ },
78
+ "context-guard-statusline-merged": {
79
+ "context-guard-statusline-merged",
80
+ "claude-token-statusline-merged",
81
+ "statusline_merged.sh",
82
+ },
83
+ "context-guard-statusline": {
84
+ "context-guard-statusline",
85
+ "claude-token-statusline",
86
+ "statusline.sh",
87
+ },
88
+ }
89
+ DEFAULT_MODEL = "sonnet"
90
+ DEFAULT_EFFORT = "medium"
91
+ DEFAULT_FAILED_ATTEMPT_NUDGE = True
92
+ DEFAULT_POST_SETUP_SCAN_TOP = 5
93
+ POST_SETUP_SCAN_TIMEOUT_SECONDS = 20
94
+ PRIVATE_DIR_MODE = stat.S_IRWXU
95
+ ALLOWED_FIRST_ABSOLUTE_SYMLINKS = {
96
+ "tmp": Path("/private/tmp"),
97
+ "var": Path("/private/var"),
98
+ }
99
+
100
+
101
+ @dataclass
102
+ class Choices:
103
+ denies: bool = True
104
+ statusline: bool = True
105
+ bash_hook: bool = True
106
+ read_guard: bool = True
107
+ model_defaults: bool = True
108
+ # 동일 Bash 명령이 두 번 연속 실패하면 /clear 권유 — recommended setup 기본 ON.
109
+ failed_attempt_nudge: bool = DEFAULT_FAILED_ATTEMPT_NUDGE
110
+
111
+
112
+ @dataclass
113
+ class SetupResult:
114
+ root: Path
115
+ settings_path: Path
116
+ scope: str
117
+ changed: bool
118
+ applied: bool
119
+ apply_requested: bool
120
+ choices: Choices
121
+ actions: list[str]
122
+ backup_path: Path | None = None
123
+ rollback_id: str | None = None
124
+ rollback_path: Path | None = None
125
+ warnings: list[str] | None = None
126
+ diet_scan: dict[str, Any] | None = None
127
+ # Per-agent cross-agent plan; None preserves the legacy Claude-only payload
128
+ # shape for callers that never engage the adapter registry.
129
+ adapter_plan: list[dict[str, Any]] | None = None
130
+
131
+ def as_dict(self) -> dict[str, Any]:
132
+ return {
133
+ "root": str(self.root),
134
+ "settings_path": str(self.settings_path),
135
+ "scope": self.scope,
136
+ "changed": self.changed,
137
+ "applied": self.applied,
138
+ "apply_requested": self.apply_requested,
139
+ "backup_path": str(self.backup_path) if self.backup_path else None,
140
+ "rollback_id": self.rollback_id,
141
+ "rollback_path": str(self.rollback_path) if self.rollback_path else None,
142
+ "warnings": self.warnings or [],
143
+ "choices": self.choices.__dict__,
144
+ "actions": self.actions,
145
+ "diet_scan": self.diet_scan,
146
+ "adapter_plan": self.adapter_plan,
147
+ }
148
+
149
+
150
+ # --- Cross-agent adapter registry & dry-run setup planner --------------------
151
+ #
152
+ # ContextGuard's helpers speak plain JSON over stdin/stdout, so the same
153
+ # guardrails can be wired into more than just Claude Code. This registry maps
154
+ # known coding agents to a *capability class* that describes HOW ContextGuard
155
+ # can integrate with each one, and the planner renders a per-agent setup plan.
156
+ #
157
+ # The planner stays conservative and Claude-compatible:
158
+ # - Only the Claude native-plugin path writes hook settings (the legacy default).
159
+ # - Repo-rule agents get an idempotent advisory rule block, opt-in via --with-init.
160
+ # - native-skill / report-only agents are never written to; they are reported.
161
+ # It never sends work to external providers and never promises token/cost savings.
162
+
163
+ ADAPTER_RULE_BLOCK_BEGIN = "<!-- contextguard:begin -->"
164
+ ADAPTER_RULE_BLOCK_END = "<!-- contextguard:end -->"
165
+ CODEX_SKILL_REL = ".agents/skills/context-guard/SKILL.md"
166
+ CODEX_SKILL_MARKER_BEGIN = "<!-- contextguard:codex-skill:begin -->"
167
+ CODEX_SKILL_MARKER_END = "<!-- contextguard:codex-skill:end -->"
168
+
169
+
170
+ class CapabilityClass:
171
+ """How ContextGuard can integrate with a given agent."""
172
+
173
+ NATIVE_PLUGIN = "native-plugin" # writes native hook settings (Claude Code)
174
+ NATIVE_SKILL = "native-skill" # invokable skills/commands; no auto-written hooks
175
+ REPO_RULE = "repo-rule" # reads a repo rule file (AGENTS.md, GEMINI.md, ...)
176
+ REPORT_ONLY = "report-only" # no integration surface; advisory reporting only
177
+
178
+
179
+ @dataclass(frozen=True)
180
+ class AgentAdapter:
181
+ """One known coding agent and how ContextGuard wires into it."""
182
+
183
+ key: str
184
+ display_name: str
185
+ capability: str
186
+ summary: str
187
+ settings_rel: str | None = None
188
+ rule_file: str | None = None
189
+ project_skill_rel: str | None = None
190
+ detect: tuple[str, ...] = ()
191
+
192
+
193
+ AGENT_ADAPTERS: tuple[AgentAdapter, ...] = (
194
+ AgentAdapter(
195
+ key="claude",
196
+ display_name="Claude Code",
197
+ capability=CapabilityClass.NATIVE_PLUGIN,
198
+ summary="Installs project-local hooks, denies, and statusline in .claude/settings.json.",
199
+ settings_rel=str(SETTINGS_REL),
200
+ rule_file="CLAUDE.md",
201
+ detect=(".claude",),
202
+ ),
203
+ AgentAdapter(
204
+ key="codex",
205
+ display_name="OpenAI Codex CLI",
206
+ capability=CapabilityClass.REPO_RULE,
207
+ summary="Reads AGENTS.md; add an advisory ContextGuard rule block with --with-init and optional project skill with --with-skill.",
208
+ rule_file="AGENTS.md",
209
+ project_skill_rel=CODEX_SKILL_REL,
210
+ detect=("AGENTS.md", ".codex"),
211
+ ),
212
+ AgentAdapter(
213
+ key="gemini",
214
+ display_name="Gemini CLI",
215
+ capability=CapabilityClass.REPO_RULE,
216
+ summary="Reads GEMINI.md; add an advisory ContextGuard rule block with --with-init.",
217
+ rule_file="GEMINI.md",
218
+ detect=("GEMINI.md", ".gemini"),
219
+ ),
220
+ AgentAdapter(
221
+ key="cursor",
222
+ display_name="Cursor",
223
+ capability=CapabilityClass.REPO_RULE,
224
+ summary="Reads project rules; add an advisory ContextGuard block with --with-init.",
225
+ rule_file=".cursorrules",
226
+ detect=(".cursor", ".cursorrules"),
227
+ ),
228
+ AgentAdapter(
229
+ key="windsurf",
230
+ display_name="Windsurf",
231
+ capability=CapabilityClass.REPO_RULE,
232
+ summary="Reads project rules; add an advisory ContextGuard block with --with-init.",
233
+ rule_file=".windsurf/rules/contextguard.md",
234
+ detect=(".windsurf", ".windsurfrules"),
235
+ ),
236
+ AgentAdapter(
237
+ key="cline",
238
+ display_name="Cline",
239
+ capability=CapabilityClass.REPO_RULE,
240
+ summary="Reads project rules; add an advisory ContextGuard block with --with-init.",
241
+ rule_file=".clinerules",
242
+ detect=(".clinerules", ".cline"),
243
+ ),
244
+ AgentAdapter(
245
+ key="copilot",
246
+ display_name="GitHub Copilot Coding Agent",
247
+ capability=CapabilityClass.REPO_RULE,
248
+ summary="Reads repository instructions; add an advisory ContextGuard block with --with-init.",
249
+ rule_file=".github/copilot-instructions.md",
250
+ detect=(".github/copilot-instructions.md",),
251
+ ),
252
+ AgentAdapter(
253
+ key="opencode",
254
+ display_name="OpenCode",
255
+ capability=CapabilityClass.NATIVE_SKILL,
256
+ summary="Expose ContextGuard helpers as OpenCode commands/rules manually; no hooks are auto-written.",
257
+ detect=("opencode.json", ".opencode"),
258
+ ),
259
+ AgentAdapter(
260
+ key="forgecode",
261
+ display_name="ForgeCode",
262
+ capability=CapabilityClass.REPORT_ONLY,
263
+ summary="No automated setup surface yet; run ContextGuard helpers from the shell and keep evidence local.",
264
+ detect=(".forgecode", "forgecode.json"),
265
+ ),
266
+ AgentAdapter(
267
+ key="generic",
268
+ display_name="Other / unknown agent",
269
+ capability=CapabilityClass.REPORT_ONLY,
270
+ summary="No automated setup surface; run ContextGuard helpers from the shell as needed.",
271
+ ),
272
+ )
273
+
274
+
275
+ def adapter_registry() -> dict[str, AgentAdapter]:
276
+ """Return the adapter registry keyed by adapter key."""
277
+ return {adapter.key: adapter for adapter in AGENT_ADAPTERS}
278
+
279
+
280
+ def adapter_registry_payload() -> list[dict[str, Any]]:
281
+ """JSON-friendly view of the adapter registry for --list-adapters."""
282
+ return [
283
+ {
284
+ "key": adapter.key,
285
+ "display_name": adapter.display_name,
286
+ "capability": adapter.capability,
287
+ "summary": adapter.summary,
288
+ "settings_rel": adapter.settings_rel,
289
+ "rule_file": adapter.rule_file,
290
+ "project_skill_rel": adapter.project_skill_rel,
291
+ "detect": list(adapter.detect),
292
+ }
293
+ for adapter in AGENT_ADAPTERS
294
+ ]
295
+
296
+
297
+ def detect_agents(root: Path) -> list[str]:
298
+ """Return adapter keys whose detection markers exist under root."""
299
+ found: list[str] = []
300
+ for adapter in AGENT_ADAPTERS:
301
+ for rel in adapter.detect:
302
+ if (root / rel).exists():
303
+ found.append(adapter.key)
304
+ break
305
+ return found
306
+
307
+
308
+ def resolve_target_adapters(root: Path, only: list[str] | None) -> list[AgentAdapter]:
309
+ """Pick the adapters to plan/apply.
310
+
311
+ Default keeps Claude compatibility: Claude is always targeted, plus any other
312
+ agent detected in the repo. ``--only`` restricts to an explicit, validated set
313
+ so a user can, for example, set up only Codex without touching Claude.
314
+ """
315
+ registry = adapter_registry()
316
+ if only:
317
+ keys: list[str] = []
318
+ for raw in only:
319
+ for part in str(raw).split(","):
320
+ key = part.strip().lower()
321
+ if not key:
322
+ continue
323
+ if key not in registry:
324
+ known = ", ".join(sorted(registry))
325
+ raise SystemExit(f"Unknown adapter key: {key!r}. Known adapters: {known}.")
326
+ if key not in keys:
327
+ keys.append(key)
328
+ return [registry[key] for key in keys]
329
+ detected = set(detect_agents(root))
330
+ keys = ["claude"] + [
331
+ adapter.key
332
+ for adapter in AGENT_ADAPTERS
333
+ if adapter.key not in ("claude", "generic") and adapter.key in detected
334
+ ]
335
+ return [registry[key] for key in keys]
336
+
337
+
338
+ def render_repo_rule_block() -> str:
339
+ """Advisory rule block written into repo-rule files. No savings guarantees."""
340
+ return "\n".join([
341
+ ADAPTER_RULE_BLOCK_BEGIN,
342
+ "## ContextGuard (advisory)",
343
+ "",
344
+ "This repository uses ContextGuard helpers to keep agent context focused.",
345
+ "These guardrails are advisory and do not guarantee any token or cost savings.",
346
+ "",
347
+ "- Prefer reading symbols over whole large files.",
348
+ "- Store large logs as local artifacts and query only the parts you need.",
349
+ "- Trim or summarize noisy command output instead of pasting it whole.",
350
+ "- Treat reported byte reductions as proxy evidence, not proof of savings.",
351
+ "- Keep provider caches and semantic caches opt-in; verify cache hits before claiming savings.",
352
+ "",
353
+ "See the ContextGuard README for the helper commands.",
354
+ ADAPTER_RULE_BLOCK_END,
355
+ ])
356
+
357
+
358
+ def render_codex_skill() -> str:
359
+ """Render the optional project-local Codex skill for ContextGuard."""
360
+ return "\n".join([
361
+ "---",
362
+ "name: context-guard",
363
+ "description: Use ContextGuard helpers to keep Codex context focused with local-first setup, audit, trimming, and artifact commands.",
364
+ "---",
365
+ "",
366
+ CODEX_SKILL_MARKER_BEGIN,
367
+ "# ContextGuard for Codex",
368
+ "",
369
+ "Use this skill when a task would otherwise paste large files, long logs, or repeated setup context into Codex.",
370
+ "",
371
+ "## Progressive disclosure",
372
+ "- Prefer `context-guard audit . --json` or `context-guard diet scan . --json` before broad repo reads.",
373
+ "- Use `context-guard pack` for a small, prioritized local context pack.",
374
+ "- Use `context-guard artifact` for large logs, then query only the relevant slices.",
375
+ "- Use `context-guard trim-output` or `context-guard sanitize-output` before sharing noisy command output.",
376
+ "",
377
+ "## Setup",
378
+ "- Project activation: `context-guard setup --agent codex --scope project --with-init --with-skill --yes`.",
379
+ "- Plan first: `context-guard setup --agent codex --scope project --with-init --with-skill --plan`.",
380
+ "- If `context-guard` is not on PATH, install it explicitly or run via `npx @ictechgy/context-guard`.",
381
+ "",
382
+ "Do not claim fixed token or cost savings from these helpers; treat byte reductions as local proxy evidence only.",
383
+ CODEX_SKILL_MARKER_END,
384
+ "",
385
+ ])
386
+
387
+
388
+ def _read_rule_file_text(path: Path) -> str | None:
389
+ """Best-effort no-follow read; only a missing file is treated as absent.
390
+
391
+ Unreadable, symlinked, directory, or otherwise unsafe targets must not be
392
+ collapsed into "missing"; doing so could overwrite user-owned instruction
393
+ files. Callers that want a non-throwing view should use
394
+ ``_rule_file_state`` and skip unsafe targets explicitly.
395
+ """
396
+ try:
397
+ return _read_text_no_follow(path)
398
+ except FileNotFoundError:
399
+ return None
400
+
401
+
402
+ def _rule_file_state(path: Path) -> dict[str, Any]:
403
+ """Return a non-throwing state for project rule/skill files."""
404
+ try:
405
+ st = os.lstat(path)
406
+ except FileNotFoundError:
407
+ return {"status": "missing", "text": None, "reason": None}
408
+ except OSError as exc:
409
+ return {"status": "unsafe", "text": None, "reason": f"could not inspect rule file: {exc.__class__.__name__}"}
410
+ if stat.S_ISLNK(st.st_mode):
411
+ return {"status": "unsafe", "text": None, "reason": f"refused to read symlinked rule file: {path.name}"}
412
+ if stat.S_ISDIR(st.st_mode):
413
+ return {"status": "directory", "text": None, "reason": f"refused to replace directory rule target: {path.name}"}
414
+ try:
415
+ text = _read_text_no_follow(path)
416
+ except OSError as exc:
417
+ return {
418
+ "status": "unsafe",
419
+ "text": None,
420
+ "reason": f"could not read rule file without following symlinks: {exc.__class__.__name__}",
421
+ }
422
+ return {"status": "file", "text": text, "reason": None}
423
+
424
+
425
+ def repo_rule_block_present(path: Path) -> bool:
426
+ """True when the advisory ContextGuard block already exists in the rule file."""
427
+ state = _rule_file_state(path)
428
+ return state["status"] == "file" and ADAPTER_RULE_BLOCK_BEGIN in str(state.get("text") or "")
429
+
430
+
431
+ def write_repo_rule_init(path: Path) -> dict[str, Any]:
432
+ """Idempotently append the advisory ContextGuard block to a repo rule file.
433
+
434
+ Returns a status dict: ``applied`` (block written), ``exists`` (already
435
+ present), or ``skipped`` (refused, e.g. symlinked target) with a reason.
436
+ """
437
+ state = _rule_file_state(path)
438
+ if state["status"] not in {"missing", "file"}:
439
+ return {"status": "skipped", "reason": state.get("reason") or f"refused unsafe rule target: {path.name}"}
440
+ existing = state.get("text")
441
+ if existing is not None and ADAPTER_RULE_BLOCK_BEGIN in existing:
442
+ return {"status": "exists"}
443
+ block = render_repo_rule_block()
444
+ if existing:
445
+ new_text = existing.rstrip("\n") + "\n\n" + block + "\n"
446
+ mode = existing_mode_or_default(path, 0o644)
447
+ else:
448
+ new_text = block + "\n"
449
+ mode = 0o644
450
+ try:
451
+ atomic_write(path, new_text, mode, dir_mode=0o755)
452
+ except OSError as exc:
453
+ return {"status": "skipped", "reason": f"could not write repo rule file {path.name}: {exc.__class__.__name__}"}
454
+ return {"status": "applied"}
455
+
456
+
457
+ def codex_skill_status(path: Path) -> str:
458
+ state = _rule_file_state(path)
459
+ if state["status"] == "missing":
460
+ return "missing"
461
+ if state["status"] != "file":
462
+ return "unsafe"
463
+ text = str(state.get("text") or "")
464
+ if text == render_codex_skill():
465
+ return "exists"
466
+ if CODEX_SKILL_MARKER_BEGIN in text and CODEX_SKILL_MARKER_END in text:
467
+ return "update-needed"
468
+ return "foreign"
469
+
470
+
471
+ def write_codex_project_skill(path: Path) -> dict[str, Any]:
472
+ """Idempotently create/update the project-local Codex ContextGuard skill."""
473
+ state = _rule_file_state(path)
474
+ if state["status"] not in {"missing", "file"}:
475
+ return {"status": "skipped", "reason": state.get("reason") or f"refused unsafe skill target: {path.name}"}
476
+ status = codex_skill_status(path)
477
+ if status == "exists":
478
+ return {"status": "exists"}
479
+ if status == "foreign":
480
+ return {
481
+ "status": "skipped",
482
+ "reason": f"refused to overwrite non-ContextGuard Codex skill file: {path}",
483
+ }
484
+ try:
485
+ atomic_write(path, render_codex_skill(), 0o644, dir_mode=0o755)
486
+ except OSError as exc:
487
+ return {"status": "skipped", "reason": f"could not write Codex skill file {path}: {exc.__class__.__name__}"}
488
+ return {"status": "updated" if status == "update-needed" else "applied"}
489
+
490
+
491
+ def adapter_rule_path(root: Path, adapter: AgentAdapter) -> Path | None:
492
+ """Resolve a repo-rule adapter's write target.
493
+
494
+ Most adapters have a stable file target. Cline is deliberately flexible:
495
+ existing projects commonly use `.clinerules` as a file, while some may use a
496
+ directory-style rules surface. Pick a file when `.clinerules` is absent or a
497
+ file; use a nested advisory file only when `.clinerules` already exists as a
498
+ real directory. This avoids crashing or replacing a user-owned file-form rule.
499
+ """
500
+ if adapter.rule_file is None:
501
+ return None
502
+ if adapter.key == "cline":
503
+ base = root / ".clinerules"
504
+ if base.exists() and base.is_dir() and not base.is_symlink():
505
+ return base / "contextguard.md"
506
+ return base
507
+ return root / adapter.rule_file
508
+
509
+
510
+ def build_adapter_plan(
511
+ root: Path,
512
+ targets: list[AgentAdapter],
513
+ *,
514
+ scope: str,
515
+ claude_actions: list[str],
516
+ claude_changed: bool,
517
+ claude_applied: bool,
518
+ with_init: bool,
519
+ with_skill: bool,
520
+ applied: bool,
521
+ ) -> list[dict[str, Any]]:
522
+ """Render a per-adapter plan, performing safe repo-rule writes when applied.
523
+
524
+ Only repo-rule adapters write, and only when both ``with_init`` and ``applied``
525
+ are set. Native-plugin entries mirror the Claude settings result; native-skill
526
+ and report-only entries are advisory and never write.
527
+ """
528
+ detected = set(detect_agents(root))
529
+ plan: list[dict[str, Any]] = []
530
+ for adapter in targets:
531
+ entry: dict[str, Any] = {
532
+ "key": adapter.key,
533
+ "display_name": adapter.display_name,
534
+ "capability": adapter.capability,
535
+ "scope": scope,
536
+ "detected": adapter.key in detected,
537
+ "summary": adapter.summary,
538
+ "writable": False,
539
+ "status": "report-only",
540
+ "planned_actions": [],
541
+ "applied_actions": [],
542
+ "unsupported_reason": None,
543
+ }
544
+ if scope == "user" and adapter.key != "claude":
545
+ entry["status"] = "unsupported"
546
+ entry["writable"] = False
547
+ entry["unsupported_reason"] = (
548
+ f"user-scope activation for {adapter.display_name} is not implemented/verified yet; "
549
+ "use --scope project or run the helper commands manually."
550
+ )
551
+ entry["planned_actions"] = [entry["unsupported_reason"]]
552
+ plan.append(entry)
553
+ continue
554
+ if adapter.capability == CapabilityClass.NATIVE_PLUGIN:
555
+ entry["writable"] = True
556
+ if adapter.settings_rel:
557
+ entry["settings_path"] = str(root / adapter.settings_rel)
558
+ entry["planned_actions"] = list(claude_actions)
559
+ if claude_applied and claude_changed:
560
+ entry["status"] = "applied"
561
+ elif claude_changed:
562
+ entry["status"] = "planned"
563
+ else:
564
+ entry["status"] = "unchanged"
565
+ elif adapter.capability == CapabilityClass.REPO_RULE:
566
+ entry["writable"] = True
567
+ rule_path = adapter_rule_path(root, adapter)
568
+ entry["rule_file"] = str(rule_path.relative_to(root)) if rule_path else adapter.rule_file
569
+ if rule_path is not None and repo_rule_block_present(rule_path):
570
+ entry["status"] = "exists"
571
+ entry["planned_actions"] = [f"advisory ContextGuard rules already present in {entry['rule_file']}"]
572
+ elif not with_init:
573
+ entry["status"] = "planned"
574
+ entry["planned_actions"] = [f"run with --with-init to add advisory ContextGuard rules to {entry['rule_file']}"]
575
+ elif not applied:
576
+ entry["status"] = "planned"
577
+ entry["planned_actions"] = [f"would add advisory ContextGuard rules to {entry['rule_file']}"]
578
+ elif rule_path is not None:
579
+ result = write_repo_rule_init(rule_path)
580
+ entry["status"] = result["status"]
581
+ if result["status"] == "applied":
582
+ entry["applied_actions"] = [f"wrote advisory ContextGuard rules to {entry['rule_file']}"]
583
+ entry["planned_actions"] = list(entry["applied_actions"])
584
+ elif result["status"] == "exists":
585
+ entry["planned_actions"] = [f"advisory ContextGuard rules already present in {entry['rule_file']}"]
586
+ else:
587
+ entry["planned_actions"] = [result.get("reason", "skipped")]
588
+ if adapter.key == "codex" and adapter.project_skill_rel:
589
+ skill_path = root / adapter.project_skill_rel
590
+ entry["project_skill_file"] = adapter.project_skill_rel
591
+ skill_state = codex_skill_status(skill_path)
592
+ entry["project_skill_status"] = skill_state
593
+ if skill_state == "exists":
594
+ entry["planned_actions"].append(
595
+ f"project Codex skill already present in {adapter.project_skill_rel}"
596
+ )
597
+ elif skill_state == "unsafe":
598
+ entry["planned_actions"].append(
599
+ f"refused unsafe project Codex skill target at {adapter.project_skill_rel}"
600
+ )
601
+ elif not with_skill:
602
+ entry["planned_actions"].append(
603
+ f"run with --with-skill to generate project Codex skill at {adapter.project_skill_rel}"
604
+ )
605
+ elif not applied:
606
+ entry["planned_actions"].append(
607
+ f"would generate project Codex skill at {adapter.project_skill_rel}"
608
+ )
609
+ else:
610
+ skill_result = write_codex_project_skill(skill_path)
611
+ entry["project_skill_status"] = skill_result["status"]
612
+ if skill_result["status"] in {"applied", "updated"}:
613
+ action = f"wrote project Codex skill to {adapter.project_skill_rel}"
614
+ entry["applied_actions"].append(action)
615
+ entry["planned_actions"].append(action)
616
+ if entry["status"] in {"planned", "exists", "unchanged"}:
617
+ entry["status"] = "applied"
618
+ elif skill_result["status"] == "exists":
619
+ entry["planned_actions"].append(
620
+ f"project Codex skill already present in {adapter.project_skill_rel}"
621
+ )
622
+ else:
623
+ entry["planned_actions"].append(skill_result.get("reason", "skipped"))
624
+ elif adapter.capability == CapabilityClass.NATIVE_SKILL:
625
+ entry["planned_actions"] = [adapter.summary]
626
+ else: # REPORT_ONLY
627
+ entry["planned_actions"] = [adapter.summary]
628
+ plan.append(entry)
629
+ return plan
630
+
631
+
632
+ class AtomicWriteDurabilityError(OSError):
633
+ """Raised after rename when the new file exists but directory durability is uncertain."""
634
+
635
+
636
+ def find_project_root(start: Path | None = None) -> Path:
637
+ current = (start or Path.cwd()).expanduser().resolve()
638
+ if current.is_file():
639
+ current = current.parent
640
+ for candidate in [current, *current.parents]:
641
+ if (candidate / ".git").exists():
642
+ return candidate
643
+ return current
644
+
645
+
646
+ def resolve_setup_root(raw_root: str | None) -> Path:
647
+ if raw_root is None:
648
+ return find_project_root()
649
+ root = Path(raw_root).expanduser().resolve()
650
+ if not root.exists():
651
+ raise SystemExit(f"Project root does not exist: {root}")
652
+ return root.parent if root.is_file() else root
653
+
654
+
655
+ def normalize_scope(raw_scope: str | None) -> str:
656
+ scope = str(raw_scope or "project").strip().lower()
657
+ if scope == "global":
658
+ return "user"
659
+ if scope not in {"project", "user"}:
660
+ raise SystemExit("Unknown setup scope: {!r}. Known scopes: project, user.".format(raw_scope))
661
+ return scope
662
+
663
+
664
+ def resolve_scope_root(raw_root: str | None, scope: str) -> Path:
665
+ if scope == "project":
666
+ return resolve_setup_root(raw_root)
667
+ home = Path.home().expanduser().resolve()
668
+ if home == Path(home.anchor or "/"):
669
+ raise SystemExit("Refusing user-scope setup because HOME resolves to a filesystem root.")
670
+ if not home.exists() or not home.is_dir():
671
+ raise SystemExit(f"Refusing user-scope setup because HOME is not a directory: {home}")
672
+ return home
673
+
674
+
675
+ def explicit_agent_selection(args: argparse.Namespace) -> list[str] | None:
676
+ values: list[str] = []
677
+ for attr in ("agent", "only"):
678
+ raw_values = getattr(args, attr, None)
679
+ if not raw_values:
680
+ continue
681
+ for raw in raw_values:
682
+ for part in str(raw).split(","):
683
+ key = part.strip()
684
+ if key:
685
+ values.append(key)
686
+ return values or None
687
+
688
+
689
+ def validate_settings_target(root: Path, settings_path: Path, *, allow_home_settings: bool) -> None:
690
+ root = root.resolve()
691
+ home_settings = Path.home().expanduser().resolve() / SETTINGS_REL
692
+ if settings_path.expanduser().resolve() == home_settings and not allow_home_settings:
693
+ raise SystemExit(
694
+ "Refusing to modify global ~/.claude/settings.json. Run from a project directory, "
695
+ "pass --root <project>, or use --allow-home-settings if you intentionally want this."
696
+ )
697
+ claude_dir = root / ".claude"
698
+ if claude_dir.exists() and claude_dir.is_symlink():
699
+ raise SystemExit(f"Refusing to use symlinked Claude settings directory: {claude_dir}")
700
+ if settings_path.exists() and settings_path.is_symlink():
701
+ raise SystemExit(f"Refusing to write through symlinked settings file: {settings_path}")
702
+ if claude_dir.exists():
703
+ try:
704
+ claude_dir.resolve().relative_to(root)
705
+ except ValueError as exc:
706
+ raise SystemExit(f"Claude settings directory resolves outside project root: {claude_dir}") from exc
707
+
708
+
709
+ def _base_open_flags() -> int:
710
+ flags = os.O_RDONLY
711
+ if hasattr(os, "O_CLOEXEC"):
712
+ flags |= os.O_CLOEXEC
713
+ return flags
714
+
715
+
716
+ def _no_follow_flag() -> int:
717
+ if hasattr(os, "O_NOFOLLOW"):
718
+ return os.O_NOFOLLOW
719
+ raise OSError("platform does not support no-follow file opens")
720
+
721
+
722
+ def no_follow_file_ops_supported() -> bool:
723
+ return (
724
+ hasattr(os, "O_NOFOLLOW")
725
+ and os.open in os.supports_dir_fd
726
+ and os.mkdir in os.supports_dir_fd
727
+ and os.rename in os.supports_dir_fd
728
+ and os.unlink in os.supports_dir_fd
729
+ )
730
+
731
+
732
+ def require_no_follow_file_ops_supported() -> None:
733
+ if not no_follow_file_ops_supported() or fcntl is None:
734
+ raise SystemExit(
735
+ "Setup requires POSIX no-follow file operations for safe project-local settings writes; "
736
+ "this platform is not supported yet."
737
+ )
738
+
739
+
740
+ def _directory_flag() -> int:
741
+ return getattr(os, "O_DIRECTORY", 0)
742
+
743
+
744
+ def _normalized_link_target(parent: Path, raw_target: str) -> Path:
745
+ target = Path(raw_target)
746
+ if not target.is_absolute():
747
+ target = parent / target
748
+ return Path(os.path.normpath(str(target)))
749
+
750
+
751
+ def _normalize_allowed_first_absolute_symlink(path: Path) -> Path:
752
+ """Rewrite narrow platform-owned absolute aliases before no-follow traversal."""
753
+ if not path.is_absolute() or len(path.parts) < 2:
754
+ return path
755
+ first = path.parts[1]
756
+ expected = ALLOWED_FIRST_ABSOLUTE_SYMLINKS.get(first)
757
+ if expected is None:
758
+ return path
759
+ link = Path(path.anchor) / first
760
+ try:
761
+ if not stat.S_ISLNK(os.lstat(link).st_mode):
762
+ return path
763
+ if _normalized_link_target(Path(path.anchor), os.readlink(link)) != expected:
764
+ return path
765
+ except OSError:
766
+ return path
767
+ return expected.joinpath(*path.parts[2:])
768
+
769
+
770
+ def _open_directory_at(dir_fd: int, component: str, path: Path) -> int:
771
+ flags = _base_open_flags() | _directory_flag() | _no_follow_flag()
772
+ fd = os.open(component, flags, dir_fd=dir_fd)
773
+ try:
774
+ if not stat.S_ISDIR(os.fstat(fd).st_mode):
775
+ raise OSError(f"not a directory: {path}")
776
+ return fd
777
+ except Exception:
778
+ os.close(fd)
779
+ raise
780
+
781
+
782
+ def _mkdir_directory_entry_at(dir_fd: int, component: str, mode: int) -> None:
783
+ # mkdir modes are still filtered through umask. Run only the mkdir in an
784
+ # isolated child process with umask 0 so the parent process umask never
785
+ # changes, then the parent immediately reopens with O_NOFOLLOW.
786
+ helper = (
787
+ "import os, sys\n"
788
+ "dir_fd = int(sys.argv[1])\n"
789
+ "component = sys.argv[2]\n"
790
+ "mode = int(sys.argv[3], 8)\n"
791
+ "os.umask(0)\n"
792
+ "os.mkdir(component, mode, dir_fd=dir_fd)\n"
793
+ )
794
+ proc = subprocess.run(
795
+ [sys.executable, "-I", "-c", helper, str(dir_fd), component, oct(mode)],
796
+ text=True,
797
+ capture_output=True,
798
+ pass_fds=(dir_fd,),
799
+ )
800
+ if proc.returncode != 0:
801
+ detail = (proc.stderr or proc.stdout).strip().splitlines()[-1:] or [f"exit {proc.returncode}"]
802
+ raise OSError(f"could not create directory component safely: {component}: {detail[0]}")
803
+
804
+
805
+ def _open_regular_no_symlink(path: Path) -> int:
806
+ if os.open not in os.supports_dir_fd:
807
+ raise OSError("platform does not support directory-relative no-follow opens")
808
+ path = _normalize_allowed_first_absolute_symlink(path)
809
+ components = list(path.parts)
810
+ if path.is_absolute() and components:
811
+ components = components[1:]
812
+ if not components:
813
+ raise OSError(f"not a regular file: {path}")
814
+
815
+ root = path.anchor if path.is_absolute() else "."
816
+ dir_fd = os.open(root or ".", _base_open_flags() | _directory_flag())
817
+ try:
818
+ for component in components[:-1]:
819
+ next_fd = _open_directory_at(dir_fd, component, path)
820
+ os.close(dir_fd)
821
+ dir_fd = next_fd
822
+
823
+ fd = os.open(components[-1], _base_open_flags() | _no_follow_flag(), dir_fd=dir_fd)
824
+ try:
825
+ if not stat.S_ISREG(os.fstat(fd).st_mode):
826
+ raise OSError(f"not a regular file: {path}")
827
+ return fd
828
+ except Exception:
829
+ os.close(fd)
830
+ raise
831
+ finally:
832
+ os.close(dir_fd)
833
+
834
+
835
+ def _ensure_directory_no_symlink(path: Path, mode: int | None = None, *, parents_mode: int | None = None) -> int:
836
+ if os.mkdir not in os.supports_dir_fd:
837
+ raise OSError("platform does not support directory-relative directory creation")
838
+ path = _normalize_allowed_first_absolute_symlink(path)
839
+ components = list(path.parts)
840
+ if path.is_absolute() and components:
841
+ components = components[1:]
842
+ root = path.anchor if path.is_absolute() else "."
843
+ dir_fd = os.open(root or ".", _base_open_flags() | _directory_flag())
844
+ try:
845
+ for index, component in enumerate(components):
846
+ created = False
847
+ mkdir_mode = (
848
+ mode
849
+ if mode is not None and index == len(components) - 1
850
+ else (parents_mode if parents_mode is not None else PRIVATE_DIR_MODE)
851
+ )
852
+ try:
853
+ next_fd = _open_directory_at(dir_fd, component, path)
854
+ except FileNotFoundError:
855
+ _mkdir_directory_entry_at(dir_fd, component, mkdir_mode)
856
+ next_fd = _open_directory_at(dir_fd, component, path)
857
+ created = True
858
+ if created and hasattr(os, "fchmod"):
859
+ os.fchmod(next_fd, mkdir_mode)
860
+ os.close(dir_fd)
861
+ dir_fd = next_fd
862
+ return dir_fd
863
+ except Exception:
864
+ os.close(dir_fd)
865
+ raise
866
+
867
+
868
+ def _read_text_no_follow(path: Path) -> str:
869
+ fd = _open_regular_no_symlink(path)
870
+ try:
871
+ with os.fdopen(fd, "r", encoding="utf-8") as handle:
872
+ fd = -1
873
+ return handle.read()
874
+ finally:
875
+ if fd != -1:
876
+ os.close(fd)
877
+
878
+
879
+ def _read_optional_text_no_follow(path: Path) -> str | None:
880
+ try:
881
+ return _read_text_no_follow(path)
882
+ except FileNotFoundError:
883
+ return None
884
+ except OSError as exc:
885
+ raise SystemExit(f"Could not read {path} without following symlinks: {exc}") from exc
886
+
887
+
888
+ def _parse_json_object_text(text: str | None, path: Path) -> dict[str, Any]:
889
+ if text is None:
890
+ return {}
891
+ try:
892
+ data = json.loads(text)
893
+ except json.JSONDecodeError as exc:
894
+ raise SystemExit(f"Invalid JSON in {path}: line {exc.lineno}: {exc.msg}") from exc
895
+ if not isinstance(data, dict):
896
+ raise SystemExit(f"Settings file must contain a JSON object: {path}")
897
+ return data
898
+
899
+
900
+ def load_json_object(path: Path) -> dict[str, Any]:
901
+ return _parse_json_object_text(_read_optional_text_no_follow(path), path)
902
+
903
+
904
+ def ensure_permissions(settings: dict[str, Any], actions: list[str]) -> None:
905
+ permissions = settings.get("permissions")
906
+ if permissions is None:
907
+ permissions = {}
908
+ settings["permissions"] = permissions
909
+ if not isinstance(permissions, dict):
910
+ raise SystemExit("Refusing to replace non-object settings.permissions; repair it manually first.")
911
+ deny = permissions.get("deny")
912
+ if deny is None:
913
+ deny = []
914
+ permissions["deny"] = deny
915
+ if not isinstance(deny, list):
916
+ raise SystemExit("Refusing to replace non-list settings.permissions.deny; repair it manually first.")
917
+ added = 0
918
+ for rule in RECOMMENDED_DENIES:
919
+ if rule not in deny:
920
+ deny.append(rule)
921
+ added += 1
922
+ if added:
923
+ actions.append(f"added {added} permissions.deny rules for bulky/sensitive paths")
924
+
925
+
926
+ def command_values(value: Any) -> list[str]:
927
+ found: list[str] = []
928
+ if isinstance(value, dict):
929
+ for key, item in value.items():
930
+ if key == "command" and isinstance(item, str):
931
+ found.append(item)
932
+ found.extend(command_values(item))
933
+ elif isinstance(value, list):
934
+ for item in value:
935
+ found.extend(command_values(item))
936
+ return found
937
+
938
+
939
+ def matcher_covers(existing: Any, desired: str) -> bool:
940
+ if not isinstance(existing, str):
941
+ return False
942
+ parts = {part.strip().lower() for part in existing.split("|") if part.strip()}
943
+ return not parts or "*" in parts or desired.lower() in parts
944
+
945
+
946
+ def helper_argv(helper_name: str, kit_script: str, *, shell: str | None = None) -> list[str]:
947
+ """Return argv for a bundled helper without invoking a shell."""
948
+ script_dir = Path(__file__).resolve().parent
949
+ colocated = script_dir / helper_name
950
+ if colocated.exists() and os.access(colocated, os.X_OK):
951
+ return [str(colocated)]
952
+ repo_plugin = script_dir.parent / "plugins" / "context-guard" / "bin" / helper_name
953
+ if repo_plugin.exists() and os.access(repo_plugin, os.X_OK):
954
+ return [str(repo_plugin)]
955
+ kit_path = script_dir / kit_script
956
+ if kit_path.exists():
957
+ prefix = [shell] if shell else [sys.executable]
958
+ return [*prefix, str(kit_path)]
959
+ found = shutil.which(helper_name)
960
+ if found:
961
+ return [str(Path(found).resolve())]
962
+ raise SystemExit(
963
+ f"Could not resolve required helper {helper_name!r}; install the plugin or run from a checked-out repository."
964
+ )
965
+
966
+
967
+ def helper_command(helper_name: str, kit_script: str, *, shell: str | None = None) -> str:
968
+ """hook 에 기록할 단일 셸 명령 문자열을 반환한다.
969
+
970
+ 경로에 공백이나 셸 메타문자가 들어와도 안전하도록 모든 분기에서 `shlex.join` 으로
971
+ quote 한다. PATH 에서 찾은 helper 도 절대 경로로 고정해 hook hijacking 을 막는다.
972
+ """
973
+ argv = helper_argv(helper_name, kit_script, shell=shell)
974
+ return shlex.join(argv)
975
+
976
+
977
+ def statusline_setting() -> dict[str, str]:
978
+ return {"type": "command", "command": helper_command(HELPER_STATUSLINE, "statusline_merged.sh", shell="bash")}
979
+
980
+
981
+ def bash_hook_setting() -> dict[str, Any]:
982
+ return {
983
+ "matcher": "Bash",
984
+ "hooks": [{"type": "command", "command": helper_command(HELPER_REWRITE_BASH, "rewrite_bash_for_token_budget.py")}],
985
+ }
986
+
987
+
988
+ def read_hook_setting() -> dict[str, Any]:
989
+ return {
990
+ "matcher": "Read",
991
+ "hooks": [{"type": "command", "command": helper_command(HELPER_GUARD_READ, "guard_large_read.py")}],
992
+ }
993
+
994
+
995
+ def failed_nudge_setting() -> dict[str, Any]:
996
+ return {
997
+ "matcher": "Bash",
998
+ "hooks": [{"type": "command", "command": helper_command(HELPER_FAILED_NUDGE, "failed_attempt_nudge.py")}],
999
+ }
1000
+
1001
+
1002
+ def command_matches(existing: str, desired: str) -> bool:
1003
+ if existing == desired:
1004
+ return True
1005
+ try:
1006
+ existing_parts = shlex.split(existing) if existing else []
1007
+ desired_parts = shlex.split(desired) if desired else []
1008
+ except ValueError:
1009
+ return False
1010
+ return bool(existing_parts and desired_parts and existing_parts == desired_parts)
1011
+
1012
+
1013
+ def command_helper_basenames(command: str) -> set[str]:
1014
+ try:
1015
+ parts = shlex.split(command) if command else []
1016
+ except ValueError:
1017
+ return set()
1018
+ if not parts:
1019
+ return set()
1020
+ index = 0
1021
+ if os.path.basename(parts[index]) == "env":
1022
+ index += 1
1023
+ while index < len(parts) and "=" in parts[index] and not parts[index].startswith("-"):
1024
+ index += 1
1025
+ if index >= len(parts):
1026
+ return set()
1027
+ head = os.path.basename(parts[index])
1028
+ interpreter_heads = {"bash", "sh"}
1029
+ if re.fullmatch(r"python(?:\d+(?:\.\d+)?)?", head):
1030
+ interpreter_heads.add(head)
1031
+ if head in interpreter_heads:
1032
+ for token_index in range(index + 1, len(parts)):
1033
+ token = parts[token_index]
1034
+ if token == "-c":
1035
+ if token_index + 1 < len(parts):
1036
+ return command_helper_basenames(parts[token_index + 1])
1037
+ return set()
1038
+ if token.startswith("-"):
1039
+ continue
1040
+ return {os.path.basename(token)}
1041
+ return set()
1042
+ return {head}
1043
+
1044
+
1045
+ def equivalent_helper_basenames(command: str) -> set[str]:
1046
+ bases = command_helper_basenames(command)
1047
+ equivalents = set(bases)
1048
+ for base in bases:
1049
+ equivalents.update(HELPER_EQUIVALENT_BASENAMES.get(base, ()))
1050
+ return equivalents
1051
+
1052
+
1053
+ def command_matches_existing_or_equivalent(existing: str, desired: str) -> bool:
1054
+ if command_matches(existing, desired):
1055
+ return True
1056
+ desired_helpers = equivalent_helper_basenames(desired)
1057
+ if not desired_helpers:
1058
+ return False
1059
+ return bool(command_helper_basenames(existing) & desired_helpers)
1060
+
1061
+
1062
+ def canonicalize_equivalent_command(value: Any, desired: str) -> tuple[bool, bool]:
1063
+ """Return (found_equivalent, changed), rewriting legacy/bare helpers to desired.
1064
+
1065
+ Older project settings may contain bare `claude-token-*` hook commands from
1066
+ the pre-ContextGuard plugin. Treating those as equivalent for deduplication
1067
+ is useful, but preserving them can leave Claude Code hooks pointing at a
1068
+ command that no longer exists on PATH. When a matching command field is
1069
+ found, pin it to the current canonical helper command instead.
1070
+ """
1071
+ found = False
1072
+ changed = False
1073
+ if isinstance(value, dict):
1074
+ for key, item in value.items():
1075
+ if key == "command" and isinstance(item, str) and command_matches_existing_or_equivalent(item, desired):
1076
+ found = True
1077
+ if not command_matches(item, desired):
1078
+ value[key] = desired
1079
+ changed = True
1080
+ continue
1081
+ child_found, child_changed = canonicalize_equivalent_command(item, desired)
1082
+ found = found or child_found
1083
+ changed = changed or child_changed
1084
+ elif isinstance(value, list):
1085
+ for item in value:
1086
+ child_found, child_changed = canonicalize_equivalent_command(item, desired)
1087
+ found = found or child_found
1088
+ changed = changed or child_changed
1089
+ return found, changed
1090
+
1091
+
1092
+ def has_hook_command(pre_tool_use: list[Any], matcher: str, command: str) -> bool:
1093
+ for entry in pre_tool_use:
1094
+ if not isinstance(entry, dict) or not matcher_covers(entry.get("matcher"), matcher):
1095
+ continue
1096
+ if any(command_matches_existing_or_equivalent(value, command) for value in command_values(entry)):
1097
+ return True
1098
+ return False
1099
+
1100
+
1101
+ def ensure_pre_tool_hook(settings: dict[str, Any], hook: dict[str, Any], command: str, label: str, actions: list[str]) -> None:
1102
+ _ensure_tool_hook(settings, hook, command, label, actions, event="PreToolUse")
1103
+
1104
+
1105
+ def ensure_post_tool_hook(settings: dict[str, Any], hook: dict[str, Any], command: str, label: str, actions: list[str]) -> None:
1106
+ _ensure_tool_hook(settings, hook, command, label, actions, event="PostToolUse")
1107
+
1108
+
1109
+ def _ensure_tool_hook(
1110
+ settings: dict[str, Any],
1111
+ hook: dict[str, Any],
1112
+ command: str,
1113
+ label: str,
1114
+ actions: list[str],
1115
+ *,
1116
+ event: str,
1117
+ ) -> None:
1118
+ hooks = settings.get("hooks")
1119
+ if hooks is None:
1120
+ hooks = {}
1121
+ settings["hooks"] = hooks
1122
+ if not isinstance(hooks, dict):
1123
+ raise SystemExit("Refusing to replace non-object settings.hooks; repair it manually first.")
1124
+ bucket = hooks.get(event)
1125
+ if bucket is None:
1126
+ bucket = []
1127
+ hooks[event] = bucket
1128
+ if not isinstance(bucket, list):
1129
+ raise SystemExit(f"Refusing to replace non-list settings.hooks.{event}; repair it manually first.")
1130
+ matcher = str(hook.get("matcher") or "")
1131
+ found_any = False
1132
+ changed_any = False
1133
+ for entry in bucket:
1134
+ if not isinstance(entry, dict) or not matcher_covers(entry.get("matcher"), matcher):
1135
+ continue
1136
+ found, changed = canonicalize_equivalent_command(entry, command)
1137
+ found_any = found_any or found
1138
+ changed_any = changed_any or changed
1139
+ if found_any:
1140
+ if changed_any:
1141
+ actions.append(f"migrated {label} hook to {command}")
1142
+ return
1143
+ bucket.append(copy.deepcopy(hook))
1144
+ actions.append(f"enabled {label} hook via {command}")
1145
+
1146
+
1147
+ def summarize_diet_report(report: dict[str, Any]) -> dict[str, Any]:
1148
+ if not isinstance(report, dict):
1149
+ raise ValueError("report must be an object")
1150
+ raw_findings = report.get("findings", [])
1151
+ if not isinstance(raw_findings, list):
1152
+ raise ValueError("findings must be a list")
1153
+ findings: list[dict[str, Any]] = []
1154
+ for finding in raw_findings:
1155
+ if not isinstance(finding, dict):
1156
+ raise ValueError("findings must contain objects")
1157
+ findings.append(finding)
1158
+
1159
+ counts = {"high": 0, "medium": 0, "low": 0}
1160
+ for finding in findings:
1161
+ severity = str(finding.get("severity", "")).lower()
1162
+ if severity in counts:
1163
+ counts[severity] += 1
1164
+ top_findings = []
1165
+ for finding in findings[:DEFAULT_POST_SETUP_SCAN_TOP]:
1166
+ top_findings.append({
1167
+ "severity": finding.get("severity"),
1168
+ "id": finding.get("id"),
1169
+ "path": finding.get("path"),
1170
+ "message": finding.get("message"),
1171
+ "action": finding.get("action"),
1172
+ })
1173
+ raw_finding_count = report.get("finding_count", len(findings))
1174
+ try:
1175
+ finding_count = int(raw_finding_count)
1176
+ except (TypeError, ValueError) as exc:
1177
+ raise ValueError("finding_count must be an integer") from exc
1178
+ return {
1179
+ "status": "completed",
1180
+ "finding_count": finding_count,
1181
+ "severity_counts": counts,
1182
+ "top_findings": top_findings,
1183
+ }
1184
+
1185
+
1186
+ def run_post_setup_diet_scan(root: Path) -> dict[str, Any]:
1187
+ argv = [
1188
+ *helper_argv(HELPER_DIET, "context_guard_diet.py"),
1189
+ "scan",
1190
+ str(root),
1191
+ "--json",
1192
+ "--top",
1193
+ str(DEFAULT_POST_SETUP_SCAN_TOP),
1194
+ ]
1195
+ try:
1196
+ proc = subprocess.run(
1197
+ argv,
1198
+ text=True,
1199
+ capture_output=True,
1200
+ check=False,
1201
+ timeout=POST_SETUP_SCAN_TIMEOUT_SECONDS,
1202
+ )
1203
+ except subprocess.TimeoutExpired:
1204
+ return {"status": "failed", "reason": "timeout", "timeout_seconds": POST_SETUP_SCAN_TIMEOUT_SECONDS}
1205
+ except UnicodeError:
1206
+ return {"status": "failed", "reason": "decode-error"}
1207
+ except OSError as exc:
1208
+ return {"status": "failed", "reason": exc.__class__.__name__}
1209
+ if proc.returncode != 0:
1210
+ return {"status": "failed", "reason": "nonzero-exit", "returncode": proc.returncode}
1211
+ try:
1212
+ report = json.loads(proc.stdout)
1213
+ except json.JSONDecodeError:
1214
+ return {"status": "failed", "reason": "invalid-json"}
1215
+ try:
1216
+ return summarize_diet_report(report)
1217
+ except ValueError:
1218
+ return {"status": "failed", "reason": "invalid-report"}
1219
+
1220
+
1221
+ def apply_choices(settings: dict[str, Any], choices: Choices) -> list[str]:
1222
+ actions: list[str] = []
1223
+ if choices.model_defaults:
1224
+ if not settings.get("model"):
1225
+ settings["model"] = DEFAULT_MODEL
1226
+ actions.append(f"set default model to {DEFAULT_MODEL}")
1227
+ if not settings.get("effortLevel"):
1228
+ settings["effortLevel"] = DEFAULT_EFFORT
1229
+ actions.append(f"set default effortLevel to {DEFAULT_EFFORT}")
1230
+ if choices.statusline:
1231
+ statusline = statusline_setting()
1232
+ if "statusLine" not in settings:
1233
+ settings["statusLine"] = statusline
1234
+ actions.append("enabled token statusline")
1235
+ elif settings.get("statusLine") != statusline:
1236
+ actions.append("kept existing statusLine; add context-guard-statusline-merged manually if desired")
1237
+ if choices.denies:
1238
+ ensure_permissions(settings, actions)
1239
+ if choices.bash_hook:
1240
+ bash_hook = bash_hook_setting()
1241
+ bash_command = bash_hook["hooks"][0]["command"]
1242
+ ensure_pre_tool_hook(settings, bash_hook, bash_command, "Bash trim/sanitize", actions)
1243
+ if choices.read_guard:
1244
+ read_hook = read_hook_setting()
1245
+ read_command = read_hook["hooks"][0]["command"]
1246
+ ensure_pre_tool_hook(settings, read_hook, read_command, "large Read guard", actions)
1247
+ if choices.failed_attempt_nudge:
1248
+ nudge_hook = failed_nudge_setting()
1249
+ nudge_command = nudge_hook["hooks"][0]["command"]
1250
+ ensure_post_tool_hook(settings, nudge_hook, nudge_command, "failed-attempt /clear nudge", actions)
1251
+ return actions
1252
+
1253
+
1254
+ def atomic_write(path: Path, text: str, mode: int = 0o600, *, dir_mode: int = PRIVATE_DIR_MODE) -> None:
1255
+ if os.rename not in os.supports_dir_fd or os.unlink not in os.supports_dir_fd:
1256
+ raise OSError("platform does not support directory-relative atomic writes")
1257
+ parent_fd = _ensure_directory_no_symlink(path.parent, dir_mode, parents_mode=dir_mode)
1258
+ tmp_name = f".{path.name}.{os.getpid()}.{uuid.uuid4().hex}.tmp"
1259
+ flags = os.O_CREAT | os.O_EXCL | os.O_WRONLY | _no_follow_flag()
1260
+ fd = os.open(tmp_name, flags, mode, dir_fd=parent_fd)
1261
+ try:
1262
+ if hasattr(os, "fchmod"):
1263
+ os.fchmod(fd, mode)
1264
+ with os.fdopen(fd, "w", encoding="utf-8") as f:
1265
+ fd = -1
1266
+ f.write(text)
1267
+ f.flush()
1268
+ os.fsync(f.fileno())
1269
+ os.fsync(parent_fd)
1270
+ os.rename(tmp_name, path.name, src_dir_fd=parent_fd, dst_dir_fd=parent_fd)
1271
+ try:
1272
+ os.fsync(parent_fd)
1273
+ except OSError as exc:
1274
+ raise AtomicWriteDurabilityError(
1275
+ f"write committed but parent directory durability is uncertain: {path}"
1276
+ ) from exc
1277
+ finally:
1278
+ if fd != -1:
1279
+ os.close(fd)
1280
+ try:
1281
+ os.unlink(tmp_name, dir_fd=parent_fd)
1282
+ except FileNotFoundError:
1283
+ pass
1284
+ os.close(parent_fd)
1285
+
1286
+
1287
+ def existing_mode_or_default(path: Path, default: int = 0o600) -> int:
1288
+ try:
1289
+ fd = _open_regular_no_symlink(path)
1290
+ except FileNotFoundError:
1291
+ return default
1292
+ except OSError:
1293
+ return default
1294
+ try:
1295
+ return os.fstat(fd).st_mode & 0o777
1296
+ finally:
1297
+ os.close(fd)
1298
+
1299
+
1300
+ def backup_existing(path: Path) -> Path | None:
1301
+ try:
1302
+ text = _read_text_no_follow(path)
1303
+ except FileNotFoundError:
1304
+ return None
1305
+ mode = existing_mode_or_default(path, 0o600)
1306
+ stamp = _dt.datetime.now().strftime("%Y%m%d%H%M%S%f")
1307
+ backup = path.with_name(f"{path.name}.bak-{stamp}-{uuid.uuid4().hex[:8]}")
1308
+ atomic_write(backup, text, mode)
1309
+ return backup
1310
+
1311
+
1312
+ def write_rollback_record(
1313
+ *,
1314
+ root: Path,
1315
+ scope: str,
1316
+ settings_path: Path,
1317
+ backup_path: Path | None,
1318
+ original_existed: bool,
1319
+ ) -> tuple[str | None, Path | None]:
1320
+ """Record a minimal rollback handle for user-scope writes.
1321
+
1322
+ Project-scope setup keeps the legacy backup-only behavior. User-scope setup
1323
+ can affect many future projects, so every write gets a local rollback record
1324
+ under the user's ContextGuard state directory.
1325
+ """
1326
+ if scope != "user":
1327
+ return None, None
1328
+ rollback_id = _dt.datetime.now().strftime("%Y%m%d%H%M%S") + "-" + uuid.uuid4().hex[:8]
1329
+ rollback_dir = root / ".context-guard" / "rollback"
1330
+ rollback_path = rollback_dir / f"{rollback_id}.json"
1331
+ record = {
1332
+ "schema_version": "contextguard.rollback.v1",
1333
+ "rollback_id": rollback_id,
1334
+ "created_at": _dt.datetime.now(_dt.UTC).isoformat().replace("+00:00", "Z"),
1335
+ "scope": scope,
1336
+ "target_path": str(settings_path),
1337
+ "backup_path": str(backup_path) if backup_path else None,
1338
+ "original_existed": original_existed,
1339
+ "restore": (
1340
+ f"cp {shlex.quote(str(backup_path))} {shlex.quote(str(settings_path))}"
1341
+ if backup_path
1342
+ else f"rm -f {shlex.quote(str(settings_path))}"
1343
+ ),
1344
+ }
1345
+ atomic_write(rollback_path, json.dumps(record, indent=2, sort_keys=True) + "\n", 0o600)
1346
+ return rollback_id, rollback_path
1347
+
1348
+
1349
+ def acquire_settings_lock(path: Path) -> int:
1350
+ """Take an exclusive project-local settings lock without following links."""
1351
+ if fcntl is None:
1352
+ raise OSError("platform does not support advisory file locks")
1353
+ parent_fd = _ensure_directory_no_symlink(path.parent, PRIVATE_DIR_MODE)
1354
+ lock_name = f".{path.name}.lock"
1355
+ flags = os.O_CREAT | os.O_RDWR | _no_follow_flag()
1356
+ if hasattr(os, "O_CLOEXEC"):
1357
+ flags |= os.O_CLOEXEC
1358
+ try:
1359
+ fd = os.open(lock_name, flags, 0o600, dir_fd=parent_fd)
1360
+ finally:
1361
+ os.close(parent_fd)
1362
+ try:
1363
+ st = os.fstat(fd)
1364
+ if not stat.S_ISREG(st.st_mode):
1365
+ raise OSError(f"settings lock is not a regular file: {path.with_name(lock_name)}")
1366
+ if hasattr(os, "fchmod"):
1367
+ os.fchmod(fd, 0o600)
1368
+ fcntl.flock(fd, fcntl.LOCK_EX)
1369
+ return fd
1370
+ except Exception:
1371
+ os.close(fd)
1372
+ raise
1373
+
1374
+
1375
+ def release_settings_lock(fd: int) -> None:
1376
+ try:
1377
+ if fcntl is not None:
1378
+ fcntl.flock(fd, fcntl.LOCK_UN)
1379
+ finally:
1380
+ os.close(fd)
1381
+
1382
+
1383
+ def prompt_bool(question: str, default: bool) -> bool:
1384
+ suffix = "Y/n" if default else "y/N"
1385
+ while True:
1386
+ answer = input(f"{question} [{suffix}] ").strip().lower()
1387
+ if not answer:
1388
+ return default
1389
+ if answer in {"y", "yes"}:
1390
+ return True
1391
+ if answer in {"n", "no"}:
1392
+ return False
1393
+ print("Please answer y or n.")
1394
+
1395
+
1396
+ def interactive_choices(defaults: Choices) -> Choices:
1397
+ print("ContextGuard setup wizard")
1398
+ print("Project-local changes only. Existing settings are merged, not replaced.\n")
1399
+ choices = Choices(
1400
+ denies=prompt_bool("Add deny rules for bulky/sensitive paths?", defaults.denies),
1401
+ statusline=prompt_bool("Enable token/cost statusline?", defaults.statusline),
1402
+ bash_hook=prompt_bool("Enable Bash output trim + grep/diff sanitizer hook?", defaults.bash_hook),
1403
+ read_guard=prompt_bool("Enable large Read guard?", defaults.read_guard),
1404
+ model_defaults=prompt_bool("Set missing defaults to model=sonnet and effortLevel=medium?", defaults.model_defaults),
1405
+ failed_attempt_nudge=prompt_bool(
1406
+ "Enable failed-attempt /clear nudge? (PostToolUse hook on Bash; recommended default)",
1407
+ defaults.failed_attempt_nudge,
1408
+ ),
1409
+ )
1410
+ return choices
1411
+
1412
+
1413
+ def choices_from_args(args: argparse.Namespace) -> Choices:
1414
+ return Choices(
1415
+ denies=not args.no_denies,
1416
+ statusline=not args.no_statusline,
1417
+ bash_hook=not args.no_bash_hook,
1418
+ read_guard=not args.no_read_guard,
1419
+ model_defaults=not args.no_model_defaults,
1420
+ failed_attempt_nudge=(
1421
+ DEFAULT_FAILED_ATTEMPT_NUDGE
1422
+ if args.failed_attempt_nudge is None
1423
+ else args.failed_attempt_nudge
1424
+ ),
1425
+ )
1426
+
1427
+
1428
+ def render_text(result: SetupResult) -> str:
1429
+ mode = "applied" if result.applied else ("apply requested; no writes" if result.apply_requested else "plan only")
1430
+ lines = [
1431
+ f"ContextGuard setup ({mode})",
1432
+ f"scope={result.scope}",
1433
+ f"root={result.root}",
1434
+ f"settings={result.settings_path}",
1435
+ ]
1436
+ if result.backup_path:
1437
+ lines.append(f"backup={result.backup_path}")
1438
+ if result.rollback_path:
1439
+ lines.append(f"rollback={result.rollback_path}")
1440
+ for warning in result.warnings or []:
1441
+ lines.append(f"warning={warning}")
1442
+ if result.diet_scan:
1443
+ scan = result.diet_scan
1444
+ lines.append("post-setup diet scan:")
1445
+ if scan.get("status") == "completed":
1446
+ counts = scan.get("severity_counts", {})
1447
+ lines.append(
1448
+ "- "
1449
+ f"findings={scan.get('finding_count', 0)} "
1450
+ f"high={counts.get('high', 0)} medium={counts.get('medium', 0)} low={counts.get('low', 0)}"
1451
+ )
1452
+ for finding in scan.get("top_findings", []):
1453
+ lines.append(f"- [{str(finding.get('severity', '')).upper()}] {finding.get('id')} @ {finding.get('path')}")
1454
+ else:
1455
+ lines.append(f"- skipped/failed: {scan.get('reason', scan.get('status', 'unknown'))}")
1456
+ lines.append("actions:")
1457
+ if result.actions:
1458
+ lines.extend(f"- {action}" for action in result.actions)
1459
+ else:
1460
+ lines.append("- no settings changes needed")
1461
+ # Only surface the cross-agent section when a non-Claude adapter is engaged,
1462
+ # keeping the default Claude-only text output unchanged.
1463
+ extra_adapters = [entry for entry in (result.adapter_plan or []) if entry.get("key") != "claude"]
1464
+ if extra_adapters:
1465
+ lines.append("cross-agent adapters:")
1466
+ for entry in result.adapter_plan or []:
1467
+ lines.append(f"- {entry['key']} [{entry['capability']}] status={entry['status']}")
1468
+ for action in entry.get("planned_actions", []):
1469
+ lines.append(f" - {action}")
1470
+ if result.apply_requested and not result.applied:
1471
+ lines.append("No supported writes were applied.")
1472
+ elif not result.applied:
1473
+ lines.append("Run with --yes to apply the selected plan non-interactively.")
1474
+ return "\n".join(lines) + "\n"
1475
+
1476
+
1477
+ def run(args: argparse.Namespace) -> SetupResult:
1478
+ require_no_follow_file_ops_supported()
1479
+ scope = normalize_scope(getattr(args, "scope", "project"))
1480
+ root = resolve_scope_root(args.root, scope)
1481
+ settings_path = root / SETTINGS_REL
1482
+ warnings: list[str] = []
1483
+ if scope == "user":
1484
+ warnings.append(
1485
+ "user-scope setup can affect future projects; writes require --yes and explicit --agent/--only selection"
1486
+ )
1487
+
1488
+ # Cross-agent targets. Default keeps Claude compatibility (Claude is always
1489
+ # targeted plus any detected agent); --only narrows to an explicit set.
1490
+ selected_agents = explicit_agent_selection(args)
1491
+ targets = resolve_target_adapters(root, selected_agents)
1492
+ claude_targeted = any(adapter.key == "claude" for adapter in targets)
1493
+
1494
+ if claude_targeted:
1495
+ validate_settings_target(root, settings_path, allow_home_settings=(args.allow_home_settings or scope == "user"))
1496
+ original_text = _read_optional_text_no_follow(settings_path)
1497
+ original = _parse_json_object_text(original_text, settings_path)
1498
+ settings = json.loads(json.dumps(original))
1499
+ else:
1500
+ original_text = None
1501
+ original = {}
1502
+ settings = {}
1503
+
1504
+ choices = choices_from_args(args)
1505
+ interactive = (
1506
+ sys.stdin.isatty()
1507
+ and not args.yes
1508
+ and not args.plan
1509
+ and not args.dry_run
1510
+ and claude_targeted
1511
+ )
1512
+ if interactive:
1513
+ choices = interactive_choices(choices)
1514
+
1515
+ actions = apply_choices(settings, choices) if claude_targeted else []
1516
+ changed = (settings != original) if claude_targeted else False
1517
+
1518
+ apply_requested = bool(args.yes and not args.dry_run and not args.plan)
1519
+ if scope == "user" and apply_requested and not selected_agents:
1520
+ raise SystemExit(
1521
+ "Refusing user-scope writes without an explicit agent. "
1522
+ "Pass --agent claude (or another specific adapter) with --scope user."
1523
+ )
1524
+ if interactive and changed:
1525
+ preview = SetupResult(
1526
+ root=root,
1527
+ settings_path=settings_path,
1528
+ scope=scope,
1529
+ changed=changed,
1530
+ applied=False,
1531
+ apply_requested=False,
1532
+ choices=choices,
1533
+ actions=actions,
1534
+ warnings=warnings,
1535
+ )
1536
+ print("\n" + render_text(preview))
1537
+ prompt_scope = "user-level" if scope == "user" else "project-local"
1538
+ apply_requested = prompt_bool(f"Apply these {prompt_scope} changes now?", True)
1539
+ if scope == "user" and apply_requested and not selected_agents:
1540
+ raise SystemExit(
1541
+ "Refusing user-scope writes without an explicit agent. "
1542
+ "Pass --agent claude (or another specific adapter) with --scope user."
1543
+ )
1544
+
1545
+ backup_path = None
1546
+ rollback_id = None
1547
+ rollback_path = None
1548
+ claude_settings_written = False
1549
+ if claude_targeted and apply_requested and changed:
1550
+ if scope == "user" and original_text is not None and args.no_backup:
1551
+ raise SystemExit("Refusing --no-backup for user-scope changes to existing Claude settings.")
1552
+ lock_fd = acquire_settings_lock(settings_path)
1553
+ try:
1554
+ current_text = _read_optional_text_no_follow(settings_path)
1555
+ if current_text != original_text:
1556
+ raise SystemExit(
1557
+ f"Settings changed while setup was preparing changes; re-run setup to merge latest file: {settings_path}"
1558
+ )
1559
+ if original_text is not None and not args.no_backup and settings != original:
1560
+ backup_path = backup_existing(settings_path)
1561
+ if settings != original:
1562
+ rollback_id, rollback_path = write_rollback_record(
1563
+ root=root,
1564
+ scope=scope,
1565
+ settings_path=settings_path,
1566
+ backup_path=backup_path,
1567
+ original_existed=(original_text is not None),
1568
+ )
1569
+ atomic_write(
1570
+ settings_path,
1571
+ json.dumps(settings, indent=2, sort_keys=True) + "\n",
1572
+ existing_mode_or_default(settings_path, 0o600),
1573
+ )
1574
+ claude_settings_written = True
1575
+ finally:
1576
+ release_settings_lock(lock_fd)
1577
+
1578
+ # Build the per-adapter plan; repo-rule writes happen here only when both
1579
+ # --with-init and an applying run (--yes) are in effect.
1580
+ adapter_plan = build_adapter_plan(
1581
+ root,
1582
+ targets,
1583
+ scope=scope,
1584
+ claude_actions=actions,
1585
+ claude_changed=changed,
1586
+ claude_applied=(claude_targeted and apply_requested),
1587
+ with_init=bool(getattr(args, "with_init", False)),
1588
+ with_skill=bool(getattr(args, "with_skill", False)),
1589
+ applied=apply_requested,
1590
+ )
1591
+ # Surface any repo-rule writes in the top-level actions for visibility. Claude
1592
+ # actions are already in ``actions``; only adapter-side writes are appended.
1593
+ for entry in adapter_plan:
1594
+ actions.extend(entry.get("applied_actions", []))
1595
+ adapter_writes = any(entry.get("applied_actions") for entry in adapter_plan)
1596
+ applied = bool(claude_settings_written or adapter_writes)
1597
+
1598
+ diet_scan = None
1599
+ if (applied or (apply_requested and claude_targeted)) and not getattr(args, "no_diet_scan", False):
1600
+ diet_scan = run_post_setup_diet_scan(root)
1601
+
1602
+ return SetupResult(
1603
+ root=root,
1604
+ settings_path=settings_path,
1605
+ scope=scope,
1606
+ changed=changed,
1607
+ applied=applied,
1608
+ apply_requested=apply_requested,
1609
+ choices=choices,
1610
+ actions=actions,
1611
+ backup_path=backup_path,
1612
+ rollback_id=rollback_id,
1613
+ rollback_path=rollback_path,
1614
+ warnings=warnings,
1615
+ diet_scan=diet_scan,
1616
+ adapter_plan=adapter_plan,
1617
+ )
1618
+
1619
+
1620
+ def build_parser() -> argparse.ArgumentParser:
1621
+ parser = argparse.ArgumentParser(description="Interactively configure ContextGuard project settings.")
1622
+ parser.add_argument("--root", default=None, help="project root to configure (default: nearest git root, else current directory)")
1623
+ parser.add_argument(
1624
+ "--scope",
1625
+ choices=("project", "user", "global"),
1626
+ default="project",
1627
+ help="setup scope: project-local by default; user/global targets only known user-level paths and requires explicit --agent for writes",
1628
+ )
1629
+ parser.add_argument(
1630
+ "--allow-home-settings",
1631
+ action="store_true",
1632
+ help="deprecated compatibility alias for user-level Claude settings; prefer --scope user --agent claude",
1633
+ )
1634
+ parser.add_argument("--yes", action="store_true", help="apply the recommended/selected setup without prompts")
1635
+ parser.add_argument("--plan", action="store_true", help="show the setup plan without writing files")
1636
+ parser.add_argument("--dry-run", action="store_true", help="alias for --plan")
1637
+ parser.add_argument("--json", action="store_true", help="print machine-readable result")
1638
+ parser.add_argument("--no-backup", action="store_true", help="do not create .bak-* before modifying existing settings")
1639
+ parser.add_argument("--no-denies", action="store_true", help="skip recommended permissions.deny rules")
1640
+ parser.add_argument("--no-statusline", action="store_true", help="skip token statusline")
1641
+ parser.add_argument("--no-bash-hook", action="store_true", help="skip Bash trim/sanitize hook")
1642
+ parser.add_argument("--no-read-guard", action="store_true", help="skip large Read guard hook")
1643
+ parser.add_argument("--no-model-defaults", action="store_true", help="skip model/effort defaults")
1644
+ parser.add_argument("--no-diet-scan", action="store_true", help="skip the read-only diet scan summary after applying setup")
1645
+ parser.add_argument(
1646
+ "--agent",
1647
+ action="append",
1648
+ default=None,
1649
+ metavar="ADAPTER",
1650
+ help="adapter key(s) to configure; comma-separated or repeatable. Alias for --only.",
1651
+ )
1652
+ parser.add_argument(
1653
+ "--only",
1654
+ action="append",
1655
+ default=None,
1656
+ metavar="ADAPTER",
1657
+ help="restrict cross-agent setup/plan to adapter key(s); comma-separated or repeatable "
1658
+ "(e.g. --only codex,gemini). Default: claude plus any detected agents.",
1659
+ )
1660
+ parser.add_argument(
1661
+ "--with-init",
1662
+ dest="with_init",
1663
+ action="store_true",
1664
+ help="also write advisory ContextGuard rule files for repo-rule agents (AGENTS.md, GEMINI.md, .cursorrules, etc.) "
1665
+ "when applying; safe and idempotent.",
1666
+ )
1667
+ parser.add_argument(
1668
+ "--with-skill",
1669
+ dest="with_skill",
1670
+ action="store_true",
1671
+ help="also generate optional project-local skill files where supported, currently Codex .agents/skills/context-guard/SKILL.md.",
1672
+ )
1673
+ parser.add_argument(
1674
+ "--list-adapters",
1675
+ dest="list_adapters",
1676
+ action="store_true",
1677
+ help="print the cross-agent adapter registry and exit",
1678
+ )
1679
+ nudge_group = parser.add_mutually_exclusive_group()
1680
+ nudge_group.add_argument(
1681
+ "--failed-attempt-nudge",
1682
+ dest="failed_attempt_nudge",
1683
+ action="store_true",
1684
+ default=None,
1685
+ help="enable PostToolUse Bash hook that suggests /clear when the same command fails twice in a row (recommended default)",
1686
+ )
1687
+ nudge_group.add_argument(
1688
+ "--no-failed-attempt-nudge",
1689
+ dest="failed_attempt_nudge",
1690
+ action="store_false",
1691
+ default=None,
1692
+ help="skip the failed-attempt /clear nudge hook",
1693
+ )
1694
+ return parser
1695
+
1696
+
1697
+ def main() -> int:
1698
+ parser = build_parser()
1699
+ args = parser.parse_args()
1700
+ if args.dry_run:
1701
+ args.plan = True
1702
+ if getattr(args, "list_adapters", False):
1703
+ payload = adapter_registry_payload()
1704
+ if args.json:
1705
+ print(json.dumps({"adapters": payload}, indent=2, sort_keys=True))
1706
+ else:
1707
+ print("ContextGuard cross-agent adapters:")
1708
+ for item in payload:
1709
+ print(f"- {item['key']} [{item['capability']}] {item['display_name']}: {item['summary']}")
1710
+ return 0
1711
+ # Safety default for non-interactive Claude Code Bash calls: do not write
1712
+ # unless --yes is explicit.
1713
+ if not sys.stdin.isatty() and not args.yes:
1714
+ args.plan = True
1715
+ result = run(args)
1716
+ if args.json:
1717
+ print(json.dumps(result.as_dict(), indent=2, sort_keys=True))
1718
+ else:
1719
+ print(render_text(result))
1720
+ return 0
1721
+
1722
+
1723
+ if __name__ == "__main__":
1724
+ raise SystemExit(main())