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/index.py ADDED
@@ -0,0 +1,267 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """The index: a SQLite cache of the log, for queries.
3
+
4
+ The event log is the record; the index is generated from it and is safe to
5
+ delete. It remembers the log's size and the hash of its last line; when either
6
+ differs, the index is rebuilt from a full replay before it answers. A rebuild
7
+ writes a new file and renames it into place, so a reader never sees half of
8
+ one.
9
+
10
+ ``reindex`` also repairs the item files: a front-matter ``state`` that
11
+ disagrees with the log is rewritten (the log wins), and a missing primary file
12
+ is recreated from the log with its type's starting body.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ import os
19
+ import re
20
+ import sqlite3
21
+ import tempfile
22
+ from collections.abc import Iterable, Mapping, Sequence
23
+ from contextlib import closing
24
+ from dataclasses import dataclass
25
+ from pathlib import Path
26
+ from typing import Any
27
+
28
+ from .domain import Domain
29
+ from .errors import ExitCode, ForgeError
30
+ from .events import EventStore
31
+ from .items import (
32
+ Item,
33
+ _write_atomic,
34
+ fold,
35
+ parse_item_file,
36
+ render_front_matter,
37
+ )
38
+ from .paths import Layout, rollup_intact
39
+ from .versions import FRONT_MATTER_SCHEMA_VERSION
40
+
41
+ INDEX_SCHEMA = 2
42
+ _ID = re.compile(r"^([A-Z]+)-(\d+)$")
43
+
44
+ _DDL = """
45
+ CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);
46
+ CREATE TABLE items (
47
+ id TEXT PRIMARY KEY,
48
+ prefix TEXT NOT NULL,
49
+ number INTEGER NOT NULL,
50
+ type TEXT NOT NULL,
51
+ title TEXT NOT NULL,
52
+ state TEXT NOT NULL,
53
+ path TEXT NOT NULL,
54
+ created TEXT NOT NULL,
55
+ assignee TEXT,
56
+ fields TEXT NOT NULL,
57
+ archive_sha256 TEXT
58
+ );
59
+ CREATE INDEX items_by_type ON items (type);
60
+ CREATE INDEX items_by_state ON items (state);
61
+ """
62
+
63
+
64
+ def _order(item_id: str) -> tuple[str, int]:
65
+ match = _ID.match(item_id)
66
+ return (match.group(1), int(match.group(2))) if match else (item_id, 0)
67
+
68
+
69
+ @dataclass(frozen=True)
70
+ class Repair:
71
+ """What ``reindex`` changed in the item files."""
72
+
73
+ states_fixed: tuple[str, ...] = ()
74
+ files_recreated: tuple[str, ...] = ()
75
+ archives_damaged: tuple[str, ...] = () # missing or not matching the logged hash
76
+
77
+
78
+ class Index:
79
+ """Queries over a project's items, served from ``.index.sqlite``."""
80
+
81
+ def __init__(self, layout: Layout, domain: Domain) -> None:
82
+ self.layout = layout
83
+ self.domain = domain
84
+ self.store = EventStore(layout, domain)
85
+
86
+ # ------------------------------------------------------------ freshness
87
+
88
+ def _stored_tip(self) -> tuple[int, str] | None:
89
+ if not self.layout.index.exists():
90
+ return None
91
+ try:
92
+ with closing(sqlite3.connect(f"file:{self.layout.index}?mode=ro", uri=True)) as db:
93
+ rows = dict(db.execute("SELECT key, value FROM meta").fetchall())
94
+ except sqlite3.DatabaseError:
95
+ return None
96
+ if rows.get("schema") != str(INDEX_SCHEMA):
97
+ return None
98
+ return int(rows.get("size", "-1")), rows.get("last_hash", "")
99
+
100
+ def is_fresh(self) -> bool:
101
+ """Whether the index matches the log as it is now."""
102
+ return self._stored_tip() == self.store.tip()
103
+
104
+ def rebuild(self) -> int:
105
+ """Replay the log into a new index file. Returns the number of items."""
106
+ tip = self.store.tip()
107
+ items = fold(self.store.events(), self.domain)
108
+ self.layout.state.mkdir(mode=0o700, parents=True, exist_ok=True)
109
+ fd, tmp = tempfile.mkstemp(dir=self.layout.state, prefix=".index.", suffix=".tmp")
110
+ os.close(fd)
111
+ try:
112
+ with closing(sqlite3.connect(tmp)) as db:
113
+ db.executescript(_DDL)
114
+ db.executemany(
115
+ "INSERT INTO meta (key, value) VALUES (?, ?)",
116
+ [("schema", str(INDEX_SCHEMA)), ("size", str(tip[0])), ("last_hash", tip[1])],
117
+ )
118
+ db.executemany(
119
+ "INSERT INTO items VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
120
+ [
121
+ (
122
+ i.id,
123
+ *_order(i.id),
124
+ i.type,
125
+ i.title,
126
+ i.state,
127
+ i.path,
128
+ i.created,
129
+ i.assignee,
130
+ json.dumps(dict(i.fields), sort_keys=True),
131
+ i.archive_sha256,
132
+ )
133
+ for i in items.values()
134
+ ],
135
+ )
136
+ db.commit()
137
+ os.chmod(tmp, 0o600)
138
+ os.replace(tmp, self.layout.index)
139
+ except BaseException:
140
+ Path(tmp).unlink(missing_ok=True)
141
+ raise
142
+ return len(items)
143
+
144
+ def ensure(self) -> None:
145
+ """Rebuild if the log has changed since the index was built."""
146
+ if not self.is_fresh():
147
+ self.rebuild()
148
+
149
+ # ------------------------------------------------------------ queries
150
+
151
+ def items(
152
+ self,
153
+ *,
154
+ type_name: str | None = None,
155
+ state: str | None = None,
156
+ where: Mapping[str, str] | None = None,
157
+ parent: str | None = None,
158
+ open_only: bool = False,
159
+ ) -> list[Item]:
160
+ """Items in ID order, filtered.
161
+
162
+ ``where`` keeps items whose front-matter fields equal the given values;
163
+ ``parent`` keeps the children of one item; ``open_only`` keeps items a
164
+ workflow still works on.
165
+ """
166
+ self.ensure()
167
+ sql = (
168
+ "SELECT id, type, title, state, path, created, assignee, fields, archive_sha256"
169
+ " FROM items"
170
+ )
171
+ clauses: list[str] = []
172
+ args: list[Any] = []
173
+ if type_name is not None:
174
+ clauses.append("type = ?")
175
+ args.append(type_name)
176
+ if state is not None:
177
+ clauses.append("state = ?")
178
+ args.append(state)
179
+ if clauses:
180
+ sql += " WHERE " + " AND ".join(clauses)
181
+ sql += " ORDER BY prefix, number"
182
+ with closing(sqlite3.connect(f"file:{self.layout.index}?mode=ro", uri=True)) as db:
183
+ rows = db.execute(sql, args).fetchall()
184
+ found = [
185
+ Item(
186
+ id=row[0],
187
+ type=row[1],
188
+ title=row[2],
189
+ state=row[3],
190
+ path=row[4],
191
+ created=row[5],
192
+ assignee=row[6],
193
+ fields=json.loads(row[7]),
194
+ archive_sha256=row[8],
195
+ )
196
+ for row in rows
197
+ ]
198
+ for name, value in (where or {}).items():
199
+ found = [i for i in found if i.fields.get(name) == value]
200
+ if parent is not None:
201
+ found = [i for i in found if self.domain.parent_id(i.type, i.fields) == parent]
202
+ if open_only:
203
+ found = [i for i in found if self._is_open(i)]
204
+ return found
205
+
206
+ def _is_open(self, item: Item) -> bool:
207
+ workflow = self.domain.workflows.get(item.type)
208
+ return workflow.is_open(item.state) if workflow is not None else True
209
+
210
+ # ------------------------------------------------------------ repair
211
+
212
+ def reindex(self) -> Repair:
213
+ """Rebuild the index and make every item file agree with the log."""
214
+ self.rebuild()
215
+ fixed: list[str] = []
216
+ recreated: list[str] = []
217
+ damaged: list[str] = []
218
+ for item in fold(self.store.events(), self.domain).values():
219
+ path = self.layout.state / item.path
220
+ if item.archived:
221
+ # A rollup cannot be rebuilt from the log: report it, never rewrite it.
222
+ if not rollup_intact(self.layout.state, item.path, item.archive_sha256):
223
+ damaged.append(item.id)
224
+ continue
225
+ if not path.is_file():
226
+ _write_atomic(path, self._fresh_file(item))
227
+ recreated.append(item.id)
228
+ continue
229
+ front, body = parse_item_file(path.read_text(encoding="utf-8"), self.domain, str(path))
230
+ if front["state"] != item.state or front["title"] != item.title:
231
+ front["state"] = item.state
232
+ front["title"] = item.title
233
+ _write_atomic(path, render_front_matter(front, self.domain) + body)
234
+ fixed.append(item.id)
235
+ return Repair(tuple(fixed), tuple(recreated), tuple(damaged))
236
+
237
+ def _fresh_file(self, item: Item) -> str:
238
+ try:
239
+ body = self.domain.item_type(item.type).body
240
+ except KeyError:
241
+ body = "# {id} — {title}\n"
242
+ front = {
243
+ "schema": FRONT_MATTER_SCHEMA_VERSION,
244
+ "id": item.id,
245
+ "title": item.title,
246
+ "type": item.type,
247
+ "state": item.state,
248
+ **{k: v.default for k, v in self.domain.item_schema.items()},
249
+ **dict(item.fields),
250
+ "created": item.created,
251
+ }
252
+ return (
253
+ render_front_matter(front, self.domain)
254
+ + "\n"
255
+ + body.format(id=item.id, title=item.title)
256
+ )
257
+
258
+
259
+ def replay(events: Iterable[Mapping[str, Any]], domain: Domain) -> Sequence[Item]:
260
+ """Every item in ID order, straight from the log (what the index must equal)."""
261
+ return sorted(fold(events, domain).values(), key=lambda i: _order(i.id))
262
+
263
+
264
+ def require_type(domain: Domain, type_name: str | None) -> None:
265
+ """USAGE error for an unknown ``--type``."""
266
+ if type_name is not None and type_name not in {t.name for t in domain.item_types}:
267
+ raise ForgeError(ExitCode.USAGE, "unknown_type", f"{type_name!r} is not an item type")
teaimforge/insights.py ADDED
@@ -0,0 +1,142 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """Insights: what the team learned, tagged so later work can load it.
3
+
4
+ Any role can record an insight. Insight IDs are ``INSIGHT-<NNNN>``, allocated one
5
+ past the highest ever recorded and never reused. An insight may name the item it
6
+ came from; its tags are how context loading finds it later.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import re
12
+ from collections.abc import Iterable, Mapping, Sequence
13
+ from dataclasses import dataclass, field
14
+ from typing import Any
15
+
16
+ from .domain import Domain
17
+ from .errors import ExitCode, ForgeError
18
+ from .events import EventStore
19
+ from .identity import Identity
20
+ from .items import fold, format_id, parse_id
21
+ from .paths import Layout
22
+
23
+ PREFIX = "INSIGHT"
24
+ MAX_SUMMARY = 500
25
+ MAX_TAGS = 10
26
+
27
+ _TAG = re.compile(r"^[a-z0-9][a-z0-9-]{0,39}$")
28
+ _INSIGHT_ID = re.compile(r"^INSIGHT-(\d{4,})$")
29
+
30
+
31
+ @dataclass(frozen=True)
32
+ class Insight:
33
+ """An insight as the log describes it."""
34
+
35
+ id: str
36
+ summary: str
37
+ tags: tuple[str, ...]
38
+ actor: str
39
+ recorded: str
40
+ from_item: str | None = None
41
+
42
+ def label(self) -> str:
43
+ return f"{self.id} — {self.summary}"
44
+
45
+ def as_dict(self) -> dict[str, Any]:
46
+ return {
47
+ "id": self.id,
48
+ "summary": self.summary,
49
+ "tags": list(self.tags),
50
+ "actor": self.actor,
51
+ "recorded": self.recorded,
52
+ "from_item": self.from_item,
53
+ }
54
+
55
+
56
+ def fold_insights(events: Iterable[Mapping[str, Any]]) -> dict[str, Insight]:
57
+ """Every insight, from the log."""
58
+ insights: dict[str, Insight] = {}
59
+ for event in events:
60
+ data = event.get("data", {})
61
+ if event["type"] == "insight" and isinstance(data.get("insight_id"), str):
62
+ insights[data["insight_id"]] = Insight(
63
+ id=data["insight_id"],
64
+ summary=data.get("summary", ""),
65
+ tags=tuple(data.get("tags", [])),
66
+ actor=event["actor"],
67
+ recorded=event["ts"],
68
+ from_item=data.get("from_item"),
69
+ )
70
+ return insights
71
+
72
+
73
+ def _next_id(insights: Iterable[str]) -> str:
74
+ numbers = [int(m.group(1)) for i in insights if (m := _INSIGHT_ID.match(i))]
75
+ return format_id(PREFIX, max(numbers, default=0) + 1)
76
+
77
+
78
+ def check_tags(tags: Sequence[str]) -> tuple[str, ...]:
79
+ """Lower-case words joined by hyphens, at most 40 characters, at most 10 tags."""
80
+ clean = tuple(dict.fromkeys(t.strip().lower() for t in tags if t.strip()))
81
+ bad = [t for t in clean if not _TAG.match(t)]
82
+ if bad or len(clean) > MAX_TAGS:
83
+ raise ForgeError(
84
+ ExitCode.USAGE,
85
+ "invalid_tag",
86
+ f"tags are lower-case words joined by hyphens, at most {MAX_TAGS}; "
87
+ f"bad: {', '.join(bad) or 'too many'}",
88
+ )
89
+ return clean
90
+
91
+
92
+ @dataclass
93
+ class Insights:
94
+ """Record insights as one pinned identity."""
95
+
96
+ layout: Layout
97
+ domain: Domain
98
+ identity: Identity | None = None
99
+ store: EventStore = field(init=False)
100
+
101
+ def __post_init__(self) -> None:
102
+ self.store = EventStore(self.layout, self.domain)
103
+
104
+ def all(self) -> dict[str, Insight]:
105
+ return fold_insights(self.store.events())
106
+
107
+ def add(
108
+ self, summary: str, *, from_item: str | None = None, tags: Sequence[str] = ()
109
+ ) -> Insight:
110
+ """Write ``insight``."""
111
+ if self.identity is None:
112
+ raise ForgeError(ExitCode.INTERNAL, "no_identity", "insight writes need an identity")
113
+ who = self.identity
114
+ text = summary.strip()
115
+ if not text or len(text) > MAX_SUMMARY:
116
+ raise ForgeError(
117
+ ExitCode.USAGE, "invalid_summary", f"a summary is 1-{MAX_SUMMARY} characters"
118
+ )
119
+ clean = check_tags(tags)
120
+ if from_item is not None:
121
+ parse_id(from_item)
122
+ with self.store.transaction() as tx:
123
+ events = list(tx.events())
124
+ title = None
125
+ if from_item is not None:
126
+ item = fold(events, self.domain).get(from_item)
127
+ if item is None:
128
+ raise ForgeError(ExitCode.NOT_FOUND, "item_not_found", f"no item {from_item}")
129
+ title = item.title
130
+ insight_id = _next_id(fold_insights(events))
131
+ data: dict[str, Any] = {"insight_id": insight_id, "tags": list(clean), "summary": text}
132
+ if from_item is not None:
133
+ data["from_item"] = from_item
134
+ event = tx.append(
135
+ "insight",
136
+ actor=who.role,
137
+ session=who.session,
138
+ data=data,
139
+ item=from_item,
140
+ title=title,
141
+ )
142
+ return Insight(insight_id, text, clean, who.role, event["ts"], from_item)