teaimforge 0.19.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.
teaimforge/walls.py ADDED
@@ -0,0 +1,337 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """Walls: what a role may not read or write, and the hook that enforces them.
3
+
4
+ The domain declares its walls (``Domain.walls``). This module answers two
5
+ questions, and records a ``wall_violation`` event whenever the answer is no:
6
+
7
+ * May this role read or write this path? (``path_denial``)
8
+ * May this role write items of this type through the CLI? (``item_denial``)
9
+
10
+ ``lane_guard_hook`` applies the path check to Claude Code tool calls: Read,
11
+ Write, Edit, MultiEdit, NotebookEdit, Glob, Grep, and the paths a Bash command
12
+ names.
13
+
14
+ Limits: a search (Glob, Grep) started above a walled folder is not blocked,
15
+ and a Bash command can reach a path without naming it. Agent definitions keep
16
+ each role's tools narrow; this is the backstop, and it logs every attempt.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import os
22
+ import re
23
+ import shlex
24
+ from collections.abc import Iterable, Iterator, Mapping, Sequence
25
+ from dataclasses import dataclass
26
+ from functools import lru_cache
27
+ from pathlib import Path
28
+ from typing import TYPE_CHECKING, Any
29
+
30
+ from .config import load_config
31
+ from .domain import ORCHESTRATOR, PLACEHOLDER, Domain, Wall, field_ref, names_item
32
+ from .errors import ExitCode, ForgeError
33
+ from .events import EventStore, Transaction
34
+ from .identity import HookDecision, Identity, pin_role
35
+ from .paths import Layout, find_root
36
+
37
+ if TYPE_CHECKING:
38
+ from .items import Item
39
+
40
+ READ, WRITE = "read", "write"
41
+ _ITEM_GROUP = r"(?P<item>[A-Z]+-\d{4,})"
42
+ _PATH_TOOLS = {
43
+ "Read": ("file_path", READ),
44
+ "Write": ("file_path", WRITE),
45
+ "Edit": ("file_path", WRITE),
46
+ "MultiEdit": ("file_path", WRITE),
47
+ "NotebookEdit": ("notebook_path", WRITE),
48
+ "Glob": ("path", READ),
49
+ "Grep": ("path", READ),
50
+ }
51
+
52
+
53
+ @dataclass(frozen=True)
54
+ class Denial:
55
+ """Which wall said no, to what, and why."""
56
+
57
+ wall: Wall
58
+ action: str
59
+ target: str
60
+
61
+ def message(self) -> str:
62
+ why = f": {self.wall.reason}" if self.wall.reason else ""
63
+ return f"wall {self.wall.name} denies {self.action} of {self.target}{why}"
64
+
65
+
66
+ @lru_cache(maxsize=256)
67
+ def _compile(pattern: str, state_dir: str) -> re.Pattern[str]:
68
+ text = pattern.replace("{state}", state_dir)
69
+ out = []
70
+ i = 0
71
+ while i < len(text):
72
+ if text.startswith("{item}", i):
73
+ out.append(_ITEM_GROUP)
74
+ i += len("{item}")
75
+ elif text.startswith("**", i):
76
+ out.append(".*")
77
+ i += 2
78
+ elif text[i] == "*":
79
+ out.append("[^/]*")
80
+ i += 1
81
+ else:
82
+ out.append(re.escape(text[i]))
83
+ i += 1
84
+ return re.compile("^" + "".join(out) + "$")
85
+
86
+
87
+ def _relative(layout: Layout, path: Path) -> str | None:
88
+ """``path`` relative to the repository root, or ``None`` if it is outside."""
89
+ try:
90
+ return path.resolve().relative_to(layout.root.resolve()).as_posix()
91
+ except ValueError:
92
+ return None
93
+
94
+
95
+ def _home_relative(path: Path) -> str | None:
96
+ try:
97
+ return "~/" + path.resolve().relative_to(Path.home().resolve()).as_posix()
98
+ except ValueError:
99
+ return None
100
+
101
+
102
+ def path_denial( # noqa: PLR0913 - who, what, where, and the log for item states
103
+ domain: Domain,
104
+ layout: Layout,
105
+ role: str | None,
106
+ *,
107
+ action: str,
108
+ path: Path,
109
+ events: Iterable[Mapping[str, Any]] = (),
110
+ ) -> Denial | None:
111
+ """The wall that stops ``role`` doing ``action`` on ``path``, if any."""
112
+ walls = [w for w in domain.all_walls if w.restricts(role)]
113
+ if not walls:
114
+ return None
115
+ rel = _relative(layout, path)
116
+ home = _home_relative(path)
117
+ folded: dict[str, Item] | None = None
118
+
119
+ def items() -> dict[str, Item]:
120
+ nonlocal folded
121
+ if folded is None:
122
+ from .items import fold # noqa: PLC0415 - items imports this module
123
+
124
+ folded = fold(events, domain)
125
+ return folded
126
+
127
+ for wall in walls:
128
+ patterns = wall.read if action == READ else wall.write
129
+ for pattern in patterns:
130
+ target = home if pattern.startswith("~/") else rel
131
+ if target is None:
132
+ continue
133
+ if names_item(pattern):
134
+ if any(
135
+ _compile(concrete, domain.state_dir).match(target)
136
+ for concrete in _per_item(domain, wall, pattern, items())
137
+ ):
138
+ return Denial(wall, action, target)
139
+ continue
140
+ match = _compile(pattern, domain.state_dir).match(target)
141
+ if not match:
142
+ continue
143
+ item = match.groupdict().get("item")
144
+ if item and wall.while_states:
145
+ found = items().get(item)
146
+ if found is None or found.state not in wall.while_states:
147
+ continue
148
+ return Denial(wall, action, target)
149
+ return None
150
+
151
+
152
+ def _per_item(domain: Domain, wall: Wall, pattern: str, items: Mapping[str, Item]) -> Iterator[str]:
153
+ """``pattern`` filled in for each live item the wall is about."""
154
+ for item in items.values():
155
+ if item.type not in wall.about or item.archived:
156
+ continue
157
+ if wall.while_states and item.state not in wall.while_states:
158
+ continue
159
+ parent = items.get(domain.parent_id(item.type, item.fields) or "")
160
+ concrete = _fill(pattern, item, parent)
161
+ if concrete is not None:
162
+ yield concrete
163
+
164
+
165
+ def _fill(pattern: str, item: Item, parent: Item | None) -> str | None:
166
+ """``pattern`` with this item's values, or ``None`` if one is missing or unsafe."""
167
+ out: list[str] = []
168
+ last = 0
169
+ for match in PLACEHOLDER.finditer(pattern):
170
+ name = match.group(1)
171
+ value: object
172
+ if name == "state":
173
+ value = match.group(0) # left for _compile
174
+ elif name == "item":
175
+ value = item.id
176
+ elif name == "parent":
177
+ value = parent.id if parent else None
178
+ else:
179
+ ref = field_ref(name)
180
+ source = (parent if ref and ref[0] else item) if ref else None
181
+ value = source.fields.get(ref[1]) if source and ref else None
182
+ value = _safe_value(value)
183
+ if not isinstance(value, str):
184
+ return None
185
+ out.append(pattern[last : match.start()])
186
+ out.append(value)
187
+ last = match.end()
188
+ out.append(pattern[last:])
189
+ return "".join(out)
190
+
191
+
192
+ def _safe_value(value: object) -> str | None:
193
+ """A field value usable in a path pattern: plain, relative, no globs."""
194
+ if not isinstance(value, str):
195
+ return None
196
+ text = value.rstrip("/")
197
+ parts = text.split("/")
198
+ if (
199
+ not text
200
+ or text.startswith(("/", "~"))
201
+ or ".." in parts
202
+ or "" in parts
203
+ or any(ch in "*{}\\" or ord(ch) < 32 for ch in text)
204
+ ):
205
+ return None
206
+ return text
207
+
208
+
209
+ def item_denial(domain: Domain, role: str | None, item_type: str, target: str) -> Denial | None:
210
+ """The wall that stops ``role`` writing an item of ``item_type``, if any."""
211
+ for wall in domain.all_walls:
212
+ if item_type in wall.item_types and wall.restricts(role):
213
+ return Denial(wall, WRITE, target)
214
+ return None
215
+
216
+
217
+ def violation_data(denial: Denial, agent_type: str | None = None) -> dict[str, Any]:
218
+ data: dict[str, Any] = {
219
+ "wall": denial.wall.name,
220
+ "action": denial.action,
221
+ "attempted": denial.target,
222
+ "denied": True,
223
+ }
224
+ if agent_type:
225
+ data["agent_type"] = agent_type
226
+ return data
227
+
228
+
229
+ def enforce_item_write(
230
+ tx: Transaction, domain: Domain, who: Identity, item_type: str, target: str
231
+ ) -> None:
232
+ """Inside a store transaction: record and refuse a walled item write."""
233
+ denial = item_denial(domain, who.role, item_type, target)
234
+ if denial is None:
235
+ return
236
+ tx.append("wall_violation", actor=who.role, session=who.session, data=violation_data(denial))
237
+ raise ForgeError(ExitCode.REFUSED, "wall", denial.message())
238
+
239
+
240
+ # ------------------------------------------------------------------ the hook
241
+
242
+
243
+ def _command_paths(command: str, cwd: Path) -> list[Path]:
244
+ """Paths a Bash command names, best effort."""
245
+ try:
246
+ lexer = shlex.shlex(command, posix=True, punctuation_chars=True)
247
+ lexer.whitespace_split = True
248
+ tokens = list(lexer)
249
+ except ValueError:
250
+ tokens = command.split()
251
+ paths = []
252
+ for token in tokens:
253
+ word = token.split("=", 1)[1] if re.match(r"^-{1,2}[\w-]+=", token) else token
254
+ if "/" in word or word.startswith(".") or "." in word:
255
+ expanded = Path(os.path.expanduser(word))
256
+ paths.append(expanded if expanded.is_absolute() else cwd / expanded)
257
+ return paths
258
+
259
+
260
+ def _targets(hook_input: Mapping[str, Any], cwd: Path) -> list[tuple[str, Path]]:
261
+ tool = hook_input.get("tool_name")
262
+ tool_input = hook_input.get("tool_input")
263
+ if not isinstance(tool_input, Mapping):
264
+ return []
265
+ if tool in _PATH_TOOLS:
266
+ key, action = _PATH_TOOLS[str(tool)]
267
+ value = tool_input.get(key)
268
+ if not isinstance(value, str) or not value:
269
+ return [(action, cwd)] if tool in {"Glob", "Grep"} else []
270
+ path = Path(os.path.expanduser(value))
271
+ return [(action, path if path.is_absolute() else cwd / path)]
272
+ if tool == "Bash" and isinstance(tool_input.get("command"), str):
273
+ named = _command_paths(tool_input["command"], cwd)
274
+ return [(a, p) for p in named for a in (READ, WRITE)]
275
+ return []
276
+
277
+
278
+ def lane_guard_hook(domain: Domain, hook_input: Mapping[str, Any]) -> HookDecision:
279
+ """Deny a tool call that crosses a wall, and record the attempt."""
280
+ cwd_text = hook_input.get("cwd")
281
+ cwd = Path(cwd_text) if isinstance(cwd_text, str) and cwd_text else Path.cwd()
282
+ try:
283
+ layout = find_root(domain, start=cwd)
284
+ except ForgeError:
285
+ return HookDecision() # not a project of this domain: nothing to guard
286
+ targets = _targets(hook_input, cwd)
287
+ if not targets:
288
+ return HookDecision()
289
+ role = pin_role(domain, hook_input)
290
+ store = EventStore(layout, domain)
291
+ events: Sequence[Mapping[str, Any]] = list(store.events())
292
+ for action, path in targets:
293
+ denial = path_denial(domain, layout, role, action=action, path=path, events=events)
294
+ if denial is None:
295
+ continue
296
+ agent_type = hook_input.get("agent_type")
297
+ session = hook_input.get("session_id")
298
+ store.append(
299
+ "wall_violation",
300
+ actor=role or ORCHESTRATOR,
301
+ session=session if isinstance(session, str) and session else "hook",
302
+ data=violation_data(denial, agent_type if isinstance(agent_type, str) else None),
303
+ )
304
+ return HookDecision("deny", denial.message())
305
+ too_large = _too_large(domain, layout, hook_input, cwd)
306
+ if too_large:
307
+ return HookDecision("deny", too_large)
308
+ return HookDecision()
309
+
310
+
311
+ def _too_large(
312
+ domain: Domain, layout: Layout, hook_input: Mapping[str, Any], cwd: Path
313
+ ) -> str | None:
314
+ """Why a Write into the state folder is refused for its size, if it is."""
315
+ tool_input = hook_input.get("tool_input") or {}
316
+ if hook_input.get("tool_name") != "Write" or not isinstance(tool_input, Mapping):
317
+ return None
318
+ target, content = tool_input.get("file_path"), tool_input.get("content")
319
+ if not isinstance(target, str) or not isinstance(content, str):
320
+ return None
321
+ path = Path(target) if Path(target).is_absolute() else cwd / target
322
+ try:
323
+ path.resolve().relative_to(layout.state.resolve())
324
+ except ValueError:
325
+ return None
326
+ try:
327
+ limits = load_config(layout, domain).data.get("limits") or {}
328
+ except ForgeError:
329
+ limits = {}
330
+ cap = int(limits.get("state_file_mb", 5))
331
+ size = len(content.encode("utf-8"))
332
+ if size <= cap * 1024 * 1024:
333
+ return None
334
+ return (
335
+ f"{target} would be {size / 1024 / 1024:.1f} MB, over limits.state_file_mb ({cap}) "
336
+ f"for {domain.state_dir}/; a file that large is content: put it in the product repository"
337
+ )