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,221 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """Migrate: rewrite older records at the current schema versions, once.
3
+
4
+ Readers already upgrade old records as they read them (``upgrade.py``), so
5
+ nothing breaks before a migration runs; ``migrate`` makes the upgrade
6
+ permanent. It is the only command that rewrites the event log, so it:
7
+
8
+ - is operator-only and holds the store lock throughout;
9
+ - copies every file it will change into ``migrations/<UTC time>/`` first;
10
+ - rewrites the log with the same event IDs and timestamps and a fresh hash
11
+ chain, replacing the file atomically;
12
+ - rewrites item front-matter and ``config.yaml`` (comments in an old
13
+ ``config.yaml`` are not kept; the copy has them);
14
+ - appends a ``migrated`` event naming the backup and the old log's last hash,
15
+ so the old chain can still be checked against the new one.
16
+
17
+ Archive rollups are never rewritten (the log records their hash); they are
18
+ upgraded each time they are read.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import json
24
+ import os
25
+ import shutil
26
+ import tempfile
27
+ from collections.abc import Mapping
28
+ from dataclasses import dataclass, field
29
+ from datetime import UTC, datetime
30
+ from pathlib import Path
31
+ from typing import Any
32
+
33
+ import yaml
34
+
35
+ from .config import parse_config
36
+ from .domain import OPERATOR, Domain
37
+ from .errors import ExitCode, ForgeError
38
+ from .events import GENESIS_PREV, EventStore, check_envelope, line_hash, serialize
39
+ from .identity import Identity
40
+ from .items import Items, _write_atomic, parse_item_file, render_front_matter, split_front_matter
41
+ from .paths import Layout
42
+ from .upgrade import upgrade, version_of
43
+ from .versions import VERSIONED
44
+
45
+ MIGRATIONS_DIR = "migrations"
46
+
47
+
48
+ @dataclass(frozen=True)
49
+ class Plan:
50
+ """What is older than the current schema versions."""
51
+
52
+ events: int = 0 # events below the current version
53
+ oldest: Mapping[str, int] = field(default_factory=dict) # kind → oldest version found
54
+ items: tuple[tuple[str, str], ...] = () # (item ID, path relative to the state folder)
55
+ config: bool = False
56
+
57
+ @property
58
+ def empty(self) -> bool:
59
+ return not (self.events or self.items or self.config)
60
+
61
+ def as_dict(self) -> dict[str, Any]:
62
+ return {
63
+ "events": self.events,
64
+ "items": [i for i, _ in self.items],
65
+ "config": self.config,
66
+ "oldest": dict(self.oldest),
67
+ "current": {kind: version for kind, (_, version) in VERSIONED.items()},
68
+ }
69
+
70
+
71
+ @dataclass(frozen=True)
72
+ class Migrated:
73
+ """What ``migrate`` did."""
74
+
75
+ plan: Plan
76
+ backup: str | None = None # relative to the state folder
77
+
78
+ def as_dict(self) -> dict[str, Any]:
79
+ return {**self.plan.as_dict(), "backup": self.backup}
80
+
81
+
82
+ class Migrator:
83
+ def __init__(
84
+ self,
85
+ layout: Layout,
86
+ domain: Domain,
87
+ identity: Identity | None = None,
88
+ config: Mapping[str, Any] | None = None,
89
+ ) -> None:
90
+ self.layout = layout
91
+ self.domain = domain
92
+ self.identity = identity
93
+ self.store = EventStore(layout, domain)
94
+ self.config = config
95
+
96
+ # ---------------------------------------------------------------- plan
97
+
98
+ def plan(self) -> Plan:
99
+ """What a migration would change. Read-only."""
100
+ oldest: dict[str, int] = {}
101
+
102
+ def note(kind: str, record: Any) -> bool:
103
+ version = version_of(kind, record)
104
+ if version is None or version >= VERSIONED[kind][1]:
105
+ return False
106
+ oldest[kind] = min(version, oldest.get(kind, version))
107
+ return True
108
+
109
+ events = 0
110
+ for number, raw in self.store.lines():
111
+ try:
112
+ record = json.loads(raw)
113
+ except ValueError as exc:
114
+ raise ForgeError(ExitCode.DATA, "event_invalid", f"line {number}: {exc}") from exc
115
+ events += note("events", record)
116
+ items: list[tuple[str, str]] = []
117
+ for item in Items(self.layout, self.domain, self.identity, self.config).all().values():
118
+ path = self.layout.state / item.path
119
+ if item.archived or not path.is_file():
120
+ continue # rollups are frozen; reindex recreates a missing file
121
+ raw, _ = split_front_matter(path.read_text(encoding="utf-8"), str(path))
122
+ if note("front_matter", raw):
123
+ items.append((item.id, item.path))
124
+ config = False
125
+ if self.layout.config.is_file():
126
+ try:
127
+ raw = yaml.safe_load(self.layout.config.read_text(encoding="utf-8"))
128
+ except yaml.YAMLError as exc:
129
+ raise ForgeError(
130
+ ExitCode.DATA, "config_parse", f"{self.layout.config}: {exc}"
131
+ ) from exc
132
+ config = note("config", raw)
133
+ return Plan(events, oldest, tuple(items), config)
134
+
135
+ # ----------------------------------------------------------------- run
136
+
137
+ def run(self, now: datetime | None = None) -> Migrated:
138
+ """Back up, rewrite and record. Operator only; nothing to do is not an error."""
139
+ who = self.identity
140
+ if who is None or who.role != OPERATOR:
141
+ raise ForgeError(
142
+ ExitCode.REFUSED, "role_not_allowed", "only the operator migrates project data"
143
+ )
144
+ with self.store.transaction() as tx:
145
+ plan = self.plan()
146
+ if plan.empty:
147
+ return Migrated(plan)
148
+ stamp = (now or datetime.now(UTC)).strftime("%Y%m%dT%H%M%S%fZ")
149
+ backup = f"{MIGRATIONS_DIR}/{stamp}"
150
+ self._back_up(plan, self.layout.state / backup)
151
+ old_tip = self.store.tip()[1]
152
+ if plan.events:
153
+ self._rewrite_log()
154
+ for item_id, rel in plan.items:
155
+ path = self.layout.state / rel
156
+ values, body = parse_item_file(
157
+ path.read_text(encoding="utf-8"), self.domain, f"{item_id} ({rel})"
158
+ )
159
+ _write_atomic(path, render_front_matter(values, self.domain) + body)
160
+ if plan.config:
161
+ self._rewrite_config(backup)
162
+ tx.append(
163
+ "migrated",
164
+ actor=who.role,
165
+ session=who.session,
166
+ data={**plan.as_dict(), "backup": backup, "old_tip": old_tip},
167
+ )
168
+ return Migrated(plan, backup)
169
+
170
+ # ------------------------------------------------------------ internals
171
+
172
+ def _back_up(self, plan: Plan, target: Path) -> None:
173
+ target.mkdir(mode=0o700, parents=True)
174
+ files = [self.layout.events.name] if plan.events else []
175
+ files += [rel for _, rel in plan.items]
176
+ files += [self.layout.config.name] if plan.config else []
177
+ for rel in files:
178
+ dest = target / rel
179
+ dest.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
180
+ shutil.copy2(self.layout.state / rel, dest)
181
+ os.chmod(dest, 0o600)
182
+
183
+ def _rewrite_log(self) -> None:
184
+ prev = GENESIS_PREV
185
+ lines: list[bytes] = []
186
+ for number, raw in self.store.lines():
187
+ event = upgrade("events", json.loads(raw), self.domain, f"line {number}")
188
+ event["prev"] = prev
189
+ try:
190
+ check_envelope(event)
191
+ except ValueError as exc: # pragma: no cover - plan() has read every event already
192
+ raise ForgeError(
193
+ ExitCode.DATA, "migration_invalid", f"line {number} after migration: {exc}"
194
+ ) from exc
195
+ line = serialize(event)
196
+ lines.append(line)
197
+ prev = line_hash(line)
198
+ path = self.layout.events
199
+ fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.", suffix=".tmp")
200
+ try:
201
+ with os.fdopen(fd, "wb") as handle:
202
+ handle.write(b"".join(line + b"\n" for line in lines))
203
+ handle.flush()
204
+ os.fsync(handle.fileno())
205
+ os.chmod(tmp, 0o600)
206
+ os.replace(tmp, path)
207
+ except BaseException:
208
+ Path(tmp).unlink(missing_ok=True)
209
+ raise
210
+
211
+ def _rewrite_config(self, backup: str) -> None:
212
+ path = self.layout.config
213
+ raw = yaml.safe_load(path.read_text(encoding="utf-8"))
214
+ data = upgrade("config", raw, self.domain, str(path))
215
+ header = (
216
+ f"# Migrated by {self.domain.name} migrate; the original, with its comments,\n"
217
+ f"# is {backup}/{path.name}.\n"
218
+ )
219
+ text = header + yaml.safe_dump(data, sort_keys=False, allow_unicode=True)
220
+ parse_config(text, self.domain, path) # never write a config that will not load
221
+ _write_atomic(path, text)
@@ -0,0 +1,41 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """Terse human output or a single JSON document, never both (core contract)."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import json
7
+ import sys
8
+ from dataclasses import dataclass, field
9
+ from typing import Any, TextIO
10
+
11
+ from .errors import ForgeError
12
+
13
+
14
+ @dataclass
15
+ class Output:
16
+ """Where and how a command reports its result."""
17
+
18
+ prog: str = "pluginforge"
19
+ json_mode: bool = False
20
+ quiet: bool = False
21
+ stdout: TextIO = field(default_factory=lambda: sys.stdout)
22
+ stderr: TextIO = field(default_factory=lambda: sys.stderr)
23
+
24
+ def result(self, document: dict[str, Any], human: str) -> None:
25
+ """Report success: the JSON document with ``--json``, else one terse line."""
26
+ if self.json_mode:
27
+ self._write_json(self.stdout, document)
28
+ elif not self.quiet:
29
+ print(human, file=self.stdout)
30
+
31
+ def error(self, err: ForgeError) -> None:
32
+ """Report a failure. Errors are shown even with ``--quiet``."""
33
+ if self.json_mode:
34
+ self._write_json(self.stdout, err.envelope())
35
+ else:
36
+ print(f"{self.prog}: {err.detail} [{err.reason}]", file=self.stderr)
37
+
38
+ @staticmethod
39
+ def _write_json(stream: TextIO, document: dict[str, Any]) -> None:
40
+ stream.write(json.dumps(document, sort_keys=True, ensure_ascii=False))
41
+ stream.write("\n")
@@ -0,0 +1,62 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """Where a domain's state lives under a project root."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from dataclasses import dataclass
7
+ from pathlib import Path
8
+
9
+ from .domain import Domain
10
+ from .errors import ExitCode, ForgeError
11
+
12
+
13
+ @dataclass(frozen=True)
14
+ class Layout:
15
+ """Paths of a project's state folder (``<root>/<state_dir>/``)."""
16
+
17
+ root: Path
18
+ state: Path
19
+
20
+ @classmethod
21
+ def at(cls, root: Path, domain: Domain) -> Layout:
22
+ root = root.resolve()
23
+ return cls(root=root, state=root / domain.state_dir)
24
+
25
+ @property
26
+ def config(self) -> Path:
27
+ return self.state / "config.yaml"
28
+
29
+ @property
30
+ def events(self) -> Path:
31
+ return self.state / "events.jsonl"
32
+
33
+ @property
34
+ def lock(self) -> Path:
35
+ return self.state / ".lock"
36
+
37
+ @property
38
+ def index(self) -> Path:
39
+ """The generated query cache; safe to delete."""
40
+ return self.state / ".index.sqlite"
41
+
42
+
43
+ def find_root(domain: Domain, start: Path | None = None, explicit: Path | None = None) -> Layout:
44
+ """The project whose state folder is ``explicit`` or the nearest one above ``start``."""
45
+ if explicit is not None:
46
+ layout = Layout.at(explicit, domain)
47
+ if not layout.state.is_dir():
48
+ raise ForgeError(
49
+ ExitCode.NOT_FOUND,
50
+ "not_initialized",
51
+ f"no {domain.state_dir}/ in {layout.root}; run '{domain.name} init' there",
52
+ )
53
+ return layout
54
+ here = (start or Path.cwd()).resolve()
55
+ for candidate in (here, *here.parents):
56
+ if (candidate / domain.state_dir).is_dir():
57
+ return Layout.at(candidate, domain)
58
+ raise ForgeError(
59
+ ExitCode.NOT_FOUND,
60
+ "not_initialized",
61
+ f"no {domain.state_dir}/ found in {here} or any parent; run '{domain.name} init'",
62
+ )
File without changes
@@ -0,0 +1,113 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """A small, strict schema for configuration: unknown keys are errors."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import re
7
+ from collections.abc import Mapping
8
+ from dataclasses import dataclass
9
+ from typing import Any, Literal
10
+
11
+ from .errors import ExitCode, ForgeError
12
+
13
+ Kind = Literal["str", "int", "bool", "duration", "enum", "list", "map", "section"]
14
+
15
+ _DURATION = re.compile(r"^(?:immediate|[1-9][0-9]*[mhd])$")
16
+ _DURATION_SECONDS = {"m": 60, "h": 3600, "d": 86400}
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class Field:
21
+ """One configuration value.
22
+
23
+ - ``section``: a mapping with known ``children``; unknown keys are errors.
24
+ - ``map``: a mapping with free-form keys whose values match ``item``.
25
+ - ``list``: a list whose elements match ``item``.
26
+
27
+ ``nullable`` scalars also accept ``null``.
28
+ """
29
+
30
+ kind: Kind
31
+ required: bool = False
32
+ default: Any = None
33
+ choices: tuple[str, ...] = ()
34
+ children: Mapping[str, Field] | None = None
35
+ item: Field | None = None
36
+ minimum: int | None = None
37
+ nullable: bool = False
38
+
39
+
40
+ def parse_duration(text: str) -> int | None:
41
+ """Seconds for ``15m``/``2h``/``7d``; ``None`` for ``immediate``."""
42
+ if not _DURATION.match(text):
43
+ raise ValueError(f"not a duration: {text!r}")
44
+ if text == "immediate":
45
+ return None
46
+ return int(text[:-1]) * _DURATION_SECONDS[text[-1]]
47
+
48
+
49
+ def _fail(path: str, message: str, reason: str = "config_invalid") -> ForgeError:
50
+ return ForgeError(ExitCode.DATA, reason, f"{path}: {message}")
51
+
52
+
53
+ def validate(value: Any, spec: Field, path: str) -> Any:
54
+ """Check ``value`` against ``spec``; return it with defaults filled in."""
55
+ if spec.kind == "section":
56
+ return _validate_section(value, spec, path)
57
+ if spec.kind == "map":
58
+ if not isinstance(value, dict):
59
+ raise _fail(path, "must be a mapping")
60
+ item = spec.item or Field("str")
61
+ return {str(k): validate(v, item, f"{path}.{k}") for k, v in value.items()}
62
+ if spec.kind == "list":
63
+ if not isinstance(value, list):
64
+ raise _fail(path, "must be a list")
65
+ item = spec.item or Field("str")
66
+ return [validate(v, item, f"{path}[{i}]") for i, v in enumerate(value)]
67
+ return _validate_scalar(value, spec, path)
68
+
69
+
70
+ def _validate_section(value: Any, spec: Field, path: str) -> dict[str, Any]:
71
+ if value is None:
72
+ value = {}
73
+ if not isinstance(value, dict):
74
+ raise _fail(path, "must be a mapping")
75
+ children = spec.children or {}
76
+ unknown = sorted(str(k) for k in value if k not in children)
77
+ if unknown:
78
+ where = f"{path}.{unknown[0]}" if path else unknown[0]
79
+ raise _fail(where, "unknown key", "config_unknown_key")
80
+ result: dict[str, Any] = {}
81
+ for key, child in children.items():
82
+ where = f"{path}.{key}" if path else key
83
+ if key in value:
84
+ result[key] = validate(value[key], child, where)
85
+ elif child.required:
86
+ raise _fail(where, "is required")
87
+ elif child.kind == "section":
88
+ result[key] = _validate_section({}, child, where)
89
+ else:
90
+ result[key] = child.default
91
+ return result
92
+
93
+
94
+ def _validate_scalar(value: Any, spec: Field, path: str) -> Any:
95
+ if value is None and spec.nullable:
96
+ return None
97
+ if spec.kind == "bool":
98
+ if not isinstance(value, bool):
99
+ raise _fail(path, "must be true or false")
100
+ return value
101
+ if spec.kind == "int":
102
+ if isinstance(value, bool) or not isinstance(value, int):
103
+ raise _fail(path, "must be an integer")
104
+ if spec.minimum is not None and value < spec.minimum:
105
+ raise _fail(path, f"must be at least {spec.minimum}")
106
+ return value
107
+ if not isinstance(value, str):
108
+ raise _fail(path, "must be a string")
109
+ if spec.kind == "enum" and value not in spec.choices:
110
+ raise _fail(path, f"must be one of: {', '.join(spec.choices)}")
111
+ if spec.kind == "duration" and not _DURATION.match(value):
112
+ raise _fail(path, "must be a duration like 15m, 2h, 7d, or immediate")
113
+ return value
@@ -0,0 +1,36 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """ULIDs: 48-bit millisecond timestamp + 80 random bits, Crockford base32.
3
+
4
+ Implemented here to avoid a dependency (EPIC-0001 open question 1).
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import re
10
+ import secrets
11
+ import time
12
+
13
+ ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"
14
+ PATTERN = re.compile(r"^[0-7][0-9A-HJKMNP-TV-Z]{25}$")
15
+ _MAX_TIME = (1 << 48) - 1
16
+
17
+
18
+ def new_ulid(now_ms: int | None = None, randomness: int | None = None) -> str:
19
+ """A new 26-character ULID."""
20
+ ms = int(time.time() * 1000) if now_ms is None else now_ms
21
+ if not 0 <= ms <= _MAX_TIME:
22
+ raise ValueError("timestamp out of range for a ULID")
23
+ rand = secrets.randbits(80) if randomness is None else randomness
24
+ if not 0 <= rand < (1 << 80):
25
+ raise ValueError("randomness out of range for a ULID")
26
+ value = (ms << 80) | rand
27
+ chars = []
28
+ for _ in range(26):
29
+ chars.append(ALPHABET[value & 0x1F])
30
+ value >>= 5
31
+ return "".join(reversed(chars))
32
+
33
+
34
+ def is_ulid(text: str) -> bool:
35
+ """Whether ``text`` is a well-formed ULID."""
36
+ return bool(PATTERN.match(text))
@@ -0,0 +1,57 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """Upgrade an older record to the current schema while reading it.
3
+
4
+ The compatibility rule is that a reader of version N accepts every record of
5
+ version N or lower. Readers call :func:`upgrade` before validating, so the
6
+ rest of the core only ever sees current records; ``<forge> migrate`` then
7
+ rewrites the files so the upgrade is paid once.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from typing import Any
13
+
14
+ from .domain import Domain
15
+ from .errors import ExitCode, ForgeError
16
+ from .versions import VERSIONED
17
+
18
+ _KEPT = ("id", "ts", "prev") # an event's identity and chain link never change
19
+
20
+
21
+ def version_of(kind: str, record: Any) -> int | None:
22
+ """The record's version, or None if it has none worth upgrading from."""
23
+ key, _ = VERSIONED[kind]
24
+ if not isinstance(record, dict):
25
+ return None
26
+ value = record.get(key)
27
+ if isinstance(value, bool) or not isinstance(value, int):
28
+ return None
29
+ return value
30
+
31
+
32
+ def upgrade(kind: str, record: Any, domain: Domain, where: str) -> Any:
33
+ """``record`` at the current version; anything else is returned for validation to report.
34
+
35
+ DATA (``migration_missing``) when an older record has no migration path.
36
+ """
37
+ version = version_of(kind, record)
38
+ key, current = VERSIONED[kind]
39
+ if version is None or version >= current:
40
+ return record
41
+ out: dict[str, Any] = dict(record)
42
+ while version < current:
43
+ step = domain.migration(kind, version)
44
+ if step is None:
45
+ raise ForgeError(
46
+ ExitCode.DATA,
47
+ "migration_missing",
48
+ f"{where}: {kind.replace('_', '-')} schema {version} is older than "
49
+ f"{domain.name} can read (no migration to {version + 1})",
50
+ )
51
+ upgraded = step.apply(dict(out))
52
+ if kind == "events":
53
+ upgraded.update({k: out[k] for k in _KEPT if k in out})
54
+ version += 1
55
+ upgraded[key] = version
56
+ out = upgraded
57
+ return out
@@ -0,0 +1,20 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """Current schema versions of the records the core writes.
3
+
4
+ A reader of version N accepts any record of version N or lower: older records
5
+ are upgraded on read by the domain's migrations (``migrate.py``), and
6
+ ``<forge> migrate`` rewrites them on disk.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ EVENT_SCHEMA_VERSION = 1
12
+ FRONT_MATTER_SCHEMA_VERSION = 1
13
+ CONFIG_SCHEMA_VERSION = 1
14
+
15
+ #: Record kind → (the key holding its version, the current version).
16
+ VERSIONED: dict[str, tuple[str, int]] = {
17
+ "events": ("v", EVENT_SCHEMA_VERSION),
18
+ "front_matter": ("schema", FRONT_MATTER_SCHEMA_VERSION),
19
+ "config": ("schema", CONFIG_SCHEMA_VERSION),
20
+ }
@@ -0,0 +1,67 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """Read-only views assembled from the log, for ``show``.
3
+
4
+ These fold the log directly. An index (a later feature) can make them faster
5
+ without changing what they return.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from collections.abc import Iterable, Mapping
11
+ from dataclasses import dataclass
12
+ from typing import Any
13
+
14
+ from .domain import Domain
15
+ from .errors import ExitCode, ForgeError
16
+ from .findings import Finding, fold_findings
17
+ from .gates import Gate, fold_gates
18
+ from .items import Item, fold, parse_id
19
+ from .lessons import Lesson, fold_lessons
20
+
21
+
22
+ @dataclass(frozen=True)
23
+ class ItemView:
24
+ """An item with everything recorded about it."""
25
+
26
+ item: Item
27
+ gates: tuple[Gate, ...]
28
+ findings: tuple[Finding, ...]
29
+ lessons: tuple[Lesson, ...]
30
+ history: tuple[Mapping[str, Any], ...] # state changes, oldest first
31
+
32
+ def as_dict(self) -> dict[str, Any]:
33
+ return {
34
+ **self.item.as_dict(),
35
+ "gates": [g.as_dict() for g in self.gates],
36
+ "findings": [f.as_dict() for f in self.findings],
37
+ "lessons": [lesson.as_dict() for lesson in self.lessons],
38
+ "history": [dict(h) for h in self.history],
39
+ }
40
+
41
+
42
+ def describe_item(events: Iterable[Mapping[str, Any]], domain: Domain, item_id: str) -> ItemView:
43
+ """Everything the log says about one item; NOT_FOUND if it has none."""
44
+ parse_id(item_id)
45
+ log = list(events)
46
+ item = fold(log, domain).get(item_id)
47
+ if item is None:
48
+ raise ForgeError(ExitCode.NOT_FOUND, "item_not_found", f"no item {item_id}")
49
+ history = tuple(
50
+ {
51
+ "ts": e["ts"],
52
+ "actor": e["actor"],
53
+ "from": e["data"].get("from"),
54
+ "to": e["data"].get("to"),
55
+ **({"gate": e["data"]["gate"]} if "gate" in e["data"] else {}),
56
+ **({"note": e["data"]["note"]} if "note" in e["data"] else {}),
57
+ }
58
+ for e in log
59
+ if e["type"] == "state" and e.get("item") == item_id
60
+ )
61
+ return ItemView(
62
+ item=item,
63
+ gates=tuple(g for g in fold_gates(log).values() if g.item == item_id),
64
+ findings=tuple(f for f in fold_findings(log).values() if f.item == item_id),
65
+ lessons=tuple(x for x in fold_lessons(log).values() if x.from_item == item_id),
66
+ history=history,
67
+ )