agent-certify 0.5.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,227 @@
1
+ # agent-certify — Structural verification of multiagent systems
2
+ # Copyright 2026 Cognitive Engineering (Switzerland)
3
+ # SPDX-License-Identifier: Apache-2.0
4
+ """Cursor Agent Trace parser.
5
+
6
+ `Agent Trace <https://agent-trace.dev>`_ (github.com/cursor/agent-trace) is an
7
+ open format for recording **which code was written by AI and which by
8
+ humans**. Each trace record (schema v1) is::
9
+
10
+ {"version": "1.0", "id": "<uuid>", "timestamp": "<RFC 3339>",
11
+ "vcs": {"type": "git", "revision": "<sha>"},
12
+ "tool": {"name": "cursor", "version": "..."},
13
+ "files": [{"path": "src/app.py",
14
+ "conversations": [{"url": "...",
15
+ "contributor": {"type": "ai", "model_id": "..."},
16
+ "ranges": [{"start_line": 1, "end_line": 40,
17
+ "contributor": {...}}]}]}]}
18
+
19
+ with ``contributor.type`` one of ``human``, ``ai``, ``mixed``, ``unknown``.
20
+ Records are stored as JSONL, by default in ``.agent-trace/traces.jsonl``.
21
+
22
+ The format records authorship of code, **not tool calls**: there are no
23
+ tools, MCP servers or sub-agents in it. The graph built from it is therefore a
24
+ provenance graph:
25
+
26
+ * the producing tool (``tool.name``, e.g. ``cursor``) is the orchestrator;
27
+ * each AI contributor becomes ``agent:<model_id>`` (type = model), linked
28
+ from the orchestrator; ``human`` stays ``human``; ``mixed`` / ``unknown``
29
+ become ``agent:mixed`` / ``agent:unknown``;
30
+ * each file becomes ``file:<path>``, linked from every contributor that wrote
31
+ lines in it, edge weight = lines written.
32
+
33
+ Contributors and files only link to each other through the orchestrator's
34
+ models, so the graph is bipartite and has no triangles: **FI is always 1.0**
35
+ for these graphs. Blast radius (which files a model touched), policy rules
36
+ (``agent:* → file:infra/*``) and anomaly detection (a new model, new files)
37
+ are the useful views.
38
+ """
39
+ from __future__ import annotations
40
+
41
+ import logging
42
+ from collections.abc import Iterator
43
+ from pathlib import Path
44
+
45
+ from agent_certify.graph import AgentGraph
46
+ from agent_certify.parser.base import BaseParser, decode_json
47
+ from agent_certify.paths import MAX_DOCUMENT_BYTES, MAX_FILES, iter_lines, walk
48
+
49
+ logger = logging.getLogger(__name__)
50
+
51
+ TRACE_DIR = ".agent-trace"
52
+ TRACE_FILE = "traces.jsonl"
53
+ TRACE_SUFFIX = ".agent-trace"
54
+ _SKIP_DIRS = {".git", "node_modules", ".venv", "venv", "__pycache__", ".tox", "dist", "build"}
55
+
56
+
57
+ def looks_like_trace_record(rec) -> bool:
58
+ return isinstance(rec, dict) and "files" in rec and "version" in rec
59
+
60
+
61
+ class CursorTraceParser(BaseParser):
62
+ """Parse Cursor Agent Trace records into an AgentGraph.
63
+
64
+ ``parse`` accepts a ``traces.jsonl`` file, a ``.agent-trace`` directory,
65
+ or a ``*.agent-trace`` file holding one record, a list of records, or
66
+ JSONL. All records in it are combined into one graph. Records or fields
67
+ that are missing or malformed are skipped; ``skipped`` counts them.
68
+ """
69
+
70
+ def __init__(self):
71
+ self.skipped = 0
72
+
73
+ def parse(self, path: str) -> AgentGraph:
74
+ p = self._expand(path)
75
+ files = self._trace_files(p)
76
+ if not files:
77
+ raise FileNotFoundError(p)
78
+ self.skipped = 0
79
+ g = AgentGraph(session_id=None, project=self._project_name(p))
80
+ ids, stamps, editor = [], [], None
81
+ for f in files:
82
+ for rec in self._records(f):
83
+ tool = rec.get("tool") if isinstance(rec.get("tool"), dict) else {}
84
+ editor = editor or self._add_editor(g, tool)
85
+ self._add_record(g, rec, editor)
86
+ ids.append(str(rec.get("id") or ""))
87
+ if isinstance(rec.get("timestamp"), str):
88
+ stamps.append(rec["timestamp"])
89
+ if editor is None:
90
+ self._add_editor(g, {})
91
+ g.session_id = ids[0] if len(ids) == 1 and ids[0] else (files[0].stem if len(files) == 1 else p.name)
92
+ if stamps:
93
+ g.started_at, g.ended_at = min(stamps), max(stamps)
94
+ g.total_messages = len(ids)
95
+ g.skipped_records = self.skipped
96
+ if self.skipped:
97
+ logger.warning("%s: skipped %d malformed trace record(s) or field(s)", p, self.skipped)
98
+ return g
99
+
100
+ def parse_directory(self, directory: str) -> list[AgentGraph]:
101
+ return [self.parse(str(t)) for t in self.find_traces(directory)]
102
+
103
+ def find_traces(self, directory: str = ".") -> list[Path]:
104
+ """``.agent-trace`` directories and ``*.agent-trace`` files under ``directory``.
105
+
106
+ Skips ``.git``, ``node_modules``, virtualenvs and build output, walks at
107
+ most :data:`~agent_certify.paths.MAX_DEPTH` levels down and returns at
108
+ most :data:`~agent_certify.paths.MAX_FILES` traces.
109
+ """
110
+ root = self._expand(directory)
111
+ found = []
112
+ for here, dirnames, filenames in walk(root, skip=_SKIP_DIRS):
113
+ if here.name == TRACE_DIR:
114
+ found.append(here)
115
+ dirnames[:] = []
116
+ else:
117
+ found += [here / f for f in filenames if f.endswith(TRACE_SUFFIX)]
118
+ if len(found) >= MAX_FILES:
119
+ logger.warning("%s: stopped after %d traces", root, MAX_FILES)
120
+ break
121
+ return sorted(found[:MAX_FILES])
122
+
123
+ # ------------------------------------------------------------ internals
124
+ @staticmethod
125
+ def _trace_files(p: Path) -> list[Path]:
126
+ if p.is_file():
127
+ return [p]
128
+ if p.is_dir():
129
+ inner = p / TRACE_DIR if (p / TRACE_DIR).is_dir() else p
130
+ return sorted(inner.glob("*.jsonl")) + sorted(inner.glob(f"*{TRACE_SUFFIX}"))
131
+ return []
132
+
133
+ @staticmethod
134
+ def _project_name(p: Path) -> str:
135
+ p = p.resolve()
136
+ while p.name in (TRACE_DIR, TRACE_FILE) or p.suffix in (TRACE_SUFFIX, ".jsonl"):
137
+ p = p.parent
138
+ return p.name
139
+
140
+ def _records(self, path: Path) -> Iterator[dict]:
141
+ """Trace records from one file.
142
+
143
+ A file of at most :data:`~agent_certify.paths.MAX_DOCUMENT_BYTES` is first
144
+ tried as one JSON document (an object, or an array of records); otherwise,
145
+ and for larger files, it is streamed as JSONL with the line-size limit.
146
+ """
147
+ whole = None
148
+ if path.stat().st_size <= MAX_DOCUMENT_BYTES:
149
+ text = path.read_text(encoding="utf-8", errors="replace").strip()
150
+ if not text:
151
+ return
152
+ whole = decode_json(text)
153
+ if whole is not None:
154
+ candidates = whole if isinstance(whole, list) else [whole]
155
+ for rec in candidates:
156
+ yield from self._accept(rec)
157
+ return
158
+ for _, line in iter_lines(path):
159
+ if line is None:
160
+ self.skipped += 1
161
+ elif line.strip():
162
+ yield from self._accept(decode_json(line))
163
+
164
+ def _accept(self, rec) -> Iterator[dict]:
165
+ if looks_like_trace_record(rec) and isinstance(rec["files"], list):
166
+ yield rec
167
+ else:
168
+ self.skipped += 1
169
+
170
+ @staticmethod
171
+ def _add_editor(g: AgentGraph, tool: dict) -> str:
172
+ name = str(tool.get("name") or "agent-trace")
173
+ nid = name.lower()
174
+ g.add_node(nid, "orchestrator", name, **({"version": tool["version"]} if tool.get("version") else {}))
175
+ return nid
176
+
177
+ def _contributor_node(self, g: AgentGraph, contributor, editor: str) -> str:
178
+ contributor = contributor if isinstance(contributor, dict) else {}
179
+ ctype = contributor.get("type") if contributor.get("type") in ("human", "ai", "mixed", "unknown") \
180
+ else "unknown"
181
+ if ctype == "human":
182
+ g.add_node("human", "human", "human")
183
+ return "human"
184
+ model = str(contributor.get("model_id") or "") if ctype == "ai" else ctype
185
+ model = model or "ai"
186
+ nid = f"agent:{model}"
187
+ if nid not in g.nodes:
188
+ g.add_node(nid, "agent", model, agentType=model, contributor_type=ctype)
189
+ g.add_call(editor, nid)
190
+ return nid
191
+
192
+ def _add_record(self, g: AgentGraph, rec: dict, editor: str) -> None:
193
+ for entry in rec["files"]:
194
+ if not isinstance(entry, dict) or not isinstance(entry.get("path"), str):
195
+ self.skipped += 1
196
+ continue
197
+ fid = f"file:{entry['path']}"
198
+ g.add_node(fid, "file", entry["path"])
199
+ convs = entry.get("conversations") if isinstance(entry.get("conversations"), list) else []
200
+ for conv in convs:
201
+ if not isinstance(conv, dict):
202
+ self.skipped += 1
203
+ continue
204
+ default = conv.get("contributor")
205
+ ranges = conv.get("ranges") if isinstance(conv.get("ranges"), list) else []
206
+ if not ranges:
207
+ # A conversation with no ranges still says who touched the file.
208
+ self._write(g, self._contributor_node(g, default, editor), fid, 0)
209
+ for r in ranges:
210
+ if not isinstance(r, dict):
211
+ self.skipped += 1
212
+ continue
213
+ who = self._contributor_node(g, r.get("contributor") or default, editor)
214
+ self._write(g, who, fid, self._lines(r))
215
+ g.total_tool_calls += 1
216
+
217
+ @staticmethod
218
+ def _lines(r: dict) -> int:
219
+ try:
220
+ return max(0, int(r["end_line"]) - int(r["start_line"]) + 1)
221
+ except (KeyError, TypeError, ValueError):
222
+ return 0
223
+
224
+ @staticmethod
225
+ def _write(g: AgentGraph, who: str, fid: str, lines: int) -> None:
226
+ # Edge weight = lines written (at least 1 per contribution, so a link always counts).
227
+ g.add_call(who, fid, count=max(1, lines))
@@ -0,0 +1,240 @@
1
+ # agent-certify — Structural verification of multiagent systems
2
+ # Copyright 2026 Cognitive Engineering (Switzerland)
3
+ # SPDX-License-Identifier: Apache-2.0
4
+ """MCP server logs parser.
5
+
6
+ Claude Code writes one JSONL log per MCP server and process start:
7
+
8
+ Windows: %LOCALAPPDATA%\\claude-cli-nodejs\\Cache\\<project>\\mcp-logs-<server>\\<timestamp>.jsonl
9
+ Linux: ~/.cache/claude-cli-nodejs/<project>/mcp-logs-<server>/<timestamp>.jsonl
10
+ macOS: ~/Library/Caches/claude-cli-nodejs/<project>/mcp-logs-<server>/<timestamp>.jsonl
11
+
12
+ Each record is ``{"timestamp", "sessionId", "cwd", "debug" | "error"}`` with a
13
+ free-text message. Tool calls show up as ``Calling MCP tool: <tool>``, and
14
+ failures as ``Tool '<tool>' failed after ...``. ``sessionId`` is the Claude
15
+ Code session id, so a log can be joined to that session's transcript.
16
+
17
+ The logs include calls Claude Code makes on its own (the IDE server's
18
+ ``getDiagnostics`` after an edit, for instance) that never appear as
19
+ ``tool_use`` blocks in the transcript. The logs do not say which agent made a
20
+ call, so every call is attributed to the orchestrator.
21
+
22
+ Tool nodes use Claude Code's naming, ``tool:mcp__<server>__<tool>``, and
23
+ :meth:`MCPLogsParser.enrich` reuses a transcript's existing node for the same
24
+ tool. Calls already present in the transcript are not counted twice.
25
+ """
26
+ from __future__ import annotations
27
+
28
+ import copy
29
+ import logging
30
+ import os
31
+ import re
32
+ import sys
33
+ from collections import defaultdict
34
+ from collections.abc import Iterator
35
+ from pathlib import Path
36
+
37
+ from agent_certify.graph import AgentGraph
38
+ from agent_certify.parser.base import BaseParser, decode_json
39
+ from agent_certify.parser.claude_code import ORCHESTRATOR, tool_id
40
+ from agent_certify.paths import MAX_FILES, iter_lines, walk
41
+
42
+ logger = logging.getLogger(__name__)
43
+
44
+ _CALL = re.compile(r"^Calling MCP tool: (?P<tool>\S+)")
45
+ _FAIL = re.compile(r"^Tool '(?P<tool>[^']+)' failed")
46
+ _LOG_DIR_PREFIX = "mcp-logs-"
47
+
48
+
49
+ def default_roots() -> list[Path]:
50
+ """Directories that may hold per-project MCP log folders on this platform."""
51
+ roots = []
52
+ if os.name == "nt":
53
+ local = os.environ.get("LOCALAPPDATA")
54
+ if local:
55
+ roots += [Path(local) / "claude-cli-nodejs" / "Cache", Path(local) / "claude-cli-nodejs"]
56
+ else:
57
+ xdg = os.environ.get("XDG_CACHE_HOME") or str(Path.home() / ".cache")
58
+ roots += [Path(xdg) / "claude-cli-nodejs"]
59
+ if sys.platform == "darwin":
60
+ roots += [Path.home() / "Library" / "Caches" / "claude-cli-nodejs"]
61
+ return roots
62
+
63
+
64
+ def project_key(project_path: str) -> str:
65
+ """Claude Code's folder name for a project: ``H:\\agent-certify`` -> ``H--agent-certify``."""
66
+ p = str(project_path).rstrip("\\/")
67
+ if re.fullmatch(r"[A-Za-z0-9-]+", p):
68
+ return p # already a folder name
69
+ return re.sub(r"[^A-Za-z0-9-]", "-", p)
70
+
71
+
72
+ def _norm(server: str) -> str:
73
+ return re.sub(r"[^a-z0-9]", "", server.lower())
74
+
75
+
76
+ class MCPLogsParser(BaseParser):
77
+ """Parse MCP server logs to extract tool call edges.
78
+
79
+ Usage::
80
+
81
+ mcp = MCPLogsParser()
82
+ mcp.find_logs("H:/agent-certify") # log files for one project
83
+ graph = ClaudeCodeParser().parse(session)
84
+ graph = mcp.enrich(graph) # adds that session's MCP calls
85
+
86
+ ``roots`` overrides where logs are searched for (tests, unusual installs).
87
+ """
88
+
89
+ def __init__(self, roots: list[str | os.PathLike] | None = None):
90
+ self.roots = [Path(r) for r in roots] if roots is not None else default_roots()
91
+ self.skipped_lines = 0
92
+ self.added_calls = 0
93
+
94
+ # ---------------------------------------------------------------- find
95
+ def find_logs(self, project_path: str | None = None) -> list[Path]:
96
+ """Find all MCP log files on the system, optionally for one project.
97
+
98
+ ``project_path`` may be the project's folder name (``H--agent-certify``)
99
+ or its path (``H:\\agent-certify``). Returns [] when there are none.
100
+ """
101
+ key = project_key(project_path) if project_path else None
102
+ found: set[Path] = set()
103
+ for root in self.roots:
104
+ if not root.is_dir():
105
+ continue
106
+ projects = [root / key] if key else [p for p in root.iterdir() if p.is_dir()]
107
+ for proj in projects:
108
+ if proj.is_dir():
109
+ found.update(proj.glob(f"{_LOG_DIR_PREFIX}*/*.jsonl"))
110
+ return sorted(found)
111
+
112
+ # --------------------------------------------------------------- parse
113
+ def parse(self, path: str) -> AgentGraph:
114
+ """Parse a single MCP log file into ``claude -> tool:mcp__<server>__<tool>`` edges."""
115
+ p = self._expand(path)
116
+ if not p.is_file():
117
+ raise FileNotFoundError(p)
118
+ self.skipped_lines = 0
119
+ server = self._server(p)
120
+ g = AgentGraph(session_id=None, project=p.parent.parent.name)
121
+ g.add_node(ORCHESTRATOR, "orchestrator", "claude")
122
+ sessions, stamps = set(), []
123
+ for ev in self._events(p, server):
124
+ sessions.add(ev["session"])
125
+ if ev["ts"]:
126
+ stamps.append(ev["ts"])
127
+ nid = tool_id(f"mcp__{server}__{ev['tool']}")
128
+ g.add_node(nid, "tool", f"mcp__{server}__{ev['tool']}", mcp_server=server, source="mcp-log")
129
+ if ev["kind"] == "call":
130
+ g.add_call(ORCHESTRATOR, nid)
131
+ g.total_tool_calls += 1
132
+ elif g.get_edge(ORCHESTRATOR, nid):
133
+ g.record_error(ORCHESTRATOR, nid)
134
+ sessions.discard(None)
135
+ g.skipped_records = self.skipped_lines
136
+ g.session_id = sessions.pop() if len(sessions) == 1 else p.stem
137
+ if stamps:
138
+ g.started_at, g.ended_at = min(stamps), max(stamps)
139
+ return g
140
+
141
+ def parse_directory(self, directory: str) -> list[AgentGraph]:
142
+ """One graph per log file under ``directory``."""
143
+ return [self.parse(str(f)) for f in self._log_files_under(self._expand(directory))]
144
+
145
+ # -------------------------------------------------------------- enrich
146
+ def enrich(self, graph: AgentGraph, mcp_log_dir: str | None = None) -> AgentGraph:
147
+ """Return a copy of ``graph`` with the MCP calls its session made.
148
+
149
+ Logs come from ``mcp_log_dir`` when given (a project's log folder, or
150
+ any folder above ``mcp-logs-*`` folders), otherwise from
151
+ :meth:`find_logs` for ``graph.project``. Only records whose
152
+ ``sessionId`` equals ``graph.session_id`` count. A tool the transcript
153
+ already shows keeps its node; only calls beyond the transcript's count
154
+ are added. ``added_calls`` holds how many were added.
155
+ """
156
+ if mcp_log_dir is not None:
157
+ files = self._log_files_under(self._expand(mcp_log_dir))
158
+ else:
159
+ files = self.find_logs(graph.project) if graph.project else []
160
+ calls: dict[tuple[str, str], int] = defaultdict(int)
161
+ errors: dict[tuple[str, str], int] = defaultdict(int)
162
+ for f in files:
163
+ server = self._server(f)
164
+ for ev in self._events(f, server):
165
+ if graph.session_id and ev["session"] != graph.session_id:
166
+ continue
167
+ (calls if ev["kind"] == "call" else errors)[(server, ev["tool"])] += 1
168
+
169
+ g = copy.deepcopy(graph)
170
+ self.added_calls = 0
171
+ if not calls:
172
+ return g
173
+ if ORCHESTRATOR not in g.nodes:
174
+ g.add_node(ORCHESTRATOR, "orchestrator", "claude")
175
+ for (server, tool), n in sorted(calls.items()):
176
+ nid = self._existing_node(g, server, tool) or tool_id(f"mcp__{server}__{tool}")
177
+ g.add_node(nid, "tool", nid.split(":", 1)[1], mcp_server=server, mcp_log_calls=n)
178
+ g.nodes[nid].metadata.setdefault("source", "mcp-log")
179
+ edge = g.get_edge(ORCHESTRATOR, nid)
180
+ extra = n - (edge.weight if edge else 0)
181
+ if extra > 0:
182
+ g.add_call(ORCHESTRATOR, nid, count=extra)
183
+ g.total_tool_calls += extra
184
+ self.added_calls += extra
185
+ known_errors = g.get_edge(ORCHESTRATOR, nid).errors if g.get_edge(ORCHESTRATOR, nid) else 0
186
+ for _ in range(max(0, errors.get((server, tool), 0) - known_errors)):
187
+ g.record_error(ORCHESTRATOR, nid)
188
+ return g
189
+
190
+ # ------------------------------------------------------------ internals
191
+ @staticmethod
192
+ def _log_files_under(root: Path) -> list[Path]:
193
+ """``mcp-logs-*/*.jsonl`` below ``root``, with the shared depth and file-count limits."""
194
+ found = []
195
+ for here, _dirs, filenames in walk(root):
196
+ if here.name.startswith(_LOG_DIR_PREFIX):
197
+ found += [here / f for f in filenames if f.endswith(".jsonl")]
198
+ if len(found) >= MAX_FILES:
199
+ break
200
+ return sorted(found[:MAX_FILES])
201
+
202
+ @staticmethod
203
+ def _server(path: Path) -> str:
204
+ name = path.parent.name
205
+ return name.removeprefix(_LOG_DIR_PREFIX) if name.startswith(_LOG_DIR_PREFIX) else "unknown"
206
+
207
+ @staticmethod
208
+ def _existing_node(g: AgentGraph, server: str, tool: str) -> str | None:
209
+ """A transcript node for the same MCP tool (server names are spelled differently in each)."""
210
+ want = _norm(server)
211
+ for nid, node in g.nodes.items():
212
+ parts = node.name.split("__")
213
+ if node.kind == "tool" and len(parts) == 3 and parts[0] == "mcp" \
214
+ and parts[2] == tool and _norm(parts[1]) == want:
215
+ return nid
216
+ return None
217
+
218
+ def _events(self, path: Path, server: str) -> Iterator[dict]:
219
+ """Tool-call and tool-failure events, skipping unreadable or oversized lines."""
220
+ for _, line in iter_lines(path):
221
+ if line is None:
222
+ self.skipped_lines += 1
223
+ continue
224
+ line = line.strip()
225
+ if not line:
226
+ continue
227
+ rec = decode_json(line)
228
+ if not isinstance(rec, dict):
229
+ self.skipped_lines += 1
230
+ continue
231
+ msg = rec.get("debug") or rec.get("error") or ""
232
+ if not isinstance(msg, str):
233
+ continue
234
+ m = _CALL.match(msg)
235
+ kind = "call"
236
+ if not m:
237
+ m, kind = _FAIL.match(msg), "error"
238
+ if m:
239
+ yield {"kind": kind, "tool": m.group("tool"), "session": rec.get("sessionId"),
240
+ "ts": rec.get("timestamp")}
agent_certify/paths.py ADDED
@@ -0,0 +1,128 @@
1
+ # agent-certify — Structural verification of multiagent systems
2
+ # Copyright 2026 Cognitive Engineering (Switzerland)
3
+ # SPDX-License-Identifier: Apache-2.0
4
+ """Path handling in one place: trusted CLI input, untrusted MCP input, state files.
5
+
6
+ Two kinds of input reach agent-certify:
7
+
8
+ * **Trusted** — arguments the user typed on the command line. :func:`expand_cli`
9
+ expands ``~`` and environment variables (``$HOME``, ``%USERPROFILE%``), as a
10
+ shell would.
11
+ * **Untrusted** — arguments an AI agent sends to the MCP server. :func:`confine`
12
+ expands ``~`` only (never environment variables, whose values could leak back
13
+ to the caller), resolves symlinks and ``..``, and accepts the result only if it
14
+ lies inside one of the allowed roots. Its errors never contain the path.
15
+
16
+ This module also holds the resource limits shared by the parsers, and creates
17
+ the ``.agent-certify/`` state directory with a ``.gitignore`` so that its
18
+ contents (session ids, project names) are not committed by accident.
19
+ """
20
+ from __future__ import annotations
21
+
22
+ import os
23
+ from collections.abc import Iterable, Iterator
24
+ from pathlib import Path
25
+
26
+ # ------------------------------------------------------------------ limits
27
+ MAX_DEPTH = 5 # directory levels walked below a scanned directory
28
+ MAX_FILES = 1000 # session / trace files read from one directory
29
+ MAX_LINE_BYTES = 10 * 1024 * 1024 # longer JSONL lines are skipped
30
+ MAX_DOCUMENT_BYTES = 50 * 1024 * 1024 # a whole-file JSON document (.agent-trace) larger than this is refused
31
+
32
+ STATE_DIR = Path(".agent-certify")
33
+ _STATE_GITIGNORE = ("# Created by agent-certify. These files hold session ids and project names;\n"
34
+ "# keep them out of version control.\n*\n")
35
+
36
+
37
+ class PathNotAllowed(ValueError):
38
+ """An untrusted path resolved outside every allowed root (the message never contains the path)."""
39
+
40
+ def __init__(self):
41
+ super().__init__("Path not allowed")
42
+
43
+
44
+ def expand_cli(raw: str | os.PathLike) -> Path:
45
+ """Expand ``~`` and environment variables in a path typed by the user."""
46
+ return Path(os.path.expandvars(os.path.expanduser(str(raw))))
47
+
48
+
49
+ def confine(raw: str | os.PathLike, allowed_roots: Iterable[str | os.PathLike], base: str | os.PathLike | None = None,
50
+ ) -> Path:
51
+ """Resolve an untrusted path and require it to lie inside one of ``allowed_roots``.
52
+
53
+ ``~`` is expanded; environment variables are not. A relative path is taken
54
+ relative to ``base`` (default: the working directory). Symlinks and ``..``
55
+ are resolved before the check, so neither can escape a root. Raises
56
+ :class:`PathNotAllowed` (whose message holds no path) otherwise.
57
+ """
58
+ text = str(raw)
59
+ if not text or "\x00" in text:
60
+ raise PathNotAllowed()
61
+ p = Path(os.path.expanduser(text))
62
+ if not p.is_absolute():
63
+ p = Path(base if base is not None else os.getcwd()) / p
64
+ try:
65
+ resolved = p.resolve()
66
+ except (OSError, RuntimeError): # e.g. a symlink loop
67
+ raise PathNotAllowed() from None
68
+ for root in allowed_roots:
69
+ try:
70
+ r = Path(root).resolve()
71
+ except (OSError, RuntimeError):
72
+ continue
73
+ if resolved == r or r in resolved.parents:
74
+ return resolved
75
+ raise PathNotAllowed()
76
+
77
+
78
+ def ensure_state_dir(path: str | os.PathLike) -> Path:
79
+ """Create the parent directory of ``path``; give an ``.agent-certify`` directory its ``.gitignore``."""
80
+ parent = Path(path).parent
81
+ parent.mkdir(parents=True, exist_ok=True)
82
+ if parent.name == STATE_DIR.name:
83
+ ignore = parent / ".gitignore"
84
+ if not ignore.exists():
85
+ try:
86
+ ignore.write_text(_STATE_GITIGNORE, encoding="utf-8")
87
+ except OSError:
88
+ pass # best effort: never fail a save over this
89
+ return parent
90
+
91
+
92
+ def iter_lines(path: str | os.PathLike, max_line: int = MAX_LINE_BYTES) -> Iterator[tuple[int, str | None]]:
93
+ """(line number, text) for each line; text is None for a line longer than ``max_line`` bytes.
94
+
95
+ Reads in bounded chunks, so a single huge line never has to fit in memory.
96
+ """
97
+ with open(path, "rb") as f:
98
+ lineno = 0
99
+ while True:
100
+ chunk = f.readline(max_line + 1)
101
+ if not chunk:
102
+ return
103
+ lineno += 1
104
+ if len(chunk) > max_line and not chunk.endswith(b"\n"):
105
+ while True: # drain the rest of the oversized line
106
+ rest = f.readline(1 << 20)
107
+ if not rest or rest.endswith(b"\n"):
108
+ break
109
+ yield lineno, None
110
+ continue
111
+ yield lineno, chunk.decode("utf-8", errors="replace")
112
+
113
+
114
+ def walk(root: str | os.PathLike, max_depth: int = MAX_DEPTH, skip: Iterable[str] = ()) -> Iterator[tuple[Path, list[str], list[str]]]:
115
+ """``os.walk`` limited to ``max_depth`` levels below ``root``, skipping directory names in ``skip``.
116
+
117
+ Yields (directory, subdirectory names, file names); like ``os.walk``, the
118
+ caller may prune the subdirectory list in place.
119
+ """
120
+ root = Path(root)
121
+ skip = set(skip)
122
+ base_depth = len(root.parts)
123
+ for dirpath, dirnames, filenames in os.walk(root):
124
+ here = Path(dirpath)
125
+ dirnames[:] = sorted(d for d in dirnames if d not in skip)
126
+ if len(here.parts) - base_depth >= max_depth:
127
+ dirnames[:] = []
128
+ yield here, dirnames, sorted(filenames)