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.
- codersforge/__init__.py +4 -0
- codersforge/__main__.py +8 -0
- codersforge/_core/CORE_VERSION +33 -0
- codersforge/_core/__init__.py +8 -0
- codersforge/_core/archive.py +319 -0
- codersforge/_core/backup.py +417 -0
- codersforge/_core/config.py +206 -0
- codersforge/_core/domain.py +382 -0
- codersforge/_core/errors.py +36 -0
- codersforge/_core/events.py +381 -0
- codersforge/_core/findings.py +265 -0
- codersforge/_core/gates.py +395 -0
- codersforge/_core/identity.py +259 -0
- codersforge/_core/index.py +262 -0
- codersforge/_core/items.py +513 -0
- codersforge/_core/ledger.py +194 -0
- codersforge/_core/lessons.py +142 -0
- codersforge/_core/messages.py +293 -0
- codersforge/_core/migrate.py +221 -0
- codersforge/_core/output.py +41 -0
- codersforge/_core/paths.py +62 -0
- codersforge/_core/py.typed +0 -0
- codersforge/_core/schema.py +113 -0
- codersforge/_core/ulid.py +36 -0
- codersforge/_core/upgrade.py +57 -0
- codersforge/_core/versions.py +20 -0
- codersforge/_core/views.py +67 -0
- codersforge/_core/walls.py +231 -0
- codersforge/_core/workflow.py +745 -0
- codersforge/_docs.py +33 -0
- codersforge/checks.py +94 -0
- codersforge/cli.py +865 -0
- codersforge/domain.py +270 -0
- codersforge/py.typed +0 -0
- codersforge/workflows.yaml +129 -0
- codersforge-0.0.1.dist-info/METADATA +81 -0
- codersforge-0.0.1.dist-info/RECORD +41 -0
- codersforge-0.0.1.dist-info/WHEEL +4 -0
- codersforge-0.0.1.dist-info/entry_points.txt +2 -0
- codersforge-0.0.1.dist-info/licenses/LICENSE +202 -0
- codersforge-0.0.1.dist-info/licenses/NOTICE +7 -0
|
@@ -0,0 +1,513 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
"""Work items: IDs, primary files with front-matter, and the events about them.
|
|
3
|
+
|
|
4
|
+
The event log is the record. An item's front-matter mirrors what the log says
|
|
5
|
+
(ID, type, title, state) plus fields the domain declares (``Domain.item_schema``),
|
|
6
|
+
so it can always be rebuilt. The body below the front-matter belongs to the
|
|
7
|
+
roles that work on the item.
|
|
8
|
+
|
|
9
|
+
Writes happen inside one store transaction, in this order: read the log,
|
|
10
|
+
allocate, append the event, then write the file. If the process dies after the
|
|
11
|
+
append, the item exists and its file can be regenerated from the log.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import json
|
|
17
|
+
import os
|
|
18
|
+
import re
|
|
19
|
+
import tempfile
|
|
20
|
+
from collections.abc import Iterable, Mapping
|
|
21
|
+
from dataclasses import dataclass, field, replace
|
|
22
|
+
from datetime import UTC, date, datetime
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
from typing import Any
|
|
25
|
+
|
|
26
|
+
import yaml
|
|
27
|
+
|
|
28
|
+
from .domain import Domain, ItemType
|
|
29
|
+
from .errors import ExitCode, ForgeError
|
|
30
|
+
from .events import EventStore
|
|
31
|
+
from .identity import Identity
|
|
32
|
+
from .paths import Layout
|
|
33
|
+
from .schema import Field, validate
|
|
34
|
+
from .upgrade import upgrade
|
|
35
|
+
from .versions import FRONT_MATTER_SCHEMA_VERSION
|
|
36
|
+
from .walls import enforce_item_write
|
|
37
|
+
from .workflow import (
|
|
38
|
+
PARKED,
|
|
39
|
+
RESERVED_STATES,
|
|
40
|
+
CheckContext,
|
|
41
|
+
Workflow,
|
|
42
|
+
apply_overrides,
|
|
43
|
+
decide,
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
MAX_TITLE = 80
|
|
47
|
+
MAX_NOTE = 2000
|
|
48
|
+
|
|
49
|
+
_ID = re.compile(r"^([A-Z]+)-(\d{4,})$")
|
|
50
|
+
_FENCE = "---\n"
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def format_id(prefix: str, number: int) -> str:
|
|
54
|
+
"""``FEAT-0007``; numbers past 9999 use as many digits as they need."""
|
|
55
|
+
return f"{prefix}-{number:04d}"
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def parse_id(item_id: str) -> tuple[str, int]:
|
|
59
|
+
"""``("FEAT", 7)`` for ``FEAT-0007``; ``USAGE`` error if malformed."""
|
|
60
|
+
match = _ID.match(item_id)
|
|
61
|
+
if not match:
|
|
62
|
+
raise ForgeError(
|
|
63
|
+
ExitCode.USAGE, "invalid_id", f"{item_id!r} is not an item ID like FEAT-0001"
|
|
64
|
+
)
|
|
65
|
+
return match.group(1), int(match.group(2))
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def check_title(title: str) -> str:
|
|
69
|
+
"""A title, trimmed: 1-80 characters on one line."""
|
|
70
|
+
trimmed = title.strip()
|
|
71
|
+
if not trimmed or len(trimmed) > MAX_TITLE or "\n" in trimmed or "\r" in trimmed:
|
|
72
|
+
raise ForgeError(
|
|
73
|
+
ExitCode.USAGE,
|
|
74
|
+
"invalid_title",
|
|
75
|
+
f"titles are 1-{MAX_TITLE} characters on one line; got {len(trimmed)}",
|
|
76
|
+
)
|
|
77
|
+
return trimmed
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
@dataclass(frozen=True)
|
|
81
|
+
class Item:
|
|
82
|
+
"""An item as the event log describes it."""
|
|
83
|
+
|
|
84
|
+
id: str
|
|
85
|
+
type: str
|
|
86
|
+
title: str
|
|
87
|
+
state: str
|
|
88
|
+
path: str # primary file, relative to the state folder
|
|
89
|
+
created: str # UTC date, YYYY-MM-DD
|
|
90
|
+
fields: Mapping[str, Any] = field(default_factory=dict)
|
|
91
|
+
assignee: str | None = None
|
|
92
|
+
archive_sha256: str | None = None # set once the item is rolled up (archive.py)
|
|
93
|
+
|
|
94
|
+
@property
|
|
95
|
+
def archived(self) -> bool:
|
|
96
|
+
"""Whether the item is now one archive file, frozen."""
|
|
97
|
+
return self.archive_sha256 is not None
|
|
98
|
+
|
|
99
|
+
def label(self) -> str:
|
|
100
|
+
"""``ID — title``, the form every human-facing reference uses."""
|
|
101
|
+
return f"{self.id} — {self.title}"
|
|
102
|
+
|
|
103
|
+
def as_dict(self) -> dict[str, Any]:
|
|
104
|
+
"""For ``--json`` output."""
|
|
105
|
+
return {
|
|
106
|
+
"id": self.id,
|
|
107
|
+
"type": self.type,
|
|
108
|
+
"title": self.title,
|
|
109
|
+
"state": self.state,
|
|
110
|
+
"path": self.path,
|
|
111
|
+
"created": self.created,
|
|
112
|
+
"assignee": self.assignee,
|
|
113
|
+
**dict(self.fields),
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def fold(events: Iterable[Mapping[str, Any]], domain: Domain) -> dict[str, Item]:
|
|
118
|
+
"""Every item, derived from the log (CONTRACT §5.4). Unknown events are ignored."""
|
|
119
|
+
items: dict[str, Item] = {}
|
|
120
|
+
for event in events:
|
|
121
|
+
item_id = event.get("item")
|
|
122
|
+
kind = event["type"]
|
|
123
|
+
data = event.get("data", {})
|
|
124
|
+
if kind == "created" and isinstance(item_id, str):
|
|
125
|
+
initial = next(
|
|
126
|
+
(t.initial_state for t in domain.item_types if t.name == data.get("kind")),
|
|
127
|
+
"INTAKE",
|
|
128
|
+
)
|
|
129
|
+
items[item_id] = Item(
|
|
130
|
+
id=item_id,
|
|
131
|
+
type=data.get("kind", ""),
|
|
132
|
+
title=event["title"],
|
|
133
|
+
state=initial,
|
|
134
|
+
path=data.get("path", ""),
|
|
135
|
+
created=event["ts"][:10],
|
|
136
|
+
fields={k: data[k] for k in domain.item_schema if k in data},
|
|
137
|
+
)
|
|
138
|
+
elif isinstance(item_id, str) and item_id in items:
|
|
139
|
+
current = items[item_id]
|
|
140
|
+
if kind == "renamed":
|
|
141
|
+
items[item_id] = replace(current, title=data["to"])
|
|
142
|
+
elif kind == "state":
|
|
143
|
+
items[item_id] = replace(
|
|
144
|
+
current,
|
|
145
|
+
state=data["to"],
|
|
146
|
+
path=data.get("path", current.path),
|
|
147
|
+
archive_sha256=data.get("sha256", current.archive_sha256),
|
|
148
|
+
)
|
|
149
|
+
elif kind == "assigned":
|
|
150
|
+
items[item_id] = replace(current, assignee=data["role"])
|
|
151
|
+
return items
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def refuse_archived(item: Item) -> None:
|
|
155
|
+
"""REFUSED: an archived item is frozen."""
|
|
156
|
+
if item.archived:
|
|
157
|
+
raise ForgeError(
|
|
158
|
+
ExitCode.REFUSED, "item_archived", f"{item.label()} is archived at {item.path}"
|
|
159
|
+
)
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def next_id(events: Iterable[Mapping[str, Any]], prefix: str) -> str:
|
|
163
|
+
"""The next ID for ``prefix``: one past the highest ever created. Never reused."""
|
|
164
|
+
highest = 0
|
|
165
|
+
for event in events:
|
|
166
|
+
item_id = event.get("item")
|
|
167
|
+
if event["type"] == "created" and isinstance(item_id, str):
|
|
168
|
+
match = _ID.match(item_id)
|
|
169
|
+
if match and match.group(1) == prefix:
|
|
170
|
+
highest = max(highest, int(match.group(2)))
|
|
171
|
+
return format_id(prefix, highest + 1)
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _parked_from(events: Iterable[Mapping[str, Any]], item_id: str) -> str | None:
|
|
175
|
+
"""The state an item was in when it was last parked."""
|
|
176
|
+
found = None
|
|
177
|
+
for event in events:
|
|
178
|
+
data = event.get("data", {})
|
|
179
|
+
if event["type"] == "state" and event.get("item") == item_id and data.get("to") == PARKED:
|
|
180
|
+
found = data.get("from")
|
|
181
|
+
return found
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
# ------------------------------------------------------------------ front-matter
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def _scalar(value: Any) -> str:
|
|
188
|
+
# JSON scalars and flow sequences are valid YAML, and stable to diff.
|
|
189
|
+
return json.dumps(value, ensure_ascii=False)
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def render_front_matter(values: Mapping[str, Any], domain: Domain) -> str:
|
|
193
|
+
"""Front-matter text in contract order: core keys, the domain's, then ``created``."""
|
|
194
|
+
order = ["schema", "id", "title", "type", "state", *domain.item_schema, "created"]
|
|
195
|
+
lines = [f"{key}: {_scalar(values[key])}" for key in order if key in values]
|
|
196
|
+
return _FENCE + "\n".join(lines) + "\n" + _FENCE
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def _front_matter_schema(domain: Domain) -> Field:
|
|
200
|
+
children: dict[str, Field] = {
|
|
201
|
+
"schema": Field("int", required=True),
|
|
202
|
+
"id": Field("str", required=True),
|
|
203
|
+
"title": Field("str", required=True),
|
|
204
|
+
"type": Field("enum", required=True, choices=tuple(t.name for t in domain.item_types)),
|
|
205
|
+
"state": Field("str", required=True),
|
|
206
|
+
**domain.item_schema,
|
|
207
|
+
"created": Field("str", required=True),
|
|
208
|
+
}
|
|
209
|
+
return Field("section", children=children)
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def parse_item_file(text: str, domain: Domain, where: str) -> tuple[dict[str, Any], str]:
|
|
213
|
+
"""``(front_matter, body)``. Malformed or unknown keys are DATA errors."""
|
|
214
|
+
raw, body = split_front_matter(text, where)
|
|
215
|
+
raw = upgrade("front_matter", raw, domain, where)
|
|
216
|
+
try:
|
|
217
|
+
values = validate(raw, _front_matter_schema(domain), "")
|
|
218
|
+
except ForgeError as err:
|
|
219
|
+
raise ForgeError(ExitCode.DATA, "front_matter_invalid", f"{where}: {err.detail}") from err
|
|
220
|
+
if values["schema"] != FRONT_MATTER_SCHEMA_VERSION:
|
|
221
|
+
newer = values["schema"] > FRONT_MATTER_SCHEMA_VERSION
|
|
222
|
+
hint = "; upgrade to a newer release" if newer else ""
|
|
223
|
+
raise ForgeError(
|
|
224
|
+
ExitCode.DATA,
|
|
225
|
+
"front_matter_invalid",
|
|
226
|
+
f"{where}: unsupported front-matter schema {values['schema']!r}{hint}",
|
|
227
|
+
)
|
|
228
|
+
return values, body
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def split_front_matter(text: str, where: str) -> tuple[Any, str]:
|
|
232
|
+
"""``(raw front-matter as parsed YAML, body)``, not yet validated or upgraded."""
|
|
233
|
+
if not text.startswith(_FENCE):
|
|
234
|
+
raise ForgeError(ExitCode.DATA, "front_matter_invalid", f"{where}: no front-matter")
|
|
235
|
+
end = text.find("\n" + _FENCE, len(_FENCE) - 1)
|
|
236
|
+
if end == -1:
|
|
237
|
+
raise ForgeError(
|
|
238
|
+
ExitCode.DATA, "front_matter_invalid", f"{where}: front-matter is not closed"
|
|
239
|
+
)
|
|
240
|
+
block = text[len(_FENCE) : end + 1]
|
|
241
|
+
body = text[end + 1 + len(_FENCE) :]
|
|
242
|
+
try:
|
|
243
|
+
return yaml.safe_load(block), body
|
|
244
|
+
except yaml.YAMLError as exc:
|
|
245
|
+
raise ForgeError(ExitCode.DATA, "front_matter_invalid", f"{where}: {exc}") from exc
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def _write_atomic(path: Path, text: str) -> None:
|
|
249
|
+
path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
250
|
+
fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.", suffix=".tmp")
|
|
251
|
+
try:
|
|
252
|
+
with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as handle:
|
|
253
|
+
handle.write(text)
|
|
254
|
+
handle.flush()
|
|
255
|
+
os.fsync(handle.fileno())
|
|
256
|
+
os.replace(tmp, path)
|
|
257
|
+
except BaseException:
|
|
258
|
+
Path(tmp).unlink(missing_ok=True)
|
|
259
|
+
raise
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
# ------------------------------------------------------------------ the API
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
class Items:
|
|
266
|
+
"""Create, rename and assign items as one pinned identity."""
|
|
267
|
+
|
|
268
|
+
def __init__(
|
|
269
|
+
self,
|
|
270
|
+
layout: Layout,
|
|
271
|
+
domain: Domain,
|
|
272
|
+
identity: Identity | None = None,
|
|
273
|
+
config: Mapping[str, Any] | None = None,
|
|
274
|
+
) -> None:
|
|
275
|
+
self.layout = layout
|
|
276
|
+
self.domain = domain
|
|
277
|
+
self.identity = identity
|
|
278
|
+
self.config: Mapping[str, Any] = config if config is not None else {}
|
|
279
|
+
self.store = EventStore(layout, domain)
|
|
280
|
+
|
|
281
|
+
def workflow(self, type_name: str) -> Workflow:
|
|
282
|
+
"""The item type's workflow, with this project's stricter overrides applied."""
|
|
283
|
+
overrides = self.config.get("workflows") or {}
|
|
284
|
+
workflows = apply_overrides(
|
|
285
|
+
self.domain.workflows, overrides, self.domain.all_checks, self.domain
|
|
286
|
+
)
|
|
287
|
+
if type_name not in workflows:
|
|
288
|
+
raise ForgeError(
|
|
289
|
+
ExitCode.USAGE, "no_workflow", f"{self.domain.title} has no {type_name} workflow"
|
|
290
|
+
)
|
|
291
|
+
return workflows[type_name]
|
|
292
|
+
|
|
293
|
+
def all(self) -> dict[str, Item]:
|
|
294
|
+
"""Every item, from the log."""
|
|
295
|
+
return fold(self.store.events(), self.domain)
|
|
296
|
+
|
|
297
|
+
def get(self, item_id: str) -> Item:
|
|
298
|
+
"""One item; NOT_FOUND if the log has never created it."""
|
|
299
|
+
return self.get_from(self.store.events(), item_id)
|
|
300
|
+
|
|
301
|
+
def get_from(self, events: Iterable[Mapping[str, Any]], item_id: str) -> Item:
|
|
302
|
+
"""One item from ``events`` (for callers inside a transaction)."""
|
|
303
|
+
parse_id(item_id)
|
|
304
|
+
item = fold(events, self.domain).get(item_id)
|
|
305
|
+
if item is None:
|
|
306
|
+
raise ForgeError(ExitCode.NOT_FOUND, "item_not_found", f"no item {item_id}")
|
|
307
|
+
return item
|
|
308
|
+
|
|
309
|
+
def file(self, item: Item) -> Path:
|
|
310
|
+
"""The item's primary file."""
|
|
311
|
+
return self.layout.state / item.path
|
|
312
|
+
|
|
313
|
+
def _who(self) -> Identity:
|
|
314
|
+
if self.identity is None:
|
|
315
|
+
raise ForgeError(ExitCode.INTERNAL, "no_identity", "item writes need an identity")
|
|
316
|
+
return self.identity
|
|
317
|
+
|
|
318
|
+
def _type(self, name: str) -> ItemType:
|
|
319
|
+
try:
|
|
320
|
+
return self.domain.item_type(name)
|
|
321
|
+
except KeyError:
|
|
322
|
+
known = ", ".join(t.name for t in self.domain.item_types)
|
|
323
|
+
raise ForgeError(
|
|
324
|
+
ExitCode.USAGE, "unknown_type", f"{name!r} is not an item type ({known})"
|
|
325
|
+
) from None
|
|
326
|
+
|
|
327
|
+
def create(self, type_name: str, title: str, fields: Mapping[str, Any]) -> Item:
|
|
328
|
+
"""Allocate the next ID, write ``created``, and write the primary file."""
|
|
329
|
+
who = self._who()
|
|
330
|
+
item_type = self._type(type_name)
|
|
331
|
+
title = check_title(title)
|
|
332
|
+
try:
|
|
333
|
+
values = validate(dict(fields), Field("section", children=self.domain.item_schema), "")
|
|
334
|
+
except ForgeError as err:
|
|
335
|
+
raise ForgeError(ExitCode.USAGE, "invalid_field", err.detail) from err
|
|
336
|
+
with self.store.transaction() as tx:
|
|
337
|
+
enforce_item_write(tx, self.domain, who, item_type.name, f"new {item_type.name}")
|
|
338
|
+
item_id = next_id(tx.events(), item_type.prefix)
|
|
339
|
+
path = item_type.path.format(id=item_id)
|
|
340
|
+
target = self.layout.state / path
|
|
341
|
+
if target.exists():
|
|
342
|
+
raise ForgeError(
|
|
343
|
+
ExitCode.CONFLICT,
|
|
344
|
+
"item_file_exists",
|
|
345
|
+
f"{target} already exists but the log has no {item_id}; "
|
|
346
|
+
"move it aside or run reindex",
|
|
347
|
+
)
|
|
348
|
+
data = {"kind": item_type.name, "path": path}
|
|
349
|
+
data.update({k: v for k, v in values.items() if v is not None})
|
|
350
|
+
event = tx.append(
|
|
351
|
+
"created",
|
|
352
|
+
actor=who.role,
|
|
353
|
+
session=who.session,
|
|
354
|
+
data=data,
|
|
355
|
+
item=item_id,
|
|
356
|
+
title=title,
|
|
357
|
+
)
|
|
358
|
+
item = Item(
|
|
359
|
+
id=item_id,
|
|
360
|
+
type=item_type.name,
|
|
361
|
+
title=title,
|
|
362
|
+
state=item_type.initial_state,
|
|
363
|
+
path=path,
|
|
364
|
+
created=event["ts"][:10],
|
|
365
|
+
fields={k: v for k, v in values.items() if v is not None},
|
|
366
|
+
)
|
|
367
|
+
front = {
|
|
368
|
+
"schema": FRONT_MATTER_SCHEMA_VERSION,
|
|
369
|
+
"id": item_id,
|
|
370
|
+
"title": title,
|
|
371
|
+
"type": item_type.name,
|
|
372
|
+
"state": item.state,
|
|
373
|
+
**values,
|
|
374
|
+
"created": item.created,
|
|
375
|
+
}
|
|
376
|
+
body = item_type.body.format(id=item_id, title=title)
|
|
377
|
+
_write_atomic(target, render_front_matter(front, self.domain) + "\n" + body)
|
|
378
|
+
return item
|
|
379
|
+
|
|
380
|
+
def rename(self, item_id: str, title: str) -> tuple[Item, str]:
|
|
381
|
+
"""Write ``renamed`` and update the file's title. Returns ``(item, old_title)``."""
|
|
382
|
+
who = self._who()
|
|
383
|
+
title = check_title(title)
|
|
384
|
+
with self.store.transaction() as tx:
|
|
385
|
+
item = fold(tx.events(), self.domain).get(item_id)
|
|
386
|
+
if item is None:
|
|
387
|
+
parse_id(item_id)
|
|
388
|
+
raise ForgeError(ExitCode.NOT_FOUND, "item_not_found", f"no item {item_id}")
|
|
389
|
+
enforce_item_write(tx, self.domain, who, item.type, item_id)
|
|
390
|
+
refuse_archived(item)
|
|
391
|
+
if title == item.title:
|
|
392
|
+
return item, item.title
|
|
393
|
+
target = self.file(item)
|
|
394
|
+
front, body = self._read(target)
|
|
395
|
+
tx.append(
|
|
396
|
+
"renamed",
|
|
397
|
+
actor=who.role,
|
|
398
|
+
session=who.session,
|
|
399
|
+
data={"from": item.title, "to": title},
|
|
400
|
+
item=item_id,
|
|
401
|
+
title=title,
|
|
402
|
+
)
|
|
403
|
+
front["title"] = title
|
|
404
|
+
_write_atomic(target, render_front_matter(front, self.domain) + body)
|
|
405
|
+
return replace(item, title=title), item.title
|
|
406
|
+
|
|
407
|
+
def assign(self, item_id: str, role: str, task: str | None = None) -> Item:
|
|
408
|
+
"""Write ``assigned``. Only the domain's team roles take assignments."""
|
|
409
|
+
who = self._who()
|
|
410
|
+
if role not in self.domain.roles:
|
|
411
|
+
raise ForgeError(
|
|
412
|
+
ExitCode.USAGE,
|
|
413
|
+
"unknown_role",
|
|
414
|
+
f"{role!r} cannot be assigned work. Roles: {', '.join(self.domain.roles)}.",
|
|
415
|
+
)
|
|
416
|
+
with self.store.transaction() as tx:
|
|
417
|
+
item = fold(tx.events(), self.domain).get(item_id)
|
|
418
|
+
if item is None:
|
|
419
|
+
parse_id(item_id)
|
|
420
|
+
raise ForgeError(ExitCode.NOT_FOUND, "item_not_found", f"no item {item_id}")
|
|
421
|
+
enforce_item_write(tx, self.domain, who, item.type, item_id)
|
|
422
|
+
refuse_archived(item)
|
|
423
|
+
data: dict[str, Any] = {"role": role}
|
|
424
|
+
if task:
|
|
425
|
+
data["task"] = task
|
|
426
|
+
tx.append(
|
|
427
|
+
"assigned",
|
|
428
|
+
actor=who.role,
|
|
429
|
+
session=who.session,
|
|
430
|
+
data=data,
|
|
431
|
+
item=item_id,
|
|
432
|
+
title=item.title,
|
|
433
|
+
)
|
|
434
|
+
return replace(item, assignee=role)
|
|
435
|
+
|
|
436
|
+
def move(
|
|
437
|
+
self,
|
|
438
|
+
item_id: str,
|
|
439
|
+
target: str,
|
|
440
|
+
note: str | None = None,
|
|
441
|
+
today: date | None = None,
|
|
442
|
+
) -> tuple[Item, str]:
|
|
443
|
+
"""Write a ``state`` event if the workflow allows it. Returns ``(item, old_state)``.
|
|
444
|
+
|
|
445
|
+
Refusals exit 2 with the workflow's reason: ``transition_not_allowed``,
|
|
446
|
+
``gate_not_ruled``, ``condition_unmet``, ``condition_unavailable`` or
|
|
447
|
+
``use_command``.
|
|
448
|
+
"""
|
|
449
|
+
who = self._who()
|
|
450
|
+
note = note.strip() if note else None
|
|
451
|
+
if note is not None and (not note or len(note) > MAX_NOTE):
|
|
452
|
+
raise ForgeError(ExitCode.USAGE, "invalid_note", f"notes are 1-{MAX_NOTE} characters")
|
|
453
|
+
with self.store.transaction() as tx:
|
|
454
|
+
events = list(tx.events())
|
|
455
|
+
item = fold(events, self.domain).get(item_id)
|
|
456
|
+
if item is None:
|
|
457
|
+
parse_id(item_id)
|
|
458
|
+
raise ForgeError(ExitCode.NOT_FOUND, "item_not_found", f"no item {item_id}")
|
|
459
|
+
current = item.state
|
|
460
|
+
if target == current:
|
|
461
|
+
raise ForgeError(
|
|
462
|
+
ExitCode.USAGE, "already_in_state", f"{item.label()} is already {current}"
|
|
463
|
+
)
|
|
464
|
+
if target in RESERVED_STATES and note is None:
|
|
465
|
+
raise ForgeError(
|
|
466
|
+
ExitCode.USAGE, "note_required", f"moving to {target} needs --note"
|
|
467
|
+
)
|
|
468
|
+
parked_from = _parked_from(events, item_id) if current == PARKED else None
|
|
469
|
+
ctx = CheckContext(
|
|
470
|
+
item=item,
|
|
471
|
+
events=events,
|
|
472
|
+
config=self.config,
|
|
473
|
+
today=today or datetime.now(UTC).date(),
|
|
474
|
+
domain=self.domain,
|
|
475
|
+
)
|
|
476
|
+
decision = decide(
|
|
477
|
+
self.workflow(item.type),
|
|
478
|
+
ctx,
|
|
479
|
+
current,
|
|
480
|
+
target,
|
|
481
|
+
checks=self.domain.all_checks,
|
|
482
|
+
parked_from=parked_from,
|
|
483
|
+
)
|
|
484
|
+
if not decision.allowed:
|
|
485
|
+
code = ExitCode.USAGE if decision.reason == "unknown_state" else ExitCode.REFUSED
|
|
486
|
+
raise ForgeError(code, decision.reason, f"{item.label()}: {decision.detail}")
|
|
487
|
+
path = self.file(item)
|
|
488
|
+
front, body = self._read(path)
|
|
489
|
+
data: dict[str, Any] = {"from": current, "to": target}
|
|
490
|
+
if note:
|
|
491
|
+
data["note"] = note
|
|
492
|
+
if decision.gate:
|
|
493
|
+
data["gate"] = decision.gate
|
|
494
|
+
tx.append(
|
|
495
|
+
"state",
|
|
496
|
+
actor=who.role,
|
|
497
|
+
session=who.session,
|
|
498
|
+
data=data,
|
|
499
|
+
item=item_id,
|
|
500
|
+
title=item.title,
|
|
501
|
+
)
|
|
502
|
+
front["state"] = target
|
|
503
|
+
_write_atomic(path, render_front_matter(front, self.domain) + body)
|
|
504
|
+
return replace(item, state=target), current
|
|
505
|
+
|
|
506
|
+
def _read(self, path: Path) -> tuple[dict[str, Any], str]:
|
|
507
|
+
if not path.is_file():
|
|
508
|
+
raise ForgeError(
|
|
509
|
+
ExitCode.DATA,
|
|
510
|
+
"item_file_missing",
|
|
511
|
+
f"{path} is missing; run reindex to regenerate it from the log",
|
|
512
|
+
)
|
|
513
|
+
return parse_item_file(path.read_text(encoding="utf-8"), self.domain, str(path))
|