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/__init__.py +8 -0
- teaimforge/archive.py +370 -0
- teaimforge/backup.py +441 -0
- teaimforge/cli.py +823 -0
- teaimforge/config.py +207 -0
- teaimforge/domain.py +549 -0
- teaimforge/errors.py +36 -0
- teaimforge/events.py +381 -0
- teaimforge/findings.py +291 -0
- teaimforge/gates.py +395 -0
- teaimforge/identity.py +259 -0
- teaimforge/index.py +267 -0
- teaimforge/insights.py +142 -0
- teaimforge/items.py +554 -0
- teaimforge/ledger.py +196 -0
- teaimforge/messages.py +293 -0
- teaimforge/migrate.py +230 -0
- teaimforge/output.py +41 -0
- teaimforge/paths.py +101 -0
- teaimforge/py.typed +0 -0
- teaimforge/schema.py +113 -0
- teaimforge/ulid.py +36 -0
- teaimforge/upgrade.py +57 -0
- teaimforge/versions.py +28 -0
- teaimforge/views.py +71 -0
- teaimforge/walls.py +337 -0
- teaimforge/workflow.py +788 -0
- teaimforge-0.19.0.dist-info/METADATA +77 -0
- teaimforge-0.19.0.dist-info/RECORD +32 -0
- teaimforge-0.19.0.dist-info/WHEEL +4 -0
- teaimforge-0.19.0.dist-info/licenses/LICENSE +202 -0
- teaimforge-0.19.0.dist-info/licenses/NOTICE +7 -0
teaimforge/__init__.py
ADDED
teaimforge/archive.py
ADDED
|
@@ -0,0 +1,370 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
"""Archive: roll a closed item's folder up into one file and remove the folder.
|
|
3
|
+
|
|
4
|
+
An item is archivable when its workflow has a transition into the archived
|
|
5
|
+
state made ``via: archive`` from the state it is in (usually ``DONE`` and
|
|
6
|
+
``ABANDONED``). The rollup, ``archive/<ID>.md``, holds the item's front-matter,
|
|
7
|
+
its record from the log (history, gates, findings, insights) and every text
|
|
8
|
+
file from its folder, each in its own fenced block. Any other file (a
|
|
9
|
+
screenshot, say) is kept beside it in ``archive/<ID>.files/``, and the rollup
|
|
10
|
+
lists its size and SHA-256, so the one hash the log records covers everything.
|
|
11
|
+
A file over ``limits.state_file_mb`` is refused: anything that large is
|
|
12
|
+
content, and belongs in the product repository.
|
|
13
|
+
|
|
14
|
+
The rollup cannot be rebuilt from the log, so the order differs from other
|
|
15
|
+
writes. Inside one store transaction:
|
|
16
|
+
|
|
17
|
+
1. copy any kept files into ``archive/<ID>.files/`` (through a temporary
|
|
18
|
+
folder renamed into place), then write ``archive/<ID>.md`` (atomically);
|
|
19
|
+
2. append the ``state`` event, carrying the new path and the file's SHA-256;
|
|
20
|
+
3. remove the item's folder.
|
|
21
|
+
|
|
22
|
+
A crash after 1 leaves the item unarchived and the next run replaces both. A
|
|
23
|
+
crash after 2 leaves the folder behind; the next run checks the rollup, and the
|
|
24
|
+
files kept beside it, against the recorded hash and finishes the removal.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
from __future__ import annotations
|
|
28
|
+
|
|
29
|
+
import os
|
|
30
|
+
import re
|
|
31
|
+
import shutil
|
|
32
|
+
from collections.abc import Mapping, Sequence
|
|
33
|
+
from dataclasses import dataclass
|
|
34
|
+
from datetime import UTC, date, datetime
|
|
35
|
+
from pathlib import Path
|
|
36
|
+
from typing import Any
|
|
37
|
+
|
|
38
|
+
from .domain import OPERATOR, ORCHESTRATOR, Domain
|
|
39
|
+
from .errors import ExitCode, ForgeError
|
|
40
|
+
from .events import EventStore
|
|
41
|
+
from .identity import Identity
|
|
42
|
+
from .items import (
|
|
43
|
+
Item,
|
|
44
|
+
Items,
|
|
45
|
+
_write_atomic,
|
|
46
|
+
fold,
|
|
47
|
+
render_front_matter,
|
|
48
|
+
)
|
|
49
|
+
from .paths import Layout, rollup_intact, sha256_of
|
|
50
|
+
from .versions import FRONT_MATTER_SCHEMA_VERSION
|
|
51
|
+
from .views import ItemView, describe_item
|
|
52
|
+
from .walls import enforce_item_write
|
|
53
|
+
from .workflow import CheckContext, decide
|
|
54
|
+
|
|
55
|
+
VIA = "archive"
|
|
56
|
+
ARCHIVE_DIR = "archive"
|
|
57
|
+
_DASH = " \u2014 "
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@dataclass(frozen=True)
|
|
61
|
+
class Archived:
|
|
62
|
+
"""What ``archive`` did."""
|
|
63
|
+
|
|
64
|
+
item: Item
|
|
65
|
+
previous_state: str
|
|
66
|
+
removed: str # the folder or file taken away, relative to the state folder
|
|
67
|
+
files: tuple[str, ...] # files rolled up, relative to the removed folder
|
|
68
|
+
finished: bool = False # True: an earlier interrupted run was completed
|
|
69
|
+
kept: tuple[str, ...] = () # of files, those kept beside the rollup (not text)
|
|
70
|
+
|
|
71
|
+
def as_dict(self) -> dict[str, Any]:
|
|
72
|
+
return {
|
|
73
|
+
**self.item.as_dict(),
|
|
74
|
+
"previous_state": self.previous_state,
|
|
75
|
+
"removed": self.removed,
|
|
76
|
+
"files": list(self.files),
|
|
77
|
+
"finished": self.finished,
|
|
78
|
+
"kept": list(self.kept),
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def archive_path(item_id: str) -> str:
|
|
83
|
+
"""``archive/FEAT-0001.md``, relative to the state folder."""
|
|
84
|
+
return f"{ARCHIVE_DIR}/{item_id}.md"
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def kept_dir(item_id: str) -> str:
|
|
88
|
+
"""``archive/FEAT-0001.files``: where files that are not text are kept."""
|
|
89
|
+
return f"{ARCHIVE_DIR}/{item_id}.files"
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def sha256_file(path: Path) -> str:
|
|
93
|
+
return sha256_of(path)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def is_text(path: Path) -> bool:
|
|
97
|
+
try:
|
|
98
|
+
path.read_text(encoding="utf-8")
|
|
99
|
+
except UnicodeDecodeError:
|
|
100
|
+
return False
|
|
101
|
+
return True
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _cell(text: object) -> str:
|
|
105
|
+
return str(text).replace("|", "\\|").replace("\n", " ")
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _fence(text: str) -> str:
|
|
109
|
+
"""A backtick fence longer than any run of backticks in ``text``."""
|
|
110
|
+
longest = max((len(m) for m in re.findall(r"`+", text)), default=0)
|
|
111
|
+
return "`" * max(3, longest + 1)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
class Archiver:
|
|
115
|
+
"""Archive items as one pinned identity."""
|
|
116
|
+
|
|
117
|
+
def __init__(
|
|
118
|
+
self,
|
|
119
|
+
layout: Layout,
|
|
120
|
+
domain: Domain,
|
|
121
|
+
identity: Identity,
|
|
122
|
+
config: Mapping[str, Any] | None = None,
|
|
123
|
+
) -> None:
|
|
124
|
+
self.layout = layout
|
|
125
|
+
self.domain = domain
|
|
126
|
+
self.identity = identity
|
|
127
|
+
self.items = Items(layout, domain, identity, config)
|
|
128
|
+
self.store = EventStore(layout, domain)
|
|
129
|
+
|
|
130
|
+
def may_archive(self, role: str) -> bool:
|
|
131
|
+
return role in (ORCHESTRATOR, OPERATOR, *self.domain.archivers)
|
|
132
|
+
|
|
133
|
+
def archive(self, item_id: str, today: date | None = None) -> Archived:
|
|
134
|
+
"""Roll up ``item_id`` and remove its folder; REFUSED unless it is closed."""
|
|
135
|
+
who = self.identity
|
|
136
|
+
if not self.may_archive(who.role):
|
|
137
|
+
allowed = ", ".join((ORCHESTRATOR, OPERATOR, *self.domain.archivers))
|
|
138
|
+
raise ForgeError(
|
|
139
|
+
ExitCode.REFUSED, "role_not_allowed", f"only {allowed} may archive items"
|
|
140
|
+
)
|
|
141
|
+
with self.store.transaction() as tx:
|
|
142
|
+
events = list(tx.events())
|
|
143
|
+
item = self.items.get_from(events, item_id)
|
|
144
|
+
enforce_item_write(tx, self.domain, who, item.type, item_id)
|
|
145
|
+
if item.archived:
|
|
146
|
+
return self._finish(events, item)
|
|
147
|
+
workflow = self.items.workflow(item.type)
|
|
148
|
+
edges = [e for e in workflow.via_edges(VIA) if e.source == item.state]
|
|
149
|
+
if not edges:
|
|
150
|
+
sources = sorted({e.source for e in workflow.via_edges(VIA)})
|
|
151
|
+
raise ForgeError(
|
|
152
|
+
ExitCode.REFUSED,
|
|
153
|
+
"not_archivable",
|
|
154
|
+
f"{item.label()} is {item.state}; a {item.type} is archived from "
|
|
155
|
+
f"{' or '.join(sources) or 'no state'}",
|
|
156
|
+
)
|
|
157
|
+
target = edges[0].target
|
|
158
|
+
ctx = CheckContext(
|
|
159
|
+
item=item,
|
|
160
|
+
events=events,
|
|
161
|
+
config=self.items.config,
|
|
162
|
+
today=today or datetime.now(UTC).date(),
|
|
163
|
+
domain=self.domain,
|
|
164
|
+
)
|
|
165
|
+
decision = decide(
|
|
166
|
+
workflow, ctx, item.state, target, checks=self.domain.all_checks, via=VIA
|
|
167
|
+
)
|
|
168
|
+
if not decision.allowed:
|
|
169
|
+
raise ForgeError(
|
|
170
|
+
ExitCode.REFUSED, decision.reason, f"{item.label()}: {decision.detail}"
|
|
171
|
+
)
|
|
172
|
+
removed, files = self._contents(item)
|
|
173
|
+
kept = self._keep(item_id, removed, files)
|
|
174
|
+
view = describe_item(events, self.domain, item_id)
|
|
175
|
+
rollup = self.layout.state / archive_path(item_id)
|
|
176
|
+
_write_atomic(rollup, self._render(view, target, removed, files, kept, ctx.today))
|
|
177
|
+
data: dict[str, Any] = {
|
|
178
|
+
"from": item.state,
|
|
179
|
+
"to": target,
|
|
180
|
+
"path": archive_path(item_id),
|
|
181
|
+
"was": item.path,
|
|
182
|
+
"sha256": sha256_file(rollup),
|
|
183
|
+
}
|
|
184
|
+
if decision.gate:
|
|
185
|
+
data["gate"] = decision.gate
|
|
186
|
+
tx.append(
|
|
187
|
+
"state",
|
|
188
|
+
actor=who.role,
|
|
189
|
+
session=who.session,
|
|
190
|
+
data=data,
|
|
191
|
+
item=item_id,
|
|
192
|
+
title=item.title,
|
|
193
|
+
)
|
|
194
|
+
self._remove(removed)
|
|
195
|
+
archived = fold(self.store.events(), self.domain)[item_id]
|
|
196
|
+
return Archived(archived, item.state, removed, tuple(files), kept=tuple(kept))
|
|
197
|
+
|
|
198
|
+
# ------------------------------------------------------------ internals
|
|
199
|
+
|
|
200
|
+
def _finish(self, events: Sequence[Mapping[str, Any]], item: Item) -> Archived:
|
|
201
|
+
"""An archived item whose folder survived an interrupted run."""
|
|
202
|
+
record = next(
|
|
203
|
+
e
|
|
204
|
+
for e in reversed(events)
|
|
205
|
+
if e["type"] == "state" and e.get("item") == item.id and "sha256" in e["data"]
|
|
206
|
+
)
|
|
207
|
+
was = str(record["data"]["was"])
|
|
208
|
+
removed = self._folder_of(item.id, was)
|
|
209
|
+
if not (self.layout.state / removed).exists():
|
|
210
|
+
raise ForgeError(
|
|
211
|
+
ExitCode.USAGE, "already_archived", f"{item.label()} is archived at {item.path}"
|
|
212
|
+
)
|
|
213
|
+
rollup = self.layout.state / item.path
|
|
214
|
+
if not rollup_intact(self.layout.state, item.path, item.archive_sha256):
|
|
215
|
+
raise ForgeError(
|
|
216
|
+
ExitCode.DATA,
|
|
217
|
+
"archive_altered",
|
|
218
|
+
f"{rollup} or a file kept beside it is missing or does not match the log; "
|
|
219
|
+
f"{removed} was kept so nothing is lost",
|
|
220
|
+
)
|
|
221
|
+
self._remove(removed)
|
|
222
|
+
return Archived(item, str(record["data"]["from"]), removed, (), finished=True)
|
|
223
|
+
|
|
224
|
+
def _folder_of(self, item_id: str, path: str) -> str:
|
|
225
|
+
"""The item's own folder when its file sits in one named for it, else the file."""
|
|
226
|
+
parent = Path(path).parent
|
|
227
|
+
return parent.as_posix() if parent.name == item_id else path
|
|
228
|
+
|
|
229
|
+
def _contents(self, item: Item) -> tuple[str, list[str]]:
|
|
230
|
+
removed = self._folder_of(item.id, item.path)
|
|
231
|
+
base = self.layout.state / removed
|
|
232
|
+
if base.is_symlink() or not base.exists():
|
|
233
|
+
raise ForgeError(
|
|
234
|
+
ExitCode.DATA,
|
|
235
|
+
"item_file_missing",
|
|
236
|
+
f"{base} is missing or a link; run reindex before archiving",
|
|
237
|
+
)
|
|
238
|
+
if base.is_file():
|
|
239
|
+
self._check_size(base, base.name)
|
|
240
|
+
return removed, [base.name]
|
|
241
|
+
files: list[str] = []
|
|
242
|
+
for top, dirs, names in os.walk(base, followlinks=False):
|
|
243
|
+
dirs.sort()
|
|
244
|
+
for name in [*dirs, *names]:
|
|
245
|
+
if Path(top, name).is_symlink():
|
|
246
|
+
rel = Path(top, name).relative_to(base).as_posix()
|
|
247
|
+
raise ForgeError(
|
|
248
|
+
ExitCode.DATA,
|
|
249
|
+
"archive_link",
|
|
250
|
+
f"{removed}/{rel} is a link; links are not archived. Remove it first",
|
|
251
|
+
)
|
|
252
|
+
for name in sorted(names):
|
|
253
|
+
rel = Path(top, name).relative_to(base).as_posix()
|
|
254
|
+
self._check_size(Path(top, name), f"{removed}/{rel}")
|
|
255
|
+
files.append(rel)
|
|
256
|
+
primary = Path(item.path).relative_to(removed).as_posix()
|
|
257
|
+
files.sort(key=lambda f: (f != primary, f))
|
|
258
|
+
return removed, files
|
|
259
|
+
|
|
260
|
+
def _check_size(self, path: Path, shown: str) -> None:
|
|
261
|
+
limits = self.items.config.get("limits") or {}
|
|
262
|
+
cap = int(limits.get("state_file_mb", 5))
|
|
263
|
+
size = path.stat().st_size
|
|
264
|
+
if size > cap * 1024 * 1024:
|
|
265
|
+
raise ForgeError(
|
|
266
|
+
ExitCode.DATA,
|
|
267
|
+
"archive_too_large",
|
|
268
|
+
f"{shown} is {size / 1024 / 1024:.1f} MB, over limits.state_file_mb ({cap}); "
|
|
269
|
+
"a file that large is content: move it to the product repository first",
|
|
270
|
+
)
|
|
271
|
+
|
|
272
|
+
def _keep(self, item_id: str, removed: str, files: Sequence[str]) -> list[str]:
|
|
273
|
+
"""Copy the files that are not text beside the rollup; return their names."""
|
|
274
|
+
base = self.layout.state / removed
|
|
275
|
+
archive = self.layout.state / ARCHIVE_DIR
|
|
276
|
+
final = self.layout.state / kept_dir(item_id)
|
|
277
|
+
work = archive / f".{item_id}.files.tmp"
|
|
278
|
+
shutil.rmtree(work, ignore_errors=True)
|
|
279
|
+
kept = [rel for rel in files if not is_text(base if base.is_file() else base / rel)]
|
|
280
|
+
for rel in kept:
|
|
281
|
+
target = work / rel
|
|
282
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
283
|
+
shutil.copyfile(base if base.is_file() else base / rel, target)
|
|
284
|
+
if final.exists():
|
|
285
|
+
shutil.rmtree(final) # left by an interrupted run
|
|
286
|
+
if kept:
|
|
287
|
+
archive.mkdir(parents=True, exist_ok=True)
|
|
288
|
+
os.replace(work, final)
|
|
289
|
+
return kept
|
|
290
|
+
|
|
291
|
+
def _remove(self, removed: str) -> None:
|
|
292
|
+
target = self.layout.state / removed
|
|
293
|
+
if target.is_dir():
|
|
294
|
+
shutil.rmtree(target)
|
|
295
|
+
else:
|
|
296
|
+
target.unlink(missing_ok=True)
|
|
297
|
+
|
|
298
|
+
def _render( # noqa: PLR0913, PLR0917 - the pieces of one rollup
|
|
299
|
+
self,
|
|
300
|
+
view: ItemView,
|
|
301
|
+
target: str,
|
|
302
|
+
removed: str,
|
|
303
|
+
files: Sequence[str],
|
|
304
|
+
kept: Sequence[str],
|
|
305
|
+
today: date,
|
|
306
|
+
) -> str:
|
|
307
|
+
item = view.item
|
|
308
|
+
front: dict[str, Any] = {
|
|
309
|
+
"schema": FRONT_MATTER_SCHEMA_VERSION,
|
|
310
|
+
"id": item.id,
|
|
311
|
+
"title": item.title,
|
|
312
|
+
"type": item.type,
|
|
313
|
+
"state": target,
|
|
314
|
+
**{k: v.default for k, v in self.domain.item_schema.items()},
|
|
315
|
+
**dict(item.fields),
|
|
316
|
+
"created": item.created,
|
|
317
|
+
}
|
|
318
|
+
lines = [
|
|
319
|
+
"",
|
|
320
|
+
f"# {item.label()}",
|
|
321
|
+
"",
|
|
322
|
+
f"Archived {today.isoformat()} from `{removed}` by `{self.domain.name} archive`. "
|
|
323
|
+
"Do not edit: the log records this file's hash.",
|
|
324
|
+
"",
|
|
325
|
+
"## History",
|
|
326
|
+
"",
|
|
327
|
+
"| When | By | From | To | Gate | Note |",
|
|
328
|
+
"|---|---|---|---|---|---|",
|
|
329
|
+
]
|
|
330
|
+
lines += [
|
|
331
|
+
f"| {h['ts'][:16].replace('T', ' ')} | {h['actor']} | {h['from']} | {h['to']} "
|
|
332
|
+
f"| {h.get('gate', '')} | {_cell(h.get('note', ''))} |"
|
|
333
|
+
for h in view.history
|
|
334
|
+
]
|
|
335
|
+
lines += [
|
|
336
|
+
f"| {today.isoformat()} | {self.identity.role} | {item.state} | {target} | | |",
|
|
337
|
+
]
|
|
338
|
+
sections: list[tuple[str, list[str]]] = [
|
|
339
|
+
("Gates", [f"- {g.id}{_DASH}{g.summary}{_DASH}{g.status()}" for g in view.gates]),
|
|
340
|
+
(
|
|
341
|
+
"Findings",
|
|
342
|
+
[
|
|
343
|
+
f"- {f.id}{_DASH}{f.severity}{_DASH}{f.summary}{_DASH}{f.status()}"
|
|
344
|
+
for f in view.findings
|
|
345
|
+
],
|
|
346
|
+
),
|
|
347
|
+
("Insights", [f"- {x.label()}" for x in view.insights]),
|
|
348
|
+
]
|
|
349
|
+
for heading, rows in sections:
|
|
350
|
+
lines += ["", f"## {heading} ({len(rows)})", ""]
|
|
351
|
+
lines += rows or ["None."]
|
|
352
|
+
lines += ["", "## Files", ""]
|
|
353
|
+
base = self.layout.state / removed
|
|
354
|
+
for rel in files:
|
|
355
|
+
path = base if base.is_file() else base / rel
|
|
356
|
+
if rel in kept:
|
|
357
|
+
beside = f"{kept_dir(item.id)}/{rel}"
|
|
358
|
+
lines += [
|
|
359
|
+
f"### {rel}",
|
|
360
|
+
"",
|
|
361
|
+
f"Kept beside this file: `{beside}`, {path.stat().st_size} bytes, "
|
|
362
|
+
f"SHA-256 `{sha256_of(path)}`.",
|
|
363
|
+
"",
|
|
364
|
+
]
|
|
365
|
+
continue
|
|
366
|
+
text = path.read_text(encoding="utf-8")
|
|
367
|
+
fence = _fence(text)
|
|
368
|
+
ending = "" if text.endswith("\n") or not text else "\n"
|
|
369
|
+
lines += [f"### {rel}", "", f"{fence}text", text + ending + fence, ""]
|
|
370
|
+
return render_front_matter(front, self.domain) + "\n".join(lines).rstrip("\n") + "\n"
|