codersforge 0.0.1__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.
Files changed (41) hide show
  1. codersforge/__init__.py +4 -0
  2. codersforge/__main__.py +8 -0
  3. codersforge/_core/CORE_VERSION +33 -0
  4. codersforge/_core/__init__.py +8 -0
  5. codersforge/_core/archive.py +319 -0
  6. codersforge/_core/backup.py +417 -0
  7. codersforge/_core/config.py +206 -0
  8. codersforge/_core/domain.py +382 -0
  9. codersforge/_core/errors.py +36 -0
  10. codersforge/_core/events.py +381 -0
  11. codersforge/_core/findings.py +265 -0
  12. codersforge/_core/gates.py +395 -0
  13. codersforge/_core/identity.py +259 -0
  14. codersforge/_core/index.py +262 -0
  15. codersforge/_core/items.py +513 -0
  16. codersforge/_core/ledger.py +194 -0
  17. codersforge/_core/lessons.py +142 -0
  18. codersforge/_core/messages.py +293 -0
  19. codersforge/_core/migrate.py +221 -0
  20. codersforge/_core/output.py +41 -0
  21. codersforge/_core/paths.py +62 -0
  22. codersforge/_core/py.typed +0 -0
  23. codersforge/_core/schema.py +113 -0
  24. codersforge/_core/ulid.py +36 -0
  25. codersforge/_core/upgrade.py +57 -0
  26. codersforge/_core/versions.py +20 -0
  27. codersforge/_core/views.py +67 -0
  28. codersforge/_core/walls.py +231 -0
  29. codersforge/_core/workflow.py +745 -0
  30. codersforge/_docs.py +33 -0
  31. codersforge/checks.py +94 -0
  32. codersforge/cli.py +865 -0
  33. codersforge/domain.py +270 -0
  34. codersforge/py.typed +0 -0
  35. codersforge/workflows.yaml +129 -0
  36. codersforge-0.0.1.dist-info/METADATA +81 -0
  37. codersforge-0.0.1.dist-info/RECORD +41 -0
  38. codersforge-0.0.1.dist-info/WHEEL +4 -0
  39. codersforge-0.0.1.dist-info/entry_points.txt +2 -0
  40. codersforge-0.0.1.dist-info/licenses/LICENSE +202 -0
  41. codersforge-0.0.1.dist-info/licenses/NOTICE +7 -0
