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,395 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """Gates: decisions only the operator can make.
3
+
4
+ A role opens a gate (``gate_opened``); the operator rules on it once
5
+ (``gate_ruled``). A desk-only gate cannot be ruled from a remote channel. Which
6
+ gates are desk-only is the domain's baseline plus whatever ``config.yaml``
7
+ ``notify.desk_only`` adds; a project can add to the list but never remove from
8
+ it.
9
+
10
+ Gate IDs are ``<ITEM-ID>:<KIND>:<n>`` for a gate on an item and ``<KIND>:<n>``
11
+ for a project gate, with ``n`` counting from 1 per item and kind.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import re
17
+ from collections.abc import Iterable, Mapping, Sequence
18
+ from dataclasses import dataclass, field
19
+ from datetime import UTC, date, datetime
20
+ from typing import Any
21
+
22
+ from .domain import OPERATOR, Domain, GateKind
23
+ from .errors import ExitCode, ForgeError
24
+ from .events import EventStore
25
+ from .identity import Identity
26
+ from .items import Item, fold, parse_id, refuse_archived
27
+ from .paths import Layout
28
+
29
+ LOCAL_CHANNELS = ("tui", "console")
30
+ REMOTE_CHANNELS = ("claude-app", "slack", "ntfy", "forge")
31
+ CHANNELS = LOCAL_CHANNELS + REMOTE_CHANNELS
32
+ MAX_SUMMARY = 200
33
+ MAX_NOTE = 2000
34
+
35
+ _GATE_ID = re.compile(r"^(?:([A-Z]+-\d{4,}):)?([A-Z][A-Z0-9_]*):(\d+)$")
36
+
37
+
38
+ @dataclass(frozen=True)
39
+ class Gate:
40
+ """A gate as the log describes it."""
41
+
42
+ id: str
43
+ kind: str
44
+ item: str | None
45
+ summary: str
46
+ options: tuple[str, ...]
47
+ desk_only: bool
48
+ opened: str # event timestamp
49
+ ruling: Mapping[str, Any] | None = None
50
+
51
+ @property
52
+ def is_open(self) -> bool:
53
+ return self.ruling is None
54
+
55
+ def status(self) -> str:
56
+ """``open`` or ``ruled <ruling>``."""
57
+ return "open" if self.ruling is None else f"ruled {self.ruling.get('ruling')}"
58
+
59
+ def as_dict(self) -> dict[str, Any]:
60
+ return {
61
+ "id": self.id,
62
+ "kind": self.kind,
63
+ "item": self.item,
64
+ "summary": self.summary,
65
+ "options": list(self.options),
66
+ "desk_only": self.desk_only,
67
+ "opened": self.opened,
68
+ "status": "open" if self.ruling is None else "ruled",
69
+ "ruling": dict(self.ruling) if self.ruling is not None else None,
70
+ }
71
+
72
+
73
+ def parse_gate_id(gate_id: str) -> tuple[str | None, str, int]:
74
+ """``(item, kind, n)``; USAGE error if malformed."""
75
+ match = _GATE_ID.match(gate_id)
76
+ if not match:
77
+ raise ForgeError(
78
+ ExitCode.USAGE,
79
+ "invalid_gate_id",
80
+ f"{gate_id!r} is not a gate ID like FEAT-0001:G1:1 or CHARTER:1",
81
+ )
82
+ return match.group(1), match.group(2), int(match.group(3))
83
+
84
+
85
+ def fold_gates(events: Iterable[Mapping[str, Any]]) -> dict[str, Gate]:
86
+ """Every gate, from the log. A second ruling on a gate is ignored."""
87
+ gates: dict[str, Gate] = {}
88
+ for event in events:
89
+ data = event.get("data", {})
90
+ if event["type"] == "gate_opened" and "gate" in data:
91
+ gates[data["gate"]] = Gate(
92
+ id=data["gate"],
93
+ kind=data.get("kind", ""),
94
+ item=event.get("item"),
95
+ summary=data.get("summary", ""),
96
+ options=tuple(data.get("options", [])),
97
+ desk_only=bool(data.get("desk_only", True)),
98
+ opened=event["ts"],
99
+ )
100
+ elif event["type"] == "gate_ruled" and data.get("gate") in gates:
101
+ gate = gates[data["gate"]]
102
+ if gate.ruling is None:
103
+ gates[gate.id] = Gate(**{**gate.__dict__, "ruling": dict(data)})
104
+ return gates
105
+
106
+
107
+ def desk_only_entries(domain: Domain, config: Mapping[str, Any]) -> tuple[str, ...]:
108
+ """The domain's baseline plus the project's additions (``KIND`` or ``KIND-severity``)."""
109
+ extra = (config.get("notify") or {}).get("desk_only") or []
110
+ return tuple(dict.fromkeys((*domain.desk_only, *extra)))
111
+
112
+
113
+ def is_desk_only(
114
+ entries: Sequence[str], kind: str, item: Item | None, item_types: Sequence[str] = ()
115
+ ) -> bool:
116
+ """Whether a gate of ``kind`` on ``item`` must be ruled at the desk.
117
+
118
+ Every gate on an item of a type in ``item_types`` is desk-only.
119
+ """
120
+ if kind in entries or (item is not None and item.type in item_types):
121
+ return True
122
+ severity = item.fields.get("severity") if item is not None else None
123
+ return severity is not None and f"{kind}-{severity}" in entries
124
+
125
+
126
+ def _text(value: str | None, name: str, limit: int, *, required: bool) -> str | None:
127
+ if value is None or not value.strip():
128
+ if required:
129
+ raise ForgeError(ExitCode.USAGE, f"{name}_required", f"--{name} is required here")
130
+ return None
131
+ text = value.strip()
132
+ if len(text) > limit:
133
+ raise ForgeError(ExitCode.USAGE, f"invalid_{name}", f"--{name} is 1-{limit} characters")
134
+ return text
135
+
136
+
137
+ @dataclass
138
+ class Gates:
139
+ """Open, rule and list gates as one pinned identity."""
140
+
141
+ layout: Layout
142
+ domain: Domain
143
+ identity: Identity | None = None
144
+ config: Mapping[str, Any] = field(default_factory=dict)
145
+
146
+ def __post_init__(self) -> None:
147
+ self.store = EventStore(self.layout, self.domain)
148
+
149
+ def all(self) -> dict[str, Gate]:
150
+ return fold_gates(self.store.events())
151
+
152
+ def get(self, gate_id: str) -> Gate:
153
+ parse_gate_id(gate_id)
154
+ gate = self.all().get(gate_id)
155
+ if gate is None:
156
+ raise ForgeError(ExitCode.NOT_FOUND, "gate_not_found", f"no gate {gate_id}")
157
+ return gate
158
+
159
+ def _who(self) -> Identity:
160
+ if self.identity is None:
161
+ raise ForgeError(ExitCode.INTERNAL, "no_identity", "gate writes need an identity")
162
+ return self.identity
163
+
164
+ def _kind(self, name: str) -> GateKind:
165
+ for kind in self.domain.gate_kinds:
166
+ if kind.name == name:
167
+ return kind
168
+ known = ", ".join(k.name for k in self.domain.gate_kinds)
169
+ raise ForgeError(ExitCode.USAGE, "unknown_gate_kind", f"{name!r} is not a gate ({known})")
170
+
171
+ def open(
172
+ self,
173
+ kind_name: str,
174
+ item_id: str | None,
175
+ summary: str,
176
+ options: Sequence[str] = (),
177
+ ) -> Gate:
178
+ """Write ``gate_opened``. One open gate per item and kind at a time."""
179
+ who = self._who()
180
+ kind = self._kind(kind_name)
181
+ text = _text(summary, "summary", MAX_SUMMARY, required=True)
182
+ if kind.project and item_id is not None:
183
+ raise ForgeError(
184
+ ExitCode.USAGE, "project_gate", f"{kind.name} is a project gate; give no item"
185
+ )
186
+ if not kind.project and item_id is None:
187
+ raise ForgeError(ExitCode.USAGE, "item_required", f"{kind.name} is opened on an item")
188
+ with self.store.transaction() as tx:
189
+ events = list(tx.events())
190
+ item: Item | None = None
191
+ if item_id is not None:
192
+ parse_id(item_id)
193
+ item = fold(events, self.domain).get(item_id)
194
+ if item is None:
195
+ raise ForgeError(ExitCode.NOT_FOUND, "item_not_found", f"no item {item_id}")
196
+ refuse_archived(item)
197
+ if kind.item_types and item.type not in kind.item_types:
198
+ raise ForgeError(
199
+ ExitCode.USAGE,
200
+ "wrong_item_type",
201
+ f"{kind.name} is for {', '.join(kind.item_types)} items; "
202
+ f"{item.label()} is a {item.type}",
203
+ )
204
+ same = [
205
+ g for g in fold_gates(events).values() if g.kind == kind.name and g.item == item_id
206
+ ]
207
+ still_open = [g for g in same if g.is_open]
208
+ if still_open:
209
+ raise ForgeError(
210
+ ExitCode.CONFLICT,
211
+ "gate_already_open",
212
+ f"{still_open[0].id} is still waiting for a ruling",
213
+ )
214
+ n = len(same) + 1
215
+ gate_id = f"{item_id}:{kind.name}:{n}" if item_id else f"{kind.name}:{n}"
216
+ desk = is_desk_only(
217
+ desk_only_entries(self.domain, self.config),
218
+ kind.name,
219
+ item,
220
+ self.domain.desk_only_item_types,
221
+ )
222
+ clean = [o.strip() for o in options if o.strip()]
223
+ event = tx.append(
224
+ "gate_opened",
225
+ actor=who.role,
226
+ session=who.session,
227
+ data={
228
+ "gate": gate_id,
229
+ "kind": kind.name,
230
+ "summary": text,
231
+ "options": clean,
232
+ "desk_only": desk,
233
+ },
234
+ item=item_id,
235
+ title=item.title if item else None,
236
+ )
237
+ return Gate(
238
+ id=gate_id,
239
+ kind=kind.name,
240
+ item=item_id,
241
+ summary=str(text),
242
+ options=tuple(clean),
243
+ desk_only=desk,
244
+ opened=event["ts"],
245
+ )
246
+
247
+ def rule( # noqa: PLR0913 - each argument is one field of the ruling
248
+ self,
249
+ gate_id: str,
250
+ ruling: str,
251
+ *,
252
+ channel: str,
253
+ target: str | None = None,
254
+ note: str | None = None,
255
+ review_by: str | None = None,
256
+ party: str | None = None,
257
+ today: date | None = None,
258
+ ) -> Gate:
259
+ """Write ``gate_ruled`` (CONTRACT §7.2). Only the operator; only once."""
260
+ who = self._who()
261
+ if who.role != OPERATOR:
262
+ raise ForgeError(
263
+ ExitCode.REFUSED,
264
+ "operator_only",
265
+ f"only the operator rules on gates; this call runs as {who.role}",
266
+ )
267
+ if channel not in CHANNELS:
268
+ raise ForgeError(
269
+ ExitCode.USAGE, "invalid_channel", f"channel is one of {', '.join(CHANNELS)}"
270
+ )
271
+ with self.store.transaction() as tx:
272
+ events = list(tx.events())
273
+ parse_gate_id(gate_id)
274
+ gate = fold_gates(events).get(gate_id)
275
+ if gate is None:
276
+ raise ForgeError(ExitCode.NOT_FOUND, "gate_not_found", f"no gate {gate_id}")
277
+ if not gate.is_open:
278
+ raise ForgeError(
279
+ ExitCode.CONFLICT,
280
+ "already_ruled",
281
+ f"{gate_id} was {gate.status()}; open a new {gate.kind} gate to decide again",
282
+ )
283
+ kind = self._kind(gate.kind)
284
+ data = self._ruling(
285
+ kind,
286
+ gate,
287
+ ruling=ruling,
288
+ channel=channel,
289
+ target=target,
290
+ note=note,
291
+ review_by=review_by,
292
+ party=party,
293
+ today=today,
294
+ )
295
+ tx.append(
296
+ "gate_ruled",
297
+ actor=who.role,
298
+ session=who.session,
299
+ data=data,
300
+ item=gate.item,
301
+ title=_item_title(events, gate.item, self.domain),
302
+ )
303
+ return Gate(**{**gate.__dict__, "ruling": data})
304
+
305
+ def _ruling( # noqa: PLR0913 - validates one ruling's fields together
306
+ self,
307
+ kind: GateKind,
308
+ gate: Gate,
309
+ *,
310
+ ruling: str,
311
+ channel: str,
312
+ target: str | None,
313
+ note: str | None,
314
+ review_by: str | None,
315
+ party: str | None,
316
+ today: date | None,
317
+ ) -> dict[str, Any]:
318
+ if ruling not in kind.rulings:
319
+ raise ForgeError(
320
+ ExitCode.USAGE,
321
+ "invalid_ruling",
322
+ f"{kind.name} takes {', '.join(kind.rulings)}; got {ruling!r}",
323
+ )
324
+ if gate.desk_only and channel in REMOTE_CHANNELS:
325
+ raise ForgeError(
326
+ ExitCode.REFUSED,
327
+ "desk_only",
328
+ f"{gate.id} must be ruled at your desk (tui or console), not from {channel}",
329
+ )
330
+ if target is not None and not (ruling == "revise" and kind.revise_targets):
331
+ raise ForgeError(
332
+ ExitCode.USAGE, "target_not_allowed", f"{kind.name} {ruling} takes no --target"
333
+ )
334
+ if ruling == "revise" and kind.revise_targets:
335
+ if target is None:
336
+ raise ForgeError(
337
+ ExitCode.USAGE,
338
+ "target_required",
339
+ f"revise on {kind.name} needs --target ({', '.join(kind.revise_targets)})",
340
+ )
341
+ if target not in kind.revise_targets:
342
+ raise ForgeError(
343
+ ExitCode.USAGE,
344
+ "invalid_target",
345
+ f"{kind.name} targets are {', '.join(kind.revise_targets)}",
346
+ )
347
+ text = _text(note, "note", MAX_NOTE, required=ruling in kind.note_required)
348
+ if review_by is not None and ruling not in kind.review_required:
349
+ raise ForgeError(
350
+ ExitCode.USAGE,
351
+ "review_by_not_allowed",
352
+ f"{kind.name} {ruling} takes no --review-by",
353
+ )
354
+ if party is not None and ruling not in kind.party_required:
355
+ raise ForgeError(
356
+ ExitCode.USAGE, "party_not_allowed", f"{kind.name} {ruling} takes no --party"
357
+ )
358
+ who = _text(party, "party", MAX_SUMMARY, required=ruling in kind.party_required)
359
+ data: dict[str, Any] = {"gate": gate.id, "ruling": ruling, "channel": channel}
360
+ if target is not None:
361
+ data["revise_target"] = target
362
+ if text is not None:
363
+ data["note"] = text
364
+ if who is not None:
365
+ data["party"] = who
366
+ if ruling in kind.review_required:
367
+ data["review_by"] = _review_date(review_by, today or datetime.now(UTC).date())
368
+ return data
369
+
370
+
371
+ def _review_date(review_by: str | None, today: date) -> str:
372
+ if review_by is None:
373
+ raise ForgeError(
374
+ ExitCode.USAGE, "review_by_required", "this ruling needs --review-by YYYY-MM-DD"
375
+ )
376
+ try:
377
+ until = date.fromisoformat(review_by)
378
+ except ValueError:
379
+ raise ForgeError(
380
+ ExitCode.USAGE, "invalid_review_by", f"--review-by {review_by!r} is not YYYY-MM-DD"
381
+ ) from None
382
+ if until <= today:
383
+ raise ForgeError(
384
+ ExitCode.USAGE, "invalid_review_by", f"--review-by must be after today ({today})"
385
+ )
386
+ return until.isoformat()
387
+
388
+
389
+ def _item_title(
390
+ events: Iterable[Mapping[str, Any]], item_id: str | None, domain: Domain
391
+ ) -> str | None:
392
+ if item_id is None:
393
+ return None
394
+ item = fold(events, domain).get(item_id)
395
+ return item.title if item else None
@@ -0,0 +1,259 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """Pinned role identity (CORE.md principle 4).
3
+
4
+ A role never says who it is. Identity comes from two places only:
5
+
6
+ * Claude Code's hook input. Inside a subagent, ``agent_type`` names the agent
7
+ definition, and therefore the role. In the main session it is absent, and the
8
+ caller is the orchestrator. :func:`pin_role` turns hook input into a role.
9
+ * The ``<PREFIX>_ROLE`` environment variable, which the ``identity`` hook sets
10
+ on every CLI call it lets through. :func:`resolve` reads it.
11
+
12
+ :func:`identity_hook` is the PreToolUse decision that connects the two. It
13
+ rewrites a plain CLI call so it runs with the pinned role, and refuses any tool
14
+ call that tries to set the role itself.
15
+
16
+ Limit: the hook sees the command text, not the processes it starts. A script
17
+ that calls the CLI indirectly (``bash -c``, a file the role wrote) inherits the
18
+ session's environment rather than a pinned role. The signed identity on MCP
19
+ calls is the authoritative channel; this one stops accidents and casual
20
+ overrides.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import json
26
+ import os
27
+ import re
28
+ import shlex
29
+ from collections.abc import Callable, Mapping
30
+ from dataclasses import dataclass
31
+ from pathlib import PurePosixPath
32
+ from typing import Any, Literal
33
+
34
+ from .domain import OPERATOR, ORCHESTRATOR, Domain
35
+ from .errors import ExitCode, ForgeError
36
+
37
+ #: Session used when a role is set by hand in a terminal.
38
+ CONSOLE_SESSION = "console"
39
+
40
+ _SESSION = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$")
41
+ _ITEM = re.compile(r"^[A-Z]+-\d{4,}$")
42
+ _ASSIGNMENT = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*=")
43
+ _PYTHON = re.compile(r"^python(\d+(\.\d+)?)?$")
44
+ _OPERATORS = frozenset({";", "&", "&&", "|", "||", "|&", "(", ")", ";;", "&>", ">", ">>", "<"})
45
+ _WRAPPERS = frozenset({"env", "exec", "command", "nohup", "time", "nice", "sudo", "xargs"})
46
+ _RUNNERS = frozenset({"uv", "uvx", "pipx", "poetry", "pdm", "hatch"})
47
+ _FLAGS_WITH_VALUE = frozenset({"-u", "-g", "-n", "-C", "-S"}) # env -u X, sudo -u U, nice -n N
48
+
49
+
50
+ @dataclass(frozen=True)
51
+ class Identity:
52
+ """Who is writing: the pinned role, the session, and optionally the item."""
53
+
54
+ role: str
55
+ session: str
56
+ item: str | None = None
57
+
58
+
59
+ def resolve(domain: Domain, environ: Mapping[str, str] | None = None) -> Identity:
60
+ """Read the pinned identity from the environment, or refuse (exit 2)."""
61
+ env = os.environ if environ is None else environ
62
+ role_var = domain.env("ROLE")
63
+ role = env.get(role_var, "")
64
+ if not role:
65
+ raise ForgeError(
66
+ ExitCode.REFUSED,
67
+ "missing_identity",
68
+ f"{role_var} is not set. Commands that write run under a role pinned by the "
69
+ "identity hook; in a terminal, set it to 'operator'.",
70
+ )
71
+ if role not in domain.all_roles:
72
+ raise ForgeError(
73
+ ExitCode.REFUSED,
74
+ "unknown_role",
75
+ f"{role_var}={role!r} is not a role. Roles: {', '.join(domain.all_roles)}.",
76
+ )
77
+ session = env.get(domain.env("SESSION"), "") or CONSOLE_SESSION
78
+ if not _SESSION.match(session):
79
+ raise ForgeError(
80
+ ExitCode.REFUSED, "invalid_session", f"{domain.env('SESSION')}={session!r}"
81
+ )
82
+ item = env.get(domain.env("ITEM"), "") or None
83
+ if item is not None and not _ITEM.match(item):
84
+ raise ForgeError(ExitCode.USAGE, "invalid_item", f"{domain.env('ITEM')}={item!r}")
85
+ return Identity(role=role, session=session, item=item)
86
+
87
+
88
+ def pin_role(domain: Domain, hook_input: Mapping[str, Any]) -> str | None:
89
+ """The role a tool call runs as, or ``None`` if the caller is not a team role.
90
+
91
+ No ``agent_type`` means the main session: the orchestrator. A subagent is
92
+ its role when its definition is named for one, bare (``developer``) or under
93
+ this plugin (``codersforge:developer``). Other agents (``Explore``, another
94
+ plugin's) get no role, so they can read but not write. ``operator`` is never
95
+ pinned from an agent definition.
96
+ """
97
+ agent_type = hook_input.get("agent_type")
98
+ if agent_type is None or agent_type == "":
99
+ return ORCHESTRATOR
100
+ if not isinstance(agent_type, str):
101
+ return None
102
+ name = agent_type.removeprefix(f"{domain.name}:")
103
+ if ":" in name or name == OPERATOR:
104
+ return None
105
+ return name if name in domain.all_roles else None
106
+
107
+
108
+ @dataclass(frozen=True)
109
+ class HookDecision:
110
+ """A PreToolUse answer. ``decision=None`` means no opinion: normal permissions apply."""
111
+
112
+ decision: Literal["allow", "deny"] | None = None
113
+ reason: str | None = None
114
+ updated_input: Mapping[str, Any] | None = None
115
+
116
+ def output(self) -> dict[str, Any] | None:
117
+ """The hook's stdout document, or ``None`` to print nothing."""
118
+ if self.decision is None:
119
+ return None
120
+ specific: dict[str, Any] = {
121
+ "hookEventName": "PreToolUse",
122
+ "permissionDecision": self.decision,
123
+ }
124
+ if self.reason:
125
+ specific["permissionDecisionReason"] = self.reason
126
+ if self.updated_input is not None:
127
+ specific["updatedInput"] = dict(self.updated_input)
128
+ return {"hookSpecificOutput": specific}
129
+
130
+
131
+ PASS = HookDecision()
132
+
133
+
134
+ def _segments(tokens: list[str]) -> list[list[str]]:
135
+ segments: list[list[str]] = [[]]
136
+ for token in tokens:
137
+ if token in _OPERATORS:
138
+ segments.append([])
139
+ else:
140
+ segments[-1].append(token)
141
+ return [s for s in segments if s]
142
+
143
+
144
+ def _program(segment: list[str]) -> list[str]:
145
+ """The segment from its program onward, skipping assignments and wrappers."""
146
+ i = 0
147
+ while i < len(segment):
148
+ token = segment[i]
149
+ base = PurePosixPath(token).name
150
+ if token in _FLAGS_WITH_VALUE:
151
+ i += 2
152
+ elif _ASSIGNMENT.match(token) or token.startswith("-") or base in _WRAPPERS:
153
+ i += 1
154
+ elif base in _RUNNERS and i + 1 < len(segment) and segment[i + 1] in {"run", "exec"}:
155
+ i += 2
156
+ else:
157
+ return segment[i:]
158
+ return []
159
+
160
+
161
+ def _cli_args(program: list[str], cli: str) -> list[str] | None:
162
+ """If ``program`` runs the CLI, the command that does so; else ``None``."""
163
+ if not program:
164
+ return None
165
+ if PurePosixPath(program[0]).name == cli:
166
+ return program
167
+ if (
168
+ _PYTHON.match(PurePosixPath(program[0]).name)
169
+ and len(program) >= 3
170
+ and program[1] == "-m"
171
+ and program[2] == cli
172
+ ):
173
+ return program
174
+ return None
175
+
176
+
177
+ def identity_hook(domain: Domain, hook_input: Mapping[str, Any]) -> HookDecision:
178
+ """Decide one PreToolUse call (CONTRACT §9).
179
+
180
+ * Any Bash command that mentions the role or session variable is denied.
181
+ * A Bash command that is only a CLI call is rewritten to run with the pinned
182
+ role and session, and allowed.
183
+ * A Bash command that runs the CLI inside a pipeline, chain, subshell or
184
+ expansion is denied, with a reason that says how to run it.
185
+ * Everything else passes with no opinion.
186
+ """
187
+ if hook_input.get("tool_name") != "Bash":
188
+ return PASS
189
+ tool_input = hook_input.get("tool_input")
190
+ command = tool_input.get("command") if isinstance(tool_input, Mapping) else None
191
+ if not isinstance(command, str):
192
+ return PASS
193
+ cli = domain.name
194
+ guarded = (domain.env("ROLE"), domain.env("SESSION"))
195
+ if any(var in command for var in guarded):
196
+ return HookDecision(
197
+ "deny",
198
+ f"{' and '.join(guarded)} are set by the identity hook. A tool call may not "
199
+ "set, unset or read them.",
200
+ )
201
+ alone = (
202
+ f"Run {cli} as a command on its own (no pipes, chains, redirects, subshells, "
203
+ "variables or line breaks) so the identity hook can pin your role."
204
+ )
205
+ lexer = shlex.shlex(command, posix=True, punctuation_chars=True)
206
+ lexer.whitespace_split = True
207
+ try:
208
+ tokens = list(lexer)
209
+ except ValueError:
210
+ if re.search(rf"(^|[^\w.-]){re.escape(cli)}($|[^\w.-])", command):
211
+ return HookDecision("deny", alone)
212
+ return PASS
213
+ segments = _segments(tokens)
214
+ invoking = [s for s in segments if _cli_args(_program(s), cli) is not None]
215
+ if not invoking:
216
+ return PASS
217
+ simple = (
218
+ len(segments) == 1
219
+ and len(segments[0]) == len(tokens)
220
+ and _cli_args(segments[0], cli) is not None
221
+ and not any(ch in command for ch in "$`\n\r")
222
+ )
223
+ if not simple:
224
+ return HookDecision("deny", alone)
225
+ session = hook_input.get("session_id")
226
+ if not (isinstance(session, str) and _SESSION.match(session)):
227
+ return HookDecision("deny", "The identity hook could not read a valid session ID.")
228
+ role = pin_role(domain, hook_input)
229
+ pinned = ["env", "-u", guarded[0], "-u", guarded[1]]
230
+ if role is not None:
231
+ pinned.append(f"{guarded[0]}={role}")
232
+ pinned.append(f"{guarded[1]}={session}")
233
+ updated = dict(tool_input) if isinstance(tool_input, Mapping) else {}
234
+ updated["command"] = shlex.join(pinned + tokens)
235
+ who = f"as {role}" if role is not None else "with no role (read-only)"
236
+ return HookDecision("allow", f"{cli} runs {who}", updated)
237
+
238
+
239
+ def run_hook(
240
+ domain: Domain,
241
+ stdin_text: str,
242
+ hook: Callable[[Domain, Mapping[str, Any]], HookDecision] | None = None,
243
+ ) -> str:
244
+ """Hook entry point: hook input JSON in, hook output JSON (or nothing) out.
245
+
246
+ ``hook`` defaults to :func:`identity_hook`. Fails closed: input that cannot
247
+ be read, or a hook that fails, is denied rather than let through.
248
+ """
249
+ try:
250
+ hook_input = json.loads(stdin_text)
251
+ if not isinstance(hook_input, dict):
252
+ raise TypeError("hook input is not an object")
253
+ decision = (hook or identity_hook)(domain, hook_input)
254
+ except (ValueError, TypeError) as exc:
255
+ decision = HookDecision("deny", f"The hook could not read its input: {exc}")
256
+ except ForgeError as err:
257
+ decision = HookDecision("deny", f"The hook failed closed: {err.reason}: {err.detail}")
258
+ doc = decision.output()
259
+ return "" if doc is None else json.dumps(doc, sort_keys=True, separators=(",", ":"))