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,381 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """The append-only, hash-chained event log (FEAT-0002).
3
+
4
+ Rules (core contract, event log):
5
+
6
+ - One JSON object per line, UTF-8, ``\\n`` endings, no blank lines.
7
+ - Lines are never modified or removed; corrections are new events.
8
+ - Each line is at most 64 KiB.
9
+ - Writers hold an exclusive lock on ``.lock``, flush and fsync before releasing.
10
+ - ``prev`` is ``sha256:`` + the SHA-256 of the previous line's exact bytes
11
+ (without its newline); for the first event, of the empty string.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import fcntl
17
+ import hashlib
18
+ import json
19
+ import os
20
+ import re
21
+ import time
22
+ from collections.abc import Iterator, Mapping
23
+ from contextlib import contextmanager
24
+ from dataclasses import dataclass
25
+ from datetime import UTC, datetime
26
+ from pathlib import Path
27
+ from typing import Any
28
+
29
+ from .domain import Domain
30
+ from .errors import ExitCode, ForgeError
31
+ from .paths import Layout
32
+ from .ulid import is_ulid, new_ulid
33
+ from .upgrade import upgrade
34
+ from .versions import EVENT_SCHEMA_VERSION
35
+
36
+ MAX_LINE_BYTES = 64 * 1024
37
+ DEFAULT_LOCK_TIMEOUT = 10.0
38
+
39
+ CORE_EVENT_TYPES: tuple[str, ...] = (
40
+ "created",
41
+ "renamed",
42
+ "state",
43
+ "assigned",
44
+ "gate_opened",
45
+ "gate_ruled",
46
+ "finding",
47
+ "finding_resolved",
48
+ "lesson",
49
+ "msg",
50
+ "msg_state",
51
+ "check_run",
52
+ "sync",
53
+ "budget",
54
+ "wall_violation",
55
+ "agent_start",
56
+ "agent_stop",
57
+ "tool_use",
58
+ "migrated",
59
+ "backed_up",
60
+ "restored",
61
+ )
62
+
63
+ GENESIS_PREV = "sha256:" + hashlib.sha256(b"").hexdigest()
64
+
65
+ _TS = re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$")
66
+ _ROLE = re.compile(r"^[a-z][a-z-]*$")
67
+ _ITEM = re.compile(r"^[A-Z]+-\d{4,}$")
68
+ _PREV = re.compile(r"^sha256:[0-9a-f]{64}$")
69
+ _REQUIRED = ("v", "id", "ts", "type", "actor", "session", "data", "prev")
70
+ _OPTIONAL = ("item", "title")
71
+
72
+
73
+ def utc_timestamp(now: datetime | None = None) -> str:
74
+ """RFC 3339 UTC with millisecond precision and ``Z``."""
75
+ moment = (now or datetime.now(UTC)).astimezone(UTC)
76
+ return moment.strftime("%Y-%m-%dT%H:%M:%S.") + f"{moment.microsecond // 1000:03d}Z"
77
+
78
+
79
+ def line_hash(line: bytes) -> str:
80
+ """The ``prev`` value for the event after ``line``."""
81
+ return "sha256:" + hashlib.sha256(line).hexdigest()
82
+
83
+
84
+ def serialize(event: Mapping[str, Any]) -> bytes:
85
+ """Canonical one-line encoding: sorted keys, no extra whitespace, UTF-8."""
86
+ text = json.dumps(event, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
87
+ return text.encode("utf-8")
88
+
89
+
90
+ def check_envelope(
91
+ event: Mapping[str, Any],
92
+ known_types: tuple[str, ...] | None = None,
93
+ known_roles: tuple[str, ...] | None = None,
94
+ ) -> None:
95
+ """Raise ``ValueError`` describing the first problem with ``event``.
96
+
97
+ ``known_types`` is enforced for writes; readers pass ``None`` and accept
98
+ unknown types (the contract says readers ignore types they do not know).
99
+ """
100
+ missing = [k for k in _REQUIRED if k not in event]
101
+ if missing:
102
+ raise ValueError(f"missing field {missing[0]!r}")
103
+ extra = sorted(set(event) - set(_REQUIRED) - set(_OPTIONAL))
104
+ if extra:
105
+ raise ValueError(f"unknown field {extra[0]!r}")
106
+ if event["v"] != EVENT_SCHEMA_VERSION or isinstance(event["v"], bool):
107
+ newer = isinstance(event["v"], int) and event["v"] > EVENT_SCHEMA_VERSION
108
+ hint = "; upgrade to a newer release" if newer else ""
109
+ raise ValueError(f"unsupported event version {event['v']!r}{hint}")
110
+ event_id = event["id"]
111
+ if not (isinstance(event_id, str) and event_id.startswith("evt_") and is_ulid(event_id[4:])):
112
+ raise ValueError(f"malformed id {event_id!r}")
113
+ if not (isinstance(event["ts"], str) and _TS.match(event["ts"])):
114
+ raise ValueError(f"malformed ts {event['ts']!r}")
115
+ if not isinstance(event["type"], str) or not event["type"]:
116
+ raise ValueError("type must be a non-empty string")
117
+ if known_types is not None and event["type"] not in known_types:
118
+ raise ValueError(f"unknown event type {event['type']!r}")
119
+ if not (isinstance(event["actor"], str) and _ROLE.match(event["actor"])):
120
+ raise ValueError(f"malformed actor {event['actor']!r}")
121
+ if known_roles is not None and event["actor"] not in known_roles:
122
+ raise ValueError(f"unknown actor {event['actor']!r}")
123
+ if not isinstance(event["session"], str) or not event["session"]:
124
+ raise ValueError("session must be a non-empty string")
125
+ if not isinstance(event["data"], dict):
126
+ raise ValueError("data must be an object")
127
+ if not (isinstance(event["prev"], str) and _PREV.match(event["prev"])):
128
+ raise ValueError(f"malformed prev {event['prev']!r}")
129
+ if "item" in event:
130
+ if not (isinstance(event["item"], str) and _ITEM.match(event["item"])):
131
+ raise ValueError(f"malformed item {event['item']!r}")
132
+ title = event.get("title")
133
+ if not isinstance(title, str) or not 1 <= len(title) <= 80 or "\n" in title:
134
+ raise ValueError("title is required with item and must be 1-80 characters, one line")
135
+ elif "title" in event:
136
+ raise ValueError("title is only allowed with item")
137
+
138
+
139
+ @dataclass(frozen=True)
140
+ class VerifyResult:
141
+ """Outcome of checking the chain."""
142
+
143
+ events: int
144
+ ok: bool
145
+ line: int | None = None
146
+ reason: str | None = None
147
+
148
+
149
+ class EventStore:
150
+ """Appends to and reads a domain's ``events.jsonl``."""
151
+
152
+ def __init__(
153
+ self, layout: Layout, domain: Domain, lock_timeout: float = DEFAULT_LOCK_TIMEOUT
154
+ ) -> None:
155
+ self.layout = layout
156
+ self.domain = domain
157
+ self.lock_timeout = lock_timeout
158
+ self.known_types = CORE_EVENT_TYPES + tuple(
159
+ t for t in domain.event_types if t not in CORE_EVENT_TYPES
160
+ )
161
+
162
+ # ---------------------------------------------------------------- writing
163
+
164
+ def append( # noqa: PLR0913 - mirrors the envelope's fields; all but the type are keywords
165
+ self,
166
+ event_type: str,
167
+ *,
168
+ actor: str,
169
+ session: str,
170
+ data: Mapping[str, Any] | None = None,
171
+ item: str | None = None,
172
+ title: str | None = None,
173
+ ) -> dict[str, Any]:
174
+ """Validate and append one event. Returns the event as written."""
175
+ with self._locked():
176
+ return self._append_locked(
177
+ event_type, actor=actor, session=session, data=data, item=item, title=title
178
+ )
179
+
180
+ @contextmanager
181
+ def transaction(self) -> Iterator[Transaction]:
182
+ """Hold the write lock across reads and appends, e.g. to allocate an ID.
183
+
184
+ Nothing else can append until the block ends, so what the block read is
185
+ still the end of the log when it appends.
186
+ """
187
+ with self._locked():
188
+ yield Transaction(self)
189
+
190
+ def _append_locked( # noqa: PLR0913 - same fields as append
191
+ self,
192
+ event_type: str,
193
+ *,
194
+ actor: str,
195
+ session: str,
196
+ data: Mapping[str, Any] | None,
197
+ item: str | None,
198
+ title: str | None,
199
+ ) -> dict[str, Any]:
200
+ # The caller holds the lock.
201
+ last = self._last_line()
202
+ event: dict[str, Any] = {
203
+ "v": EVENT_SCHEMA_VERSION,
204
+ "id": "evt_" + new_ulid(),
205
+ "ts": utc_timestamp(),
206
+ "type": event_type,
207
+ "actor": actor,
208
+ "session": session,
209
+ "data": dict(data or {}),
210
+ "prev": GENESIS_PREV if last is None else line_hash(last),
211
+ }
212
+ if item is not None:
213
+ event["item"] = item
214
+ event["title"] = title
215
+ elif title is not None:
216
+ event["title"] = title
217
+ try:
218
+ check_envelope(event, self.known_types, self.domain.all_roles)
219
+ except ValueError as exc:
220
+ raise ForgeError(ExitCode.DATA, "event_invalid", str(exc)) from exc
221
+ line = serialize(event)
222
+ if len(line) > MAX_LINE_BYTES:
223
+ raise ForgeError(
224
+ ExitCode.USAGE,
225
+ "event_too_large",
226
+ f"event is {len(line)} bytes; the limit is {MAX_LINE_BYTES}. "
227
+ "Store large content in a file and reference its path.",
228
+ )
229
+ self._write(line)
230
+ return event
231
+
232
+ def _write(self, line: bytes) -> None:
233
+ fd = os.open(self.layout.events, os.O_WRONLY | os.O_APPEND | os.O_CREAT, 0o600)
234
+ try:
235
+ os.write(fd, line + b"\n")
236
+ os.fsync(fd)
237
+ finally:
238
+ os.close(fd)
239
+
240
+ def _locked(self) -> _Lock:
241
+ return _Lock(self.layout.lock, self.lock_timeout)
242
+
243
+ def _last_line(self) -> bytes | None:
244
+ """The last complete line, read from the end of the file."""
245
+ path = self.layout.events
246
+ if not path.exists() or path.stat().st_size == 0:
247
+ return None
248
+ with path.open("rb") as handle:
249
+ size = handle.seek(0, os.SEEK_END)
250
+ block = 4096
251
+ data = b""
252
+ position = size
253
+ while position > 0:
254
+ step = min(block, position)
255
+ position -= step
256
+ handle.seek(position)
257
+ data = handle.read(step) + data
258
+ stripped = data[:-1] if data.endswith(b"\n") else data
259
+ if b"\n" in stripped:
260
+ break
261
+ if not data.endswith(b"\n"):
262
+ raise ForgeError(
263
+ ExitCode.DATA,
264
+ "log_truncated",
265
+ f"{path} does not end with a newline; the last write was interrupted. "
266
+ "Run verify and restore from backup.",
267
+ )
268
+ body = data[:-1]
269
+ return body.rsplit(b"\n", 1)[-1]
270
+
271
+ def tip(self) -> tuple[int, str]:
272
+ """``(size in bytes, hash of the last line)``: cheap proof the log has not changed."""
273
+ path = self.layout.events
274
+ size = path.stat().st_size if path.exists() else 0
275
+ last = self._last_line()
276
+ return size, GENESIS_PREV if last is None else line_hash(last)
277
+
278
+ # ---------------------------------------------------------------- reading
279
+
280
+ def lines(self) -> Iterator[tuple[int, bytes]]:
281
+ """``(line_number, raw_bytes)`` for every line, streaming."""
282
+ path = self.layout.events
283
+ if not path.exists():
284
+ return
285
+ with path.open("rb") as handle:
286
+ yield from enumerate(handle, start=1)
287
+
288
+ def events(self) -> Iterator[dict[str, Any]]:
289
+ """Every event, streaming. Malformed lines exit 5 (DATA)."""
290
+ for number, raw in self.lines():
291
+ if not raw.endswith(b"\n"):
292
+ raise ForgeError(ExitCode.DATA, "log_truncated", f"line {number} is incomplete")
293
+ try:
294
+ event = upgrade("events", json.loads(raw), self.domain, f"line {number}")
295
+ check_envelope(event)
296
+ except (ValueError, TypeError) as exc:
297
+ raise ForgeError(ExitCode.DATA, "event_invalid", f"line {number}: {exc}") from exc
298
+ yield event
299
+
300
+ def verify(self) -> VerifyResult:
301
+ """Recompute the hash chain; report the first broken link."""
302
+ expected = GENESIS_PREV
303
+ count = 0
304
+ for number, raw in self.lines():
305
+ if not raw.endswith(b"\n"):
306
+ return VerifyResult(count, False, number, "line is incomplete (interrupted write)")
307
+ body = raw[:-1]
308
+ try:
309
+ event = json.loads(body)
310
+ check_envelope(upgrade("events", event, self.domain, f"line {number}"))
311
+ except (ValueError, TypeError, ForgeError) as exc:
312
+ detail = exc.detail if isinstance(exc, ForgeError) else str(exc)
313
+ return VerifyResult(count, False, number, f"malformed event: {detail}")
314
+ if body != serialize(event):
315
+ return VerifyResult(count, False, number, "line is not in canonical form")
316
+ if event["prev"] != expected:
317
+ return VerifyResult(
318
+ count, False, number, "prev does not match the previous line's hash"
319
+ )
320
+ expected = line_hash(body)
321
+ count += 1
322
+ return VerifyResult(count, True)
323
+
324
+
325
+ class Transaction:
326
+ """Reads and appends made while a :meth:`EventStore.transaction` holds the lock."""
327
+
328
+ def __init__(self, store: EventStore) -> None:
329
+ self._store = store
330
+
331
+ def events(self) -> Iterator[dict[str, Any]]:
332
+ """Every event, as of now."""
333
+ return self._store.events()
334
+
335
+ def append( # noqa: PLR0913 - mirrors EventStore.append
336
+ self,
337
+ event_type: str,
338
+ *,
339
+ actor: str,
340
+ session: str,
341
+ data: Mapping[str, Any] | None = None,
342
+ item: str | None = None,
343
+ title: str | None = None,
344
+ ) -> dict[str, Any]:
345
+ """Append one event without taking the lock again."""
346
+ return self._store._append_locked(
347
+ event_type, actor=actor, session=session, data=data, item=item, title=title
348
+ )
349
+
350
+
351
+ class _Lock:
352
+ """An exclusive ``flock`` on the state folder's ``.lock``, with a timeout."""
353
+
354
+ def __init__(self, path: Path, timeout: float) -> None:
355
+ self.path = path
356
+ self.timeout = timeout
357
+ self.fd: int | None = None
358
+
359
+ def __enter__(self) -> _Lock:
360
+ self.fd = os.open(self.path, os.O_RDWR | os.O_CREAT, 0o600)
361
+ deadline = time.monotonic() + self.timeout
362
+ while True:
363
+ try:
364
+ fcntl.flock(self.fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
365
+ return self
366
+ except BlockingIOError:
367
+ if time.monotonic() >= deadline:
368
+ os.close(self.fd)
369
+ self.fd = None
370
+ raise ForgeError(
371
+ ExitCode.CONFLICT,
372
+ "lock_timeout",
373
+ f"could not lock {self.path} within {self.timeout:g}s",
374
+ ) from None
375
+ time.sleep(0.01)
376
+
377
+ def __exit__(self, *_: object) -> None:
378
+ if self.fd is not None:
379
+ fcntl.flock(self.fd, fcntl.LOCK_UN)
380
+ os.close(self.fd)
381
+ self.fd = None
@@ -0,0 +1,265 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """Findings: problems a reviewing role raises against an item, and their resolution.
3
+
4
+ A finding is raised by one of the domain's reviewing roles (``finding_sources``)
5
+ or the operator, on an open item. It is resolved once, as ``fixed``,
6
+ ``accepted`` or ``invalid``, by the role that raised it or by the operator.
7
+ Only the operator can accept one, and findings from ``no_accept_sources`` can
8
+ never be accepted here: the domain manages that risk elsewhere.
9
+
10
+ Finding IDs are ``<ITEM-ID>:F<n>``, with ``n`` counting from 1 per item.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import re
16
+ from collections.abc import Iterable, Mapping
17
+ from dataclasses import dataclass
18
+ from typing import Any
19
+
20
+ from .domain import OPERATOR, Domain
21
+ from .errors import ExitCode, ForgeError
22
+ from .events import EventStore
23
+ from .identity import Identity
24
+ from .items import fold, parse_id
25
+ from .paths import Layout
26
+ from .walls import enforce_item_write
27
+
28
+ RESOLUTIONS = ("fixed", "accepted", "invalid")
29
+ MAX_SUMMARY = 500
30
+
31
+ _FINDING_ID = re.compile(r"^([A-Z]+-\d{4,}):F(\d+)$")
32
+ _AT = re.compile(r"^(?!/)(?!.*(?:^|/)\.\.(?:/|:))[^\s:]+:\d+$")
33
+
34
+
35
+ @dataclass(frozen=True)
36
+ class Finding:
37
+ """A finding as the log describes it."""
38
+
39
+ id: str
40
+ item: str
41
+ severity: str
42
+ summary: str
43
+ source: str
44
+ raised: str
45
+ rule: str | None = None
46
+ at: str | None = None
47
+ resolution: Mapping[str, Any] | None = None
48
+
49
+ @property
50
+ def is_open(self) -> bool:
51
+ return self.resolution is None
52
+
53
+ def status(self) -> str:
54
+ """``open``, or ``fixed (verified by verifier)``."""
55
+ if self.resolution is None:
56
+ return "open"
57
+ return f"{self.resolution['how']} (verified by {self.resolution['verified_by']})"
58
+
59
+ def as_dict(self) -> dict[str, Any]:
60
+ return {
61
+ "id": self.id,
62
+ "item": self.item,
63
+ "severity": self.severity,
64
+ "summary": self.summary,
65
+ "source": self.source,
66
+ "raised": self.raised,
67
+ "rule": self.rule,
68
+ "at": self.at,
69
+ "status": "open" if self.resolution is None else "resolved",
70
+ "how": self.resolution["how"] if self.resolution else None,
71
+ "verified_by": self.resolution["verified_by"] if self.resolution else None,
72
+ }
73
+
74
+
75
+ def parse_finding_id(finding_id: str) -> tuple[str, int]:
76
+ """``(item, n)``; USAGE error if malformed."""
77
+ match = _FINDING_ID.match(finding_id)
78
+ if not match:
79
+ raise ForgeError(
80
+ ExitCode.USAGE,
81
+ "invalid_finding_id",
82
+ f"{finding_id!r} is not a finding ID like FEAT-0001:F1",
83
+ )
84
+ return match.group(1), int(match.group(2))
85
+
86
+
87
+ def fold_findings(events: Iterable[Mapping[str, Any]]) -> dict[str, Finding]:
88
+ """Every finding, from the log. A second resolution is ignored."""
89
+ found: dict[str, Finding] = {}
90
+ for event in events:
91
+ data = event.get("data", {})
92
+ fid = data.get("finding_id")
93
+ if event["type"] == "finding" and isinstance(fid, str):
94
+ found[fid] = Finding(
95
+ id=fid,
96
+ item=event.get("item", ""),
97
+ severity=data.get("severity", ""),
98
+ summary=data.get("summary", ""),
99
+ source=data.get("source", ""),
100
+ raised=event["ts"],
101
+ rule=data.get("rule"),
102
+ at=data.get("at"),
103
+ )
104
+ elif event["type"] == "finding_resolved" and fid in found:
105
+ current = found[fid]
106
+ if current.resolution is None:
107
+ found[fid] = Finding(**{**current.__dict__, "resolution": dict(data)})
108
+ return found
109
+
110
+
111
+ def _summary(text: str) -> str:
112
+ trimmed = text.strip()
113
+ if not trimmed or len(trimmed) > MAX_SUMMARY:
114
+ raise ForgeError(
115
+ ExitCode.USAGE, "invalid_summary", f"a summary is 1-{MAX_SUMMARY} characters"
116
+ )
117
+ return trimmed
118
+
119
+
120
+ @dataclass
121
+ class Findings:
122
+ """Raise and resolve findings as one pinned identity."""
123
+
124
+ layout: Layout
125
+ domain: Domain
126
+ identity: Identity | None = None
127
+
128
+ def __post_init__(self) -> None:
129
+ self.store = EventStore(self.layout, self.domain)
130
+
131
+ def all(self) -> dict[str, Finding]:
132
+ return fold_findings(self.store.events())
133
+
134
+ def _who(self) -> Identity:
135
+ if self.identity is None:
136
+ raise ForgeError(ExitCode.INTERNAL, "no_identity", "finding writes need an identity")
137
+ return self.identity
138
+
139
+ def add(
140
+ self,
141
+ item_id: str,
142
+ severity: str,
143
+ summary: str,
144
+ *,
145
+ rule: str | None = None,
146
+ at: str | None = None,
147
+ ) -> Finding:
148
+ """Write ``finding`` on an open item."""
149
+ who = self._who()
150
+ if who.role != OPERATOR and who.role not in self.domain.finding_sources:
151
+ raise ForgeError(
152
+ ExitCode.REFUSED,
153
+ "cannot_raise_findings",
154
+ f"{who.role} does not raise findings; "
155
+ f"{', '.join((*self.domain.finding_sources, OPERATOR))} do",
156
+ )
157
+ if severity not in self.domain.severities:
158
+ raise ForgeError(
159
+ ExitCode.USAGE,
160
+ "invalid_severity",
161
+ f"severity is one of {', '.join(self.domain.severities)}",
162
+ )
163
+ text = _summary(summary)
164
+ if rule is not None:
165
+ parse_id(rule)
166
+ if at is not None and not _AT.match(at):
167
+ raise ForgeError(
168
+ ExitCode.USAGE, "invalid_at", f"--at is a relative path:line; got {at!r}"
169
+ )
170
+ parse_id(item_id)
171
+ with self.store.transaction() as tx:
172
+ events = list(tx.events())
173
+ item = fold(events, self.domain).get(item_id)
174
+ if item is None:
175
+ raise ForgeError(ExitCode.NOT_FOUND, "item_not_found", f"no item {item_id}")
176
+ enforce_item_write(tx, self.domain, who, item.type, item_id)
177
+ workflow = self.domain.workflows.get(item.type)
178
+ if workflow is not None and not workflow.is_open(item.state):
179
+ raise ForgeError(
180
+ ExitCode.REFUSED,
181
+ "item_closed",
182
+ f"{item.label()} is {item.state}; findings go on open items",
183
+ )
184
+ n = 1 + sum(1 for f in fold_findings(events).values() if f.item == item_id)
185
+ finding_id = f"{item_id}:F{n}"
186
+ data: dict[str, Any] = {
187
+ "finding_id": finding_id,
188
+ "severity": severity,
189
+ "summary": text,
190
+ "source": who.role,
191
+ }
192
+ if rule is not None:
193
+ data["rule"] = rule
194
+ if at is not None:
195
+ data["at"] = at
196
+ event = tx.append(
197
+ "finding",
198
+ actor=who.role,
199
+ session=who.session,
200
+ data=data,
201
+ item=item_id,
202
+ title=item.title,
203
+ )
204
+ return Finding(
205
+ id=finding_id,
206
+ item=item_id,
207
+ severity=severity,
208
+ summary=text,
209
+ source=who.role,
210
+ raised=event["ts"],
211
+ rule=rule,
212
+ at=at,
213
+ )
214
+
215
+ def resolve(self, finding_id: str, how: str) -> Finding:
216
+ """Write ``finding_resolved``. The raising role or the operator; once."""
217
+ who = self._who()
218
+ if how not in RESOLUTIONS:
219
+ raise ForgeError(
220
+ ExitCode.USAGE, "invalid_resolution", f"--how is one of {', '.join(RESOLUTIONS)}"
221
+ )
222
+ item_id, _ = parse_finding_id(finding_id)
223
+ with self.store.transaction() as tx:
224
+ events = list(tx.events())
225
+ finding = fold_findings(events).get(finding_id)
226
+ if finding is None:
227
+ raise ForgeError(
228
+ ExitCode.NOT_FOUND, "finding_not_found", f"no finding {finding_id}"
229
+ )
230
+ if not finding.is_open:
231
+ raise ForgeError(
232
+ ExitCode.CONFLICT,
233
+ "already_resolved",
234
+ f"{finding_id} was already resolved: {finding.status()}",
235
+ )
236
+ if who.role not in {finding.source, OPERATOR}:
237
+ raise ForgeError(
238
+ ExitCode.REFUSED,
239
+ "not_the_source",
240
+ f"{finding_id} was raised by {finding.source}; "
241
+ "only that role or the operator resolves it",
242
+ )
243
+ if how == "accepted" and finding.source in self.domain.no_accept_sources:
244
+ raise ForgeError(
245
+ ExitCode.REFUSED,
246
+ "accept_not_allowed",
247
+ f"findings raised by {finding.source} cannot be accepted here",
248
+ )
249
+ if how == "accepted" and who.role != OPERATOR:
250
+ raise ForgeError(
251
+ ExitCode.REFUSED, "operator_only", "only the operator accepts a finding"
252
+ )
253
+ item = fold(events, self.domain).get(item_id)
254
+ if item is not None:
255
+ enforce_item_write(tx, self.domain, who, item.type, finding_id)
256
+ data = {"finding_id": finding_id, "how": how, "verified_by": who.role}
257
+ tx.append(
258
+ "finding_resolved",
259
+ actor=who.role,
260
+ session=who.session,
261
+ data=data,
262
+ item=item_id,
263
+ title=item.title if item else None,
264
+ )
265
+ return Finding(**{**finding.__dict__, "resolution": data})