@@ -0,0 +1,231 @@
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, Mapping, Sequence
25
+ from dataclasses import dataclass
26
+ from functools import lru_cache
27
+ from pathlib import Path
28
+ from typing import Any
29
+
30
+ from .domain import ORCHESTRATOR, Domain, Wall
31
+ from .errors import ExitCode, ForgeError
32
+ from .events import EventStore, Transaction
33
+ from .identity import HookDecision, Identity, pin_role
34
+ from .paths import Layout, find_root
35
+
36
+ READ, WRITE = "read", "write"
37
+ _ITEM_GROUP = r"(?P<item>[A-Z]+-\d{4,})"
38
+ _PATH_TOOLS = {
39
+ "Read": ("file_path", READ),
40
+ "Write": ("file_path", WRITE),
41
+ "Edit": ("file_path", WRITE),
42
+ "MultiEdit": ("file_path", WRITE),
43
+ "NotebookEdit": ("notebook_path", WRITE),
44
+ "Glob": ("path", READ),
45
+ "Grep": ("path", READ),
46
+ }
47
+
48
+
49
+ @dataclass(frozen=True)
50
+ class Denial:
51
+ """Which wall said no, to what, and why."""
52
+
53
+ wall: Wall
54
+ action: str
55
+ target: str
56
+
57
+ def message(self) -> str:
58
+ why = f": {self.wall.reason}" if self.wall.reason else ""
59
+ return f"wall {self.wall.name} denies {self.action} of {self.target}{why}"
60
+
61
+
62
+ @lru_cache(maxsize=256)
63
+ def _compile(pattern: str, state_dir: str) -> re.Pattern[str]:
64
+ text = pattern.replace("{state}", state_dir)
65
+ out = []
66
+ i = 0
67
+ while i < len(text):
68
+ if text.startswith("{item}", i):
69
+ out.append(_ITEM_GROUP)
70
+ i += len("{item}")
71
+ elif text.startswith("**", i):
72
+ out.append(".*")
73
+ i += 2
74
+ elif text[i] == "*":
75
+ out.append("[^/]*")
76
+ i += 1
77
+ else:
78
+ out.append(re.escape(text[i]))
79
+ i += 1
80
+ return re.compile("^" + "".join(out) + "$")
81
+
82
+
83
+ def _relative(layout: Layout, path: Path) -> str | None:
84
+ """``path`` relative to the repository root, or ``None`` if it is outside."""
85
+ try:
86
+ return path.resolve().relative_to(layout.root.resolve()).as_posix()
87
+ except ValueError:
88
+ return None
89
+
90
+
91
+ def _home_relative(path: Path) -> str | None:
92
+ try:
93
+ return "~/" + path.resolve().relative_to(Path.home().resolve()).as_posix()
94
+ except ValueError:
95
+ return None
96
+
97
+
98
+ def path_denial( # noqa: PLR0913 - who, what, where, and the log for item states
99
+ domain: Domain,
100
+ layout: Layout,
101
+ role: str | None,
102
+ *,
103
+ action: str,
104
+ path: Path,
105
+ events: Iterable[Mapping[str, Any]] = (),
106
+ ) -> Denial | None:
107
+ """The wall that stops ``role`` doing ``action`` on ``path``, if any."""
108
+ walls = [w for w in domain.walls if w.restricts(role)]
109
+ if not walls:
110
+ return None
111
+ rel = _relative(layout, path)
112
+ home = _home_relative(path)
113
+ states: dict[str, str] | None = None
114
+ for wall in walls:
115
+ patterns = wall.read if action == READ else wall.write
116
+ for pattern in patterns:
117
+ target = home if pattern.startswith("~/") else rel
118
+ if target is None:
119
+ continue
120
+ match = _compile(pattern, domain.state_dir).match(target)
121
+ if not match:
122
+ continue
123
+ item = match.groupdict().get("item")
124
+ if item and wall.while_states:
125
+ if states is None:
126
+ from .items import fold # noqa: PLC0415 - items imports this module
127
+
128
+ states = {i.id: i.state for i in fold(events, domain).values()}
129
+ if states.get(item) not in wall.while_states:
130
+ continue
131
+ return Denial(wall, action, target)
132
+ return None
133
+
134
+
135
+ def item_denial(domain: Domain, role: str | None, item_type: str, target: str) -> Denial | None:
136
+ """The wall that stops ``role`` writing an item of ``item_type``, if any."""
137
+ for wall in domain.walls:
138
+ if item_type in wall.item_types and wall.restricts(role):
139
+ return Denial(wall, WRITE, target)
140
+ return None
141
+
142
+
143
+ def violation_data(denial: Denial, agent_type: str | None = None) -> dict[str, Any]:
144
+ data: dict[str, Any] = {
145
+ "wall": denial.wall.name,
146
+ "action": denial.action,
147
+ "attempted": denial.target,
148
+ "denied": True,
149
+ }
150
+ if agent_type:
151
+ data["agent_type"] = agent_type
152
+ return data
153
+
154
+
155
+ def enforce_item_write(
156
+ tx: Transaction, domain: Domain, who: Identity, item_type: str, target: str
157
+ ) -> None:
158
+ """Inside a store transaction: record and refuse a walled item write."""
159
+ denial = item_denial(domain, who.role, item_type, target)
160
+ if denial is None:
161
+ return
162
+ tx.append("wall_violation", actor=who.role, session=who.session, data=violation_data(denial))
163
+ raise ForgeError(ExitCode.REFUSED, "wall", denial.message())
164
+
165
+
166
+ # ------------------------------------------------------------------ the hook
167
+
168
+
169
+ def _command_paths(command: str, cwd: Path) -> list[Path]:
170
+ """Paths a Bash command names, best effort."""
171
+ try:
172
+ lexer = shlex.shlex(command, posix=True, punctuation_chars=True)
173
+ lexer.whitespace_split = True
174
+ tokens = list(lexer)
175
+ except ValueError:
176
+ tokens = command.split()
177
+ paths = []
178
+ for token in tokens:
179
+ word = token.split("=", 1)[1] if re.match(r"^-{1,2}[\w-]+=", token) else token
180
+ if "/" in word or word.startswith(".") or "." in word:
181
+ expanded = Path(os.path.expanduser(word))
182
+ paths.append(expanded if expanded.is_absolute() else cwd / expanded)
183
+ return paths
184
+
185
+
186
+ def _targets(hook_input: Mapping[str, Any], cwd: Path) -> list[tuple[str, Path]]:
187
+ tool = hook_input.get("tool_name")
188
+ tool_input = hook_input.get("tool_input")
189
+ if not isinstance(tool_input, Mapping):
190
+ return []
191
+ if tool in _PATH_TOOLS:
192
+ key, action = _PATH_TOOLS[str(tool)]
193
+ value = tool_input.get(key)
194
+ if not isinstance(value, str) or not value:
195
+ return [(action, cwd)] if tool in {"Glob", "Grep"} else []
196
+ path = Path(os.path.expanduser(value))
197
+ return [(action, path if path.is_absolute() else cwd / path)]
198
+ if tool == "Bash" and isinstance(tool_input.get("command"), str):
199
+ named = _command_paths(tool_input["command"], cwd)
200
+ return [(a, p) for p in named for a in (READ, WRITE)]
201
+ return []
202
+
203
+
204
+ def lane_guard_hook(domain: Domain, hook_input: Mapping[str, Any]) -> HookDecision:
205
+ """Deny a tool call that crosses a wall, and record the attempt."""
206
+ cwd_text = hook_input.get("cwd")
207
+ cwd = Path(cwd_text) if isinstance(cwd_text, str) and cwd_text else Path.cwd()
208
+ try:
209
+ layout = find_root(domain, start=cwd)
210
+ except ForgeError:
211
+ return HookDecision() # not a project of this domain: nothing to guard
212
+ targets = _targets(hook_input, cwd)
213
+ if not targets:
214
+ return HookDecision()
215
+ role = pin_role(domain, hook_input)
216
+ store = EventStore(layout, domain)
217
+ events: Sequence[Mapping[str, Any]] = list(store.events())
218
+ for action, path in targets:
219
+ denial = path_denial(domain, layout, role, action=action, path=path, events=events)
220
+ if denial is None:
221
+ continue
222
+ agent_type = hook_input.get("agent_type")
223
+ session = hook_input.get("session_id")
224
+ store.append(
225
+ "wall_violation",
226
+ actor=role or ORCHESTRATOR,
227
+ session=session if isinstance(session, str) and session else "hook",
228
+ data=violation_data(denial, agent_type if isinstance(agent_type, str) else None),
229
+ )
230
+ return HookDecision("deny", denial.message())
231
+ return HookDecision()