patchops-guard 0.2.0__py3-none-any.whl

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.
@@ -0,0 +1,167 @@
1
+ """``patchops free-scan`` — Free Scan engine (135 deterministic checks).
2
+
3
+ The Free Scan engine powers https://patchguard.ai/free. Public, no auth,
4
+ IP rate-limited (6/min). Async start → poll until complete.
5
+
6
+ This command lives separate from ``url-scan`` because Free Scan is a
7
+ distinct product engine from URL Scan Flash 1.0:
8
+ * Free Scan — 135 deterministic checks · 17 categories · public · free forever
9
+ * URL Scan Flash — 84 checks + AI exploit chains · authenticated · Pro tier
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import time
14
+ from enum import Enum
15
+ from pathlib import Path
16
+
17
+ import typer
18
+
19
+ from patchops_cli import config as cfg_mod
20
+ from patchops_cli.client import APIError, PatchOpsCLIClient
21
+ from patchops_cli.formatters.json_fmt import write_json_output
22
+ from patchops_cli.utils.errors import EXIT_USAGE, fail
23
+
24
+ app = typer.Typer(
25
+ help="Free Scan — 135 deterministic checks across 17 categories. "
26
+ "Public, no auth, IP rate-limited.",
27
+ )
28
+
29
+
30
+ class _Fmt(str, Enum):
31
+ table = "table"
32
+ json = "json"
33
+
34
+
35
+ def _client() -> PatchOpsCLIClient:
36
+ """Free Scan needs no API key — empty config is fine."""
37
+ cfg = cfg_mod.load()
38
+ return PatchOpsCLIClient(cfg)
39
+
40
+
41
+ @app.command("run")
42
+ def free_scan_run(
43
+ host: str = typer.Argument(..., help="Hostname (e.g. example.com)."),
44
+ fmt: _Fmt = typer.Option(_Fmt.table, "--format", "-f"),
45
+ output: Path | None = typer.Option(
46
+ None, "--output", help="Write result to file.",
47
+ ),
48
+ timeout: int = typer.Option(
49
+ 90, "--timeout", min=10, max=300,
50
+ help="Max seconds to wait for scan completion.",
51
+ ),
52
+ ) -> None:
53
+ """Run Free Scan against a hostname. Polls until complete.
54
+
55
+ No authentication required. Rate-limited by IP (6 scans/min) and
56
+ cached per host for 5 minutes.
57
+ """
58
+ # Strip scheme if user pasted https://example.com
59
+ cleaned = host.strip()
60
+ for prefix in ("https://", "http://"):
61
+ if cleaned.startswith(prefix):
62
+ cleaned = cleaned[len(prefix):]
63
+ cleaned = cleaned.rstrip("/")
64
+ if "/" in cleaned:
65
+ cleaned = cleaned.split("/", 1)[0]
66
+
67
+ client = _client()
68
+ try:
69
+ started = client.free_scan_start(cleaned)
70
+ except APIError as exc:
71
+ if exc.status == 429:
72
+ raise fail(
73
+ "Rate limit hit (6/min per IP). Try again in a minute.",
74
+ exit_code=EXIT_USAGE,
75
+ )
76
+ raise fail(
77
+ f"free-scan start failed ({exc.status}): {exc.message}",
78
+ exit_code=EXIT_USAGE,
79
+ )
80
+ scan_id = started.get("scan_id")
81
+ if not scan_id:
82
+ raise fail("free-scan: no scan_id in response", exit_code=EXIT_USAGE)
83
+
84
+ if started.get("cached"):
85
+ typer.secho(
86
+ f"Cached result for {cleaned} (5min TTL)", fg="cyan",
87
+ )
88
+
89
+ deadline = time.time() + timeout
90
+ final: dict | None = None
91
+ last_status = ""
92
+ while time.time() < deadline:
93
+ try:
94
+ final = client.free_scan_get(scan_id)
95
+ except APIError as exc:
96
+ raise fail(
97
+ f"free-scan poll failed ({exc.status}): {exc.message}",
98
+ exit_code=EXIT_USAGE,
99
+ )
100
+ status = str(final.get("status") or "")
101
+ if status != last_status and fmt is _Fmt.table:
102
+ typer.secho(f" status: {status}", dim=True)
103
+ last_status = status
104
+ if status == "complete":
105
+ break
106
+ if status == "error":
107
+ raise fail(
108
+ f"scan failed: {final.get('error', 'unknown')}",
109
+ exit_code=EXIT_USAGE,
110
+ )
111
+ time.sleep(2)
112
+
113
+ if final is None:
114
+ raise fail("free-scan: timed out", exit_code=EXIT_USAGE)
115
+
116
+ if fmt is _Fmt.json:
117
+ write_json_output(final, output)
118
+ return
119
+
120
+ grade = final.get("grade", "?")
121
+ score = final.get("score", "?")
122
+ summary = final.get("summary") or {}
123
+ duration = final.get("duration_sec")
124
+ typer.echo(f"Host: {final.get('host', cleaned)}")
125
+ typer.secho(f"Grade: {grade} (score {score}/100)", fg="green" if grade in ("A", "A+") else "yellow")
126
+ if duration is not None:
127
+ typer.echo(f"Time: {duration:.1f}s")
128
+ sev_line = (
129
+ f"Critical: {summary.get('critical', 0)} · "
130
+ f"High: {summary.get('high', 0)} · "
131
+ f"Medium: {summary.get('medium', 0)} · "
132
+ f"Low: {summary.get('low', 0)}"
133
+ )
134
+ typer.echo(sev_line)
135
+ typer.echo(f"Total: {summary.get('total_findings', 0)} findings · {summary.get('total_checks', 0)} checks")
136
+
137
+ achievements = final.get("achievements") or []
138
+ if achievements:
139
+ typer.echo("\nAchievements:")
140
+ for a in achievements[:5]:
141
+ typer.echo(f" {a.get('emoji', '*')} {a.get('name')}")
142
+
143
+ if output is not None:
144
+ write_json_output(final, output)
145
+
146
+
147
+ @app.command("badge")
148
+ def free_scan_badge(
149
+ scan_id: str = typer.Argument(..., help="scan_id from `free-scan run`."),
150
+ output: Path = typer.Option(
151
+ Path("badge.svg"), "--output", "-o", help="Where to save the SVG.",
152
+ ),
153
+ ) -> None:
154
+ """Download the SVG badge for a completed Free Scan."""
155
+ client = _client()
156
+ try:
157
+ svg = client.free_scan_badge(scan_id)
158
+ except APIError as exc:
159
+ raise fail(
160
+ f"badge fetch failed ({exc.status}): {exc.message}",
161
+ exit_code=EXIT_USAGE,
162
+ )
163
+ output.write_text(svg if isinstance(svg, str) else str(svg))
164
+ typer.secho(f"Wrote badge to {output}", fg="green")
165
+
166
+
167
+ __all__ = ["app"]
@@ -0,0 +1,271 @@
1
+ """patchops mcp-audit — MCP 설정 감사 (21 패턴 + optional Haiku semantic).
2
+
3
+ 사용:
4
+ patchops mcp-audit ~/.cursor/mcp.json
5
+ patchops mcp-audit --recursive ./configs/
6
+ patchops mcp-audit config.json --format sarif > report.sarif
7
+ patchops mcp-audit config.json --semantic # Haiku LLM 추가
8
+ patchops mcp-audit --fail-on-severity high
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ import sys
14
+ from enum import StrEnum
15
+ from pathlib import Path
16
+
17
+ import typer
18
+
19
+ from patchops_cli.mcp_remote import LOCAL_ENGINE_MISSING, audit_remote, remote_enabled
20
+
21
+ app = typer.Typer(
22
+ name="mcp-audit",
23
+ help="Audit MCP (Model Context Protocol) server configs for 21 security patterns.",
24
+ invoke_without_command=True,
25
+ no_args_is_help=False,
26
+ )
27
+
28
+
29
+ class OutputFormat(StrEnum):
30
+ pretty = "pretty"
31
+ json = "json"
32
+ sarif = "sarif"
33
+
34
+
35
+ _SEV_COLORS = {
36
+ "critical": "red", "high": "yellow", "medium": "cyan",
37
+ "low": "blue", "info": "white",
38
+ }
39
+ _SEV_ORDER = {"critical": 0, "high": 1, "medium": 2, "low": 3, "info": 4}
40
+
41
+
42
+ def _load_config(path: Path) -> dict | None:
43
+ try:
44
+ with path.open("r", encoding="utf-8") as f:
45
+ return json.load(f)
46
+ except json.JSONDecodeError:
47
+ return None
48
+ except OSError:
49
+ return None
50
+
51
+
52
+ def _find_config_files(root: Path, recursive: bool) -> list[Path]:
53
+ if root.is_file():
54
+ return [root]
55
+ if not root.is_dir():
56
+ return []
57
+ patterns = ("*.json", ".mcp.json", "mcp.json", "mcp*.json")
58
+ out: list[Path] = []
59
+ if recursive:
60
+ for pat in patterns:
61
+ out.extend(root.rglob(pat))
62
+ else:
63
+ for pat in patterns:
64
+ out.extend(root.glob(pat))
65
+ # dedup
66
+ seen = set()
67
+ unique = []
68
+ for p in out:
69
+ if p in seen:
70
+ continue
71
+ seen.add(p)
72
+ unique.append(p)
73
+ return unique
74
+
75
+
76
+ def _audit_config(cfg: dict, *, remote: bool = False) -> dict:
77
+ """Import orchestrator lazily — CLI 가 backend 파이썬 경로에서 실행될 때.
78
+
79
+ 로컬 엔진이 없을 때 서버 분석은 remote 를 켰을 때만, 비밀값을 가린 사본으로 (ISSUE-042).
80
+ """
81
+ try:
82
+ from app.services.mcp_guard_orchestrator import audit_mcp_config
83
+ return audit_mcp_config(cfg)
84
+ except ImportError:
85
+ if not remote_enabled(remote):
86
+ typer.secho(LOCAL_ENGINE_MISSING, fg="yellow", err=True)
87
+ raise typer.Exit(2) from None
88
+ return audit_remote(cfg)
89
+
90
+
91
+ def _print_pretty(path: Path, result: dict) -> None:
92
+ typer.echo(f"\n📄 {path}")
93
+ typer.echo(f" Servers: {result['n_servers']} Findings: {result['n_findings']}")
94
+ if result["n_findings"] == 0:
95
+ typer.secho(" ✓ clean", fg="green")
96
+ return
97
+ by_sev: dict[str, list[dict]] = {}
98
+ for f in result["findings"]:
99
+ by_sev.setdefault(f.get("severity", "info"), []).append(f)
100
+ for sev in ("critical", "high", "medium", "low", "info"):
101
+ items = by_sev.get(sev, [])
102
+ if not items:
103
+ continue
104
+ typer.secho(
105
+ f" [{sev.upper()} × {len(items)}]",
106
+ fg=_SEV_COLORS.get(sev, "white"), bold=True,
107
+ )
108
+ for f in items[:20]:
109
+ typer.echo(
110
+ f" - {f.get('rule_id', ''):<40} "
111
+ f"{f.get('name', '')[:60]}",
112
+ )
113
+ if len(items) > 20:
114
+ typer.echo(f" ... and {len(items)-20} more")
115
+
116
+
117
+ def _to_sarif(path: Path, result: dict) -> dict:
118
+ runs = []
119
+ results = []
120
+ rule_map: dict[str, dict] = {}
121
+ for f in result.get("findings", []):
122
+ rid = f.get("rule_id", "mcp.unknown")
123
+ rule_map.setdefault(rid, {
124
+ "id": rid,
125
+ "name": f.get("name", rid),
126
+ "shortDescription": {"text": f.get("name", rid)},
127
+ "defaultConfiguration": {"level": _to_sarif_level(
128
+ f.get("severity", "info"),
129
+ )},
130
+ })
131
+ results.append({
132
+ "ruleId": rid,
133
+ "level": _to_sarif_level(f.get("severity", "info")),
134
+ "message": {"text": f.get("description", "")},
135
+ "locations": [{
136
+ "physicalLocation": {
137
+ "artifactLocation": {"uri": str(path)},
138
+ "region": {"startLine": 1},
139
+ },
140
+ "logicalLocations": [{
141
+ "name": f.get("location", ""),
142
+ }],
143
+ }],
144
+ })
145
+ runs.append({
146
+ "tool": {
147
+ "driver": {
148
+ "name": "patchops-mcp-guard",
149
+ "version": "2.1.0",
150
+ "informationUri": "https://patchguard.ai",
151
+ "rules": list(rule_map.values()),
152
+ },
153
+ },
154
+ "results": results,
155
+ })
156
+ return {
157
+ "$schema": "https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json",
158
+ "version": "2.1.0",
159
+ "runs": runs,
160
+ }
161
+
162
+
163
+ def _to_sarif_level(sev: str) -> str:
164
+ return {"critical": "error", "high": "error", "medium": "warning",
165
+ "low": "note", "info": "note"}.get(sev, "note")
166
+
167
+
168
+ @app.callback()
169
+ def main_cmd(
170
+ path: str = typer.Argument(
171
+ "", help="MCP config file or directory. Ignored with --watch.",
172
+ ),
173
+ recursive: bool = typer.Option(
174
+ False, "--recursive", "-r",
175
+ help="Recursively scan *.json / mcp.json under directory.",
176
+ ),
177
+ fmt: OutputFormat = typer.Option(
178
+ OutputFormat.pretty, "--format", "-f",
179
+ help="Output format.",
180
+ ),
181
+ fail_on: str = typer.Option(
182
+ "", "--fail-on-severity",
183
+ help="Exit non-zero if finding at/above this severity "
184
+ "(critical/high/medium/low).",
185
+ ),
186
+ watch: bool = typer.Option(
187
+ False, "--watch", "-w",
188
+ help="Daemon mode: watch known MCP config paths and notify on change.",
189
+ ),
190
+ daemon: bool = typer.Option(
191
+ False, "--daemon", "-d",
192
+ help="With --watch: detach and run in background (Unix only).",
193
+ ),
194
+ remote: bool = typer.Option(
195
+ False, "--remote",
196
+ help="If the local engine is unavailable, analyze on the server "
197
+ "(secret values are masked before upload). Also PATCHOPS_MCP_REMOTE=1.",
198
+ ),
199
+ ) -> None:
200
+ """Audit MCP server config JSON file(s)."""
201
+ # --watch 모드는 PATH 인자 무시하고 daemon 실행
202
+ if watch:
203
+ from patchops_cli.commands.mcp_watch import (
204
+ detach_daemon,
205
+ run_watcher,
206
+ )
207
+ if daemon:
208
+ detach_daemon()
209
+ extra = [path] if path else []
210
+ raise typer.Exit(run_watcher(extra, remote=remote))
211
+
212
+ if not path:
213
+ typer.secho(
214
+ "Missing argument: path (or use --watch)", fg="red",
215
+ )
216
+ raise typer.Exit(2)
217
+ root = Path(path).expanduser()
218
+ files = _find_config_files(root, recursive)
219
+ if not files:
220
+ typer.secho(f"No MCP config found under {root}", fg="red")
221
+ raise typer.Exit(2)
222
+
223
+ all_results: list[tuple[Path, dict]] = []
224
+ worst_sev_rank = 99
225
+ for p in files:
226
+ cfg = _load_config(p)
227
+ if cfg is None:
228
+ typer.secho(f"⚠ skip (invalid JSON): {p}", fg="yellow")
229
+ continue
230
+ if not isinstance(cfg, dict) or "mcpServers" not in cfg:
231
+ typer.secho(f"⚠ skip (no mcpServers): {p}", fg="yellow")
232
+ continue
233
+ result = _audit_config(cfg, remote=remote)
234
+ all_results.append((p, result))
235
+ for f in result.get("findings", []):
236
+ rank = _SEV_ORDER.get(f.get("severity", "info"), 99)
237
+ worst_sev_rank = min(worst_sev_rank, rank)
238
+
239
+ if fmt == OutputFormat.pretty:
240
+ typer.secho(
241
+ f"🛡️ MCP 가드 v2.1 — scanned {len(all_results)} config(s)",
242
+ bold=True,
243
+ )
244
+ for p, r in all_results:
245
+ _print_pretty(p, r)
246
+ elif fmt == OutputFormat.json:
247
+ typer.echo(json.dumps(
248
+ [{"path": str(p), **r} for p, r in all_results],
249
+ indent=2, ensure_ascii=False, default=str,
250
+ ))
251
+ elif fmt == OutputFormat.sarif:
252
+ merged_runs = []
253
+ for p, r in all_results:
254
+ sarif = _to_sarif(p, r)
255
+ merged_runs.extend(sarif["runs"])
256
+ typer.echo(json.dumps({
257
+ "$schema": "https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json",
258
+ "version": "2.1.0",
259
+ "runs": merged_runs,
260
+ }, indent=2, default=str))
261
+
262
+ if fail_on:
263
+ fail_rank = _SEV_ORDER.get(fail_on.lower(), 99)
264
+ if worst_sev_rank <= fail_rank:
265
+ typer.secho(
266
+ f"\n✗ findings at or above '{fail_on}' — failing",
267
+ fg="red", bold=True,
268
+ )
269
+ raise typer.Exit(1)
270
+
271
+ sys.exit(0)
@@ -0,0 +1,248 @@
1
+ """patchops mcp-audit --watch : 백그라운드 자동 감시 daemon.
2
+
3
+ ### 감시 대상 (기본)
4
+ - ~/.claude/claude_desktop_config.json
5
+ - macOS: ~/Library/Application Support/Claude/claude_desktop_config.json
6
+ - ~/.cursor/mcp.json
7
+ - macOS: ~/Library/Application Support/Cursor/User/globalStorage/
8
+ - ~/.continue/config.json (continue.dev)
9
+ - ./.mcp.json (프로젝트 로컬)
10
+
11
+ ### 동작
12
+ 1. watchdog 로 파일 변경 감지 (create / modify)
13
+ 2. 변경된 파일 즉시 감사
14
+ 3. 결과를 OS 알림으로 (plyer) + 터미널 로그
15
+ 4. --daemon 모드면 detach, 아니면 foreground
16
+
17
+ ### 배포
18
+ `patchops mcp-audit --watch` 한 번만 실행 → 상주
19
+ `patchops mcp-audit --watch --daemon` 으로 백그라운드
20
+ """
21
+ from __future__ import annotations
22
+
23
+ import json
24
+ import os
25
+ import sys
26
+ import time
27
+ from pathlib import Path
28
+
29
+ WATCH_PATHS_DEFAULT: list[str] = [
30
+ "~/.claude/claude_desktop_config.json",
31
+ "~/Library/Application Support/Claude/claude_desktop_config.json",
32
+ "~/.cursor/mcp.json",
33
+ "~/Library/Application Support/Cursor/User/globalStorage",
34
+ "~/.continue/config.json",
35
+ "~/.config/Claude/claude_desktop_config.json", # Linux
36
+ ]
37
+
38
+
39
+ def _resolve_watch_targets(extra: list[str]) -> list[Path]:
40
+ """실제 존재하는 대상만. 디렉토리도 재귀 감시 가능."""
41
+ out: list[Path] = []
42
+ for p in WATCH_PATHS_DEFAULT + extra:
43
+ pp = Path(p).expanduser()
44
+ if pp.exists():
45
+ out.append(pp)
46
+ # 추가: 현재 프로젝트 ./.mcp.json
47
+ cwd_mcp = Path.cwd() / ".mcp.json"
48
+ if cwd_mcp.exists():
49
+ out.append(cwd_mcp)
50
+ return out
51
+
52
+
53
+ def _audit_path(path: Path, remote: bool = False) -> dict:
54
+ """파일 한 개 감사. 로컬 엔진이 없으면 remote 를 켰을 때만 서버로 (비밀값 가림, ISSUE-042)."""
55
+ try:
56
+ with path.open("r", encoding="utf-8") as f:
57
+ cfg = json.load(f)
58
+ except (json.JSONDecodeError, OSError) as e:
59
+ return {"error": f"{type(e).__name__}: {e}"}
60
+ if not isinstance(cfg, dict) or "mcpServers" not in cfg:
61
+ return {"skip": "no mcpServers"}
62
+ try:
63
+ from app.services.mcp_guard_orchestrator import audit_mcp_config
64
+ return audit_mcp_config(cfg)
65
+ except ImportError:
66
+ from patchops_cli.mcp_remote import LOCAL_ENGINE_MISSING, audit_remote, remote_enabled
67
+
68
+ if not remote_enabled(remote):
69
+ return {"error": LOCAL_ENGINE_MISSING}
70
+ try:
71
+ return audit_remote(cfg, timeout=30.0)
72
+ except Exception as e:
73
+ return {"error": f"API: {e}"}
74
+
75
+
76
+ def _notify(title: str, message: str, urgent: bool = False) -> None:
77
+ """OS 알림 (plyer) + 터미널."""
78
+ try:
79
+ from plyer import notification
80
+ notification.notify(
81
+ title=title[:80], message=message[:200],
82
+ app_name="PatchOps MCP Guard",
83
+ timeout=10 if not urgent else 30,
84
+ )
85
+ except Exception:
86
+ # plyer fallback: stderr 로 고정
87
+ pass
88
+ icon = "🚨" if urgent else "🛡️"
89
+ print(f"\n{icon} {title}\n {message}\n", flush=True)
90
+
91
+
92
+ def _summarize_findings(result: dict) -> tuple[str, str, bool]:
93
+ """(title, message, urgent) 3tuple."""
94
+ if "error" in result:
95
+ return ("MCP 감사 실패", result["error"], False)
96
+ if "skip" in result:
97
+ return ("", "", False)
98
+ n = result.get("n_findings", 0)
99
+ if n == 0:
100
+ return ("✓ MCP 안전", "새 MCP config 안전", False)
101
+ fs = result.get("findings", [])
102
+ crit = sum(1 for f in fs if f.get("severity") == "critical")
103
+ high = sum(1 for f in fs if f.get("severity") == "high")
104
+ top_names = [
105
+ f.get("rule_id", "?")[:40]
106
+ for f in fs[:3]
107
+ ]
108
+ urgent = crit > 0 or high > 0
109
+ title = (
110
+ f"⚠️ MCP 위험 {n}건 (critical {crit} / high {high})"
111
+ if urgent
112
+ else f"ℹ️ MCP 경고 {n}건"
113
+ )
114
+ msg = ", ".join(top_names)
115
+ return (title, msg, urgent)
116
+
117
+
118
+ def run_watcher(extra_paths: list[str], interval: int = 1, remote: bool = False) -> int:
119
+ """메인 watcher 루프 — watchdog 설치 없으면 polling fallback."""
120
+ targets = _resolve_watch_targets(extra_paths)
121
+ if not targets:
122
+ print("⚠️ 감시 대상 파일 0. ~/.claude/... 또는 ~/.cursor/... "
123
+ "존재하는지 확인하세요.")
124
+ return 1
125
+
126
+ print(f"🛡️ MCP 가드 daemon 시작 — 감시 {len(targets)} 개")
127
+ for p in targets:
128
+ print(f" • {p}")
129
+ print(" Ctrl+C 로 종료.\n", flush=True)
130
+
131
+ # 초기 1회 스캔
132
+ for p in targets:
133
+ if p.is_file():
134
+ result = _audit_path(p, remote)
135
+ title, msg, urgent = _summarize_findings(result)
136
+ if title:
137
+ _notify(f"[초기] {title}", f"{p.name}: {msg}", urgent)
138
+
139
+ # watchdog 우선, 없으면 polling
140
+ try:
141
+ from watchdog.events import FileSystemEventHandler
142
+ from watchdog.observers import Observer
143
+ except ImportError:
144
+ return _polling_loop(targets, interval, remote)
145
+
146
+ class _Handler(FileSystemEventHandler):
147
+ def __init__(self):
148
+ self._last_audit: dict[str, float] = {}
149
+
150
+ def _maybe_scan(self, path_str: str):
151
+ # Debounce: 같은 파일 연속 이벤트 1.5초 내 skip
152
+ now = time.time()
153
+ prev = self._last_audit.get(path_str, 0)
154
+ if now - prev < 1.5:
155
+ return
156
+ self._last_audit[path_str] = now
157
+ p = Path(path_str)
158
+ if not p.exists() or not p.is_file():
159
+ return
160
+ # json 만 감사 (또는 mcp 관련 이름)
161
+ if not (p.suffix == ".json"
162
+ or "mcp" in p.name.lower()
163
+ or "claude" in p.name.lower()):
164
+ return
165
+ print(f"[{time.strftime('%H:%M:%S')}] 변경 감지: {p}", flush=True)
166
+ result = _audit_path(p, remote)
167
+ title, msg, urgent = _summarize_findings(result)
168
+ if title:
169
+ _notify(title, f"{p.name}: {msg}", urgent)
170
+
171
+ def on_modified(self, event):
172
+ if not event.is_directory:
173
+ self._maybe_scan(event.src_path)
174
+
175
+ def on_created(self, event):
176
+ if not event.is_directory:
177
+ self._maybe_scan(event.src_path)
178
+
179
+ observer = Observer()
180
+ handler = _Handler()
181
+ watched_dirs: set[str] = set()
182
+ for p in targets:
183
+ parent = str(p.parent if p.is_file() else p)
184
+ if parent in watched_dirs:
185
+ continue
186
+ watched_dirs.add(parent)
187
+ observer.schedule(handler, parent, recursive=False)
188
+ observer.start()
189
+ try:
190
+ while True:
191
+ time.sleep(1)
192
+ except KeyboardInterrupt:
193
+ print("\n🛡️ daemon 종료.", flush=True)
194
+ observer.stop()
195
+ observer.join()
196
+ return 0
197
+
198
+
199
+ def _polling_loop(targets: list[Path], interval: int, remote: bool = False) -> int:
200
+ """watchdog 없을 때 fallback — mtime polling."""
201
+ last_mtime: dict[Path, float] = {}
202
+ for p in targets:
203
+ if p.is_file():
204
+ last_mtime[p] = p.stat().st_mtime
205
+ try:
206
+ while True:
207
+ for p in targets:
208
+ if not p.exists() or not p.is_file():
209
+ continue
210
+ m = p.stat().st_mtime
211
+ prev = last_mtime.get(p)
212
+ if prev is None:
213
+ last_mtime[p] = m
214
+ continue
215
+ if m != prev:
216
+ last_mtime[p] = m
217
+ print(f"[{time.strftime('%H:%M:%S')}] 변경: {p}")
218
+ result = _audit_path(p, remote)
219
+ title, msg, urgent = _summarize_findings(result)
220
+ if title:
221
+ _notify(title, f"{p.name}: {msg}", urgent)
222
+ time.sleep(interval)
223
+ except KeyboardInterrupt:
224
+ print("\n🛡️ daemon 종료.")
225
+ return 0
226
+
227
+
228
+ def detach_daemon() -> None:
229
+ """Unix 유일 — fork 로 백그라운드 실행."""
230
+ if sys.platform == "win32":
231
+ print("⚠️ Windows 에서 --daemon 미지원. 포그라운드로 실행합니다.")
232
+ return
233
+ try:
234
+ pid = os.fork()
235
+ except OSError as e:
236
+ print(f"⚠️ fork 실패: {e}. 포그라운드 실행.")
237
+ return
238
+ if pid > 0:
239
+ print(f"🛡️ daemon 백그라운드 실행 중 (pid={pid})")
240
+ sys.exit(0)
241
+ os.setsid()
242
+
243
+
244
+ __all__ = [
245
+ "WATCH_PATHS_DEFAULT",
246
+ "detach_daemon",
247
+ "run_watcher",
248
+ ]