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/migrate.py ADDED
@@ -0,0 +1,230 @@
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 contextlib
24
+ import json
25
+ import os
26
+ import shutil
27
+ import tempfile
28
+ from collections.abc import Mapping
29
+ from dataclasses import dataclass, field
30
+ from datetime import UTC, datetime
31
+ from pathlib import Path
32
+ from typing import Any
33
+
34
+ import yaml
35
+
36
+ from .config import parse_config
37
+ from .domain import OPERATOR, Domain
38
+ from .errors import ExitCode, ForgeError
39
+ from .events import GENESIS_PREV, EventStore, check_envelope, line_hash, serialize
40
+ from .identity import Identity
41
+ from .items import Items, _write_atomic, parse_item_file, render_front_matter, split_front_matter
42
+ from .paths import Layout
43
+ from .upgrade import upgrade, version_of
44
+ from .versions import RETIRED_FILES, VERSIONED
45
+
46
+ MIGRATIONS_DIR = "migrations"
47
+
48
+
49
+ @dataclass(frozen=True)
50
+ class Plan:
51
+ """What is older than the current schema versions."""
52
+
53
+ events: int = 0 # events below the current version
54
+ oldest: Mapping[str, int] = field(default_factory=dict) # kind → oldest version found
55
+ items: tuple[tuple[str, str], ...] = () # (item ID, path relative to the state folder)
56
+ config: bool = False
57
+ retired: tuple[str, ...] = () # generated files a core change retired, still present
58
+
59
+ @property
60
+ def empty(self) -> bool:
61
+ return not (self.events or self.items or self.config or self.retired)
62
+
63
+ def as_dict(self) -> dict[str, Any]:
64
+ return {
65
+ "events": self.events,
66
+ "items": [i for i, _ in self.items],
67
+ "config": self.config,
68
+ "retired": list(self.retired),
69
+ "oldest": dict(self.oldest),
70
+ "current": {kind: version for kind, (_, version) in VERSIONED.items()},
71
+ }
72
+
73
+
74
+ @dataclass(frozen=True)
75
+ class Migrated:
76
+ """What ``migrate`` did."""
77
+
78
+ plan: Plan
79
+ backup: str | None = None # relative to the state folder
80
+
81
+ def as_dict(self) -> dict[str, Any]:
82
+ return {**self.plan.as_dict(), "backup": self.backup}
83
+
84
+
85
+ class Migrator:
86
+ def __init__(
87
+ self,
88
+ layout: Layout,
89
+ domain: Domain,
90
+ identity: Identity | None = None,
91
+ config: Mapping[str, Any] | None = None,
92
+ ) -> None:
93
+ self.layout = layout
94
+ self.domain = domain
95
+ self.identity = identity
96
+ self.store = EventStore(layout, domain)
97
+ self.config = config
98
+
99
+ # ---------------------------------------------------------------- plan
100
+
101
+ def plan(self) -> Plan:
102
+ """What a migration would change. Read-only."""
103
+ oldest: dict[str, int] = {}
104
+
105
+ def note(kind: str, record: Any) -> bool:
106
+ version = version_of(kind, record)
107
+ if version is None or version >= VERSIONED[kind][1]:
108
+ return False
109
+ oldest[kind] = min(version, oldest.get(kind, version))
110
+ return True
111
+
112
+ events = 0
113
+ for number, raw in self.store.lines():
114
+ try:
115
+ record = json.loads(raw)
116
+ except ValueError as exc:
117
+ raise ForgeError(ExitCode.DATA, "event_invalid", f"line {number}: {exc}") from exc
118
+ events += note("events", record)
119
+ items: list[tuple[str, str]] = []
120
+ for item in Items(self.layout, self.domain, self.identity, self.config).all().values():
121
+ path = self.layout.state / item.path
122
+ if item.archived or not path.is_file():
123
+ continue # rollups are frozen; reindex recreates a missing file
124
+ raw, _ = split_front_matter(path.read_text(encoding="utf-8"), str(path))
125
+ if note("front_matter", raw):
126
+ items.append((item.id, item.path))
127
+ config = False
128
+ if self.layout.config.is_file():
129
+ try:
130
+ raw = yaml.safe_load(self.layout.config.read_text(encoding="utf-8"))
131
+ except yaml.YAMLError as exc:
132
+ raise ForgeError(
133
+ ExitCode.DATA, "config_parse", f"{self.layout.config}: {exc}"
134
+ ) from exc
135
+ config = note("config", raw)
136
+ retired = tuple(f for f in RETIRED_FILES if (self.layout.state / f).is_file())
137
+ return Plan(events, oldest, tuple(items), config, retired)
138
+
139
+ # ----------------------------------------------------------------- run
140
+
141
+ def run(self, now: datetime | None = None) -> Migrated:
142
+ """Back up, rewrite and record. Operator only; nothing to do is not an error."""
143
+ who = self.identity
144
+ if who is None or who.role != OPERATOR:
145
+ raise ForgeError(
146
+ ExitCode.REFUSED, "role_not_allowed", "only the operator migrates project data"
147
+ )
148
+ with self.store.transaction() as tx:
149
+ plan = self.plan()
150
+ if plan.empty:
151
+ return Migrated(plan)
152
+ stamp = (now or datetime.now(UTC)).strftime("%Y%m%dT%H%M%S%fZ")
153
+ backup = f"{MIGRATIONS_DIR}/{stamp}"
154
+ self._back_up(plan, self.layout.state / backup)
155
+ old_tip = self.store.tip()[1]
156
+ if plan.events:
157
+ self._rewrite_log()
158
+ for item_id, rel in plan.items:
159
+ path = self.layout.state / rel
160
+ values, body = parse_item_file(
161
+ path.read_text(encoding="utf-8"), self.domain, f"{item_id} ({rel})"
162
+ )
163
+ _write_atomic(path, render_front_matter(values, self.domain) + body)
164
+ if plan.config:
165
+ self._rewrite_config(backup)
166
+ for rel in plan.retired:
167
+ (self.layout.state / rel).unlink()
168
+ with contextlib.suppress(OSError): # the folder may hold other files
169
+ (self.layout.state / rel).parent.rmdir()
170
+ tx.append(
171
+ "migrated",
172
+ actor=who.role,
173
+ session=who.session,
174
+ data={**plan.as_dict(), "backup": backup, "old_tip": old_tip},
175
+ )
176
+ return Migrated(plan, backup)
177
+
178
+ # ------------------------------------------------------------ internals
179
+
180
+ def _back_up(self, plan: Plan, target: Path) -> None:
181
+ target.mkdir(mode=0o700, parents=True)
182
+ files = [self.layout.events.name] if plan.events else []
183
+ files += [rel for _, rel in plan.items]
184
+ files += [self.layout.config.name] if plan.config else []
185
+ files += list(plan.retired)
186
+ for rel in files:
187
+ dest = target / rel
188
+ dest.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
189
+ shutil.copy2(self.layout.state / rel, dest)
190
+ os.chmod(dest, 0o600)
191
+
192
+ def _rewrite_log(self) -> None:
193
+ prev = GENESIS_PREV
194
+ lines: list[bytes] = []
195
+ for number, raw in self.store.lines():
196
+ event = upgrade("events", json.loads(raw), self.domain, f"line {number}")
197
+ event["prev"] = prev
198
+ try:
199
+ check_envelope(event)
200
+ except ValueError as exc: # pragma: no cover - plan() has read every event already
201
+ raise ForgeError(
202
+ ExitCode.DATA, "migration_invalid", f"line {number} after migration: {exc}"
203
+ ) from exc
204
+ line = serialize(event)
205
+ lines.append(line)
206
+ prev = line_hash(line)
207
+ path = self.layout.events
208
+ fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.", suffix=".tmp")
209
+ try:
210
+ with os.fdopen(fd, "wb") as handle:
211
+ handle.write(b"".join(line + b"\n" for line in lines))
212
+ handle.flush()
213
+ os.fsync(handle.fileno())
214
+ os.chmod(tmp, 0o600)
215
+ os.replace(tmp, path)
216
+ except BaseException:
217
+ Path(tmp).unlink(missing_ok=True)
218
+ raise
219
+
220
+ def _rewrite_config(self, backup: str) -> None:
221
+ path = self.layout.config
222
+ raw = yaml.safe_load(path.read_text(encoding="utf-8"))
223
+ data = upgrade("config", raw, self.domain, str(path))
224
+ header = (
225
+ f"# Migrated by {self.domain.name} migrate; the original, with its comments,\n"
226
+ f"# is {backup}/{path.name}.\n"
227
+ )
228
+ text = header + yaml.safe_dump(data, sort_keys=False, allow_unicode=True)
229
+ parse_config(text, self.domain, path) # never write a config that will not load
230
+ _write_atomic(path, text)
teaimforge/output.py ADDED
@@ -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 = "teaimforge"
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")
teaimforge/paths.py ADDED
@@ -0,0 +1,101 @@
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
+ import hashlib
7
+ import re
8
+ from dataclasses import dataclass
9
+ from pathlib import Path
10
+
11
+ from .domain import Domain
12
+ from .errors import ExitCode, ForgeError
13
+
14
+
15
+ @dataclass(frozen=True)
16
+ class Layout:
17
+ """Paths of a project's state folder (``<root>/<state_dir>/``)."""
18
+
19
+ root: Path
20
+ state: Path
21
+
22
+ @classmethod
23
+ def at(cls, root: Path, domain: Domain) -> Layout:
24
+ root = root.resolve()
25
+ return cls(root=root, state=root / domain.state_dir)
26
+
27
+ @property
28
+ def config(self) -> Path:
29
+ return self.state / "config.yaml"
30
+
31
+ @property
32
+ def events(self) -> Path:
33
+ return self.state / "events.jsonl"
34
+
35
+ @property
36
+ def lock(self) -> Path:
37
+ return self.state / ".lock"
38
+
39
+ @property
40
+ def index(self) -> Path:
41
+ """The generated query cache; safe to delete."""
42
+ return self.state / ".index.sqlite"
43
+
44
+
45
+ def find_root(domain: Domain, start: Path | None = None, explicit: Path | None = None) -> Layout:
46
+ """The project whose state folder is ``explicit`` or the nearest one above ``start``."""
47
+ if explicit is not None:
48
+ layout = Layout.at(explicit, domain)
49
+ if not layout.state.is_dir():
50
+ raise ForgeError(
51
+ ExitCode.NOT_FOUND,
52
+ "not_initialized",
53
+ f"no {domain.state_dir}/ in {layout.root}; run '{domain.name} init' there",
54
+ )
55
+ return layout
56
+ here = (start or Path.cwd()).resolve()
57
+ for candidate in (here, *here.parents):
58
+ if (candidate / domain.state_dir).is_dir():
59
+ return Layout.at(candidate, domain)
60
+ raise ForgeError(
61
+ ExitCode.NOT_FOUND,
62
+ "not_initialized",
63
+ f"no {domain.state_dir}/ found in {here} or any parent; run '{domain.name} init'",
64
+ )
65
+
66
+
67
+ CHUNK = 1 << 20
68
+ #: How a rollup names a file kept beside it (archive.py writes, rollup_intact reads).
69
+ KEPT = re.compile(
70
+ r"^Kept beside this file: `(archive/[A-Z]+-\d{4,}\.files/[^`]+)`, "
71
+ r"(\d+) bytes, SHA-256 `([0-9a-f]{64})`\.$",
72
+ re.MULTILINE,
73
+ )
74
+
75
+
76
+ def sha256_of(path: Path) -> str:
77
+ """SHA-256 of a file, read in chunks."""
78
+ digest = hashlib.sha256()
79
+ with path.open("rb") as handle:
80
+ while chunk := handle.read(CHUNK):
81
+ digest.update(chunk)
82
+ return digest.hexdigest()
83
+
84
+
85
+ def rollup_intact(state: Path, rollup: str, sha256: str | None) -> bool:
86
+ """Whether an archive rollup, and every file kept beside it, match the log.
87
+
88
+ The log records the rollup's hash; the rollup records each kept file's size
89
+ and hash, so one recorded hash covers them all.
90
+ """
91
+ path = state / rollup
92
+ if sha256 is None or not path.is_file() or path.is_symlink() or sha256_of(path) != sha256:
93
+ return False
94
+ for match in KEPT.finditer(path.read_text(encoding="utf-8")):
95
+ rel, size, digest = match.group(1), int(match.group(2)), match.group(3)
96
+ kept = state / rel
97
+ if ".." in rel.split("/") or kept.is_symlink() or not kept.is_file():
98
+ return False
99
+ if kept.stat().st_size != size or sha256_of(kept) != digest:
100
+ return False
101
+ return True
teaimforge/py.typed ADDED
File without changes
teaimforge/schema.py ADDED
@@ -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
teaimforge/ulid.py ADDED
@@ -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))
teaimforge/upgrade.py ADDED
@@ -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
teaimforge/versions.py ADDED
@@ -0,0 +1,28 @@
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 = 2 # 2: lessons became insights
12
+ FRONT_MATTER_SCHEMA_VERSION = 1
13
+ CONFIG_SCHEMA_VERSION = 2 # 2: the forge section became publish
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
+ }
21
+
22
+ #: Generated files a core change retired; ``migrate`` backs them up and removes them.
23
+ RETIRED_FILES = ("lessons/LESSONS.md",)
24
+
25
+ #: Names the core owns: a team may not use them for item types, prefixes or walls.
26
+ RESERVED_PREFIXES = frozenset({"INSIGHT", "LESSON", "PERSON", "MSG"})
27
+ RESERVED_TYPES = frozenset({"insight", "lesson", "person", "message"})
28
+ TEAM_WALL = "team"
teaimforge/views.py ADDED
@@ -0,0 +1,71 @@
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 .insights import Insight, fold_insights
19
+ from .items import Item, children_of, fold, parse_id
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
+ insights: tuple[Insight, ...]
30
+ history: tuple[Mapping[str, Any], ...] # state changes, oldest first
31
+ children: tuple[Item, ...] = () # items naming this one as their parent
32
+
33
+ def as_dict(self) -> dict[str, Any]:
34
+ return {
35
+ **self.item.as_dict(),
36
+ "gates": [g.as_dict() for g in self.gates],
37
+ "findings": [f.as_dict() for f in self.findings],
38
+ "insights": [insight.as_dict() for insight in self.insights],
39
+ "history": [dict(h) for h in self.history],
40
+ "children": [{"id": c.id, "title": c.title, "state": c.state} for c in self.children],
41
+ }
42
+
43
+
44
+ def describe_item(events: Iterable[Mapping[str, Any]], domain: Domain, item_id: str) -> ItemView:
45
+ """Everything the log says about one item; NOT_FOUND if it has none."""
46
+ parse_id(item_id)
47
+ log = list(events)
48
+ items = fold(log, domain)
49
+ item = items.get(item_id)
50
+ if item is None:
51
+ raise ForgeError(ExitCode.NOT_FOUND, "item_not_found", f"no item {item_id}")
52
+ history = tuple(
53
+ {
54
+ "ts": e["ts"],
55
+ "actor": e["actor"],
56
+ "from": e["data"].get("from"),
57
+ "to": e["data"].get("to"),
58
+ **({"gate": e["data"]["gate"]} if "gate" in e["data"] else {}),
59
+ **({"note": e["data"]["note"]} if "note" in e["data"] else {}),
60
+ }
61
+ for e in log
62
+ if e["type"] == "state" and e.get("item") == item_id
63
+ )
64
+ return ItemView(
65
+ item=item,
66
+ gates=tuple(g for g in fold_gates(log).values() if g.item == item_id),
67
+ findings=tuple(f for f in fold_findings(log).values() if f.item == item_id),
68
+ insights=tuple(x for x in fold_insights(log).values() if x.from_item == item_id),
69
+ history=history,
70
+ children=tuple(children_of(domain, items, item_id)),
71
+ )